Merge master and preserve catalog-recursive subagent discovery

This commit is contained in:
Dudu-0223 committed 2026-09-27 15:23:31 +08:00
commit 3254ed611d
5076 files changed
+226902 -51386

No files matched your search

@@ -0,0 +1,56 @@
/**
* The controller's admission gate for archived Sessions: an archived
* Session, or a subagent descendant of one, must not run a model step until
* it is restored. The work a Session still runs is reported and stopped by
* its owners — the Agent registry (`turn`), the job registry seam (`job`),
* the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) —
* through the Workspace registry's archive-admission events.
*/
import type { Context, Plugin } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { SessionId } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-workspace'
/**
* The gate as a plugin for `ctx.plugin(...)`: it loads once the Agent
* registry, Session store, and Workspace registry are available and unwinds
* with the plugin's fiber. A late waking delivery to an archived Session — a
* subagent settlement, a queued follow-up — proposes a step the gate rejects,
* which the loop ends as `blocked` without a request; unarchiving lifts the
* gate for the whole lineage.
*/
export const ArchivedSessionGate: Plugin.Object<void> = {
name: 'archived-session-gate',
inject: ['agents', 'sessions', 'workspaceRegistry'],
apply(ctx: Context): void {
ctx.on('agent/pre-step', (payload, next) =>
underArchivedSession(ctx, payload.agent)
? Promise.resolve({ kind: 'reject' as const })
: next())
},
}
/**
* Whether the Agent's Session, or a Session above it in its subagent lineage,
* is archived. Lineage follows the durable header fields through
* subagent-origin Sessions only: a fork of an archived Session is an
* independent conversation.
* @param ctx - Host context.
* @param agent - the Agent proposing a step.
* @returns whether an archived Session owns the step.
*/
export function underArchivedSession(ctx: Context, agent: Agent): boolean {
const archived = ctx.workspaceRegistry.archivedSessionIds
let header = agent.session.header
const visited = new Set<SessionId>()
while (!visited.has(header.id)) {
if (archived.includes(header.id)) return true
visited.add(header.id)
if (header.origin !== 'subagent' || header.parentSession === undefined) return false
const parent = ctx.sessions.get(header.parentSession)
if (parent === undefined) return archived.includes(header.parentSession)
header = parent.header
}
return false
}
+52 -3
View File
@@ -1,5 +1,9 @@
/** Shared projection of the live LLM registry into the browser model catalog. */
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
import type {} from '@deepseek-ai/dsh-settings'
import type { LlmModelInfo } from '@deepseek-ai/dsh-llm'
import type { Context } from '@deepseek-ai/cordis'
import type {
ModelCatalog,
@@ -57,11 +61,56 @@ export async function buildModelCatalog(
}
}
}))
const groups = catalog.flatMap(item => item.kind === 'group' ? [item.group] : [])
.filter(group => group.models.length > 0)
return {
default: { ...defaultSelection },
routableProviders: providers.map(provider => provider.id),
groups: catalog.flatMap(item => item.kind === 'group' ? [item.group] : [])
.filter(group => group.models.length > 0),
routableProviders: groups.map(group => group.id),
groups,
failures: catalog.flatMap(item => item.kind === 'failure' ? [item.failure] : []),
}
}
/**
* Check a GUI selection against the current available provider catalog.
* @param ctx - Host LLM registry.
* @param selection - stored or explicitly requested selection.
* @returns whether the exact model is currently advertised as available.
*/
export async function modelAvailable(ctx: Context, selection: ModelSelection): Promise<boolean> {
if (!ctx.llm.listProviders().some(provider => provider.id === selection.provider)) return false
let models: readonly LlmModelInfo[]
try { models = await ctx.llm.listModels(selection.provider) }
catch (error) {
throw new RemoteError('session/model-unavailable',
error instanceof Error ? error.message : String(error),
{ provider: selection.provider, model: selection.model })
}
return models.some(model => model.id === selection.model)
}
/**
* Check configured provider API-key references independently of model availability.
* @param ctx - Host registry, settings, and credential services.
* @returns whether any API-key provider has a configured credential.
*/
export async function hasProviderApiKey(ctx: Context): Promise<boolean> {
const settings = ctx.get('settings')
const credentials = ctx.get('credentials')
if (settings === undefined || credentials === undefined) {
throw new RemoteError('session/provider-credentials-unavailable', 'provider credentials are unavailable', {})
}
const namespaces = settings.describe({ redactSecrets: true })
for (const provider of ctx.llm.listConfigurableProviders()) {
if (provider.provider === 'deepseek-account') continue
let profile = namespaces.find(namespace => namespace.ns === provider.settingsNs)?.value
for (const key of provider.settingsPath) {
profile = typeof profile === 'object' && profile !== null ? Reflect.get(profile, key) : undefined
}
if (typeof profile !== 'object' || profile === null) continue
const ref: unknown = Reflect.get(profile, 'apiKeyEnv')
if (typeof ref === 'string' && ref.length > 0
&& (await credentials.describe(credentialRef(ref))).configured) return true
}
return false
}
@@ -68,9 +68,10 @@ export interface ISession {
/**
* Register one local submission echo in `snapshot.pendingSubmissions`,
* synchronously, before the caller serializes and sends the prompt. The
* echo retires when a durable `user/message` event or queue occurrence
* carrying the returned identity arrives, or when the identified prompt
* call fails.
* Chat echoes persist until durable admission; transcript identities also
* wait for the Inbox claim watermark so stale queue rows stay suppressed.
* Queued echoes retire on queue acceptance. Identified failures retire
* submissions that have not already reached durable admission.
* @param input - echo content and the optional settlement callback.
* @returns the minted identity for {@link prompt} plus the pre-prompt abandon path.
*/
@@ -118,7 +119,9 @@ export interface ISession {
*/
rename(title: string): Promise<RemoteResult<{ title: string; seq: SessionSeq }>>
/**
* Extend the history window backwards (older messages pagination).
* Extend history by at least 50 messages and two Turn starts, including a
* partial Turn at the window's beginning. Stop at 500 messages or history
* exhaustion even when those minima cannot be met. Publish one prepend.
* @returns completion; failures land in snapshot.openState/loadingOlder.
*/
loadOlder(): Promise<void>
@@ -127,6 +130,8 @@ export interface ISession {
* turn-jump loader. Repeated calls while a jump is paging lower its shared
* target and return the in-flight completion; `snapshot.loadingOlder` is
* the busy signal for the whole jump.
* Each page uses the same Turn alignment as loadOlder, with a 200-message
* minimum. The 500-message limit applies per page, not to the whole jump.
* Older pages publish together at completion, including successful pages
* before a later failure; live events remain independently visible.
* @param seq - durable event seq the window must reach (a turn's `turn/start` seq).
@@ -125,11 +125,16 @@ export interface ISessions {
* seq (a real event seq the caller already knows; a cut inside an open
* turn is balanced Host-side with synthetic closers, and omission selects
* the latest completed-turn prefix), and whether to increment an
* inherited durable title before resolving.
* inherited durable title before resolving. `onCreated` observes the catalogued child before that optional rename.
* @returns the child session id.
* @throws when the fork fails, or when a requested child-title rename fails after creation.
*/
fork(opts: { sessionId: SessionId; atSeq?: number; increaseTitle?: boolean }): Promise<SessionId>
fork(opts: {
sessionId: SessionId
atSeq?: number
increaseTitle?: boolean
onCreated?: (childId: SessionId) => void
}): Promise<SessionId>
/**
* Borrow an already-retained Agent-scoped Context without extending its lifetime.
* @param id - session id.
@@ -46,7 +46,7 @@ export type PendingSubmissionPlacement = 'transcript' | 'queued' | 'steering'
export interface PendingSubmission {
/** The prompt RPC identity; the durable `user/message` source echoes it as `rpcId`. */
readonly requestId: SessionRequestId
/** Expected surface until the Host reports the admitted queue or durable occurrence. */
/** Surface fixed at submission time; Inbox acceptance does not move a Chat echo into the dock. */
readonly placement: PendingSubmissionPlacement
/** Client wall-clock ms when the submission began. */
readonly time: number
@@ -24,7 +24,12 @@ interface ActiveAttempt {
/** One Web publication decision from the assistant stream fold. */
export type ClientAssistantStreamResult =
| { readonly type: 'publish'; readonly entry: SessionLiveEventEntry }
| {
readonly type: 'publish'
readonly entry: SessionLiveEventEntry
/** Retire the successful attempt's transient rows after publishing its Step end. */
readonly retireAttemptId?: LlmAttemptId
}
| {
readonly type: 'settlement'
readonly attemptId: LlmAttemptId
@@ -38,6 +43,7 @@ export type ClientAssistantStreamResult =
/** Keeps transient Assistant presentation behind one settlement-aware interface. */
export class ClientAssistantStream {
private activeAttempt: ActiveAttempt | undefined
private retainedAttempt: Pick<ActiveAttempt, 'attemptId' | 'turn' | 'step'> | undefined
private readonly pending = new Map<number, SessionAssistantSettlementEntry>()
private publishedSeqs = new Set<number>()
private durableCursor = -1
@@ -56,6 +62,7 @@ export class ClientAssistantStream {
this.pending.clear()
this.transientInGap = 0
this.activeAttempt = undefined
this.retainedAttempt = undefined
const opening = baseline?.activeAttempt
if (opening !== undefined) {
this.activeAttempt = {
@@ -114,13 +121,16 @@ export class ClientAssistantStream {
/**
* Fold one dense transient frame and release its named durable settlement.
* Successful messages retain their transient rows until the owning Step ends;
* interrupted messages, failed attempts, and abandonment retire them immediately.
* @param frame - next Assistant stream frame received by the follow connection.
* @returns a transient, publication, or rebaseline decision, or `undefined` when no entry becomes visible.
*/
acceptFrame(frame: SessionAssistantStreamFrame): ClientAssistantStreamResult {
switch (frame.type) {
case 'start':
if (this.activeAttempt !== undefined || this.pending.size > 0) return { type: 'rebaseline' }
if (this.activeAttempt !== undefined || this.retainedAttempt !== undefined
|| this.pending.size > 0) return { type: 'rebaseline' }
this.pending.clear()
this.activeAttempt = {
attemptId: frame.attemptId,
@@ -176,6 +186,10 @@ export class ClientAssistantStream {
return { type: 'rebaseline' }
}
this.pending.delete(frame.outcome.seq)
if (entry.event.type === 'assistant/message' && entry.event.data.interrupted !== true) {
this.retainedAttempt = { attemptId: attempt.attemptId, turn: attempt.turn, step: attempt.step }
return this.publish(entry)
}
this.publishedSeqs.add(entry.event.seq)
return { type: 'settlement', attemptId: attempt.attemptId, entry }
}
@@ -196,6 +210,12 @@ export class ClientAssistantStream {
private publish(entry: SessionLiveEventEntry): ClientAssistantStreamResult {
this.publishedSeqs.add(entry.event.seq)
const retained = this.retainedAttempt
if (retained !== undefined && entry.event.type === 'step/end'
&& entry.event.data.turn === retained.turn && entry.event.data.step === retained.step) {
this.retainedAttempt = undefined
return { type: 'publish', entry, retireAttemptId: retained.attemptId }
}
return { type: 'publish', entry }
}
}
@@ -117,6 +117,16 @@ export class ProjectionValueStore {
return this.rows.get(key)?.value
}
/**
* Read the accepted Host watermark without subscribing or copying a value.
* @param key - projection key.
* @returns the current sequence, or undefined for absent and cached values.
*/
seqOf(key: string): SessionSeqCursor | undefined {
const row = this.rows.get(key)
return row?.kind === 'sequenced' ? row.seq : undefined
}
/**
* Read every current projection value as one reference-stable snapshot.
* @returns The same frozen value map until a row changes.
@@ -452,6 +452,7 @@ export class ClientSessions implements ISessions {
sessionId: SessionId
atSeq?: number
increaseTitle?: boolean
onCreated?: (childId: SessionId) => void
}): Promise<SessionId> {
const sourceTitle = opts.increaseTitle
? this.list.getSnapshot().byId[opts.sessionId]?.title
@@ -463,6 +464,7 @@ export class ClientSessions implements ISessions {
if (!result.ok) throw new SessionForkError(result.error, opts.sessionId)
this.projectList()
const childId = result.value.sessionId
opts.onCreated?.(childId)
if (sourceTitle !== undefined) {
const renamed = await this.manager.rename(childId, increasedForkTitle(sourceTitle))
if (!renamed.ok) throw new Error(`fork child rename failed: ${renamed.error.code}: ${renamed.error.message}`)
@@ -1,11 +1,12 @@
// Sessions remain resident after creation so their open Remote sources keep running off-screen.
import type { Context } from '@deepseek-ai/cordis'
import type { InboxState } from '@deepseek-ai/dsh-agent/types'
import type { InboxState, InboxTarget } from '@deepseek-ai/dsh-agent/types'
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
import type { AttachmentIdType, FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
import type { MessageId } from '@deepseek-ai/dsh-llm/brand'
import type { UserMessage } from '@deepseek-ai/dsh-llm/types'
import { SessionLogOffset, SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types'
import { SessionEventStream } from '../transport.ts'
import type { SessionJournalChange } from '../transport.ts'
@@ -25,7 +26,7 @@ import type {
} from '../contract/snapshot.ts'
import { MutableSessionEventSource } from '../contract/events.ts'
import type {
SessionEventLikeEntry, SessionLiveEventEntry,
SessionEventLike, SessionEventLikeEntry, SessionLiveEventEntry,
} from '../contract/events.ts'
import { Notifier } from './notifier.ts'
import { isRemoteFailure } from '@deepseek-ai/dsh-api-gateway/client'
@@ -47,12 +48,19 @@ function projectionsBaseline(value: SessionProjectionBaseline): ProjectionsBasel
}
}
/** Messages requested per history page. */
/** Minimum message count for ordinary history windows. */
export const PAGE_MESSAGES = 50
/** Messages requested per page while a turn jump loops backwards (fewer, larger round trips). */
const HISTORY_PAGE_OPTIONS = { maxMessages: 500, turnWindow: { minMessages: PAGE_MESSAGES, minTurns: 2 } }
/** Minimum messages per page while a turn jump loops backwards. */
export const JUMP_PAGE_MESSAGES = 200
const JUMP_PAGE_OPTIONS = {
...HISTORY_PAGE_OPTIONS,
turnWindow: { ...HISTORY_PAGE_OPTIONS.turnWindow, minMessages: JUMP_PAGE_MESSAGES },
}
interface PendingHistory {
beforeSeq: SessionLogOffset
hasMore: boolean
@@ -124,6 +132,16 @@ export class Session implements SessionFace {
/** Per-echo settlement state; `retiring` latches the first observation so a
* Inbox projection and its durable event cannot both retire one echo. */
private readonly submissionSettlements = new Map<SessionRequestId, {
readonly placement: PendingSubmission['placement']
/** Latest received Inbox position; null means removed from that queue. */
receipt?: {
readonly target: InboxTarget
readonly seq: number
readonly index: number | null
readonly attachments: readonly (ImageAttachmentRef | FileAttachmentRef)[]
}
/** Durable admission may precede the Inbox projection acknowledging its claim. */
admitted?: readonly (ImageAttachmentRef | FileAttachmentRef)[]
readonly onRetire?: ((retirement: PendingSubmissionRetirement) => void) | undefined
retiring: boolean
}>()
@@ -209,16 +227,15 @@ export class Session implements SessionFace {
*/
beginSubmission(input: BeginSubmissionInput): SubmissionHandle {
const requestId = randomUUID() as SessionRequestId
const placement = this.running ? input.mode === 'steer' ? 'steering' : 'queued' : 'transcript'
this.pendingSubmissions = [...this.pendingSubmissions, {
requestId,
placement: this.running
? input.mode === 'steer' ? 'steering' : 'queued'
: 'transcript',
placement,
time: Date.now(),
text: input.text,
attachments: input.attachments,
}]
this.submissionSettlements.set(requestId, { onRetire: input.onRetire, retiring: false })
this.submissionSettlements.set(requestId, { placement, onRetire: input.onRetire, retiring: false })
// The blank → engaging edge flips here, ahead of prompt(): the composer
// docks and the echo renders on the click's own frame.
this.promptAttempted = true
@@ -385,7 +402,7 @@ export class Session implements SessionFace {
return promise
}
/** Page up: pull one earlier page with the window's first seq as beforeSeq and prepend. */
/** Prepend one Turn-aligned page: at least 50 messages and two Turn starts, capped at 500 messages. */
async loadOlder(): Promise<void> {
if (this.openState !== 'open' || !this.hasMore || this.loadingOlder) return
const events = this.events
@@ -393,7 +410,10 @@ export class Session implements SessionFace {
this.loadingOlder = true
this.notifier.markDirty()
try {
await events.prepend({ beforeSeq: this.baseSeq, maxMessages: PAGE_MESSAGES })
await events.prepend({
beforeSeq: this.baseSeq,
...HISTORY_PAGE_OPTIONS,
})
} catch (error) {
if (!isRemoteFailure(error)) {
console.error('[session-controller] loadOlder failed:', error)
@@ -437,7 +457,7 @@ export class Session implements SessionFace {
while (pending.hasMore && this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) {
if (generation !== this.openGeneration) return
const before = pending.beforeSeq
await events.prepend({ beforeSeq: before, maxMessages: JUMP_PAGE_MESSAGES })
await events.prepend({ beforeSeq: before, ...JUMP_PAGE_OPTIONS })
// No-progress guard: an empty or dropped page that still claims more
// history must end the loop, not spin it.
if (pending.beforeSeq >= before) return
@@ -579,10 +599,10 @@ export class Session implements SessionFace {
async dispose(): Promise<void> {
this.stopObservingInbox()
// Unsettled echoes retire as failed so their owners can restore or
// release browser resources; echoes already scheduled as observed keep
// that settlement.
for (const requestId of [...this.submissionSettlements.keys()]) {
this.retireFailedSubmission(requestId)
// release browser resources; admitted echoes keep their observed outcome.
for (const [requestId, settlement] of [...this.submissionSettlements]) {
if (settlement.admitted !== undefined) this.scheduleObservedRetirement(requestId, settlement.admitted)
else this.retireFailedSubmission(requestId)
}
this.openGeneration++
const events = this.events
@@ -608,7 +628,7 @@ export class Session implements SessionFace {
})
this.events = events
try {
await events.open({ maxMessages: PAGE_MESSAGES })
await events.open(HISTORY_PAGE_OPTIONS)
if (generation !== this.openGeneration || this.events !== events) return
this.openState = 'open'
} catch (error) {
@@ -665,7 +685,22 @@ export class Session implements SessionFace {
if (visible.some(entry => entry.event.type === 'turn/start')) this.firstPromptPendingTurn = false
if (projections !== undefined) this.projections.seed(projections)
this.eventSource.replace(visible, hasMore)
// A new follow baseline replaces confirmed optimistic inputs with Host-owned rows.
// Receipt-backed inputs are accepted, not failed, even if their history is outside this window.
if (projections !== undefined) {
for (const [requestId, { receipt }] of this.submissionSettlements) {
if (receipt !== undefined && receipt.seq <= projections.asOfSeq) {
this.scheduleObservedRetirement(requestId, receipt.attachments)
}
}
}
for (const entry of visible) this.observeSubmissionEvent(entry.event)
if (projections !== undefined) {
const inbox = projections.values.inbox as InboxState | undefined
for (const target of ['next-turn', 'next-step'] as const) {
this.observeSubmissionInsertions(target, inbox?.[target] ?? [], 0, projections.asOfSeq)
}
}
this.notifier.markDirty()
}
@@ -688,8 +723,10 @@ export class Session implements SessionFace {
this.notifier.markDirty()
return
}
if (result?.type === 'publish' && this.appendLive(result.entry)) {
this.notifier.markDirty()
if (result?.type === 'publish') {
const changed = this.appendLive(result.entry)
if (result.retireAttemptId !== undefined) this.eventSource.settleAssistant(result.retireAttemptId)
if (changed || result.retireAttemptId !== undefined) this.notifier.markDirty()
} else if (result?.type === 'transient') {
this.eventSource.append(result.entry)
this.notifier.markDirty()
@@ -724,36 +761,80 @@ export class Session implements SessionFace {
}
/** Observe durable acceptance even when insertion and claim share one projection notification. */
private observeSubmissionEvent(event: { readonly type: string; readonly data?: unknown }): void {
private observeSubmissionEvent(event: SessionEventLike): void {
if (this.submissionSettlements.size === 0) return
if (event.type === 'agent/inbox/spliced') {
const splice = event.data as { readonly inserted?: unknown } | undefined
if (Array.isArray(splice?.inserted)) {
for (const message of splice.inserted) this.observeSubmissionEvent({ type: 'user/message', data: message })
const { target, start, removedCount = 0, inserted, outcome } = event.data
for (const [requestId, settlement] of this.submissionSettlements) {
const receipt = settlement.receipt
if (receipt?.target !== target || receipt.index === null || receipt.seq >= event.seq) continue
const removed = receipt.index >= start && receipt.index < start + removedCount
if (removed && outcome === 'canceled') this.retireFailedSubmission(requestId)
else settlement.receipt = {
...receipt,
seq: event.seq,
index: removed ? null : receipt.index < start ? receipt.index : receipt.index + inserted.length - removedCount,
}
}
this.observeSubmissionInsertions(target, inserted, start, event.seq)
for (const message of inserted) this.observeSubmissionMessage(message, false)
return
}
if (event.type === 'request/context' || event.type === 'turn/end') {
for (const [requestId, settlement] of this.submissionSettlements) {
if (settlement.admitted === undefined && settlement.receipt?.index === null
&& settlement.receipt.seq < event.seq) this.retireFailedSubmission(requestId)
}
return
}
if (event.type !== 'user/message') return
// Structural read: window entries may be compact history records, so the
// fields are narrowed rather than trusted (same posture as Conversation
// assembly matchers).
const data = event.data as { readonly source?: unknown; readonly content?: unknown } | undefined
const source = data?.source as { readonly kind?: unknown; readonly rpcId?: unknown } | undefined
if (source?.kind !== 'user' || typeof source.rpcId !== 'string') return
this.scheduleObservedRetirement(source.rpcId as SessionRequestId, attachmentRefsIn(data?.content))
if (event.type === 'user/message') this.observeSubmissionMessage(event.data, true)
}
/** Retire local echoes when their accepted messages appear in the durable Inbox projection. */
private observeSubmissionInsertions(target: InboxTarget, messages: readonly UserMessage[], start: number, seq: number): void {
for (const [index, message] of messages.entries()) {
const source = message.source
if (source.kind !== 'user' || !('rpcId' in source)) continue
const settlement = this.submissionSettlements.get(source.rpcId)
if (settlement === undefined || settlement.placement === 'queued'
|| settlement.retiring || (settlement.receipt?.seq ?? -1) > seq) continue
settlement.receipt = { target, seq, index: start + index, attachments: attachmentRefsIn(message.content) }
}
}
private observeSubmissionMessage(message: UserMessage, admitted: boolean): void {
const source = message.source
if (source.kind !== 'user' || !('rpcId' in source)) return
const settlement = this.submissionSettlements.get(source.rpcId)
if (settlement === undefined || settlement.retiring) return
if (!admitted) {
if (settlement.placement === 'queued') this.scheduleObservedRetirement(source.rpcId, attachmentRefsIn(message.content))
return
}
settlement.admitted = attachmentRefsIn(message.content)
this.retireAdmittedSubmission(source.rpcId)
}
/** Retire admitted Chat identities only after stale Inbox rows can no longer reappear. */
private retireAdmittedSubmission(requestId: SessionRequestId): void {
const settlement = this.submissionSettlements.get(requestId)
if (settlement?.admitted === undefined) return
const receipt = settlement.receipt
if (receipt?.index === null
&& (this.projections.seqOf('inbox') ?? -1) < receipt.seq) return
this.scheduleObservedRetirement(requestId, settlement.admitted)
}
/** Inbox acceptance retires queued echoes; its watermark completes admitted Chat handoffs. */
private observeSubmissionInbox(): void {
if (this.submissionSettlements.size === 0) return
const inbox = this.projections.get('inbox') as InboxState | undefined
if (inbox === undefined) return
for (const message of [...inbox['next-turn'], ...inbox['next-step']]) {
const source = message.source
if (source.kind === 'user' && 'rpcId' in source) {
this.scheduleObservedRetirement(source.rpcId, attachmentRefsIn(message.content))
}
const seq = this.projections.seqOf('inbox')
for (const target of ['next-turn', 'next-step'] as const) {
if (seq !== undefined) this.observeSubmissionInsertions(target, inbox[target], 0, seq)
for (const message of inbox[target]) this.observeSubmissionMessage(message, false)
}
for (const requestId of this.submissionSettlements.keys()) this.retireAdmittedSubmission(requestId)
}
/**
@@ -775,7 +856,7 @@ export class Session implements SessionFace {
/** Remove one unsettled echo immediately (prompt rejection, abort, or disposal). */
private retireFailedSubmission(requestId: SessionRequestId): void {
const settlement = this.submissionSettlements.get(requestId)
if (settlement === undefined || settlement.retiring) return
if (settlement === undefined || settlement.retiring || settlement.admitted !== undefined) return
settlement.retiring = true
this.finishSubmission(requestId, { reason: 'failed' })
}
@@ -179,7 +179,7 @@ export class SessionEventStream extends RemoteJournalStream<
for await (const frame of this.remote.session.follow({
address: this.address,
assistantStream: true,
...(request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }),
...this.repairRequest(request),
}, signal)) {
if (frame.type === 'snapshot') {
for (const record of frame.records) assertSessionWireEvent(record.event)
@@ -238,6 +238,9 @@ export class SessionEventStream extends RemoteJournalStream<
protected override repairRequest(
request: ClientSessionPageRequest,
): ClientSessionPageRequest {
return request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }
return {
...(request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }),
...(request.turnWindow === undefined ? {} : { turnWindow: request.turnWindow }),
}
}
}
+13 -18
View File
@@ -1,5 +1,6 @@
/** Session commands whose activation policy is explicit at each Remote method. */
import { modelAvailable } from './catalog.ts'
import { randomUUID } from 'node:crypto'
import type { Context } from '@deepseek-ai/cordis'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -143,14 +144,15 @@ export class SessionCommandController {
}
/**
* Validate and install one Session-local model selection.
* Validate and install one Session-local model selection; save the default in the background.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
* @returns the normalized selection installed for the Session, without waiting for default persistence.
*/
async selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
const agent = await this.resolveAgent(request.sessionId)
return this.agents.serializeImageAdmission(agent, async () => {
try {
await this.requireModel(request)
const resolved = await this.ctx.llm.resolveCallConfig({
provider: request.provider,
model: request.model,
@@ -166,13 +168,11 @@ export class SessionCommandController {
: { reasoningEffort: resolved.reasoningEffort }),
}
this.agents.selectForNextRequest(agent, selected)
try {
await this.ctx.agentDefaultModel.saveSelection(selected)
} catch (error) {
void this.ctx.agentDefaultModel.saveSelection(selected).catch((error: unknown) => {
this.ctx.logger.warn(
`session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`,
)
}
})
return { selected: { ...selected } }
} catch (error) {
if (remoteErrorOf(error) !== undefined) throw error
@@ -328,14 +328,6 @@ export class SessionCommandController {
}
const agent = await this.resolveAgent(request.sessionId)
if (hasPromptRequest(agent, request.requestId)) return { accepted: true }
const selection = this.agents.selectionFor(agent).current
if (!routeServed(this.ctx, selection.provider)) {
throw new RemoteError(
'session/model-unavailable',
`no adapter serves provider "${selection.provider}"; select a model for this session`,
{ provider: selection.provider, model: selection.model },
)
}
const source: MessageSource = {
kind: 'user',
rpcId: request.requestId,
@@ -384,6 +376,13 @@ export class SessionCommandController {
return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit()
}
private async requireModel(selection: Pick<AgentModelSelection, 'provider' | 'model'>): Promise<void> {
if (!await modelAvailable(this.ctx, selection)) {
throw new RemoteError('session/model-unavailable', 'Select an available model before sending a message.',
{ provider: selection.provider, model: selection.model })
}
}
/**
* Read one durable image after proving the Session log references it.
* @param request - Session and attachment identities used for authorization.
@@ -690,7 +689,3 @@ function referencedImage(
}
return undefined
}
function routeServed(ctx: Context, provider: string): boolean {
return ctx.llm.listProviders().some(entry => entry.id === provider)
}
+26 -9
View File
@@ -102,6 +102,7 @@ export class SessionHistoryController {
beforeSeq,
request.maxMessages ?? DEFAULT_MAX_MESSAGES,
throughSeq,
request.turnWindow,
)
const records = pageRecords(page.events)
return {
@@ -117,7 +118,7 @@ export class SessionHistoryController {
* @returns a complete opening snapshot followed by gap-free durable events and opted-in assistant frames.
*/
async *follow(request: SessionFollowRequest, signal: AbortSignal): AsyncIterable<SessionFollowFrame> {
validateFollowRequest(request)
validateHistoryWindow(request)
const { address } = request
const target = addressId(address)
const buffered = new Deque<
@@ -180,7 +181,7 @@ export class SessionHistoryController {
signal.throwIfAborted()
const cursor = source.cursor
snapshotCursor = cursor
const page = paginate(events, undefined, request.maxMessages ?? DEFAULT_MAX_MESSAGES)
const page = paginate(events, undefined, request.maxMessages ?? DEFAULT_MAX_MESSAGES, cursor, request.turnWindow)
const assistantStream = request.assistantStream === true
? this.assistantStreams.get(target)?.snapshot() ?? { revision: 0 }
: undefined
@@ -313,16 +314,23 @@ function validatePageRequest(request: SessionPageRequest): void {
|| Object.is(request.beforeSeq, -0))) {
throw new RemoteError('gateway/bad-request', 'beforeSeq must be a non-negative safe integer', {})
}
validateHistoryWindow(request)
}
function validateHistoryWindow(request: Pick<SessionPageRequest, 'maxMessages' | 'turnWindow'>): void {
if (request.maxMessages !== undefined
&& (!Number.isSafeInteger(request.maxMessages) || request.maxMessages <= 0)) {
throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {})
}
}
function validateFollowRequest(request: SessionFollowRequest): void {
if (request.maxMessages !== undefined
&& (!Number.isSafeInteger(request.maxMessages) || request.maxMessages <= 0)) {
throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {})
const window = request.turnWindow
if (window !== undefined) {
if (!Number.isSafeInteger(window.minMessages) || window.minMessages <= 0
|| window.minMessages > (request.maxMessages ?? DEFAULT_MAX_MESSAGES)) {
throw new RemoteError('gateway/bad-request', 'turnWindow.minMessages must be a positive safe integer no greater than maxMessages', {})
}
if (!Number.isSafeInteger(window.minTurns) || window.minTurns <= 0) {
throw new RemoteError('gateway/bad-request', 'turnWindow.minTurns must be a positive safe integer', {})
}
}
}
@@ -385,13 +393,22 @@ function paginate(
events: readonly SessionEvent[],
beforeSeq: SessionLogOffsetType | undefined,
maxMessages: number,
throughSeq: SessionSeqCursor = events.at(-1)?.seq ?? -1,
throughSeq: SessionSeqCursor,
turnWindow?: SessionPageRequest['turnWindow'],
): { readonly events: SessionEvent[]; readonly hasMore: boolean } {
const end = SessionLogOffset(Math.min(throughSeq + 1, beforeSeq ?? throughSeq + 1))
let count = 0
let turns = 0
let cut = SessionLogOffset(0)
for (let index = end - 1; index >= 0; index--) {
const event = events[index] as SessionEvent
if (turnWindow !== undefined && event.type === 'turn/start') {
turns++
if (count >= turnWindow.minMessages && turns >= turnWindow.minTurns) {
cut = SessionLogOffset(index)
break
}
}
if (!MESSAGE_TYPES.has(event.type) || !isAppendSurfaceEvent(event)) continue
count++
const sources = event.sourceEventSeqs
+27 -4
View File
@@ -6,7 +6,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-fs'
import { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { errorChain } from '@deepseek-ai/dsh-llm'
import { errorChain, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-client-file-upload'
import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativeFileApplication, openNativeAssociatedPath, revealNativePath } from '@deepseek-ai/dsh-native-command'
import type { SessionId } from '@deepseek-ai/dsh-session'
@@ -23,10 +23,11 @@ import { SessionControlController } from './control.ts'
import { SessionHistoryController } from './history.ts'
import { SessionFileReferences } from './file-references.ts'
import { ApiSessionList } from './list.ts'
import { buildModelCatalog } from './catalog.ts'
import { buildModelCatalog, hasProviderApiKey } from './catalog.ts'
import { installModelSelectionProjection } from './model-selection-projection.ts'
import { SessionSkillCatalog } from './skill-catalog.ts'
import { SessionMediaReferences } from './media-references.ts'
import { ArchivedSessionGate } from './archived-session-gate.ts'
import type {
ModelCatalog,
SessionWorkspacePathApplication,
@@ -158,6 +159,10 @@ export class SessionController extends TypertRemoteService {
ctx.plugin(SessionFileReferences)
ctx.plugin(SessionMediaReferences)
ctx.plugin(SessionSkillCatalog)
// An archived Session, or a subagent descendant of one, runs no model step
// until it is restored; what it still runs is stopped by the owners that
// answer the Workspace registry's archive-admission events.
ctx.plugin(ArchivedSessionGate)
ctx.on('session/created', (session) => {
ctx.emit('api-session/added', this.listState.summaryFor(session))
@@ -270,15 +275,33 @@ export class SessionController extends TypertRemoteService {
}
/**
* Select one Session-local model after explicitly resuming the Session.
* Select one Session-local model after explicitly resuming the Session; save the default in the background.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
* @returns the normalized selection installed for the Session, without waiting for default persistence.
*/
@Remote('selectModel')
selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
return this.commands.selectModel(request)
}
/**
* Select the first available account model after login when no provider API key is configured.
* @returns after saving the first available model or retaining the existing default.
*/
@Remote
async initializeDefaultModel(): Promise<void> {
const provider = 'deepseek-account'
if (await hasProviderApiKey(this.ctx)) return
const catalog = await buildModelCatalog(this.ctx)
const model = catalog.groups.find(group => group.id === provider)?.models[0]
if (model === undefined) throw new RemoteError('session/provider-models-unavailable',
`provider "${provider}" has no available models`, { provider })
const selection = { provider, model: model.id,
...model.reasoning?.defaultEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(model.reasoning.defaultEffort) },
}
await this.ctx.agentDefaultModel.saveSelection(selection)
}
/**
* Describe every currently routable model for Host-generation selectors.
* @returns provider-grouped models, the deployment default, and isolated provider failures.
+11 -3
View File
@@ -157,7 +157,7 @@ export interface ModelCatalogFailure {
/** Host-generation model catalog and the default used by unconfigured Sessions. */
export interface ModelCatalog {
readonly default: ModelSelection
/** Provider routes currently able to serve a request, including empty catalogs. */
/** Provider routes with at least one currently available catalog model. */
readonly routableProviders: readonly string[]
readonly groups: readonly ModelProviderGroup[]
readonly failures: readonly ModelCatalogFailure[]
@@ -201,6 +201,8 @@ export const SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS = 240
declare module '@deepseek-ai/dsh-typert-protocol' {
interface RemoteErrorDetailsMap {
'session/provider-credentials-unavailable': Record<string, never>
'session/provider-models-unavailable': { readonly provider: string }
'session/model-unavailable': { readonly provider: string; readonly model: string }
'session/conflict': {
readonly sessionId: SessionId
@@ -472,12 +474,18 @@ export interface SessionPageRequest {
readonly throughSeq: number
readonly beforeSeq?: number
readonly maxMessages?: number
/** Stop at a Turn start after both minima, unless maxMessages or history exhaustion wins. */
readonly turnWindow?: {
/** Minimum append-origin user/assistant messages; must not exceed maxMessages. */
readonly minMessages: number
/** Minimum Turn starts crossed, including the partial Turn at beforeSeq. */
readonly minTurns: number
}
}
/** One live event request for a durable Session address. */
export interface SessionFollowRequest {
export interface SessionFollowRequest extends Pick<SessionPageRequest, 'maxMessages' | 'turnWindow'> {
readonly address: SessionAddress
readonly maxMessages?: number
/** Include process-local assistant presentation frames for the Web client. */
readonly assistantStream?: true
}