Merge master and reconcile translation records

This commit is contained in:
Dudu-0223 committed 2026-10-23 18:19:07 +08:00
commit 00a2e76b87
127 files changed
+4167 -557

No files matched your search

@@ -6,7 +6,7 @@ import { Context } from '@deepseek-ai/cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionId } from '@deepseek-ai/dsh-session'
import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
import type { SessionHeader } from '@deepseek-ai/dsh-session'
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
import type { SessionObservation } from '@deepseek-ai/dsh-session-query'
@@ -15,8 +15,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
ApiSessionAgentController,
ApiSessionCwdConflict,
ApiSessionNotFound,
inspectApiSession,
} from '../src/agent.ts'
import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts'
@@ -83,61 +81,6 @@ describe('ApiSession identity failures', () => {
expect(new ApiSessionCwdConflict(SessionId('wrong-cwd'), '/wanted', '/existing').message)
.toContain('belongs to "/existing"')
})
it('maps absent and cwd-less point observations to not found', async () => {
const ctx = new Context()
roots.push(ctx)
await ctx.plugin(SessionStore)
installSessionReadTestServices(ctx)
await expect(inspectApiSession(ctx, SessionId('missing')))
.rejects.toBeInstanceOf(ApiSessionNotFound)
const inspect = vi.fn(() => Promise.resolve(undefined))
const stat = vi.fn(() => Promise.resolve(undefined))
const disposeMissing = providePersistence(ctx, {
list: () => Promise.resolve([]),
stat,
inspect,
})
await expect(inspectApiSession(ctx, SessionId('missing'))).rejects.toBeInstanceOf(ApiSessionNotFound)
// Absence is decided by the stat preflight; the log itself is never opened.
expect(stat).toHaveBeenCalledOnce()
expect(inspect).not.toHaveBeenCalled()
disposeMissing()
const listed = header('cwd-less-catalog', null)
const disposeListed = providePersistence(ctx, {
list: () => Promise.resolve([listed]),
inspect: () => Promise.resolve({ meta: listed, events: [] }),
})
await expect(inspectApiSession(ctx, listed.id)).rejects.toBeInstanceOf(ApiSessionNotFound)
disposeListed()
const catalog = header('cwd-less-inspect')
const inspected = header('cwd-less-inspect', null)
providePersistence(ctx, {
list: () => Promise.resolve([catalog]),
inspect: () => Promise.resolve({ meta: inspected, events: [] }),
})
await expect(inspectApiSession(ctx, catalog.id)).rejects.toBeInstanceOf(ApiSessionNotFound)
})
it('forwards an explicit inspection signal', async () => {
const ctx = new Context()
roots.push(ctx)
await ctx.plugin(SessionStore)
installSessionReadTestServices(ctx)
const meta = header('signalled-inspection')
const inspect = vi.fn(() => Promise.resolve({ meta, inheritedEventCount: SessionLogOffset(0), events: [] }))
providePersistence(ctx, {
list: () => Promise.resolve([meta]),
inspect,
})
const signal = new AbortController().signal
await expect(inspectApiSession(ctx, meta.id, signal)).resolves.toEqual({ meta, inheritedEventCount: SessionLogOffset(0), events: [] })
expect(inspect).toHaveBeenCalledWith(meta.id, signal)
})
})
describe('ApiSession Agent lookup and recovery', () => {
@@ -342,6 +342,7 @@ function event(type: string, seq: SessionSeq, data: unknown): SessionEvent {
async function persistedController(
events: SessionEvent[],
readImage: (ref: ImageAttachmentRef) => Promise<{ ref: ImageAttachmentRef; data: Uint8Array }>,
workspace: Pick<SessionHeader, 'cwd'> = { cwd: '/workspace' },
): Promise<{ ctx: Context; controller: SessionCommandController; sessionId: SessionId }> {
const ctx = new Context()
await ctx.plugin(SessionStore)
@@ -350,7 +351,7 @@ async function persistedController(
version: SESSION_FORMAT_VERSION,
id: sessionId,
createdAt: 1,
cwd: '/workspace',
...workspace,
isSeeded: false,
}
ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
@@ -563,6 +564,23 @@ describe('Session attachment authorization', () => {
}
})
it('rejects a cold Session without cwd before reading its referenced image', async () => {
const ref = imageRef('missing-cwd')
const readImage = vi.fn(async () => ({ ref, data: new Uint8Array([1]) }))
const fixture = await persistedController(
[event('user/message', SessionSeq(0), { id: 'image', role: 'user', source: { kind: 'user' }, content: [{ type: 'image', attachment: ref }] })],
readImage,
{},
)
try {
await expect(fixture.controller.attachment({ sessionId: fixture.sessionId, attachmentId: ref.attachmentId }))
.rejects.toMatchObject({ code: 'session/not-found', details: { sessionId: fixture.sessionId } })
expect(readImage).not.toHaveBeenCalled()
} finally {
await fixture.ctx.fiber.dispose()
}
})
it('maps a cold observation failure to an internal authorization error', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
@@ -63,13 +63,6 @@ describe('SessionController facade', () => {
ctx.on('api-session/error', failure)
ctx.on('api-session/activity', activity)
await expect(controller.inspect(sessionId)).resolves.toEqual({
meta: header,
inheritedEventCount: SessionLogOffset(0),
events,
})
expect(inspect).toHaveBeenCalledOnce()
const session = ctx.sessions.create(sessionId, { meta: header })
const agent = {
id: sessionId,
@@ -91,12 +84,6 @@ describe('SessionController facade', () => {
await expect(resolveUploadAgent(sessionId)).rejects.toBe(activationError)
await expect(controller.resolveAgent(sessionId)).resolves.toEqual({ agent })
await expect(controller.inspect(sessionId)).resolves.toEqual({
meta: header,
inheritedEventCount: SessionLogOffset(0),
events,
})
expect(inspect).toHaveBeenCalledOnce()
ctx.emit('agent/status', { agent, status: 'running' })
ctx.emit('agent/error', { agent, turn: 1, step: 0, error: new Error('fixture failure') })
session.append('user/message', createUserMessage({
@@ -1,10 +1,10 @@
/**
* Session Controller under non-owner callers: the Session resource kind it
* registers, the Session readers of `session/page` and `session/follow`,
* `session/list`, `session/search`, and `session/control` called through a
* `global` role and filtered per Session through `remoteAccess.allows()`, the caller recorded
* on prompt sources, and `session/projections` admitted per Session through
* the Gateway.
* registers and its default resolver, which supplies the identities of
* `session/page` and `session/follow`, `session/list`, `session/search`, and
* `session/control` called through a `global` role and filtered per Session
* through `remoteAccess.allows()`, the caller recorded on prompt sources, and
* `session/projections` admitted per Session through the Gateway.
*/
import { Context } from '@deepseek-ai/cordis'
@@ -86,8 +86,8 @@ async function harness(): Promise<{
await ctx.plugin(TypertRegistry)
await mountAgentLoopTestDependencies(ctx)
const loop = await mountAgentLoopTestHarness(ctx)
const shared = await loop.create(SHARED)
const hidden = await loop.create(PRIVATE)
const shared = await loop.create(SHARED, {}, { cwd: '/tmp' })
const hidden = await loop.create(PRIVATE, {}, { cwd: '/tmp' })
const controller = await createSessionTestController(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
const as = (principal: Principal, method: string): Context => {
const invocation: RemoteInvocation = {
@@ -107,18 +107,77 @@ function message(text: string) {
}
describe('Session Controller access', () => {
it('owns the Session resource kind and its default sessionId field', async () => {
it('owns the Session resource kind and its default resolver', async () => {
const { ctx } = await harness()
expect(() => ctx.typert.resources.register('session', { field: 'sessionId' })).toThrow(/already registered/)
})
it('reads the Session resource of page and follow requests from the addressed Session', async () => {
const { controller } = await harness()
const { ctx, controller } = await harness()
const resource = ctx.typert.resources.get('session')
if (resource?.resolve === undefined) throw new Error('Session resource resolver is missing')
for (const method of ['page', 'follow']) {
const reader = remoteMethods(controller).find(marker => marker.method === method)?.resources?.['session']
expect(reader?.({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED)
// A subagent address reads the child transcript; whether the parent's access covers it is the policy's rule.
expect(reader?.({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE)
const marker = remoteMethods(controller).find(marker => marker.method === method)
expect(marker).toBeDefined()
expect(marker?.resources?.['session']).toBeUndefined()
}
const resolve = (request: unknown) => resource.resolve({ args: { request }, parameters: [{ name: 'request', wire: 'request' }] })
expect(resolve({ address: { kind: 'session', sessionId: SHARED } })).toBe(SHARED)
expect(resolve({ address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } })).toBe(PRIVATE)
})
it('resolves named Session IDs and first-object requests without treating unrelated strings as identities', async () => {
const { ctx } = await harness()
const resource = ctx.typert.resources.get('session')
if (resource?.resolve === undefined) throw new Error('Session resource resolver is missing')
const resolve = (args: Readonly<Record<string, unknown>>, ...names: string[]) => resource.resolve({
args, parameters: names.map(name => ({ name, wire: name })),
})
expect(resolve({ sessionId: SHARED, zzz: 'other' }, 'sessionId', 'zzz')).toBe(SHARED)
expect(resolve({ options: { sessionId: SHARED }, yyy: 'other' }, 'options', 'yyy')).toBe(SHARED)
expect(resolve({ options: { address: { kind: 'session', sessionId: SHARED } }, xxx: 'other' }, 'options', 'xxx')).toBe(SHARED)
expect(resolve({ options: { address: { kind: 'subagent', parentSessionId: SHARED, childSessionId: PRIVATE } } }, 'options')).toBe(PRIVATE)
expect(resolve({ ns: SHARED, value: 'other' }, 'ns', 'value')).toBeUndefined()
expect(resolve({ ref: SHARED, value: 'other' }, 'ref', 'value')).toBeUndefined()
expect(resolve({ zzz: 'other', sessionId: SHARED }, 'zzz', 'sessionId')).toBe(SHARED)
expect(resolve({ first: {}, later: { sessionId: SHARED } }, 'first', 'later')).toBeUndefined()
expect(resolve({ count: 1, tags: [], empty: null, options: { sessionId: SHARED } }, 'count', 'tags', 'empty', 'options')).toBe(SHARED)
expect(resolve({}, 'sessionId')).toBeUndefined()
expect(resolve({})).toBeUndefined()
expect(resource.resolve({ args: { target: SHARED }, parameters: [{ name: 'sessionId', wire: 'target' }] })).toBe(SHARED)
})
it.each(['page', 'follow'])('authorizes %s by Address and rejects coexisting Session IDs through SRC dispatch', async (method) => {
const { ctx, shared, hidden } = await harness()
shared.inbox.append('next-turn', message('shared history'))
hidden.inbox.append('next-turn', message('private history'))
await ctx.plugin(TypertGatewayService)
guestPolicy(ctx, {
role: { name: 'test:history-reader', resource: 'session', actions: ['session/page', 'session/follow'] },
resource: { kind: 'session', id: SHARED },
})
const abort = new AbortController()
const peer: PeerScope = { id: 'history-access-peer' as PeerId, ctx, principal: GUEST, interactions: 'answer', signal: abort.signal, dispose: async () => {} }
const invoke = async (request: Record<string, unknown>): Promise<unknown> => {
const call = { peer, namespace: 'session', method, args: { request }, signal: abort.signal }
if (method === 'page') return ctx.typertGateway.invoke(call)
const stream = (await ctx.typertGateway.stream(call))[Symbol.asyncIterator]()
try {
return (await stream.next()).value
} finally {
await stream.return?.()
}
}
const request = (sessionId: SessionId) => ({ address: { kind: 'session', sessionId }, throughSeq: 0 })
try {
await expect(invoke(request(SHARED))).resolves.toBeDefined()
await expect(invoke(request(PRIVATE))).rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'no-allow' } })
for (const target of [SHARED, PRIVATE]) {
await expect(invoke({ ...request(target), sessionId: SHARED }))
.rejects.toMatchObject({ code: 'remote-access/denied', details: { reason: 'resource-invalid' } })
}
} finally {
abort.abort()
}
})