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

@@ -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 }),
}
}
}