Merge remote-tracking branch 'origin/master' into fix/web-prompt-retry
# Conflicts: # packages/api/session-controller/README.i18n.yaml # packages/api/session-controller/src/commands.ts
This commit is contained in:
commit
a186602dc3
727 files changed
+7875
-3727
No files matched your search
@@ -128,7 +128,8 @@ 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. `onCreated` observes the catalogued child before that optional rename.
|
||||
* inherited durable title, skipping numbers Host-listed titles already use,
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@@ -130,12 +130,24 @@ function displayTitleOf(title: string | undefined, cwd: string | undefined, id:
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment a trailing fork number while preserving its half-width or
|
||||
* full-width parentheses; an unnumbered title starts with ` (1)`.
|
||||
* Increment the fork number until the candidate is not taken.
|
||||
* @param title - source session's durable title.
|
||||
* @param taken - durable titles of Host-listed sessions.
|
||||
* @returns the title assigned to the fork child.
|
||||
*/
|
||||
function increasedForkTitle(title: string): string {
|
||||
function increasedForkTitle(title: string, taken: ReadonlySet<string>): string {
|
||||
let next = incrementedTitle(title)
|
||||
while (taken.has(next)) next = incrementedTitle(next)
|
||||
return next
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment a trailing fork number while preserving its half-width or
|
||||
* full-width parentheses; an unnumbered title starts with ` (1)`.
|
||||
* @param title - title to increment.
|
||||
* @returns the title with the next fork number.
|
||||
*/
|
||||
function incrementedTitle(title: string): string {
|
||||
const ascii = /^(.*?)\((\d+)\)$/u.exec(title)
|
||||
if (ascii?.[1] !== undefined && ascii[2] !== undefined) {
|
||||
return `${ascii[1]}(${BigInt(ascii[2]) + 1n})`
|
||||
@@ -455,7 +467,8 @@ export class ClientSessions implements 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, plus permission to start source migration.
|
||||
* inherited durable title, skipping numbers Host-listed titles already use,
|
||||
* before resolving, plus permission to start source migration.
|
||||
* @returns the child session id.
|
||||
* @throws {SessionForkError} with the source id.
|
||||
* @throws {Error} when a requested child-title rename fails after creation.
|
||||
@@ -480,7 +493,9 @@ export class ClientSessions implements ISessions {
|
||||
const childId = result.value.sessionId
|
||||
opts.onCreated?.(childId)
|
||||
if (sourceTitle !== undefined) {
|
||||
const renamed = await this.manager.rename(childId, increasedForkTitle(sourceTitle))
|
||||
const list = this.list.getSnapshot()
|
||||
const taken = new Set(list.ids.flatMap(id => list.byId[id]?.title ?? []))
|
||||
const renamed = await this.manager.rename(childId, increasedForkTitle(sourceTitle, taken))
|
||||
if (!renamed.ok) throw new Error(`fork child rename failed: ${renamed.error.code}: ${renamed.error.message}`)
|
||||
}
|
||||
return childId
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
/** Session commands whose activation policy is explicit at each Remote method. */
|
||||
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import { continuationProjectionDefinition, type ContinuationState } from './continuation.ts'
|
||||
|
||||
import { modelAvailable } from './catalog.ts'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
@@ -59,7 +62,7 @@ type PromptContentCandidate =
|
||||
/**
|
||||
* Whether prompt content carries non-whitespace text or an attachment.
|
||||
* @param content - submitted or edited prompt parts.
|
||||
* @returns false for content the Agent must not receive.
|
||||
* @returns whether any part supplies ordinary prompt content.
|
||||
*/
|
||||
export function hasPromptContent(content: readonly PromptContentCandidate[]): boolean {
|
||||
return content.some(part => part.type !== 'text' || part.text.trim().length > 0)
|
||||
@@ -90,6 +93,13 @@ export class SessionCommandController {
|
||||
requests: Set<SessionRequestId>
|
||||
}>()
|
||||
|
||||
private continuation!: ProjectionHandle<ContinuationState>
|
||||
|
||||
/** Register complete-history empty-prompt eligibility. @returns when command admission is ready. */
|
||||
async initialize(): Promise<void> {
|
||||
this.continuation = await this.ctx.sessionProjections.register(continuationProjectionDefinition)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ctx - Host context carrying Agent, model, attachment, title, and Workspace services.
|
||||
* @param agents - sole owner of create, resume, and Agent composition.
|
||||
@@ -305,12 +315,28 @@ export class SessionCommandController {
|
||||
* Admit one prompt after Agent and attachment validation; the Remote method
|
||||
* has already validated the content and built the durable message source.
|
||||
* @param request - Session identity, prompt content, and delivery mode.
|
||||
* @param source - the correlated user source recorded on the accepted message.
|
||||
* @param source - caller metadata recorded on the accepted ordinary or retry user message.
|
||||
* @returns acknowledgement that the Agent accepted the prompt.
|
||||
*/
|
||||
async prompt(request: SessionPromptRequest, source: MessageSource): Promise<SessionPromptValue> {
|
||||
const agent = await this.resolveAgent(request.sessionId)
|
||||
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
||||
if (request.content.length === 0) {
|
||||
try {
|
||||
return await agent.runMaintenance(() => {
|
||||
const inbox = agent.inbox
|
||||
if (request.mode !== 'queue' || this.continuation.stateOf(agent.session).ending === null
|
||||
|| inbox.nextTurn.length > 0 || inbox.nextStep.some(message => message.source.kind === 'user')) {
|
||||
throw new RemoteError('session/agent-busy', 'generation continuation is unavailable', { reason: 'NO_CONTINUABLE_FAILURE_OR_PENDING_INPUT' })
|
||||
}
|
||||
agent.followup(createUserMessage({ content: [], source }))
|
||||
return Promise.resolve({ accepted: true as const })
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (remoteErrorOf(error) !== undefined) throw error
|
||||
throw new RemoteError('session/agent-busy', 'generation continuation was not accepted', { reason: String(error) })
|
||||
}
|
||||
}
|
||||
const admission = resolvePromptFileReceipts(
|
||||
request.content,
|
||||
receiptId => this.ctx.fileUploads.resolve(agent, receiptId),
|
||||
@@ -378,7 +404,7 @@ export class SessionCommandController {
|
||||
// A copied input is not a new request in the child, even if later reinserted there.
|
||||
if (event.seq < session.inheritedEventCount) continue
|
||||
const source = message.source
|
||||
if (source.kind === 'user' && 'rpcId' in source) receipts.requests.add(source.rpcId)
|
||||
if ((source.kind === 'user' || source.kind === 'retry') && 'rpcId' in source) receipts.requests.add(source.rpcId)
|
||||
}
|
||||
}
|
||||
receipts.offset = session.seq
|
||||
@@ -476,7 +502,7 @@ export class SessionCommandController {
|
||||
case 'remove': {
|
||||
agent.inbox.remove(request.itemId)
|
||||
const source = message.source
|
||||
if (source.kind === 'user' && 'rpcId' in source) {
|
||||
if ((source.kind === 'user' || source.kind === 'retry') && 'rpcId' in source) {
|
||||
this.ctx.fileUploads.retirePrompt(agent, source.rpcId)
|
||||
}
|
||||
break
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/** Constant-size continuation eligibility over the complete durable Session. */
|
||||
import type {} from './types.ts'
|
||||
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
|
||||
import type { SessionSeq } from '@deepseek-ai/dsh-session/types'
|
||||
import { brandNumber } from '@deepseek-ai/dsh-brand'
|
||||
import { z } from 'zod'
|
||||
|
||||
// Explicit manual requests use a fixed product policy, independent of automatic retry configuration.
|
||||
const CONTINUABLE_FAILURES: ReadonlySet<string> = new Set([
|
||||
'RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT', 'EMPTY_RESPONSE', 'STREAM_CLOSED',
|
||||
])
|
||||
|
||||
const endingSchema = z.number().int().nonnegative().transform(brandNumber<SessionSeq>).nullable()
|
||||
const stateSchema = z.object({
|
||||
admitted: z.boolean(),
|
||||
failedAttempt: z.boolean(),
|
||||
ending: endingSchema,
|
||||
})
|
||||
|
||||
/** Recoverable manual-continuation facts over admitted user input and empty retry messages. */
|
||||
export type ContinuationState = z.infer<typeof stateSchema>
|
||||
|
||||
const EMPTY: ContinuationState = { admitted: false, failedAttempt: false, ending: null }
|
||||
|
||||
/** Eligibility requires admitted human work and a failed settlement in the last request step. */
|
||||
export const continuationProjectionDefinition = {
|
||||
key: 'conversationContinuation',
|
||||
stateVersion: 4,
|
||||
stateSchema,
|
||||
init: (): ContinuationState => EMPTY,
|
||||
apply: (state, event) => {
|
||||
switch (event.type) {
|
||||
case 'turn/start':
|
||||
return EMPTY
|
||||
case 'step/start':
|
||||
case 'assistant/message':
|
||||
return state.failedAttempt ? { ...state, failedAttempt: false } : state
|
||||
case 'user/message':
|
||||
return !state.admitted && event.surfaceOp === 'append'
|
||||
&& ((event.data.source.kind === 'user' && event.data.content.length > 0)
|
||||
|| (event.data.source.kind === 'retry' && event.data.content.length === 0))
|
||||
? { ...state, admitted: true } : state
|
||||
case 'assistant/attempt':
|
||||
return state.failedAttempt ? state : { ...state, failedAttempt: true }
|
||||
case 'turn/end': {
|
||||
const ending = event.data.reason.kind === 'error' && CONTINUABLE_FAILURES.has(event.data.reason.error.code)
|
||||
&& state.admitted && state.failedAttempt ? event.seq : null
|
||||
return ending === null ? EMPTY : { ...EMPTY, ending }
|
||||
}
|
||||
default:
|
||||
return state
|
||||
}
|
||||
},
|
||||
wire: {
|
||||
viewSchema: endingSchema,
|
||||
view: (state: ContinuationState) => state.ending,
|
||||
},
|
||||
} satisfies ProjectionDefinition<'conversationContinuation', ContinuationState>
|
||||
@@ -209,7 +209,10 @@ export class SessionController extends TypertRemoteService {
|
||||
this.stateController = new StateController(ctx, this.historyController)
|
||||
this.webController = new WebController(ctx, this.historyController, (observation) => { this.promote(observation) })
|
||||
this.listState = new ApiSessionList(ctx, this.listWorkSliceMs)
|
||||
await this.commands.initialize()
|
||||
ctx.fiber.assertActive()
|
||||
await this.listState.initialize()
|
||||
ctx.fiber.assertActive()
|
||||
ctx.plugin(SessionFileReferences)
|
||||
ctx.plugin(SessionMediaReferences)
|
||||
ctx.plugin(SessionSkillCatalog)
|
||||
@@ -464,7 +467,7 @@ export class SessionController extends TypertRemoteService {
|
||||
@Remote('prompt')
|
||||
async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<SessionPromptValue> {
|
||||
signal.throwIfAborted()
|
||||
if (!hasPromptContent(request.content)) {
|
||||
if (request.content.length > 0 && !hasPromptContent(request.content)) {
|
||||
throw new RemoteError('gateway/bad-request', 'prompt content must include non-whitespace text or an attachment', {})
|
||||
}
|
||||
const clientTimeZone = request.clientTimeZone === undefined
|
||||
@@ -480,7 +483,7 @@ export class SessionController extends TypertRemoteService {
|
||||
// The caller is recorded only when it is not the owner, so owner messages keep their exact source.
|
||||
const principal = principalOf(this.ctx.invocation)
|
||||
const source: MessageSource = {
|
||||
kind: 'user',
|
||||
kind: request.content.length === 0 ? 'retry' : 'user',
|
||||
rpcId: request.requestId,
|
||||
...(clientTimeZone === undefined ? {} : { clientTimeZone }),
|
||||
...(principal === undefined ? {} : { principal }),
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
import type { LlmAttemptId, MessageId } from '@deepseek-ai/dsh-llm/brand'
|
||||
import type { LlmModelBadge, TextBlock } from '@deepseek-ai/dsh-llm'
|
||||
import type { SessionId, SessionSeqCursor } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionId, SessionSeq, SessionSeqCursor } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionProjectionMap, SessionProjectionSummaryExcluded, SessionProjectionSummaryValues } from '@deepseek-ai/dsh-session-projection/types'
|
||||
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
|
||||
@@ -16,6 +16,8 @@ import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
|
||||
|
||||
declare module '@deepseek-ai/dsh-session-projection/types' {
|
||||
interface SessionProjectionMap {
|
||||
/** Eligible latest failed turn/end for an empty prompt, or null. */
|
||||
conversationContinuation: SessionSeq | null
|
||||
/** Persisted facts used to summarize a Session without activating it. */
|
||||
sessionListMetadata: SessionListMetadata
|
||||
/**
|
||||
@@ -320,11 +322,11 @@ export interface SessionForkValue {
|
||||
|
||||
/** Session prompt request. */
|
||||
export interface SessionPromptRequest {
|
||||
/** Client-minted identity persisted on the exact accepted user message. */
|
||||
/** Client-minted identity persisted on the accepted inbox input, including empty continuation. */
|
||||
readonly requestId: SessionRequestId
|
||||
readonly sessionId: SessionId
|
||||
readonly mode: 'queue' | 'steer'
|
||||
/** At least one non-whitespace text part or attachment. */
|
||||
/** Non-whitespace text or attachments; an empty array continues an eligible failed idle Session. */
|
||||
readonly content: readonly PromptContentPart[]
|
||||
readonly clientTimeZone?: string
|
||||
}
|
||||
@@ -396,6 +398,8 @@ declare module '@deepseek-ai/dsh-llm' {
|
||||
* caller other than the owner, so an absent `principal` means the owner.
|
||||
*/
|
||||
'user-rpc': { kind: 'user'; rpcId: SessionRequestId; clientTimeZone?: string; principal?: Principal }
|
||||
/** Empty retry user message with browser prompt correlation and caller metadata. */
|
||||
'retry-rpc': { kind: 'retry'; rpcId: SessionRequestId; clientTimeZone?: string; principal?: Principal }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user