Merge branch 'feat/session-workspace-root' into feat/session-workspace-root-consumers
# Conflicts: # apps/desktop-host/package.json # docs/capability-seams.i18n.yaml # docs/config-catalog.md # docs/config-catalog.zh.md # docs/event-producer-consumer.md # docs/event-producer-consumer.zh.md # docs/subsystems/sandbox.md # docs/subsystems/sandbox.zh.md # packages/api/terminal-controller/README.i18n.yaml # packages/api/terminal-controller/README.md # packages/api/terminal-controller/README.zh.md # packages/api/terminal-controller/src/index.ts # packages/client/tsdown.client.ts # packages/client/ui-open-in-app/src/client/index.ts # packages/client/ui-open-in-app/src/client/session-reveal.tsx # packages/experimental/client-ui-forge/README.i18n.yaml # packages/experimental/client-ui-forge/README.md # packages/experimental/client-ui-forge/README.zh.md # packages/experimental/worktree/src/index.ts # packages/extensions/tool-cordis/src/api-catalog.ts # packages/sandbox/sandbox-local/README.i18n.yaml # packages/sandbox/sandbox-local/README.md # packages/sandbox/sandbox-local/README.zh.md # packages/sandbox/sandbox-local/src/index.ts # packages/sandbox/sandbox-local/tests/local.spec.ts # packages/sandbox/sandbox-policy/README.i18n.yaml # packages/sandbox/sandbox-policy/README.md # packages/sandbox/sandbox-policy/README.zh.md # packages/sandbox/sandbox-policy/src/index.ts # packages/sandbox/sandbox/README.i18n.yaml # packages/sandbox/sandbox/README.md # packages/sandbox/sandbox/README.zh.md # packages/sandbox/sandbox/tests/roots.spec.ts # pnpm-lock.yaml
This commit is contained in:
commit
e7a1c26e04
2656 files changed
+62452
-13838
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'
|
||||
@@ -14,10 +17,10 @@ import type {} from '@deepseek-ai/dsh-client-file-upload'
|
||||
import {
|
||||
ReasoningEffortId, createUserMessage, freezeMessage,
|
||||
} from '@deepseek-ai/dsh-llm'
|
||||
import type { MessageSource } from '@deepseek-ai/dsh-llm'
|
||||
import type { MessageId, MessageSource } from '@deepseek-ai/dsh-llm'
|
||||
import { buildForkSeed } from '@deepseek-ai/dsh-session/fork'
|
||||
import { SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent, SessionHeader, SessionId, UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query'
|
||||
import { SessionTitleInvalidError } from '@deepseek-ai/dsh-session-title'
|
||||
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
||||
@@ -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)
|
||||
@@ -83,6 +86,20 @@ function latestCompletedPrefixBoundary(events: readonly SessionEvent[]): Session
|
||||
|
||||
/** Implements Session business commands delegated by the Session Controller Remote service. */
|
||||
export class SessionCommandController {
|
||||
/** First-insertion facts cached per exact Session; the log remains the recovery source. */
|
||||
private readonly promptReceipts = new WeakMap<Session, {
|
||||
offset: SessionLogOffset
|
||||
messages: Set<MessageId>
|
||||
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.
|
||||
@@ -298,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 `user-rpc` 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 (hasPromptRequest(agent, request.requestId)) return { accepted: true }
|
||||
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),
|
||||
@@ -312,6 +345,7 @@ export class SessionCommandController {
|
||||
const hasImage = admission.content.some(part => part.type === 'image')
|
||||
const admit = async (): Promise<SessionPromptValue> => {
|
||||
try {
|
||||
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
||||
if (hasImage) {
|
||||
const current = agent.model.current()
|
||||
if (current !== undefined) {
|
||||
@@ -326,6 +360,7 @@ export class SessionCommandController {
|
||||
}
|
||||
}
|
||||
const content = await this.ctx.attachments.admitPromptContent(admission.content)
|
||||
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
||||
const message: UserMessage = createUserMessage({ content, source })
|
||||
if (this.ctx.agents.get(agent.id) !== agent) {
|
||||
throw new RemoteError(
|
||||
@@ -339,6 +374,7 @@ export class SessionCommandController {
|
||||
else agent.followup(message)
|
||||
binding.commit()
|
||||
} catch (error) {
|
||||
if (this.hasPromptRequest(agent.session, request.requestId)) return { accepted: true }
|
||||
if (remoteErrorOf(error) !== undefined) throw error
|
||||
if (error instanceof AttachmentError) {
|
||||
throw new RemoteError('session/attachment-invalid', error.message, { reason: error.code })
|
||||
@@ -350,6 +386,32 @@ export class SessionCommandController {
|
||||
return hasImage ? this.agents.serializeImageAdmission(agent, admit) : admit()
|
||||
}
|
||||
|
||||
/** Recover first input acceptance, including claimed or removed messages, from unseen log entries. */
|
||||
private hasPromptRequest(session: Session, requestId: SessionRequestId): boolean {
|
||||
let receipts = this.promptReceipts.get(session)
|
||||
if (receipts === undefined) {
|
||||
receipts = { offset: SessionLogOffset(0), messages: new Set(), requests: new Set() }
|
||||
this.promptReceipts.set(session, receipts)
|
||||
}
|
||||
if (receipts.offset !== session.seq) {
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- Existing prompt retry history read, retained for acceptance recovery.
|
||||
for (const event of session.snapshotEvents(receipts.offset)) {
|
||||
if (event.type !== 'agent/inbox/spliced' && event.type !== 'user/message') continue
|
||||
const messages = event.type === 'agent/inbox/spliced' ? event.data.inserted : [event.data]
|
||||
for (const message of messages) {
|
||||
if (receipts.messages.has(message.id)) continue
|
||||
receipts.messages.add(message.id)
|
||||
// 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' || source.kind === 'retry') && 'rpcId' in source) receipts.requests.add(source.rpcId)
|
||||
}
|
||||
}
|
||||
receipts.offset = session.seq
|
||||
}
|
||||
return receipts.requests.has(requestId)
|
||||
}
|
||||
|
||||
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.',
|
||||
@@ -538,17 +600,3 @@ function resolvePromptFileReceipts(
|
||||
})
|
||||
return { content: resolved, receiptIds: [...receiptIds] }
|
||||
}
|
||||
|
||||
function hasPromptRequest(agent: Agent, requestId: SessionRequestId): boolean {
|
||||
const matches = (message: UserMessage): boolean => {
|
||||
const source = message.source
|
||||
return source.kind === 'user' && 'rpcId' in source && source.rpcId === requestId
|
||||
}
|
||||
if (agent.inbox.nextTurn.some(matches) || agent.inbox.nextStep.some(matches)) return true
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
|
||||
return agent.session.snapshotEvents().some((event) => {
|
||||
if (event.type !== 'user/message') return false
|
||||
const source = event.data.source
|
||||
return source.kind === 'user' && 'rpcId' in source && source.rpcId === requestId
|
||||
})
|
||||
}
|
||||
@@ -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