Merge remote-tracking branch 'origin/master' into feat/mcp-manager-core

# Conflicts:
#	docs/event-producer-consumer.i18n.yaml
#	docs/event-producer-consumer.md
#	docs/event-producer-consumer.zh.md
This commit is contained in:
Yichen Jiang committed 2026-09-04 14:36:39 +08:00
commit 5428df154f
1001 files changed
+30415 -11809

No files matched your search

@@ -2,6 +2,7 @@
import { describe, expect, it } from 'vitest'
import {
checkDshFamilyVersion,
checkExperimentalDependencyIsolation,
checkExperimentalManifest,
expectedDshPackageFiles,
@@ -76,6 +77,38 @@ describe('experimental workspace constraints', () => {
})
})
describe('dsh family version coherence', () => {
it('rejects a package carrying a stale shared version', () => {
expect(checkDshFamilyVersion(
{ name: '@deepseek-ai/dsh-http-proxy', version: '0.1.2-alpha.5' },
'0.1.2-rc.1',
)).toBe('@deepseek-ai/dsh-http-proxy: package.json version must match root version 0.1.2-rc.1')
})
it('rejects the root-named CLI app on a stale shared version', () => {
expect(checkDshFamilyVersion(
{ name: '@deepseek-ai/dsh', version: '0.1.2-alpha.5' },
'0.1.2-rc.1',
)).toBe('@deepseek-ai/dsh: package.json version must match root version 0.1.2-rc.1')
})
it('accepts a manifest carrying the shared version', () => {
expect(checkDshFamilyVersion(
{ name: '@deepseek-ai/dsh-http-proxy', version: '0.1.2-rc.1' },
'0.1.2-rc.1',
)).toBeUndefined()
})
it('leaves other sequences to their own version lines', () => {
expect(checkDshFamilyVersion({ name: '@deepseek-ai/cordis', version: '4.0.1' }, '0.1.2-rc.1')).toBeUndefined()
expect(checkDshFamilyVersion(
{ name: '@deepseek-ai/node-addon-landlock-run', version: '0.1.1' },
'0.1.2-rc.1',
)).toBeUndefined()
expect(checkDshFamilyVersion({ version: '0.1.2-alpha.5' }, '0.1.2-rc.1')).toBeUndefined()
})
})
describe('package payload constraints', () => {
it('includes a declared profile patch without a package-name allowlist', () => {
expect(expectedDshPackageFiles({
+24 -3
View File
@@ -262,6 +262,28 @@ export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest):
return errors
}
/**
* Require a dsh-family manifest to carry the workspace version.
*
* The dsh release sequence publishes packages/ and apps/ members and every
* private dsh package on one shared version, written by `release:dsh` and
* shared with the workspace root. This name test is that boundary: it covers
* the family wherever the manifest lives, so apps/ members cannot drift with
* only the release lane noticing.
* @param manifest - the workspace package manifest.
* @param expected - the version every dsh-family manifest must carry (the root's).
* @returns one violation naming the manifest and the expected version, or
* undefined when the manifest is compliant or not in the family.
*/
export function checkDshFamilyVersion(manifest: PackageManifest, expected: string | undefined): string | undefined {
const name = manifest.name
if (name !== '@deepseek-ai/dsh' && name?.startsWith('@deepseek-ai/dsh-') !== true) return undefined
if (manifest.version !== expected) {
return `${name}: package.json version must match root version ${expected ?? '(missing)'}`
}
return undefined
}
/**
* Check one workspace manifest against publication and dsh-package policy.
* @param workspace - package directory and parsed manifest.
@@ -270,6 +292,8 @@ export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest):
export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): string[] {
const errors = checkExperimentalManifest({ dir, manifest })
const label = manifest.name ?? dir
const familyVersionError = checkDshFamilyVersion(manifest, repositoryVersion)
if (familyVersionError !== undefined) errors.push(familyVersionError)
const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/')
const isPublicLandlockPackage = isLandlockPackageDir
&& manifest.name !== undefined
@@ -354,9 +378,6 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st
if (peer && dev && peer !== dev) {
errors.push(`${label}: @deepseek-ai/cordis peer (${peer}) and dev (${dev}) ranges must match`)
}
if (manifest.version !== repositoryVersion) {
errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
}
if (manifest.type !== 'module') {
errors.push(`${label}: package.json must set "type": "module"`)
}
+10 -3
View File
@@ -1,4 +1,4 @@
import { access, mkdir, mkdtemp, readFile, symlink, writeFile } from 'node:fs/promises'
import { access, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -22,7 +22,12 @@ import {
const passed: CoverageCommandResult = { exitCode: 0, signalCode: null }
afterEach(() => vi.restoreAllMocks())
/** Every temporary root created by this file, removed after each test. */
const roots: string[] = []
afterEach(async () => {
vi.restoreAllMocks()
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
})
async function writeBlob(command: CoverageCommand): Promise<void> {
if (command.blobPath === undefined) return
@@ -31,7 +36,9 @@ async function writeBlob(command: CoverageCommand): Promise<void> {
}
async function temporaryRoot(): Promise<string> {
return await mkdtemp(join(tmpdir(), 'dsh-coverage-partitions-'))
const root = await mkdtemp(join(tmpdir(), 'dsh-coverage-partitions-'))
roots.push(root)
return root
}
/** Write a Vitest results cache under a temporary root. */
+3
View File
@@ -63,6 +63,9 @@ const PACKAGE_LIBRARIES: Readonly<Record<string, string>> = {
'packages/sandbox/sandbox-windows-acl': 'Windows ACL sandbox library consumed by sandbox-local.',
'packages/sdk/client': 'Client-process library; the spawned runtime owns plugin behavior.',
'packages/sdk/protocol': 'Wire-protocol library with type declarations only.',
'packages/session/session-format': 'Pure Session format planning, codec dispatch, and lossless JSON library.',
'packages/session/session-format-catalog': 'Generated build-static Session format inventory with no plugin registration.',
'packages/session/session-format-v0-to-v1': 'Pure released-v0 codec and adjacent migration library.',
'packages/session/session-telemetry': 'Telemetry Service Definition and capture library; providers mount the backend.',
'packages/session/session-title-llm': 'Shared LLM title-provider registration and request policy.',
'packages/subagent/subagent-in-process-driver': 'Shared one-shot child-agent driver used by provider plugins.',
+1
View File
@@ -248,6 +248,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
SubagentModelSelectionSettings: 'subagent.md',
AgentOptions: 'core.md',
AgentStatus: 'core.md',
AssistantStreamFrame: 'core.md',
ContentBlock: 'llm-streaming.md',
CreateAgentOptions: 'core.md',
GenerateOptions: 'llm-streaming.md',
+5 -3
View File
@@ -1333,14 +1333,16 @@ function renderLifecycle(): string {
` Driver->>Prompt: ${mermaidCode('system-prompt/assemble')} waterfall`,
` Driver->>LLM: ${mermaidCode('agent/request')} waterfall, then ${mermaidCode('llm/stream')} waterfall`,
' LLM-->>Driver: StreamChunk*',
` Driver->>Session: ${mermaidCode('assistant/chunk')}*`,
` Session-->>SDK: ${mermaidCode('session/event')} ${mermaidCode('assistant/chunk')}*`,
` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} chunk*`,
' alt final adapter or terminal in-band request failure',
` Driver->>Session: ${mermaidCode('assistant/attempt')}`,
` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`,
` Driver->>Session: ${mermaidCode('step/end')}`,
` Driver->>Hooks: ${mermaidCode('agent/request-error')} waterfall`,
' Hooks-->>Driver: return retry action or preserve the original error',
' else model request succeeded',
` Driver->>Session: ${mermaidCode('assistant/message')}`,
` Driver-->>SDK: ${mermaidCode('agent/assistant-stream')} committed end`,
' Driver->>Tools: classify pending call by executionMode',
' loop barriers and bounded rolling pool, reclassify before start',
' opt call starts',
@@ -1369,7 +1371,7 @@ function renderLifecycle(): string {
` Driver-->>SDK: ${mermaidCode('agent/status')} idle`,
'```',
'',
'The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes. Empty content stays out of derived history, while the durable event keeps usage and `sourceEventSeqs` listing the exact `assistant/chunk` events, including an explicit empty list.',
'The `assistant/message` event records every successful provider call, including content-less and `max-tokens` finishes, and embeds the exact compact timed stream. Empty content stays out of derived history. A failed, retried, cancelled, or stream-error attempt that reaches settlement without a surface message records its stream as `assistant/attempt`. Live `agent/assistant-stream` chunk frames are transient; replay reads either durable settlement, and a hard process loss before settlement leaves no durable attempt stream.',
'',
'`dsh-compaction-basic` uses `agent/pre-step` for pressure before request derivation and `agent/request-error` only for canonical context overflow. Once either trigger qualifies, optional tool-result pruning runs before summary selection. Recovery works between the closed failed step and failed turn close, and opens a fresh retry turn only when pruning or summarization advances the surface replacement generation; otherwise the original request error remains authoritative.',
'',
+1 -1
View File
@@ -368,7 +368,7 @@ export function render(events: AnnotatedLogEventEntry[], envelopeTypes: EventEnv
'',
'This file is GENERATED from source (`scripts/gen-persistence-catalog.ts`) and verified fresh by `pnpm run verify-persistence-catalog` (part of `doc-sync`) — do not edit it by hand. Declaration blocks retain the source declaration and nested property JSDoc, removing only the indentation imposed by a containing interface/module, and use a `ts persistence-catalog` fence (skipped by doc-typecheck because declarations reference types from their owning modules). Type names in a payload link to the page that documents them. See [the persistence-log-catalog Agent Note](../.agents/notes/archived/process/2026-07-04-persistence-log-catalog.md).',
'',
'The envelope declarations below compose each event\'s `type`, monotonic `seq`, epoch-ms `time`, `data`, the optional `ignorable` unknown-type skip marker, and the conditional `surfaceOp`/`sourceEventSeqs` fields. **surface** marks a `SurfaceEventType` member: it produces an LLM message and declares how it joins the surface list. **log-only** marks everything else: a durable, replayable record with no derived-history contribution. Every payload is JSON-serializable (enforced at `Session.append`), and the whole format is pinned at `SESSION_FORMAT_VERSION = 0` — pre-release, no compatibility implied ([the version stance](subsystems/persistence.md)). Scope: the packages in this repo; a downstream plugin can merge further event types, which are outside this catalog by construction.',
'The envelope declarations below compose each event\'s `type`, monotonic `seq`, epoch-ms `time`, `data`, the optional `ignorable` unknown-type skip marker, and the conditional `surfaceOp`/`sourceEventSeqs` fields. **surface** marks a `SurfaceEventType` member: it produces an LLM message and declares how it joins the surface list. **log-only** marks everything else: a durable, replayable record with no derived-history contribution. Every payload is JSON-serializable (enforced at `Session.append`). Current writers stamp `SESSION_FORMAT_VERSION`; supported historical artifacts reach this current vocabulary through the build-static adjacent migration catalog ([the version lifecycle](subsystems/persistence.md)). Scope: the packages in this repo; a downstream plugin can merge further current-version event types, which are outside this catalog by construction and require an explicit disposition at a later format edge.',
'',
'## Event envelope',
'',
+166
View File
@@ -0,0 +1,166 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
collectSessionFormatMigrations,
readCurrentSessionFormatVersion,
renderSessionFormatCatalog,
} from './gen-session-format-catalog.ts'
const fixtureRoots: string[] = []
afterEach(() => {
for (const root of fixtureRoots.splice(0)) rmSync(root, { recursive: true, force: true })
})
function fixture(edges: Array<[number, number]>): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-session-format-catalog-'))
fixtureRoots.push(root)
mkdirSync(join(root, 'packages/core/session/src'), { recursive: true })
writeFileSync(join(root, 'packages/core/session/src/types.ts'), 'export const SESSION_FORMAT_VERSION = 2\n')
const catalogDependencies: Record<string, string> = {}
for (const [from, to] of edges) {
const dir = join(root, `packages/session/session-format-v${from}-to-v${to}`)
const name = `@deepseek-ai/dsh-session-format-v${from}-to-v${to}`
mkdirSync(dir, { recursive: true })
catalogDependencies[name] = 'workspace:^'
writeFileSync(join(dir, 'package.json'), JSON.stringify({
name,
dsh: { sessionFormatMigration: {
from, to, export: '.',
migration: `sessionFormatV${from}ToV${to}`,
sourceCodec: `releasedV${from}SessionFormatCodec`,
targetCodec: `releasedV${to}SessionFormatCodec`,
targetHeaderValidator: `assertReleasedV${to}Header`,
targetRestorer: `restoreReleasedV${to}Artifact`,
} },
dependencies: from === 0
? { '@deepseek-ai/dsh-session-format': 'workspace:^' }
: {
'@deepseek-ai/dsh-session-format': 'workspace:^',
[`@deepseek-ai/dsh-session-format-v${from - 1}-to-v${from}`]: 'workspace:^',
},
}))
}
const catalog = join(root, 'packages/session/session-format-catalog')
mkdirSync(catalog, { recursive: true })
writeFileSync(join(catalog, 'package.json'), JSON.stringify({
dependencies: catalogDependencies,
peerDependencies: { '@deepseek-ai/dsh-session': 'workspace:^' },
devDependencies: { '@deepseek-ai/dsh-session': 'workspace:^' },
}))
return root
}
function edgeManifest(root: string, from: number, to: number): {
path: string
value: Record<string, unknown> & {
dependencies: Record<string, string>
dsh: { sessionFormatMigration: Record<string, unknown> }
}
} {
const path = join(root, `packages/session/session-format-v${from}-to-v${to}/package.json`)
return {
path,
value: JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown> & {
dependencies: Record<string, string>
dsh: { sessionFormatMigration: Record<string, unknown> }
},
}
}
describe('session format catalog generator', () => {
it('normalizes Windows separators in discovered manifest paths before validation', async () => {
const root = fixture([[0, 1], [1, 2]])
vi.resetModules()
vi.doMock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>()
return {
...actual,
globSync: () => [
'packages\\session\\session-format-v0-to-v1\\package.json',
'packages\\session\\session-format-v1-to-v2\\package.json',
],
}
})
try {
const { collectSessionFormatMigrations: collect } = await import('./gen-session-format-catalog.ts')
expect(collect(root, 2).map(item => [item.from, item.to])).toEqual([[0, 1], [1, 2]])
} finally {
vi.doUnmock('node:fs')
vi.resetModules()
}
})
it('discovers one complete adjacent chain and renders direct imports', () => {
const root = fixture([[0, 1], [1, 2]])
const version = readCurrentSessionFormatVersion(root)
const declarations = collectSessionFormatMigrations(root, version)
const output = renderSessionFormatCatalog(declarations, version)
expect(declarations.map(item => [item.from, item.to])).toEqual([[0, 1], [1, 2]])
expect(output).toContain("from '@deepseek-ai/dsh-session-format-v0-to-v1'")
expect(output).toContain('currentVersion: 2')
expect(output).toContain('encodeCurrentArtifact: artifact => releasedV2SessionFormatCodec.encodeArtifact(artifact)')
expect(output).toContain('restoreReleasedV2Artifact(artifact, KNOWN_SESSION_EVENT_TYPES)')
expect(output).toContain('assertReleasedV2Header(header)')
expect(output).toContain('validateInstalledCurrentSessionHeader(header)')
expect(output).toContain("from '@deepseek-ai/dsh-session'")
expect(output).toContain("from './current.ts'")
const imports = output.split('\n').filter(line => line.startsWith('import {'))
expect(imports.filter(line => line.includes('releasedV1SessionFormatCodec'))).toHaveLength(1)
})
it('refuses a missing adjacent edge', () => {
const root = fixture([[0, 1]])
expect(() => collectSessionFormatMigrations(root, 2)).toThrow(/exactly one v1->v2/)
})
it('refuses a later edge whose declared source codec does not continue the prior target', () => {
const root = fixture([[0, 1], [1, 2]])
const manifest = edgeManifest(root, 1, 2)
manifest.value.dsh.sessionFormatMigration['sourceCodec'] = 'UnrelatedV1Codec'
writeFileSync(manifest.path, JSON.stringify(manifest.value))
expect(() => collectSessionFormatMigrations(root, 2))
.toThrow(/source codec UnrelatedV1Codec does not continue releasedV1SessionFormatCodec/)
})
it('requires every later edge to depend on the package that owns its source codec', () => {
const root = fixture([[0, 1], [1, 2]])
const manifest = edgeManifest(root, 1, 2)
delete manifest.value.dependencies['@deepseek-ai/dsh-session-format-v0-to-v1']
writeFileSync(manifest.path, JSON.stringify(manifest.value))
expect(() => collectSessionFormatMigrations(root, 2))
.toThrow(/must depend on @deepseek-ai\/dsh-session-format-v0-to-v1/)
})
it('requires the package name to identify its declared adjacent edge', () => {
const root = fixture([[0, 1], [1, 2]])
const manifest = edgeManifest(root, 1, 2)
manifest.value['name'] = '@deepseek-ai/dsh-session-format-other'
writeFileSync(manifest.path, JSON.stringify(manifest.value))
expect(() => collectSessionFormatMigrations(root, 2))
.toThrow(/name must be @deepseek-ai\/dsh-session-format-v1-to-v2/)
})
it('requires the catalog to share the installed Session package as a peer', () => {
const root = fixture([[0, 1], [1, 2]])
const path = join(root, 'packages/session/session-format-catalog/package.json')
const manifest = JSON.parse(readFileSync(path, 'utf8')) as {
dependencies: Record<string, string>
peerDependencies: Record<string, string>
devDependencies: Record<string, string>
}
manifest.dependencies['@deepseek-ai/dsh-session'] = 'workspace:^'
delete manifest.peerDependencies['@deepseek-ai/dsh-session']
writeFileSync(path, JSON.stringify(manifest))
expect(() => collectSessionFormatMigrations(root, 2))
.toThrow(/must share @deepseek-ai\/dsh-session through peer \+ dev dependencies/)
})
})
+237
View File
@@ -0,0 +1,237 @@
/** Generate the build-static Session format catalog from edge package metadata. */
import { globSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
const root = resolve(import.meta.dirname, '..')
const OUT = 'packages/session/session-format-catalog/src/generated.ts'
/** One adjacent migration declaration read from a workspace manifest. */
export interface SessionFormatMigrationManifest {
readonly packageName: string
readonly importPath: string
readonly from: number
readonly to: number
readonly migration: string
readonly sourceCodec: string
readonly targetCodec: string
readonly targetHeaderValidator: string
readonly targetRestorer: string
}
interface RawManifest {
readonly name?: unknown
readonly dependencies?: Readonly<Record<string, unknown>>
readonly peerDependencies?: Readonly<Record<string, unknown>>
readonly devDependencies?: Readonly<Record<string, unknown>>
readonly dsh?: {
readonly sessionFormatMigration?: Readonly<Record<string, unknown>>
}
}
function readJson(path: string): RawManifest {
return JSON.parse(readFileSync(path, 'utf8')) as RawManifest
}
function safeVersion(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0 || Object.is(value, -0)) {
throw new Error(`gen-session-format-catalog: ${label} must be a non-negative safe integer`)
}
return value as number
}
function nonempty(value: unknown, label: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new Error(`gen-session-format-catalog: ${label} must be a non-empty string`)
}
return value
}
/**
* Read the current writer version from the core Session source of truth.
* @param scanRoot - repository root whose Session source is authoritative.
* @returns the current non-negative Session format version.
*/
export function readCurrentSessionFormatVersion(scanRoot: string = root): number {
const source = readFileSync(resolve(scanRoot, 'packages/core/session/src/types.ts'), 'utf8')
const match = source.match(/export const SESSION_FORMAT_VERSION = (\d+)\b/)
if (match === null) throw new Error('gen-session-format-catalog: cannot read SESSION_FORMAT_VERSION')
return safeVersion(Number(match[1]), 'SESSION_FORMAT_VERSION')
}
/**
* Collect and validate the unique complete adjacent migration inventory.
* @param scanRoot - repository root containing migration package manifests.
* @param currentVersion - writer version the inventory must reach exactly.
* @returns ordered adjacent migration declarations from v0 to the current writer.
*/
export function collectSessionFormatMigrations(
scanRoot: string = root,
currentVersion: number = readCurrentSessionFormatVersion(scanRoot),
): SessionFormatMigrationManifest[] {
const declarations: SessionFormatMigrationManifest[] = []
for (const discovered of globSync('packages/session/session-format-v*-to-v*/package.json', { cwd: scanRoot }).sort()) {
const rel = discovered.replaceAll('\\', '/')
const manifest = readJson(resolve(scanRoot, rel))
const metadata = manifest.dsh?.sessionFormatMigration
if (metadata === undefined) {
throw new Error(`gen-session-format-catalog: ${rel} lacks dsh.sessionFormatMigration`)
}
const allowed = new Set([
'from', 'to', 'export', 'migration', 'sourceCodec', 'targetCodec',
'targetHeaderValidator', 'targetRestorer',
])
const extra = Object.keys(metadata).find(key => !allowed.has(key))
if (extra !== undefined) throw new Error(`gen-session-format-catalog: ${rel} has unknown metadata member ${extra}`)
const packageName = nonempty(manifest.name, `${rel} name`)
const from = safeVersion(metadata['from'], `${rel} from`)
const to = safeVersion(metadata['to'], `${rel} to`)
if (to !== from + 1) throw new Error(`gen-session-format-catalog: ${rel} must declare adjacent v${from}->v${from + 1}`)
const expectedPackageName = `@deepseek-ai/dsh-session-format-v${from}-to-v${to}`
if (packageName !== expectedPackageName) {
throw new Error(`gen-session-format-catalog: ${rel} name must be ${expectedPackageName}`)
}
const directoryMatch = rel.match(/session-format-v(\d+)-to-v(\d+)\/package\.json$/)
if (directoryMatch === null || Number(directoryMatch[1]) !== from || Number(directoryMatch[2]) !== to) {
throw new Error(`gen-session-format-catalog: ${rel} directory does not match v${from}->v${to}`)
}
const exportPath = nonempty(metadata['export'], `${rel} export`)
declarations.push({
packageName,
importPath: exportPath === '.' ? packageName : `${packageName}/${exportPath.replace(/^\.\//, '')}`,
from,
to,
migration: nonempty(metadata['migration'], `${rel} migration`),
sourceCodec: nonempty(metadata['sourceCodec'], `${rel} sourceCodec`),
targetCodec: nonempty(metadata['targetCodec'], `${rel} targetCodec`),
targetHeaderValidator: nonempty(metadata['targetHeaderValidator'], `${rel} targetHeaderValidator`),
targetRestorer: nonempty(metadata['targetRestorer'], `${rel} targetRestorer`),
})
}
declarations.sort((left, right) => left.from - right.from)
for (let version = 0; version < currentVersion; version += 1) {
const matches = declarations.filter(item => item.from === version)
if (matches.length !== 1) {
throw new Error(`gen-session-format-catalog: expected exactly one v${version}->v${version + 1} package, found ${matches.length}`)
}
}
const extra = declarations.find(item => item.from >= currentVersion)
if (extra !== undefined || declarations.length !== currentVersion) {
throw new Error(`gen-session-format-catalog: migration inventory does not end exactly at current v${currentVersion}`)
}
const catalog = readJson(resolve(scanRoot, 'packages/session/session-format-catalog/package.json'))
if (catalog.dependencies?.['@deepseek-ai/dsh-session'] !== undefined
|| catalog.peerDependencies?.['@deepseek-ai/dsh-session'] === undefined
|| catalog.devDependencies?.['@deepseek-ai/dsh-session'] === undefined) {
throw new Error(
'gen-session-format-catalog: catalog must share @deepseek-ai/dsh-session through peer + dev dependencies',
)
}
for (const [index, declaration] of declarations.entries()) {
if (catalog.dependencies?.[declaration.packageName] === undefined) {
throw new Error(`gen-session-format-catalog: catalog package lacks dependency ${declaration.packageName}`)
}
const previous = declarations[index - 1]
if (previous === undefined) continue
if (declaration.sourceCodec !== previous.targetCodec) {
throw new Error(
`gen-session-format-catalog: v${declaration.from} source codec ${declaration.sourceCodec} `
+ `does not continue ${previous.targetCodec}`,
)
}
const manifest = readJson(resolve(
scanRoot,
`packages/session/session-format-v${declaration.from}-to-v${declaration.to}/package.json`,
))
if (manifest.dependencies?.[previous.packageName] === undefined) {
throw new Error(
`gen-session-format-catalog: ${declaration.packageName} must depend on ${previous.packageName} `
+ 'to share the adjacent source codec',
)
}
}
return declarations
}
/**
* Render the deterministic direct-import catalog source.
* @param declarations - validated adjacent migrations in version order.
* @param currentVersion - writer version reached by the final declaration.
* @returns complete generated TypeScript source.
*/
export function renderSessionFormatCatalog(
declarations: readonly SessionFormatMigrationManifest[],
currentVersion: number,
): string {
const imports = declarations.map((item) => {
const names = [item.targetCodec, item.migration]
if (item.from === 0) names.push(item.sourceCodec)
if (item.to === currentVersion) names.push(item.targetRestorer, item.targetHeaderValidator)
return `import { ${[...new Set(names)].sort().join(', ')} } from '${item.importPath}'`
})
const first = declarations[0]
const codecs = first === undefined
? []
: [first.sourceCodec, ...declarations.map(item => item.targetCodec)]
const restorer = declarations.at(-1)?.targetRestorer
const headerValidator = declarations.at(-1)?.targetHeaderValidator
const currentCodec = declarations.at(-1)?.targetCodec
if (restorer === undefined) throw new Error('gen-session-format-catalog: current format has no target restorer')
if (headerValidator === undefined) {
throw new Error('gen-session-format-catalog: current format has no target header validator')
}
if (currentCodec === undefined) throw new Error('gen-session-format-catalog: current format has no target codec')
return [
'/**',
' * GENERATED by `scripts/gen-session-format-catalog.ts` — do not edit by hand.',
' * The direct imports make historical readability independent of mounted plugins.',
' */',
'',
"import { KNOWN_SESSION_EVENT_TYPES } from '@deepseek-ai/dsh-session'",
"import { createSessionFormatCatalog } from '@deepseek-ai/dsh-session-format'",
"import { validateInstalledCurrentSessionArtifact, validateInstalledCurrentSessionHeader } from './current.ts'",
...imports,
'',
'/** Physical codec dispatch and complete adjacent chain, independent of mounted plugins. */',
'export const sessionFormatCatalog = createSessionFormatCatalog({',
` currentVersion: ${currentVersion},`,
` codecs: [${codecs.join(', ')}],`,
` encodeCurrentArtifact: artifact => ${currentCodec}.encodeArtifact(artifact),`,
` migrations: [${declarations.map(item => item.migration).join(', ')}],`,
' restoreCurrent(artifact) {',
` const restored = ${restorer}(artifact, KNOWN_SESSION_EVENT_TYPES)`,
' validateInstalledCurrentSessionArtifact(restored)',
' return restored',
' },',
' restoreCurrentHeader(header) {',
` ${headerValidator}(header)`,
' validateInstalledCurrentSessionHeader(header)',
' return header',
' },',
'})',
'',
].join('\n')
}
function main(): void {
const currentVersion = readCurrentSessionFormatVersion(root)
const declarations = collectSessionFormatMigrations(root, currentVersion)
const output = renderSessionFormatCatalog(declarations, currentVersion)
const target = resolve(root, OUT)
if (process.argv.includes('--check')) {
let current = ''
try { current = readFileSync(target, 'utf8') } catch { /* missing is stale */ }
if (current !== output) {
console.error(`gen-session-format-catalog: ${OUT} is stale; run pnpm run gen-session-format-catalog`)
process.exitCode = 1
return
}
console.log(`gen-session-format-catalog: ${OUT} is up to date.`)
return
}
writeFileSync(target, output)
console.log(`gen-session-format-catalog: wrote ${OUT}.`)
}
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()
+3 -1
View File
@@ -43,7 +43,8 @@ const DUPLICATE_SAFE_PACKAGES: readonly string[] = [
const SAFE_HOST_DEPENDENCY_EXPORTS = {
'@deepseek-ai/dsh-credentials': ['credentialKey'],
'@deepseek-ai/dsh-deque': ['Deque'],
'@deepseek-ai/dsh-llm': ['callConfigEquals'],
'@deepseek-ai/dsh-llm': ['BlockAssembler', 'callConfigEquals', 'expandAssistantStream'],
'@deepseek-ai/dsh-session-format': ['sessionFormatLogFilename'],
'@deepseek-ai/dsh-timeout': ['MAX_TIMER_DELAY_MS'],
'@deepseek-ai/schemastery': ['default'],
} as const satisfies HostDependencyExports
@@ -51,6 +52,7 @@ const SAFE_HOST_DEPENDENCY_EXPORTS = {
/** Runtime exports that require every consumer to resolve the provider's shared peer instance. */
const PEER_REQUIRED_HOST_EXPORTS = {
'@deepseek-ai/dsh-scope': ['carrierKeyOf', 'scopeOf', 'scopeTarget'],
'@deepseek-ai/dsh-session': ['SESSION_FORMAT_VERSION'],
'@deepseek-ai/dsh-session-persistence': ['SessionPersistenceNotFoundError'],
} as const satisfies HostDependencyExports
+1
View File
@@ -734,6 +734,7 @@ function docSyncLeafGates(options: {
pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
pnpmScript('session-format-catalog', 'verify-session-format-catalog', { label: 'Session format catalog' }),
pnpmScript('public-repository-links', 'verify-public-repository-links', { label: 'public repository links', quick: true }),
pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs', quick: true }),
pnpmScript('subsystem-pages', 'verify-subsystem-pages', { label: 'subsystem pages' }),
+68 -19
View File
@@ -1,5 +1,6 @@
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { createAssistantMessage } from '@deepseek-ai/dsh-llm'
import { SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session'
import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
import {
@@ -8,24 +9,48 @@ import {
isPhysicalSessionFixture,
} from './session-fixture-layout.ts'
const HEADER = ' {"type":"session","version":0,"id":"fixture","createdAt":1,"delegationDepth":0} '
const HEADER = ' {"type":"session","version":2,"id":"fixture","createdAt":1,"isSeeded":false,"delegationDepth":0} '
const root = resolve(import.meta.dirname, '..')
const FIXTURE_MESSAGE = createAssistantMessage({
content: [{ type: 'text', text: 'part-0part-1part-2part-3' }],
source: { provider: 'mock', model: 'mock' },
})
const FIXTURE_STREAM: SessionEvent<'assistant/message'>['data']['stream'] = [
{
type: 'text-chunks',
time0: 10,
index: 0,
dt: [1, 1, 1],
texts: ['part-0', 'part-1', 'part-2', 'part-3'],
},
{ type: 'chunk', time: 14, chunk: { type: 'finish', reason: { kind: 'stop' } } },
]
function chunkRun(): SessionEvent[] {
return Array.from({ length: 4 }, (_, index) => ({
type: 'assistant/chunk',
seq: SessionSeq(index),
time: 10 + index,
function assistantMessage(): SessionEvent<'assistant/message'> {
return {
type: 'assistant/message',
seq: SessionSeq(2),
time: 14,
data: {
turn: 1,
step: 1,
chunk: { type: 'text-delta', index: 0, text: `part-${index}` },
message: FIXTURE_MESSAGE,
stream: FIXTURE_STREAM,
},
}))
surfaceOp: 'append',
}
}
function fixtureEvents(): SessionEvent[] {
return [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
{ type: 'step/start', seq: SessionSeq(1), time: 2, data: { turn: 1, step: 1 } },
assistantMessage(),
]
}
function unpackedFixture(): string {
return [HEADER, ...chunkRun().map(event => JSON.stringify(event)), ''].join('\n')
return [HEADER, ...fixtureEvents().map(event => JSON.stringify(event)), ''].join('\n')
}
function decodedBody(content: string): SessionEvent[] {
@@ -33,16 +58,23 @@ function decodedBody(content: string): SessionEvent[] {
}
describe('canonicalSessionFixture', () => {
it('preserves the header line and packs an unpacked event run losslessly', () => {
it('preserves the header line and nested compact stream losslessly', () => {
const canonical = canonicalSessionFixture(unpackedFixture(), 'fixture.jsonl')
expect(canonical).toBeDefined()
expect(canonical?.split('\n')[0]).toBe(HEADER)
const packed = JSON.parse(canonical?.split('\n')[1] ?? '{}') as Record<string, unknown>
expect(packed).toMatchObject({ type: 'text-chunks' })
expect(packed).not.toHaveProperty('seq0')
expect(packed).not.toHaveProperty('time0')
const message = canonical?.split('\n')
.map(line => JSON.parse(line || '{}') as Record<string, unknown>)
.find(record => record.type === 'assistant/message')
expect(message).toMatchObject({
type: 'assistant/message',
data: {
stream: FIXTURE_STREAM,
},
})
expect(message).not.toHaveProperty('seq')
expect(message).not.toHaveProperty('time')
expect(decodedBody(canonical ?? '').map(({ seq: _seq, time: _time, ...event }) => event))
.toStrictEqual(chunkRun().map(({ seq: _seq, time: _time, ...event }) => event))
.toStrictEqual(fixtureEvents().map(({ seq: _seq, time: _time, ...event }) => event))
})
it('ignores JSONL whose first record is not a session header', () => {
@@ -58,7 +90,17 @@ describe('canonicalSessionFixture', () => {
it('is idempotent for an already projected fixture', () => {
const projected = [
HEADER,
'{"type":"turn/start","data":{"turn":1,"seq":99,"time":100}}',
'{"type":"turn/start","data":{"turn":1}}',
'',
].join('\n')
expect(canonicalSessionFixture(projected)).toBe(projected)
})
it('preserves owner-restored request-header tokens in current projected fixtures', () => {
const projected = [
HEADER,
'{"type":"turn/start","data":{"turn":1}}',
'{"type":"request/header","data":{"header":{"config":{"provider":"mock","model":"mock"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}}',
'',
].join('\n')
expect(canonicalSessionFixture(projected)).toBe(projected)
@@ -70,8 +112,9 @@ describe('canonicalSessionFixture', () => {
})
it('labels malformed packed rows with the fixture path and line', () => {
expect(() => canonicalSessionFixture(`${HEADER}\n{"type":"text-chunks"}\n`, 'broken.jsonl'))
.toThrow(/broken\.jsonl: session snapshot line 2: malformed text-chunks storage row/)
const releasedHeader = '{"type":"session","version":0,"id":"fixture","createdAt":1,"delegationDepth":0}'
expect(() => canonicalSessionFixture(`${releasedHeader}\n{"type":"text-chunks"}\n`, 'broken.jsonl'))
.toThrow(/broken\.jsonl: session snapshot line 2: released text-chunks row 0 lacks required member "data"/)
})
})
@@ -80,9 +123,15 @@ describe('isPhysicalSessionFixture', () => {
expect(isPhysicalSessionFixture(
'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/main/session.jsonl',
)).toBe(true)
expect(isPhysicalSessionFixture(
'packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/main/session.v1.jsonl',
)).toBe(true)
expect(isPhysicalSessionFixture(
'scripts/snapshots/python-sdk-single-exe/advanced/session.1.jsonl',
)).toBe(true)
expect(isPhysicalSessionFixture(
'scripts/snapshots/python-sdk-single-exe/advanced/session.1.v1.jsonl',
)).toBe(true)
expect(isPhysicalSessionFixture(
'scripts/snapshots/python-sdk-single-exe/advanced/session.jsonl',
)).toBe(true)
@@ -99,7 +148,7 @@ describe('isPhysicalSessionFixture', () => {
})
})
it('keeps every session-format JSONL fixture projected into canonical packed layout', () => {
it('keeps every session-format JSONL fixture projected into canonical event layout', () => {
const nonCanonical = inspectSessionFixtureLayouts(root)
.filter(fixture => fixture.source !== fixture.canonical)
.map(fixture => fixture.path)
+120 -11
View File
@@ -4,8 +4,13 @@ import { deepStrictEqual } from 'node:assert'
import { execFileSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { packChunkRuns, type SessionEvent } from '@deepseek-ai/dsh-session'
import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
import {
decodeSeqRanges,
SessionLogOffset,
type SessionEvent,
} from '@deepseek-ai/dsh-session'
import type { SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
/** Physical persistence artifacts validated by the WebWorker runtime fixture spec. */
const WEBWORKER_PHYSICAL_SESSION_FIXTURE_ROOT =
@@ -33,31 +38,123 @@ export interface SessionFixtureLayout {
*/
export function isPhysicalSessionFixture(path: string): boolean {
if (path.startsWith(WEBWORKER_PHYSICAL_SESSION_FIXTURE_ROOT)) {
return path.endsWith('/session.jsonl')
return /\/session(?:\.v[1-9]\d*)?\.jsonl$/.test(path)
}
return path.startsWith(PYTHON_RUNTIME_PHYSICAL_SESSION_FIXTURE_ROOT)
&& /\/session(?:\.\d+)?\.jsonl$/.test(path)
&& /\/session(?:\.[1-9]\d*)?(?:\.v[1-9]\d*)?\.jsonl$/.test(path)
}
function isSessionHeader(value: unknown): boolean {
return value !== null && typeof value === 'object' && (value as { type?: unknown }).type === 'session'
}
function validationHeader(value: unknown): unknown {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
const header = { ...value as Record<string, unknown> }
if (header.version === 0 && !Object.hasOwn(header, 'delegationDepth')) header.delegationDepth = 0
if (typeof header.cwd === 'string' && /^\{\{cwd\}\}(?:\/|$)/.test(header.cwd)) {
header.cwd = header.cwd.replace('{{cwd}}', '/dsh-snapshot-cwd')
}
return header
}
function renderFixture(headerLine: string, events: readonly SessionEvent[]): string {
return [
headerLine,
...packChunkRuns(events).map((stored) => {
const record = stored as unknown as Record<string, unknown>
...events.map((event) => {
const record = { ...event } as unknown as Record<string, unknown>
delete record.seq
delete record.time
delete record.seq0
delete record.time0
return JSON.stringify(record)
}),
'',
].join('\n')
}
function projectedRowCardinality(record: Readonly<Record<string, unknown>>): number {
const data = record.data
if (data === null || typeof data !== 'object' || Array.isArray(data)) return 1
const key = record.type === 'tool-call-chunks' ? 'args' : 'texts'
const values = (data as Record<string, unknown>)[key]
return Array.isArray(values) && values.length > 0 ? values.length : 1
}
function parseFixtureObjectLine(line: string, lineNumber: number): Record<string, unknown> {
let value: unknown
try {
value = JSON.parse(line) as unknown
} catch (error) {
throw new Error(`session snapshot line ${lineNumber} contains invalid JSON`, { cause: error })
}
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`session snapshot line ${lineNumber} must be a JSON object`)
}
return value as Record<string, unknown>
}
function parseFixtureRows(content: string, headerValue: unknown): SessionEvent[] {
const rows: Record<string, unknown>[] = []
const rowLines: number[] = []
let nextSeq: SessionLogOffsetType = SessionLogOffset(0)
let headerSkipped = false
for (const [index, line] of content.split(/\r?\n/).entries()) {
if (line.trim().length === 0) continue
if (!headerSkipped) {
headerSkipped = true
continue
}
const record = parseFixtureObjectLine(line, index + 1)
const packed = record.type === 'text-chunks'
|| record.type === 'reasoning-chunks'
|| record.type === 'tool-call-chunks'
const seqKey = packed ? 'seq0' : 'seq'
const timeKey = packed ? 'time0' : 'time'
if (!Object.hasOwn(record, seqKey)) record[seqKey] = nextSeq
if (!Object.hasOwn(record, timeKey)) record[timeKey] = 0
rows.push(record)
rowLines.push(index + 1)
nextSeq = SessionLogOffset(nextSeq + projectedRowCardinality(record))
}
// Versionless protocol fixtures and current projected snapshots use scalar
// event rows. Current snapshots may contain owner-restored scrub tokens such
// as `{{tools}}`; semantic replay restores those sidecars, while this layout
// gate owns only envelopes, provenance ranges, and one-event-per-row form.
const projectedCurrent = headerValue !== null
&& typeof headerValue === 'object'
&& !Array.isArray(headerValue)
&& (headerValue as Record<string, unknown>).version === sessionFormatCatalog.currentVersion
if (headerValue === null || typeof headerValue !== 'object' || Array.isArray(headerValue)
|| !Object.hasOwn(headerValue, 'version') || projectedCurrent) {
return rows.map((source, index) => {
const record = { ...source }
try {
if (record.type === 'text-chunks'
|| record.type === 'reasoning-chunks'
|| record.type === 'tool-call-chunks') {
throw new Error('current projected fixtures cannot contain legacy packed rows')
}
if (Object.hasOwn(record, 'sourceEventSeqs')) {
record.sourceEventSeqs = decodeSeqRanges(record.sourceEventSeqs)
}
return record as unknown as SessionEvent
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
throw new Error(`session snapshot line ${rowLines[index] ?? 1}: ${detail}`, { cause: error })
}
})
}
try {
return [
...sessionFormatCatalog.decodeArtifact(validationHeader(headerValue), rows).events,
] as unknown as SessionEvent[]
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
const storedRow = /\brow (\d+)\b/.exec(detail)
const line = storedRow === null ? 1 : rowLines[Number(storedRow[1])] ?? 1
throw new Error(`session snapshot line ${line}: ${detail}`, { cause: error })
}
}
function withoutEnvelope(events: readonly SessionEvent[]): Array<Omit<SessionEvent, 'seq' | 'time'>> {
return events.map((event) => {
const { seq: _seq, time: _time, ...projected } = event
@@ -68,7 +165,7 @@ function withoutEnvelope(events: readonly SessionEvent[]): Array<Omit<SessionEve
/**
* Canonicalize one JSONL document when its first record is a session header.
* The header line remains byte-identical; body records decode to logical events,
* re-encode with {@link packChunkRuns}, and omit storage sequence/time envelopes.
* re-encode one event per row, and omit storage sequence/time envelopes.
* Non-session JSONL returns undefined.
*
* @param content - JSONL source text.
@@ -89,13 +186,25 @@ export function canonicalSessionFixture(content: string, label = '<session-fixtu
let events
try {
events = parseSessionLog(content)
events = parseFixtureRows(content, headerValue)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
throw new Error(`${label}: ${detail}`, { cause: error })
}
const storedVersion = headerValue !== null
&& typeof headerValue === 'object'
&& !Array.isArray(headerValue)
&& typeof (headerValue as Record<string, unknown>).version === 'number'
? (headerValue as Record<string, number>).version
: undefined
// Released predecessor generations are immutable compatibility fixtures.
// Parsing above still validates their physical rows, but canonicalization
// never rewrites their committed bytes into the current scalar layout.
if (storedVersion !== undefined && storedVersion < sessionFormatCatalog.currentVersion) {
return content
}
const canonical = renderFixture(headerLine, events)
const decoded = parseSessionLog(canonical)
const decoded = parseFixtureRows(canonical, headerValue)
try {
deepStrictEqual(withoutEnvelope(decoded), withoutEnvelope(events))
} catch (error) {
@@ -0,0 +1,111 @@
import { describe, expect, it } from 'vitest'
import { assertV2SnapshotCorpusPolicy } from './session-snapshot-corpus-policy.ts'
const completeV0 = {
key: 'session/v0',
selectedVersions: [0],
retained: {
version: 0,
coverage: ['multi-hop', 'packed-row', 'retry-failure', 'shipped-profile'],
},
} as const
describe('v2 recorded-session corpus policy', () => {
it('accepts a current majority and the complete bounded v0/v1 migration set', () => {
expect(assertV2SnapshotCorpusPolicy([
{ key: 'session/current', selectedVersions: [2, 2, 2, 2, 2, 2, 2, 2] },
{
key: 'session/multi-hop',
selectedVersions: [0, 0, 0],
retained: { version: 0, coverage: ['multi-hop', 'shipped-profile'] },
},
{
key: 'session/packed',
selectedVersions: [0],
retained: { version: 0, coverage: ['packed-row'] },
},
{
key: 'session/retry',
selectedVersions: [0],
retained: { version: 0, coverage: ['retry-failure'] },
},
{
key: 'sdk/adjacent',
selectedVersions: [1, 1],
retained: { version: 1, coverage: ['adjacent-migration'] },
},
])).toEqual({ currentRoles: 8, retainedRoles: 7, retainedScenarios: 4 })
})
it('requires v0 coverage from v0 fixtures and adjacent coverage from v1 fixtures', () => {
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/current', selectedVersions: Array<number>(8).fill(2) },
{
key: 'sdk/wrong-generation',
selectedVersions: [1],
retained: {
version: 1,
coverage: ['adjacent-migration'],
},
},
])).toThrow('v2 Session corpus lacks v0 coverage')
})
it('does not let one retained generation claim another edge\'s coverage', () => {
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/current', selectedVersions: Array<number>(8).fill(2) },
completeV0,
{
key: 'sdk/adjacent',
selectedVersions: [1],
retained: { version: 1, coverage: ['adjacent-migration', 'multi-hop'] },
},
])).toThrow('sdk/adjacent: v1 retained coverage must be adjacent-migration')
})
it('rejects an undeclared historical role and a retained current generation', () => {
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/empty', selectedVersions: [] },
])).toThrow('session/empty: scenario owns no selected Session role')
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/old', selectedVersions: [1] },
])).toThrow('session/old: selected Session generation v1 does not match expected v2')
expect(() => assertV2SnapshotCorpusPolicy([
{
key: 'session/not-historical',
selectedVersions: [2],
retained: { version: 2, coverage: ['adjacent-migration'] },
},
])).toThrow('session/not-historical: v2 corpus may retain only Session format v0 or v1')
})
it('requires one direct v1 migration fixture', () => {
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/current', selectedVersions: Array<number>(8).fill(2) },
completeV0,
])).toThrow('v2 Session corpus lacks v1 coverage: adjacent-migration')
})
it('bounds historical roles and requires the current generation to remain the majority', () => {
const retained = [
{
...completeV0,
selectedVersions: Array<number>(11).fill(0),
},
{
key: 'sdk/v1',
selectedVersions: [1],
retained: { version: 1, coverage: ['adjacent-migration'] },
},
] as const
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/current', selectedVersions: Array<number>(20).fill(2) },
...retained,
])).toThrow('v2 Session corpus retains 12 historical roles; maximum is 10')
expect(() => assertV2SnapshotCorpusPolicy([
{ key: 'session/current', selectedVersions: [2] },
{ ...retained[0], selectedVersions: [0, 0] },
retained[1],
])).toThrow('v2 Session corpus requires a current majority; current=1, retained=3')
})
})
+96
View File
@@ -0,0 +1,96 @@
/** Enforced generation mix for the v2 recorded-session corpus. */
import type { SnapshotSessionFormatManifest } from '@deepseek-ai/dsh-session-snapshot'
/** One owning scenario's selected parent and child generations. */
export interface SnapshotCorpusScenarioGenerations {
/** Corpus-relative profile/scenario key. */
readonly key: string
/** Highest selected generation for each contiguous role. */
readonly selectedVersions: readonly number[]
/** Explicit historical generation and the behavior it preserves. */
readonly retained?: SnapshotSessionFormatManifest
}
/** Counts returned after the v2 corpus policy accepts the inventory. */
export interface SnapshotCorpusGenerationSummary {
readonly currentRoles: number
readonly retainedRoles: number
readonly retainedScenarios: number
}
const CURRENT_VERSION = 2
const MAX_RETAINED_ROLES = 10
const REQUIRED_V0_COVERAGE = new Set([
'multi-hop',
'packed-row',
'retry-failure',
'shipped-profile',
])
const REQUIRED_V1_COVERAGE = new Set(['adjacent-migration'])
/**
* Require a v2 majority plus a small explicit v0/v1 migration corpus.
*
* @param scenarios - Every owning top-level recorded-session scenario.
* @returns Accepted current and retained role counts.
*/
export function assertV2SnapshotCorpusPolicy(
scenarios: readonly SnapshotCorpusScenarioGenerations[],
): SnapshotCorpusGenerationSummary {
let currentRoles = 0
let retainedRoles = 0
let retainedScenarios = 0
const v0Coverage = new Set<string>()
const v1Coverage = new Set<string>()
for (const scenario of scenarios) {
if (scenario.selectedVersions.length === 0) {
throw new Error(`${scenario.key}: scenario owns no selected Session role`)
}
const expectedVersion = scenario.retained?.version ?? CURRENT_VERSION
const mismatched = scenario.selectedVersions.find(version => version !== expectedVersion)
if (mismatched !== undefined) {
throw new Error(
`${scenario.key}: selected Session generation v${mismatched} does not match expected v${expectedVersion}`,
)
}
if (scenario.retained === undefined) {
currentRoles += scenario.selectedVersions.length
continue
}
if (scenario.retained.version !== 0 && scenario.retained.version !== 1) {
throw new Error(`${scenario.key}: v2 corpus may retain only Session format v0 or v1`)
}
const allowedCoverage = scenario.retained.version === 0
? REQUIRED_V0_COVERAGE
: REQUIRED_V1_COVERAGE
if (scenario.retained.coverage.some(item => !allowedCoverage.has(item))) {
throw new Error(
`${scenario.key}: v${scenario.retained.version} retained coverage must be ${[...allowedCoverage].join(', ')}`,
)
}
retainedRoles += scenario.selectedVersions.length
retainedScenarios += 1
const coverage = scenario.retained.version === 0 ? v0Coverage : v1Coverage
for (const item of scenario.retained.coverage) coverage.add(item)
}
const missingV0Coverage = [...REQUIRED_V0_COVERAGE].filter(item => !v0Coverage.has(item))
if (missingV0Coverage.length > 0) {
throw new Error(`v2 Session corpus lacks v0 coverage: ${missingV0Coverage.join(', ')}`)
}
const missingV1Coverage = [...REQUIRED_V1_COVERAGE].filter(item => !v1Coverage.has(item))
if (missingV1Coverage.length > 0) {
throw new Error(`v2 Session corpus lacks v1 coverage: ${missingV1Coverage.join(', ')}`)
}
if (retainedRoles > MAX_RETAINED_ROLES) {
throw new Error(`v2 Session corpus retains ${retainedRoles} historical roles; maximum is ${MAX_RETAINED_ROLES}`)
}
if (currentRoles <= retainedRoles) {
throw new Error(
`v2 Session corpus requires a current majority; current=${currentRoles}, retained=${retainedRoles}`,
)
}
return { currentRoles, retainedRoles, retainedScenarios }
}
+34 -5
View File
@@ -2,18 +2,23 @@
import { existsSync } from 'node:fs'
import { lstat, readFile, readdir, realpath } from 'node:fs/promises'
import { dirname, join, relative, resolve } from 'node:path'
import { basename, dirname, join, relative, resolve } from 'node:path'
import { expect, it } from 'vitest'
import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
import {
assertSessionFixtureVersion,
captureExpectedWorkspaceSnapshot,
EMPTY_WORKSPACE_MARKER,
parseSnapshotManifest,
parseSessionFixtureName,
redactSessionSnapshotIds,
scrubSystemPrompts,
scrubToolSchemas,
sessionFixtureFiles,
sessionFixtureNames,
type SnapshotManifest,
} from '@deepseek-ai/dsh-session-snapshot'
import { assertV2SnapshotCorpusPolicy } from './session-snapshot-corpus-policy.ts'
const repoRoot = resolve(import.meta.dirname, '..')
const corpusRoot = join(repoRoot, 'snapshots')
@@ -113,17 +118,21 @@ it('keeps every recorded session owned, pinned, redacted, and header-scrubbed',
const classKey = `${manifest.composition}/${manifest.header.class}`
expect(pinByClass.has(classKey), `${key}: missing composition/header pin ${classKey}`).toBe(true)
const localSession = join(dir, 'session.jsonl')
const localEntries = await readdir(dir)
const localSessionNames = localEntries.filter(name => parseSessionFixtureName(name) !== undefined)
if (manifest.session === undefined) {
expect(existsSync(localSession), `${key}: owner session.jsonl`).toBe(true)
expect(localSessionNames.length, `${key}: owner Session fixture`).toBeGreaterThan(0)
} else {
expect(existsSync(localSession), `${key}: borrower must not own session.jsonl`).toBe(false)
expect(localSessionNames, `${key}: borrower must not own a Session fixture`).toEqual([])
const target = resolve(dir, manifest.session.source)
expect(existsSync(target), `${key}: session source`).toBe(true)
const targetDir = await realpath(dirname(target))
const sourceKey = relative(corpusRoot, targetDir).split(/[/\\]/).join('/')
expect(byKey.has(sourceKey), `${key}: session source must name a corpus owner`).toBe(true)
expect(byKey.get(sourceKey)?.manifest.session, `${key}: session source cannot chain through a borrower`).toBeUndefined()
const [selectedParent] = sessionFixtureFiles(await readdir(targetDir))
expect(basename(target), `${key}: session source must name the owner's selected parent generation`)
.toBe(selectedParent?.name)
}
expect(existsSync(join(dir, 'replay.override.json')), `${key}: replay override presence`)
@@ -161,8 +170,11 @@ it('keeps every recorded session owned, pinned, redacted, and header-scrubbed',
}
if (manifest.session !== undefined) continue
const names = sessionFixtureNames(await readdir(dir))
const names = sessionFixtureNames(localEntries)
const fixtures = await Promise.all(names.map(name => readFile(join(dir, name), 'utf8')))
for (const name of localSessionNames) {
assertSessionFixtureVersion(name, await readFile(join(dir, name), 'utf8'))
}
expect(redactSessionSnapshotIds(fixtures), `${key}: typed identity fixed point`).toEqual(fixtures)
for (const [index, fixture] of fixtures.entries()) {
expect(scrubSystemPrompts(fixture), `${key}/${names[index]}: system prompt must be a sidecar`).toBe(fixture)
@@ -178,3 +190,20 @@ it('keeps every recorded session owned, pinned, redacted, and header-scrubbed',
}
}
})
it('keeps a current v2 majority plus the bounded declared v0/v1 migration corpus', async () => {
expect(SESSION_FORMAT_VERSION).toBe(2)
const owners = (await scenarios()).filter(scenario => scenario.manifest.session === undefined)
const inventory = await Promise.all(owners.map(async scenario => ({
key: scenario.key,
selectedVersions: sessionFixtureFiles(await readdir(scenario.dir)).map(file => file.version),
...(scenario.manifest.sessionFormat === undefined
? {}
: { retained: scenario.manifest.sessionFormat }),
})))
expect(assertV2SnapshotCorpusPolicy(inventory)).toMatchObject({
retainedRoles: 7,
retainedScenarios: 5,
})
})
+367 -39
View File
@@ -10,6 +10,7 @@ import importlib.metadata
import json
import os
import queue
import re
import shutil
import subprocess
import sys
@@ -124,7 +125,9 @@ SNAPSHOT_WORKFLOW_SCRIPT = (
ADVANCED_SNAPSHOT_DIRECTORY = (
Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "advanced"
)
ADVANCED_SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl", "session.2.jsonl")
ADVANCED_SNAPSHOT_FILENAMES = (
"result.json", "session.v2.jsonl", "session.1.v2.jsonl", "session.2.v2.jsonl",
)
MINIMAL_SNAPSHOT_DIRECTORY = (
Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "minimal"
)
@@ -134,7 +137,9 @@ MINIMAL_SNAPSHOT_FILENAMES = ("model-visible.json",)
RESTART_SNAPSHOT_DIRECTORY = (
Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "restart"
)
RESTART_SNAPSHOT_FILENAMES = ("result.json", "requests.json", "session.1.jsonl", "session.2.jsonl")
RESTART_SNAPSHOT_FILENAMES = (
"result.json", "requests.json", "session.1.v2.jsonl", "session.2.v2.jsonl",
)
MCP_SERVER_SCRIPT = """\
import json
import os
@@ -1357,7 +1362,14 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots
if expected not in render_jsonl(records):
raise AssertionError(f"restart snapshot durable log has no {expected}")
files = build_restart_snapshot_files(first, second, requests, logs, root, sessions)
files = build_restart_snapshot_files(
first,
second,
requests,
logs,
root,
sessions,
)
compare_snapshot_files(
files, update_snapshots, RESTART_SNAPSHOT_DIRECTORY, RESTART_SNAPSHOT_FILENAMES,
)
@@ -1479,11 +1491,108 @@ class RuntimePeer:
self.stderr.extend(self.process.stderr)
PERSISTED_SESSION_FILENAME = re.compile(r"^session(?:\.v([1-9]\d*))?\.jsonl(\.zstd)?$")
SNAPSHOT_SESSION_FILENAME = re.compile(
r"^session(?:\.([1-9]\d*))?(?:\.v([1-9]\d*))?\.jsonl$",
)
def persisted_session_filename_version(path: Path, compressed: bool = False) -> int | None:
"""Return one canonical persistence basename's generation for the selected encoding."""
match = PERSISTED_SESSION_FILENAME.fullmatch(path.name)
if match is None or (match.group(2) is not None) != compressed:
return None
return int(match.group(1) or 0)
def latest_persisted_session_paths(sessions: Path, compressed: bool = False) -> list[Path]:
"""Select the numeric-highest immutable generation in each physical Session directory."""
pattern = "*.jsonl.zstd" if compressed else "*.jsonl"
selected: dict[Path, tuple[int, Path]] = {}
for path in sessions.rglob(pattern):
version = persisted_session_filename_version(path, compressed)
if version is None:
continue
previous = selected.get(path.parent)
if previous is None or version > previous[0]:
selected[path.parent] = (version, path)
return sorted((entry[1] for entry in selected.values()), key=lambda path: str(path))
def session_header_version(content: str, label: str) -> int:
"""Read a non-negative physical Session generation from the first JSONL record."""
first = next((line for line in content.splitlines() if line), None)
if first is None:
raise AssertionError(f"{label}: Session log is empty")
header = json.loads(first)
version = header.get("version") if isinstance(header, dict) and header.get("type") == "session" else None
if not isinstance(version, int) or isinstance(version, bool) or version < 0:
raise AssertionError(f"{label}: Session header has no non-negative integer version")
return version
def assert_persisted_session_version(path: Path, content: str) -> int:
"""Require a raw persistence basename and header to name the same generation."""
filename_version = persisted_session_filename_version(path)
if filename_version is None:
raise AssertionError(f"non-canonical Session persistence filename: {path.name}")
header_version = session_header_version(content, path.name)
if filename_version != header_version:
raise AssertionError(
f"{path.name}: filename declares Session format v{filename_version}, "
f"header declares v{header_version}",
)
return header_version
def snapshot_session_filename(index: int, version: int) -> str:
"""Render parent/ordinal snapshot role plus an omitted-v0 generation."""
if index < 0 or version < 0:
raise ValueError("snapshot Session index and version must be non-negative")
ordinal = "" if index == 0 else f".{index}"
generation = "" if version == 0 else f".v{version}"
return f"session{ordinal}{generation}.jsonl"
def parse_snapshot_session_filename(name: str) -> tuple[int, int] | None:
"""Parse one canonical parent/ordinal snapshot filename."""
match = SNAPSHOT_SESSION_FILENAME.fullmatch(name)
if match is None:
if name.startswith("session") and name.endswith(".jsonl"):
raise AssertionError(f"invalid snapshot Session filename: {name}")
return None
return int(match.group(1) or 0), int(match.group(2) or 0)
def selected_snapshot_session_files(directory: Path) -> dict[int, Path]:
"""Select one highest-generation expected file per parent/ordinal role."""
selected: dict[int, tuple[int, Path]] = {}
for path in directory.iterdir():
if not path.is_file():
continue
parsed = parse_snapshot_session_filename(path.name)
if parsed is None:
continue
index, version = parsed
content = path.read_text(encoding="utf-8")
header_version = session_header_version(content, path.name)
if header_version != version:
raise AssertionError(
f"{path.name}: filename declares Session format v{version}, header declares v{header_version}",
)
previous = selected.get(index)
if previous is None or version > previous[0]:
selected[index] = (version, path)
return {index: value[1] for index, value in selected.items()}
def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None:
logs = list(sessions.rglob("*.jsonl"))
logs = latest_persisted_session_paths(sessions)
if len(logs) != 1:
raise AssertionError(f"expected one JSONL session log under {sessions}, found {logs}")
lines = logs[0].read_text().splitlines()
content = logs[0].read_text()
assert_persisted_session_version(logs[0], content)
lines = content.splitlines()
header = json.loads(lines[0])
if header.get("cwd") != str(cwd):
raise AssertionError(f"session header cwd is not absolute/canonical: {header}")
@@ -1494,7 +1603,7 @@ def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None:
def assert_zstd_session_log(sessions: Path) -> None:
logs = list(sessions.rglob("*.jsonl.zstd"))
logs = latest_persisted_session_paths(sessions, compressed=True)
if len(logs) != 1:
raise AssertionError(f"expected one Zstandard JSONL session log under {sessions}, found {logs}")
if not logs[0].read_bytes().startswith(bytes.fromhex("28b52ffd")):
@@ -1504,10 +1613,12 @@ def assert_zstd_session_log(sessions: Path) -> None:
def read_session_logs(sessions: Path) -> dict[str, list[dict[str, object]]]:
"""Parse every persisted JSONL session into a map keyed by header id."""
logs: dict[str, list[dict[str, object]]] = {}
for path in sorted(sessions.rglob("*.jsonl")):
for path in latest_persisted_session_paths(sessions):
content = path.read_text(encoding="utf-8")
assert_persisted_session_version(path, content)
records = [
json.loads(line)
for line in path.read_text(encoding="utf-8").splitlines()
for line in content.splitlines()
if line
]
if not records or records[0].get("type") != "session":
@@ -1626,20 +1737,23 @@ def build_snapshot_files(
],
}
normalized_result = normalize_snapshot_value(result_value, replacements)
parent_records = project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]
])
files = {
"result.json": json.dumps(normalized_result, indent=2, ensure_ascii=False) + "\n",
"session.jsonl": render_jsonl(
project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]
])
),
snapshot_session_filename(
0, session_header_version(render_jsonl(parent_records), "advanced parent"),
): render_jsonl(parent_records),
}
for index, child_id in enumerate(child_ids, start=1):
files[f"session.{index}.jsonl"] = render_jsonl(
project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[child_id]
])
)
child_records = project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[child_id]
])
child_content = render_jsonl(child_records)
files[snapshot_session_filename(
index, session_header_version(child_content, f"advanced child {index}"),
)] = child_content
return files
@@ -1663,8 +1777,14 @@ def build_restart_snapshot_files(
"session_id": result.session_id,
"final_response": result.final_response,
"finish_reason": result.finish_reason,
"eventTypes": [event.get("type") for event in result.events],
"notificationMethods": [notification.method for notification in result.notifications],
"eventTypes": [
event.get("type")
for event in result.events
],
"notificationMethods": [
notification.method
for notification in result.notifications
],
}
for result in (first, second)
]
@@ -1676,6 +1796,14 @@ def build_restart_snapshot_files(
}
for request in requests
]
first_records = project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[RESTART_FIRST_SESSION_ID]
])
second_records = project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[RESTART_SECOND_SESSION_ID]
])
first_content = render_jsonl(first_records)
second_content = render_jsonl(second_records)
return {
"result.json": json.dumps(
normalize_snapshot_value(result_value, replacements), indent=2, ensure_ascii=False,
@@ -1683,12 +1811,12 @@ def build_restart_snapshot_files(
"requests.json": json.dumps(
normalize_snapshot_value(request_value, replacements), indent=2, ensure_ascii=False,
) + "\n",
"session.1.jsonl": render_jsonl(project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[RESTART_FIRST_SESSION_ID]
])),
"session.2.jsonl": render_jsonl(project_session_snapshot([
normalize_snapshot_value(record, replacements) for record in logs[RESTART_SECOND_SESSION_ID]
])),
snapshot_session_filename(
1, session_header_version(first_content, "restart Session 1"),
): first_content,
snapshot_session_filename(
2, session_header_version(second_content, "restart Session 2"),
): second_content,
}
@@ -1759,6 +1887,20 @@ def normalize_snapshot_value(
normalized["createdAt"] = 0
if "seq" in normalized and "time" in normalized:
normalized["time"] = 0
if normalized.get("type") in ("assistant/message", "assistant/attempt"):
data = normalized.get("data")
stream = data.get("stream") if isinstance(data, dict) else None
if isinstance(stream, list):
for member in stream:
if not isinstance(member, dict):
continue
if isinstance(member.get("time"), (int, float)):
member["time"] = 0
if isinstance(member.get("time0"), (int, float)):
member["time0"] = 0
dt = member.get("dt")
if isinstance(dt, list):
member["dt"] = [0] * len(dt)
if isinstance(normalized.get("id"), str) and normalized.get("role") in ("assistant", "user"):
normalized["id"] = "{{messageId}}"
scrub_snapshot_header(normalized)
@@ -1801,6 +1943,165 @@ def project_session_snapshot(records: list[dict[str, object]]) -> list[dict[str,
return projected
SESSION_FORMAT_PROVENANCE = "{{sessionFormatVersion}}"
def expand_snapshot_stream_member(member: object) -> list[dict[str, object]]:
"""Expand one compact Assistant stream member into logical provider chunks."""
if not isinstance(member, dict):
raise AssertionError(f"snapshot Assistant stream member is not an object: {member!r}")
member_type = member.get("type")
if member_type == "chunk":
chunk = member.get("chunk")
if not isinstance(chunk, dict):
raise AssertionError(f"snapshot Assistant chunk member has no chunk: {member!r}")
return [chunk]
packed_kinds = {
"text-chunks": ("texts", "text-delta", "text"),
"reasoning-chunks": ("texts", "reasoning-delta", "text"),
"tool-call-chunks": ("args", "tool-call-delta", "argumentsDelta"),
}
packed = packed_kinds.get(member_type)
if packed is None:
raise AssertionError(f"snapshot Assistant stream has unknown member type: {member_type!r}")
values_key, chunk_type, value_key = packed
values = member.get(values_key)
if not isinstance(values, list):
raise AssertionError(f"snapshot Assistant stream member has no {values_key}: {member!r}")
shared = {
key: member[key]
for key in ("index", "id", "name")
if key in member
}
return [
{"type": chunk_type, **shared, value_key: value}
for value in values
]
def expand_snapshot_assistant_event(value: object) -> list[object]:
"""Expand one direct or SDK-wrapped v2 settlement for generation-neutral comparison."""
if not isinstance(value, dict):
return [value]
event = value
wrapper_key: str | None = None
wrapper: dict[str, object] | None = None
if value.get("method") == "session.event":
for candidate in ("payload", "params"):
container = value.get(candidate)
nested = container.get("event") if isinstance(container, dict) else None
if isinstance(nested, dict):
event = nested
wrapper_key = candidate
wrapper = container
break
if event.get("type") not in ("assistant/message", "assistant/attempt"):
return [value]
data = event.get("data")
stream = data.get("stream") if isinstance(data, dict) else None
if not isinstance(stream, list):
return [value]
def wrap(expanded: dict[str, object]) -> object:
if wrapper_key is None or wrapper is None:
return expanded
return {**value, wrapper_key: {**wrapper, "event": expanded}}
common = {
key: data[key]
for key in ("turn", "step")
if key in data
}
expanded = [
wrap({
"type": "assistant/chunk",
"data": {**common, "chunk": chunk},
})
for member in stream
for chunk in expand_snapshot_stream_member(member)
]
if event.get("type") == "assistant/message":
expanded.append(wrap({
**event,
"data": {key: item for key, item in data.items() if key != "stream"},
}))
return expanded
def normalize_session_format_comparison(
value: object,
source_session_version: int | None = None,
) -> object:
"""Canonicalize only generation provenance that differs across immutable Session files."""
if isinstance(value, list):
return [
normalize_session_format_comparison(expanded, source_session_version)
for item in value
for expanded in expand_snapshot_assistant_event(item)
]
if not isinstance(value, dict):
return value
normalized = {
key: normalize_session_format_comparison(item, source_session_version)
for key, item in value.items()
}
if normalized.get("type") == "session" and "version" in normalized:
normalized["version"] = SESSION_FORMAT_PROVENANCE
normalized.setdefault("isSeeded", False)
ordered_header = {
key: normalized[key]
for key in ("type", "version", "id", "createdAt", "cwd", "isSeeded", "delegationDepth")
if key in normalized
}
normalized = {
**ordered_header,
**{key: item for key, item in normalized.items() if key not in ordered_header},
}
if isinstance(normalized.get("type"), str) and "data" in normalized:
normalized.pop("seq", None)
normalized.pop("time", None)
if source_session_version == 1 and normalized.get("type") == "assistant/message":
normalized.pop("sourceEventSeqs", None)
if normalized.get("type") == "session-log-deepseek/delivery-accepted":
data = normalized.get("data")
if isinstance(data, dict):
data.pop("throughSeq", None)
data.pop("sessionFormatVersion", None)
data["sessionFormatVersion"] = SESSION_FORMAT_PROVENANCE
if normalized.get("kind") == "session-reference":
references = normalized.get("references")
if isinstance(references, list):
for reference in references:
if isinstance(reference, dict):
reference.pop("capturedFormatVersion", None)
reference["capturedFormatVersion"] = SESSION_FORMAT_PROVENANCE
return normalized
def normalize_snapshot_comparison_text(name: str, content: str) -> str:
"""Normalize Session generation provenance only while comparing committed expected outputs."""
if name.startswith("session") and name.endswith(".jsonl"):
parsed = [json.loads(line) for line in content.splitlines() if line]
header = parsed[0] if parsed else None
source_version = header.get("version") if isinstance(header, dict) else None
if not isinstance(source_version, int):
raise AssertionError(f"{name}: snapshot Session header has no integer format version")
records = [
normalize_session_format_comparison(expanded, source_version)
for record in parsed
for expanded in expand_snapshot_assistant_event(record)
]
return render_jsonl(records)
if name.endswith(".json"):
return json.dumps(
normalize_session_format_comparison(json.loads(content)),
indent=2,
ensure_ascii=False,
) + "\n"
return content
def compare_snapshot_files(
files: dict[str, str],
update: bool,
@@ -1817,25 +2118,52 @@ def compare_snapshot_files(
(directory / name).write_text(content, encoding="utf-8", newline="\n")
print(f"smoke-python-runtime: updated snapshots in {directory}")
existing = {
path.name
for path in directory.iterdir()
if path.is_file()
} if directory.is_dir() else set()
expected = set(filenames)
if existing != expected:
existing = [path for path in directory.iterdir() if path.is_file()] if directory.is_dir() else []
expected_non_session = {
name for name in filenames if parse_snapshot_session_filename(name) is None
}
existing_non_session = {
path.name for path in existing if parse_snapshot_session_filename(path.name) is None
}
if existing_non_session != expected_non_session:
raise AssertionError(
f"{scenario} snapshot files differ: "
f"missing={sorted(expected - existing)}, unexpected={sorted(existing - expected)}"
f"missing={sorted(expected_non_session - existing_non_session)}, "
f"unexpected={sorted(existing_non_session - expected_non_session)}"
)
selected_expected = selected_snapshot_session_files(directory)
actual_sessions: dict[int, tuple[str, str]] = {}
for name, content in files.items():
parsed = parse_snapshot_session_filename(name)
if parsed is None:
continue
index, filename_version = parsed
header_version = session_header_version(content, name)
if filename_version != header_version:
raise AssertionError(
f"{name}: filename declares Session format v{filename_version}, "
f"header declares v{header_version}",
)
if index in actual_sessions:
raise AssertionError(f"{scenario} snapshot builder produced duplicate Session role {index}")
actual_sessions[index] = (name, content)
if set(selected_expected) != set(actual_sessions):
raise AssertionError(
f"{scenario} snapshot Session roles differ: "
f"expected={sorted(selected_expected)}, actual={sorted(actual_sessions)}",
)
for name, actual in files.items():
expected_text = (directory / name).read_text(encoding="utf-8")
if actual == expected_text:
parsed = parse_snapshot_session_filename(name)
expected_path = directory / name if parsed is None else selected_expected[parsed[0]]
expected_text = expected_path.read_text(encoding="utf-8")
compared_actual = normalize_snapshot_comparison_text(name, actual)
compared_expected = normalize_snapshot_comparison_text(expected_path.name, expected_text)
if compared_actual == compared_expected:
continue
diff = "".join(difflib.unified_diff(
expected_text.splitlines(keepends=True),
actual.splitlines(keepends=True),
fromfile=f"expected/{name}",
compared_expected.splitlines(keepends=True),
compared_actual.splitlines(keepends=True),
fromfile=f"expected/{expected_path.name}",
tofile=f"actual/{name}",
))
raise AssertionError(
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
{"type":"session","version":0,"id":"{{child-1}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","origin":"subagent","delegationDepth":1}
{"type":"session","version":2,"id":"{{child-1}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","isSeeded":false,"origin":"subagent","delegationDepth":1}
{"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}}
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
{"type":"permission/preset","data":{"preset":"danger-full-access"}}
@@ -12,12 +12,7 @@
{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[8],"source":{"kind":"fallback"}}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","throughSeq":12}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"DIRECT_CHILD_OK"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[14,18]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":2,"throughSeq":12}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
@@ -1,4 +1,4 @@
{"type":"session","version":0,"id":"{{child-2}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","origin":"subagent","delegationDepth":1}
{"type":"session","version":2,"id":"{{child-2}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","isSeeded":false,"origin":"subagent","delegationDepth":1}
{"type":"sandbox/mode","data":{"mode":"danger-full-access","source":"delegation"}}
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
{"type":"permission/preset","data":{"preset":"danger-full-access"}}
@@ -12,12 +12,7 @@
{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[8],"source":{"kind":"fallback"}}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","throughSeq":12}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"WORKFLOW_CHILD_OK"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[14,18]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":2,"throughSeq":12}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
@@ -1,4 +1,4 @@
{"type":"session","version":0,"id":"{{parent}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0}
{"type":"session","version":2,"id":"{{parent}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0}
{"type":"permission/preset","data":{"preset":"danger-full-access"}}
{"type":"sandbox/mode","data":{"mode":"danger-full-access"}}
{"type":"approval/policy","data":{"policy":"never"}}
@@ -11,86 +11,51 @@
{"type":"session/title","data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[7],"source":{"kind":"fallback"}}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":11}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-define","name":"cordis_define","argumentsDelta":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[13,17]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":11}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-define","name":"cordis_define","args":["{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"advanced-define"},"content":[{"type":"tool-result","toolCallId":"advanced-define","content":[{"type":"text","text":"Defined snap-1/pkg-1 (Snapshot Double); it is not running yet. Use cordis_run to activate this Package."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1"}},"sourceEventSeqs":[19],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"advanced-define"},"content":[{"type":"tool-result","toolCallId":"advanced-define","content":[{"type":"text","text":"Defined snap-1/pkg-1 (Snapshot Double); it is not running yet. Use cordis_run to activate this Package."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1"}},"sourceEventSeqs":[14],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"step/start","data":{"turn":1,"step":2}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":22}}
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-run","name":"cordis_run","argumentsDelta":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[24,28]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":17}}
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-run","name":"cordis_run","args":["{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":2,"callId":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}
{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"advanced-run"},"content":[{"type":"tool-result","toolCallId":"advanced-run","content":[{"type":"text","text":"snap-1/pkg-1 is running (run-1)."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1","pluginRunId":"run-1"}},"sourceEventSeqs":[30],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"advanced-run"},"content":[{"type":"tool-result","toolCallId":"advanced-run","content":[{"type":"text","text":"snap-1/pkg-1 is running (run-1)."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1","pluginRunId":"run-1"}},"sourceEventSeqs":[20],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":2}}
{"type":"step/start","data":{"turn":1,"step":3}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"change"}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":34}}
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-code","name":"run_code","argumentsDelta":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[36,40]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":24}}
{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-code","name":"run_code","args":["{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}
{"type":"tool/code-dispatch-start","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21}}}
{"type":"tool/code-dispatch","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21},"isError":false,"content":[{"type":"text","text":"42"}]}}
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"advanced-code"},"content":[{"type":"tool-result","toolCallId":"advanced-code","content":[{"type":"text","text":"42"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[42],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"advanced-code"},"content":[{"type":"tool-result","toolCallId":"advanced-code","content":[{"type":"text","text":"42"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[27],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":3}}
{"type":"step/start","data":{"turn":1,"step":4}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":47}}
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-direct-child","name":"subagent","argumentsDelta":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[49,53]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":32}}
{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-direct-child","name":"subagent","args":["{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":4,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}
{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-direct-child"},"content":[{"type":"tool-result","toolCallId":"advanced-direct-child","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[55],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-direct-child"},"content":[{"type":"tool-result","toolCallId":"advanced-direct-child","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":4}}
{"type":"step/start","data":{"turn":1,"step":5}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":58}}
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-workflow","name":"workflow","argumentsDelta":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[60,64]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":38}}
{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-workflow","name":"workflow","args":["{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":5,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}
{"type":"tool-workflow/run-start","data":{"runId":"{{workflow-run}}","name":"advanced-exe-snapshot"}}
{"type":"tool-workflow/agent-start","data":{"runId":"{{workflow-run}}","seq":1,"label":"workflow-child","phase":"Delegate","childId":"{{child-2}}"}}
{"type":"tool-workflow/agent-end","data":{"runId":"{{workflow-run}}","seq":1,"outcome":"completed"}}
{"type":"tool-workflow/run-end","data":{"runId":"{{workflow-run}}","stopReason":"completed"}}
{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-exe-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[66],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-exe-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[41],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":5}}
{"type":"step/start","data":{"turn":1,"step":6}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":73}}
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-undefine","name":"cordis_undefine","argumentsDelta":"{\"pluginId\": \"snap-1\"}"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[75,79]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":48}}
{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-undefine","name":"cordis_undefine","args":["{\"pluginId\": \"snap-1\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":6,"callId":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}
{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"advanced-undefine"},"content":[{"type":"tool-result","toolCallId":"advanced-undefine","content":[{"type":"text","text":"Removed dynamic Plugin snap-1 and all of its Packages."}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[81],"surfaceOp":"append"}
{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"advanced-undefine"},"content":[{"type":"tool-result","toolCallId":"advanced-undefine","content":[{"type":"text","text":"Removed dynamic Plugin snap-1 and all of its Packages."}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[51],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":6}}
{"type":"step/start","data":{"turn":1,"step":7}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"change"}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":85}}
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_EXECUTABLE_OK"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[87,91]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":2,"throughSeq":55}}
{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["ADVANCED_EXECUTABLE_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":7}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
@@ -14,11 +14,6 @@
"request/header",
"request/context",
"session-log-deepseek/delivery-accepted",
"assistant/chunk",
"assistant/chunk",
"assistant/chunk",
"assistant/chunk",
"assistant/chunk",
"assistant/message",
"step/end",
"turn/end"
@@ -38,11 +33,6 @@
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.status"
]
},
@@ -61,11 +51,6 @@
"request/header",
"request/context",
"session-log-deepseek/delivery-accepted",
"assistant/chunk",
"assistant/chunk",
"assistant/chunk",
"assistant/chunk",
"assistant/chunk",
"assistant/message",
"step/end",
"turn/end"
@@ -85,11 +70,6 @@
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.event",
"session.status"
]
}
@@ -1,4 +1,4 @@
{"type":"session","version":0,"id":"{{session-1}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0}
{"type":"session","version":2,"id":"{{session-1}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0}
{"type":"permission/preset","data":{"preset":"danger-full-access"}}
{"type":"sandbox/mode","data":{"mode":"danger-full-access"}}
{"type":"approval/policy","data":{"policy":"never"}}
@@ -11,12 +11,7 @@
{"type":"session/title","data":{"title":"Complete the first isolated Python","messageSeqs":[7],"source":{"kind":"fallback"}}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-1}}","throughSeq":11}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"PROCESS_ONE_OK"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROCESS_ONE_OK"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_ONE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[13,17]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-1}}","sessionFormatVersion":2,"throughSeq":11}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_ONE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["PROCESS_ONE_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROCESS_ONE_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
@@ -1,4 +1,4 @@
{"type":"session","version":0,"id":"{{session-2}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0}
{"type":"session","version":2,"id":"{{session-2}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0}
{"type":"permission/preset","data":{"preset":"danger-full-access"}}
{"type":"sandbox/mode","data":{"mode":"danger-full-access"}}
{"type":"approval/policy","data":{"policy":"never"}}
@@ -11,12 +11,7 @@
{"type":"session/title","data":{"title":"Complete the second isolated Python","messageSeqs":[7],"source":{"kind":"fallback"}}}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-2}}","throughSeq":11}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"PROCESS_TWO_OK"}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROCESS_TWO_OK"}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}}}
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_TWO_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}},"sourceEventSeqs":[[13,17]],"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session-2}}","sessionFormatVersion":2,"throughSeq":11}}
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"PROCESS_TWO_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["PROCESS_TWO_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PROCESS_TWO_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":1}}
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
+10
View File
@@ -736,6 +736,11 @@
"symbol": "SessionReferenceMentionCandidate",
"source": "packages/context/session-reference/src/types.ts"
},
{
"doc": "docs/subsystems/session-reference.md",
"symbol": "SessionReferenceSource",
"source": "packages/context/session-reference/src/types.ts"
},
{
"doc": "docs/subsystems/session-reference.md",
"symbol": "PreparedReferencedMessage",
@@ -1906,6 +1911,11 @@
"symbol": "AgentStatus",
"source": "packages/core/agent/src/runtime-types.ts"
},
{
"doc": "docs/subsystems/core.md",
"symbol": "AssistantStreamFrame",
"source": "packages/core/agent/src/runtime-types.ts"
},
{
"doc": "docs/subsystems/core.md",
"symbol": "AgentOptions",