Merge origin/master into worktree/web-multimodal-image-input

# Conflicts:
#	docs/architecture.i18n.yaml
#	docs/architecture.md
#	docs/architecture.zh.md
#	docs/cordis-catalog/events.md
#	docs/cordis-catalog/services.md
#	docs/core-data-structures/llm-streaming.i18n.yaml
#	docs/event-producer-consumer.md
#	docs/module-graph.md
#	examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl
#	packages/client/connection/src/client/fixture.ts
#	packages/client/connection/tests/node-half.spec.ts
#	packages/client/ui-conversation/README.i18n.yaml
#	packages/client/ui-conversation/README.md
#	packages/client/ui-conversation/README.zh.md
#	packages/compact/compact-basic/README.i18n.yaml
#	packages/llm/llm/README.i18n.yaml
#	scripts/test-invariants.ts
This commit is contained in:
creatixchu
2026-07-31 17:39:06 +08:00
400 changed files with 79356 additions and 4154 deletions

View File

@@ -168,6 +168,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
SubagentService: 'subagent.md',
SubagentStartRequest: 'subagent.md',
AssembleContext: 'system-prompt.md',
PromptContext: 'system-prompt.md',
PromptSection: 'system-prompt.md',
SystemPrompt: 'system-prompt.md',
ToolProviderResult: 'system-prompt.md',

View File

@@ -1,11 +1,15 @@
import { describe, expect, it, vi } from 'vitest'
import { Context, Service } from 'cordis'
import { Context, FiberState, Service, ValidationError } from 'cordis'
import Loader from '@cordisjs/plugin-loader'
import z from 'schemastery'
import InvariantService from '@deepseek-ai/dsh-invariants'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import { packageInvariantOwners } from './package-invariants.ts'
import {
TEST_INVARIANT_READY_SERVICE,
testInvariantCompanionPaths,
testInvariantCompanions,
type TestInvariantCompanion,
usesManualInvariantTree,
} from './test-invariants.ts'
@@ -21,6 +25,87 @@ class TestInvariantProbe extends Service {
}
}
function deferred(): { readonly promise: Promise<void>; readonly resolve: () => void } {
let resolve!: () => void
const promise = new Promise<void>((done) => {
resolve = done
})
return { promise, resolve }
}
function requiredConfig() {
return z.object({
requiredValue: z.string().required(),
})
}
function queuedReadinessConfig(
ctx: Context,
onPublished: (dispose: () => void) => void,
) {
return z.transform(z.any(), () => {
queueMicrotask(() => {
onPublished(ctx.provide(TEST_INVARIANT_READY_SERVICE, true))
})
return {}
}, true)
}
function invalidConfigApply(): never {
throw new Error('invalid plugin apply executed')
}
async function rejectionOf(fiber: ReturnType<Context['plugin']>): Promise<unknown> {
return fiber.then(
() => undefined,
(error: unknown) => error,
)
}
function expectRequiredConfigValidation(error: unknown): void {
expect(error).toBeInstanceOf(ValidationError)
expect(error).toHaveProperty('message', expect.stringMatching(/requiredValue/))
}
async function withFakeCompanions(
create: (path: string, index: number) => () => Promise<TestInvariantCompanion>,
run: () => Promise<void>,
): Promise<void> {
const mutable = testInvariantCompanions as Record<string, () => Promise<TestInvariantCompanion>>
const originals = Object.entries(mutable)
for (const [index, [path]] of originals.entries()) {
mutable[path] = create(path, index)
}
try {
await run()
} finally {
for (const [path, load] of originals) {
mutable[path] = load
}
}
}
async function withDelayedFirstCompanion(
run: (control: { readonly started: Promise<void>; readonly release: () => void }) => Promise<void>,
): Promise<void> {
const started = deferred()
const release = deferred()
await withFakeCompanions(
(_path, index) => async () => ({
name: `test-invariant-${index}`,
inject: ['invariants'],
async apply() {
if (index === 0) {
started.resolve()
await release.promise
}
return () => {}
},
}),
() => run({ started: started.promise, release: release.resolve }),
)
}
describe('global test invariant host', () => {
it('uses one exhaustive topology to reserve every package name with enabled checks', async () => {
const ctx = new Context()
@@ -85,4 +170,291 @@ describe('global test invariant host', () => {
expect(usesManualInvariantTree('/repo/packages/examples/agent-spine-demo/tests/agent-core.spec.ts')).toBe(true)
expect(usesManualInvariantTree('/repo/packages/core/session/tests/session.spec.ts')).toBe(false)
})
it('preserves config validation failures without starting the rejected plugin', async () => {
const ctx = new Context()
const apply = vi.fn(invalidConfigApply)
const plugin = {
apply,
Config: requiredConfig(),
}
const fiber = ctx.plugin(plugin, {})
const firstError = await rejectionOf(fiber)
expectRequiredConfigValidation(firstError)
await ctx.plugin(TestInvariantProbe)
const secondError = await rejectionOf(fiber)
expect(secondError).toBe(firstError)
expect(fiber.state).toBe(FiberState.DISPOSED)
expect(apply).not.toHaveBeenCalled()
})
it('disposes invalid config when readiness refresh wins the rejection-handler race', async () => {
await withDelayedFirstCompanion(
async ({ started, release }) => {
const ctx = new Context()
const apply = vi.fn(invalidConfigApply)
let disposeQueuedReadiness: (() => void) | undefined
const plugin = {
apply,
Config: z.intersect([
queuedReadinessConfig(ctx, (dispose) => {
disposeQueuedReadiness = dispose
}),
requiredConfig(),
]),
}
const fiber = ctx.plugin(plugin, {})
const firstError = await rejectionOf(fiber)
expectRequiredConfigValidation(firstError)
expect(fiber.state).toBe(FiberState.DISPOSED)
expect(apply).not.toHaveBeenCalled()
await started
if (disposeQueuedReadiness === undefined) throw new Error('queued readiness was not published')
disposeQueuedReadiness()
release()
await ctx.plugin(TestInvariantProbe)
const secondError = await rejectionOf(fiber)
expect(secondError).toBe(firstError)
expect(fiber.state).toBe(FiberState.DISPOSED)
expect(apply).not.toHaveBeenCalled()
},
)
})
it('retains a valid plugin failure when readiness wins the initial-probe race', async () => {
await withDelayedFirstCompanion(
async ({ started, release }) => {
const ctx = new Context()
const failure = new Error('valid plugin apply failed')
const applied = deferred()
const apply = vi.fn(function validConfigApply() {
applied.resolve()
throw failure
})
let disposeQueuedReadiness: (() => void) | undefined
const plugin = {
apply,
Config: queuedReadinessConfig(ctx, (dispose) => {
disposeQueuedReadiness = dispose
}),
}
const fiber = ctx.plugin(plugin, {})
const returnedError = rejectionOf(fiber)
try {
await Promise.all([started, applied.promise])
expect(fiber.state).toBe(FiberState.FAILED)
expect(apply).toHaveBeenCalledOnce()
expect(ctx.registry.has(plugin)).toBe(true)
expect(ctx.registry.get(plugin)?.fibers).toHaveLength(1)
if (disposeQueuedReadiness === undefined) throw new Error('queued readiness was not published')
Reflect.deleteProperty(fiber.inject, TEST_INVARIANT_READY_SERVICE)
disposeQueuedReadiness()
release()
expect(await returnedError).toBe(failure)
expect(fiber.state).toBe(FiberState.FAILED)
expect(apply).toHaveBeenCalledOnce()
expect(ctx.registry.has(plugin)).toBe(true)
expect(ctx.registry.get(plugin)?.fibers).toHaveLength(1)
} finally {
Reflect.deleteProperty(fiber.inject, TEST_INVARIANT_READY_SERVICE)
disposeQueuedReadiness?.()
release()
}
},
)
})
it('holds a root plugin until every lazy companion is active, then permits nested startup', async () => {
const delayedStarted = deferred()
const releaseDelayed = deferred()
const order: string[] = []
let delayedCompanion: TestInvariantCompanion | undefined
const companionNestedApply = vi.fn(function companionNestedApply() {})
await withFakeCompanions(
(path, index) => async () => {
const companion: TestInvariantCompanion = {
name: `test-invariant-${index}`,
inject: ['invariants'],
async apply(companionCtx) {
order.push(`companion-start:${path}`)
if (index === 0) {
delayedStarted.resolve()
await releaseDelayed.promise
}
if (index === 1) await companionCtx.plugin(companionNestedApply)
order.push(`companion-active:${path}`)
return () => {}
},
}
if (index === 0) delayedCompanion = companion
return companion
},
async () => {
const ctx = new Context()
ctx.provide('testInvariantTargetDependency', true)
let nestedFiber: ReturnType<Context['plugin']> | undefined
const nestedApply = vi.fn(function nestedApply() {
order.push('nested')
})
const targetApply = Object.assign(vi.fn(function targetApply(targetCtx: Context) {
order.push('target')
nestedFiber = targetCtx.plugin(nestedApply)
}), {
inject: ['testInvariantTargetDependency'],
})
const targetFiber = ctx.plugin(targetApply)
expect(ctx.registry.get(targetApply)?.callback).toBe(targetApply)
expect(targetFiber.inject).toEqual({
testInvariantTargetDependency: null,
[TEST_INVARIANT_READY_SERVICE]: null,
})
await delayedStarted.promise
await Promise.resolve()
await Promise.resolve()
expect(targetApply).not.toHaveBeenCalled()
releaseDelayed.resolve()
await targetFiber
if (nestedFiber === undefined) throw new Error('target did not register its nested plugin')
await nestedFiber
expect(targetFiber.state).toBe(FiberState.ACTIVE)
expect(targetApply).toHaveBeenCalledOnce()
expect(nestedApply).toHaveBeenCalledOnce()
expect(companionNestedApply).toHaveBeenCalledOnce()
const targetIndex = order.indexOf('target')
expect(targetIndex).toBeGreaterThan(-1)
expect(order.slice(0, targetIndex)).toHaveLength(Object.keys(testInvariantCompanions).length * 2)
expect(order.at(-1)).toBe('nested')
if (delayedCompanion === undefined) throw new Error('delayed companion did not load')
await ctx.plugin(InvariantService, { enabled: true })
await ctx.plugin(delayedCompanion)
expect(ctx.registry.get(InvariantService)?.fibers).toHaveLength(1)
expect(ctx.registry.get(delayedCompanion)?.fibers).toHaveLength(1)
},
)
})
it('holds plugins registered on a root-derived context until companion readiness', async () => {
await withDelayedFirstCompanion(
async ({ started, release }) => {
const ctx = new Context()
const rootApply = vi.fn(function rootApply() {})
const derivedApply = vi.fn(function derivedApply() {})
const derived = ctx.extend()
.isolate('testInvariantDerived')
.intercept('testInvariantDerived', {})
const rootFiber = ctx.plugin(rootApply)
const derivedFiber = derived.plugin(derivedApply)
await started
await Promise.resolve()
await Promise.resolve()
expect(rootApply).not.toHaveBeenCalled()
expect(derivedApply).not.toHaveBeenCalled()
expect(derivedFiber.inject).toEqual({
[TEST_INVARIANT_READY_SERVICE]: null,
})
release()
await Promise.all([rootFiber, derivedFiber])
expect(rootFiber.state).toBe(FiberState.ACTIVE)
expect(derivedFiber.state).toBe(FiberState.ACTIVE)
expect(rootApply).toHaveBeenCalledOnce()
expect(derivedApply).toHaveBeenCalledOnce()
},
)
})
it('holds a child registered externally on a pending target context', async () => {
await withDelayedFirstCompanion(
async ({ started, release }) => {
const ctx = new Context()
const targetApply = vi.fn(function targetApply() {})
const childApply = vi.fn(function childApply() {})
const targetFiber = ctx.plugin(targetApply)
const childFiber = targetFiber.ctx.plugin(childApply)
await started
await Promise.resolve()
await Promise.resolve()
expect(targetFiber.state).toBe(FiberState.PENDING)
expect(childFiber.state).toBe(FiberState.PENDING)
expect(targetApply).not.toHaveBeenCalled()
expect(childApply).not.toHaveBeenCalled()
expect(childFiber.inject).toEqual({
[TEST_INVARIANT_READY_SERVICE]: null,
})
release()
await Promise.all([targetFiber, childFiber])
expect(targetFiber.state).toBe(FiberState.ACTIVE)
expect(childFiber.state).toBe(FiberState.ACTIVE)
expect(targetApply).toHaveBeenCalledOnce()
expect(childApply).toHaveBeenCalledOnce()
},
)
})
it.each(['load', 'startup'] as const)(
'rejects a target when a lazy companion fails during %s without starting the target',
async (phase) => {
const failure = new Error(`test invariant companion ${phase} failed`)
await withFakeCompanions(
(_path, index) => phase === 'load' && index === 0
? async () => { throw failure }
: async () => ({
name: `test-invariant-${index}`,
inject: ['invariants'],
async apply() {
if (phase === 'startup' && index === 0) throw failure
return () => {}
},
}),
async () => {
const ctx = new Context()
const targetApply = vi.fn(function targetApply() {})
const targetFiber = ctx.plugin(targetApply)
await expect(targetFiber).rejects.toBe(failure)
expect(targetApply).not.toHaveBeenCalled()
expect(targetFiber.state).toBe(FiberState.PENDING)
await expect(targetFiber.dispose()).resolves.toBeUndefined()
expect(targetFiber.state).toBe(FiberState.DISPOSED)
},
)
},
)
it('disposes a pending target without waiting for companion readiness', async () => {
await withDelayedFirstCompanion(
async ({ started, release }) => {
const ctx = new Context()
const targetApply = vi.fn(function targetApply() {})
const targetFiber = ctx.plugin(targetApply)
await started
await expect(targetFiber.dispose()).resolves.toBeUndefined()
expect(targetFiber.state).toBe(FiberState.DISPOSED)
expect(targetApply).not.toHaveBeenCalled()
release()
await targetFiber
expect(targetApply).not.toHaveBeenCalled()
},
)
})
})

View File

@@ -6,7 +6,7 @@
*/
import { expect } from 'vitest'
import { RegistryService } from 'cordis'
import { FiberState, Inject, RegistryService } from 'cordis'
import type { Context, Plugin } from 'cordis'
import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
import type {
@@ -32,6 +32,9 @@ export interface TestInvariantCompanion {
apply(ctx: Context): Promise<() => void>
}
/** Private service dependency that holds ordinary root plugins until invariant startup completes. */
export const TEST_INVARIANT_READY_SERVICE = 'testInvariantReady'
/**
* Every package companion as a lazy loader keyed by glob path. Ordinary tests
* load only their owner's module; the exhaustive topology test loads and
@@ -50,10 +53,12 @@ const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
interface InvariantHost {
readonly byCallback: ReadonlyMap<unknown, PluginFiber>
readonly barrierOwners: WeakSet<Context['fiber']>
readonly ready: Promise<void>
}
type PluginFiber = ReturnType<RegistryService['plugin']>
type PluginCallback = Plugin.Function | Plugin.Constructor
const hosts = new WeakMap<Context, InvariantHost>()
// oxlint-disable-next-line typescript/unbound-method -- every call below supplies its RegistryService receiver explicitly.
@@ -68,14 +73,28 @@ RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, ge
const callback = this.resolve(plugin)
const existing = callback === undefined ? undefined : host.byCallback.get(callback)
if (existing !== undefined) {
return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
return hasBarrierOwner(host, this.ctx) ? existing : joinInvariantStartup(existing, host.ready)
}
const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
// A root-level await is the test's composition boundary. Nested plugin
// fibers must not await their own companion parent through the global host.
if (this.ctx !== root) return fiber
return joinInvariantStartup(fiber, host.ready)
// Causal descendants of a gated target have already crossed the barrier.
// Host service and companion descendants also bypass it so their own startup
// cannot depend on the readiness they are responsible for providing.
if (hasBarrierOwner(host, this.ctx)) {
return originalPlugin.call(this, plugin, config, getOuterStack)
}
if (callback === undefined) {
return originalPlugin.call(this, plugin, config, getOuterStack)
}
const fiber = originalPlugin.call(
this,
withInvariantReadiness(plugin, callback as PluginCallback),
config,
getOuterStack,
)
const initiallyPending = fiber.ctx.fiber.state === FiberState.PENDING
host.barrierOwners.add(fiber.ctx.fiber)
return joinInvariantStartup(fiber, host.ready, initiallyPending)
}
/**
@@ -138,11 +157,13 @@ export function testInvariantCompanionPaths(testPath: string): string[] {
function startInvariantHost(root: Context): InvariantHost {
const byCallback = new Map<unknown, PluginFiber>()
const barrierOwners = new WeakSet<Context['fiber']>()
const mount = (plugin: Plugin, config?: unknown): PluginFiber => {
const fiber = originalPlugin.call(root.registry, plugin, config)
const callback = root.registry.resolve(plugin)
if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
byCallback.set(callback, fiber)
barrierOwners.add(fiber.ctx.fiber)
return fiber
}
@@ -156,11 +177,11 @@ function startInvariantHost(root: Context): InvariantHost {
const serviceFiber = mount(InvariantService, { enabled: true })
const testPath = expect.getState().testPath ?? ''
const companionPaths = testInvariantCompanionPaths(testPath)
const ready = serviceFiber.await().then(async () => {
const ready = requireActive(serviceFiber, 'invariant service').then(async () => {
const attachmentFiber = companionPaths.includes(ATTACHMENT_COMPANION)
? mount(TestAttachmentStore)
: undefined
const companionFibers = await Promise.all(companionPaths.map(async (path) => {
const companions = await Promise.all(companionPaths.map(async (path) => {
const load = testInvariantCompanions[path]
if (load === undefined) {
throw new Error(`test invariants: selected companion vanished at ${path}`)
@@ -169,23 +190,80 @@ function startInvariantHost(root: Context): InvariantHost {
if (!companion.inject.includes('invariants')) {
throw new Error(`test invariants: ${path} must inject the invariant service`)
}
return mount(companion)
return { companion, path }
}))
const companionFibers = companions.map(({ companion, path }) => ({
fiber: mount(companion),
path,
}))
await Promise.all([
...(attachmentFiber === undefined ? [] : [attachmentFiber.await()]),
...companionFibers.map(fiber => fiber.await()),
...(attachmentFiber === undefined
? []
: [requireActive(attachmentFiber, 'test attachment store')]),
...companionFibers.map(({ fiber, path }) => requireActive(fiber, path)),
])
root.provide(TEST_INVARIANT_READY_SERVICE, true)
})
const host = { byCallback, ready }
const host = { byCallback, barrierOwners, ready }
hosts.set(root, host)
return host
}
function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
const readiness = fiber.await().then(async (loaded) => {
await invariantReady
return loaded
})
function hasBarrierOwner(host: InvariantHost, ctx: Context): boolean {
let fiber = ctx.fiber
while (true) {
if (
host.barrierOwners.has(fiber)
&& (fiber.state === FiberState.LOADING || fiber.state === FiberState.ACTIVE)
) {
return true
}
const parent = fiber.parent.fiber
if (parent === fiber) return false
fiber = parent
}
}
async function requireActive(fiber: PluginFiber, label: string): Promise<void> {
await fiber.await()
if (fiber.state !== FiberState.ACTIVE) {
throw new Error(`test invariants: ${label} settled without becoming active`)
}
}
function withInvariantReadiness(plugin: Plugin, callback: PluginCallback): Plugin.Object {
return {
apply: callback as Plugin.Function,
inject: {
...Inject.resolve(plugin.inject),
[TEST_INVARIANT_READY_SERVICE]: null,
},
...(plugin.name === undefined ? {} : { name: plugin.name }),
...(plugin.Config === undefined ? {} : { Config: plugin.Config }),
...(plugin.provide === undefined ? {} : { provide: plugin.provide }),
...(plugin.intercept === undefined ? {} : { intercept: plugin.intercept }),
}
}
function joinInvariantStartup(
fiber: PluginFiber,
invariantReady: Promise<void>,
disposeInitialFailure = false,
): PluginFiber {
// RegistryService returns a thenable wrapper whose context still points to
// the raw Fiber. Calling inherited await() on the wrapper would return and
// assimilate that thenable, accidentally following later plugin startup.
const rawFiber = fiber.ctx.fiber
const initialized = disposeInitialFailure
? rawFiber.await().catch(async (error: unknown) => {
// Config validation is the only failure recorded while a gated fiber
// is initially PENDING. Dispose it even if queued readiness publication
// changes its state before this rejection handler runs.
await rawFiber.dispose()
throw error
})
: Promise.resolve()
const readiness = initialized.then(() => invariantReady).then(() => rawFiber.await())
const joined = Object.create(fiber) as PluginFiber
joined.then = readiness.then.bind(readiness)
return joined

View File

@@ -271,6 +271,11 @@
"symbol": "AssembleContext",
"source": "packages/core/system-prompt/src/index.ts"
},
{
"doc": "docs/core-data-structures/system-prompt.md",
"symbol": "PromptContext",
"source": "packages/core/system-prompt/src/index.ts"
},
{
"doc": "docs/core-data-structures/system-prompt.md",
"symbol": "PromptSection",
@@ -348,6 +353,11 @@
"symbol": "EpochHeader",
"source": "packages/core/session/src/types.ts"
},
{
"doc": "docs/core-data-structures/session.md",
"symbol": "RequestContext",
"source": "packages/core/session/src/types.ts"
},
{
"doc": "docs/core-data-structures/session.md",
"symbol": "TodoItem",

View File

@@ -79,7 +79,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/examples/agent-spine-demo': { kind: 'indirect', reason: 'The bundle only mounts model-facing child plugins.' },
'packages/fs/fs': { kind: 'indirect', reason: 'The service interface delegates model rendering to dsh-tool-fs.' },
'packages/fs/fs-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
'packages/fs/fs-sandbox': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' },
'packages/host/apiproxy': { kind: 'none', reason: 'The wire contract and fetch carriers move already-composed messages and register no model surface.' },
'packages/host/directory-picker': { kind: 'none', reason: 'The GUI-host picking seam registers no model surface.' },
@@ -94,7 +93,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/subprocess/subprocess': { kind: 'indirect', reason: 'The seam delegates all model rendering to consumer seams such as the bash executor family.' },
'packages/subprocess/subprocess-local': { kind: 'indirect', reason: 'The spawn backend delegates model rendering to consumer seams such as the bash executor family.' },
'packages/sandbox/sandbox-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-bash-sandbox and dsh-tool-bash.' },
'packages/sandbox/sandbox-policy': { kind: 'indirect', reason: 'The policy service holds the mode dsh-tool-bash and dsh-tool-fs render in their denial markers.' },
'packages/sdk/create-sdk': { kind: 'indirect', reason: 'The initializer only writes project files; selected runtime plugins provide the generated project model surface.' },
'packages/sdk/helper': { kind: 'none', reason: 'The project domain edits files and registers no live agent or model surface.' },
'packages/sdk/scripts': { kind: 'indirect', reason: 'The launcher delegates model context to the loaded project plugin tree.' },