Enable maximum-strict TypeScript across our packages

tsconfig.base.json adds noUncheckedIndexedAccess,
exactOptionalPropertyTypes, noImplicitOverride,
noFallthroughCasesInSwitch, noUnusedLocals, and noUnusedParameters on
top of strict. Vendored packages opt out of the new flags locally
(their tsconfigs are ours to regenerate; their source is not), keeping
upstream-sync friendliness.

Our code fixed accordingly: index accesses acknowledge undefined
(assembler flush cursors, lastTurnNumber); optional properties are
omitted instead of set-to-undefined (GenerateResult.usage,
ToolDefinition.strict, GenerateOptions.system/tools, error payloads
via an errorData helper); Session.onAppend is explicitly
`(…) => void | undefined`; tests and examples updated for unused
parameters and indexed access.
This commit is contained in:
Tianyi Cui
2026-06-11 14:02:47 +08:00
parent 2b447625fa
commit d2fb352f3e
21 changed files with 214 additions and 86 deletions

View File

@@ -11,7 +11,7 @@ export const inject = ['agents']
* is "just a plugin" — it only consumes the agent/* event taxonomy.
*/
export function apply(ctx: Context) {
ctx.on('agent/stream-chunk', (agent, _turn, _step, chunk) => {
ctx.on('agent/stream-chunk', (_agent, _turn, _step, chunk) => {
if (chunk.type === 'text-delta') process.stdout.write(chunk.text)
})

View File

@@ -18,6 +18,19 @@ import type { LoopAgent } from './agent.ts'
/** An Error with an optional machine-readable code (e.g., from LlmError or a throwing plugin). */
type CodedError = Error & { code?: string }
/** Normalize an arbitrary thrown value into a (possibly coded) Error. */
function toError(error: unknown): CodedError {
return error instanceof Error ? error : new Error(String(error))
}
/**
* Build the `{ message, code? }` part of an error payload, omitting the
* `code` key entirely when absent (exactOptionalPropertyTypes-correct).
*/
function errorData(err: CodedError): { message: string; code?: string } {
return { message: err.message, ...typeof err.code === 'string' ? { code: err.code } : {} }
}
/**
* Ambient handles the loop driver receives from the agent. Decouples the
* pure function `runLoop` from the mutable LoopAgent fields, making the
@@ -79,8 +92,8 @@ export async function runLoop(ctx: Context, agent: LoopAgent, handle: LoopHandle
// Backstop: a throwing emit listener (turn boundaries) or a broken
// finalizer must not kill the driver. Record what we can and move on.
try {
const err: CodedError = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step: 0, message: err.message, code: err.code })
const err = toError(error)
session.append('error', { turn, step: 0, ...errorData(err) })
ctx.emit('agent/error', agent, turn, 0, err)
} catch { /* the error path itself is broken; nothing left to do */ }
}
@@ -146,9 +159,9 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
reason = { kind: 'aborted', reason: String(abort.signal.reason ?? 'aborted') }
} else {
const coded = error as CodedError
session.append('error', { turn, step, message: coded.message, code: coded.code })
session.append('error', { turn, step, ...errorData(coded) })
ctx.emit('agent/error', agent, turn, step, error)
reason = { kind: 'error', message: coded.message, code: coded.code }
reason = { kind: 'error', ...errorData(coded) }
}
break
}
@@ -168,10 +181,10 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
)
} catch (error: unknown) {
// A broken continuation plugin ends the turn, not the loop.
const err: CodedError = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step, message: err.message, code: err.code })
const err = toError(error)
session.append('error', { turn, step, ...errorData(err) })
ctx.emit('agent/error', agent, turn, step, err)
reason = { kind: 'error', message: err.message, code: err.code }
reason = { kind: 'error', ...errorData(err) }
break
}
@@ -194,8 +207,8 @@ async function runTurn(ctx: Context, agent: LoopAgent, handle: LoopHandle, turn:
try {
await ctx.parallel('session/flush', session)
} catch (error: unknown) {
const err: CodedError = error instanceof Error ? error : new Error(String(error))
session.append('error', { turn, step, message: err.message, code: err.code })
const err = toError(error)
session.append('error', { turn, step, ...errorData(err) })
ctx.emit('agent/error', agent, turn, step, err)
}
}
@@ -229,8 +242,8 @@ async function runStep(
let request: GenerateOptions = {
model: options.model ?? '',
messages: session.deriveMessages(),
system: system || undefined,
tools: assembly.tools.length > 0 ? assembly.tools : undefined,
...system ? { system } : {},
...assembly.tools.length > 0 ? { tools: assembly.tools } : {},
signal,
}
request = await ctx.waterfall('agent/request', agent, turn, step, request, async () => request)
@@ -293,7 +306,7 @@ async function runStep(
/** The last turn number in a (possibly seeded) session log, or 0. */
function lastTurnNumber(session: Session): number {
for (let index = session.events.length - 1; index >= 0; index--) {
const event = session.events[index]
const event = session.events[index]!
if (event.type === 'turn/start') return event.data.turn
}
return 0

View File

@@ -67,7 +67,7 @@ describe('agent loop', () => {
// derived history: user + assistant
const messages = agent.session.deriveMessages()
expect(messages.map(m => m.role)).toEqual(['user', 'assistant'])
expect(messages[1].content).toEqual([{ type: 'text', text: 'hello there' }])
expect(messages[1]!.content).toEqual([{ type: 'text', text: 'hello there' }])
})
it('round-trips tool calls: model requests tool → executes → result in next request', async () => {
@@ -93,7 +93,7 @@ describe('agent loop', () => {
expect(adapter.requests).toHaveLength(2)
// the second request's derived history contains the tool result
const secondMessages = adapter.requests[1].messages
const secondMessages = adapter.requests[1]!.messages
const toolResultMessage = secondMessages.find(m =>
m.content.some(b => b.type === 'tool-result'))
expect(toolResultMessage).toBeDefined()
@@ -125,8 +125,8 @@ describe('agent loop', () => {
await waitForIdle(ctx, agent)
const request = adapter.requests[0]
expect(request.system).toBe('You are a test agent.\n\nAgent-specific suffix.')
expect(request.tools?.map(t => t.name)).toEqual(['noop'])
expect(request!.system).toBe('You are a test agent.\n\nAgent-specific suffix.')
expect(request!.tools?.map(t => t.name)).toEqual(['noop'])
})
it('records raw chunks for replay and emits agent/stream-chunk', async () => {
@@ -185,7 +185,7 @@ describe('agent loop', () => {
// the second model request saw the steering content
const secondRequest = adapter.requests[1]
const flat = JSON.stringify(secondRequest.messages)
const flat = JSON.stringify(secondRequest!.messages)
expect(flat).toContain('change of plans')
})
@@ -212,7 +212,7 @@ describe('agent loop', () => {
send(agent, 'go')
await waitForIdle(ctx, agent)
const flat = JSON.stringify(adapter.requests[0].messages)
const flat = JSON.stringify(adapter.requests[0]!.messages)
expect(flat).toContain('file changed: a.ts')
expect(flat).toContain('<context source=\\"plugin\\">')
})
@@ -276,7 +276,7 @@ describe('agent loop', () => {
send(agent, 'hi')
await waitForIdle(ctx, agent)
expect(adapter.requests[0].model).toBe('other-model')
expect(adapter.requests[0]!.model).toBe('other-model')
})
it('abort() mid-stream ends the turn with reason aborted', async () => {
@@ -356,7 +356,7 @@ describe('agent loop', () => {
await waitForIdle(ctx, agent)
expect(errors).toHaveLength(1)
expect(errors[0].message).toContain('script exhausted')
expect(errors[0]!.message).toContain('script exhausted')
expect(reasons[0]).toMatchObject({ kind: 'error' })
expect(agent.session.events.some(e => e.type === 'error')).toBe(true)
})

View File

@@ -59,7 +59,7 @@ export class MockAdapter extends LlmAdapter {
if (entry === 'hang') {
yield { type: 'block-start', index: 0, blockType: 'text' }
yield { type: 'text-delta', index: 0, text: 'partial' }
await new Promise<void>((resolve, reject) => {
await new Promise<void>((_resolve, reject) => {
if (options.signal?.aborted) return reject(new Error('aborted'))
options.signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true })
})

View File

@@ -58,7 +58,7 @@ describe('HIGH: session log records what agent/step-result actually produced', (
// Plugin rewrites the message: replaces the text AND adds a tool call.
let rewritten = false
ctx.on('agent/step-result', async (_agent, _turn, _step, message, next) => {
ctx.on('agent/step-result', async (_agent, _turn, _step, _message, next) => {
if (rewritten) return next()
rewritten = true
return {
@@ -166,7 +166,7 @@ describe('HIGH: steering from late extension points is never stranded', () => {
await waitForIdle(ctx, agent)
expect(adapter.requests).toHaveLength(2)
expect(JSON.stringify(adapter.requests[1].messages)).toContain('goal reminder from step-end')
expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('goal reminder from step-end')
})
it('steer() from an agent/turn-continuation listener overrides a stop decision', async () => {
@@ -191,7 +191,7 @@ describe('HIGH: steering from late extension points is never stranded', () => {
// the default decision was false (no tools), but steering forced step 2
expect(adapter.requests).toHaveLength(2)
expect(JSON.stringify(adapter.requests[1].messages)).toContain('one more thing')
expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('one more thing')
})
it('steer() from an agent/turn-end listener becomes a queued message for the next turn', async () => {
@@ -216,7 +216,7 @@ describe('HIGH: steering from late extension points is never stranded', () => {
expect(turns).toEqual([1, 2])
expect(adapter.requests).toHaveLength(2)
expect(JSON.stringify(adapter.requests[1].messages)).toContain('too late for this turn')
expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('too late for this turn')
})
it('steering queued during an aborted step is re-delivered, not silently consumed', async () => {
@@ -232,7 +232,7 @@ describe('HIGH: steering from late extension points is never stranded', () => {
// a new turn ran with the steering content delivered as a message
expect(adapter.requests).toHaveLength(2)
expect(JSON.stringify(adapter.requests[1].messages)).toContain('redirect')
expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('redirect')
})
})
@@ -361,8 +361,8 @@ describe('MEDIUM: misc registry and config fixes', () => {
send(agent, 'go')
await waitForIdle(ctx, agent)
expect(errors).toHaveLength(1)
expect(errors[0].message).toContain('has no model')
expect(errors[0].message).toContain('agent/request')
expect(errors[0]!.message).toContain('has no model')
expect(errors[0]!.message).toContain('agent/request')
})
it('the agent/request waterfall can supply the model for a model-less agent', async () => {

View File

@@ -123,7 +123,8 @@ export class BlockAssembler {
flushReady(): ContentBlock[] {
const ready: ContentBlock[] = []
while (this.flushed < this.order.length) {
const partial = this.partials.get(this.order[this.flushed])!
const index = this.order[this.flushed]!
const partial = this.partials.get(index)!
if (!partial.block) break
ready.push(partial.block)
this.flushed += 1
@@ -140,7 +141,7 @@ export class BlockAssembler {
flushRemaining(): ContentBlock[] {
const remaining: ContentBlock[] = []
while (this.flushed < this.order.length) {
const index = this.order[this.flushed]
const index = this.order[this.flushed]!
remaining.push(this.assemble(this.partials.get(index)!, index))
this.flushed += 1
}
@@ -162,6 +163,10 @@ export class BlockAssembler {
/** The assembled non-streaming result. */
result(): GenerateResult {
return { message: this.message(), usage: this._usage, finish: this.finish }
return {
message: this.message(),
...this._usage !== undefined ? { usage: this._usage } : {},
finish: this.finish,
}
}
}

View File

@@ -57,7 +57,7 @@ describe('LlmService', () => {
await ctx.plugin(LlmService)
ctx.llm.registerAdapter(['test-model'], new ScriptedAdapter(SCRIPT))
ctx.on('llm/stream', function (options, next) {
ctx.on('llm/stream', function (_options, next) {
const inner = next()
return (async function * () {
yield { type: 'block-start', index: 99, blockType: 'text' } satisfies StreamChunk

View File

@@ -57,8 +57,8 @@ function renderTagged(tag: string, content: ContentBlock[], source: MessageSourc
*/
export class Session {
private log: SessionEvent[] = []
/** Set by the store so appends are observable; no-op when detached. */
onAppend?: (event: SessionEvent) => void
/** Set by the store so appends are observable; undefined when detached. */
onAppend: ((event: SessionEvent) => void) | undefined
constructor(public readonly id: string, seed?: SessionEvent[]) {
if (seed) this.log = [...seed]

View File

@@ -21,8 +21,8 @@ describe('Session', () => {
const messages = session.deriveMessages()
expect(messages.map(m => m.role)).toEqual(['user', 'assistant', 'user'])
// raw chunks must NOT appear in derived history
expect(messages[1].content).toHaveLength(2)
expect(messages[2].content[0]).toMatchObject({ type: 'tool-result', toolCallId: 'c1' })
expect(messages[1]!.content).toHaveLength(2)
expect(messages[2]!.content[0]).toMatchObject({ type: 'tool-result', toolCallId: 'c1' })
})
it('renders context and steering messages as tagged synthetic user content', () => {
@@ -38,10 +38,10 @@ describe('Session', () => {
})
const [contextMessage, steeringMessage] = session.deriveMessages()
expect(contextMessage.role).toBe('user')
expect(contextMessage.content[0]).toMatchObject({ type: 'text', text: '<context source="plugin">' })
expect(contextMessage.content.at(-1)).toMatchObject({ type: 'text', text: '</context>' })
expect(steeringMessage.content[0]).toMatchObject({ type: 'text', text: '<steering source="user">' })
expect(contextMessage!.role).toBe('user')
expect(contextMessage!.content[0]).toMatchObject({ type: 'text', text: '<context source="plugin">' })
expect(contextMessage!.content.at(-1)).toMatchObject({ type: 'text', text: '</context>' })
expect(steeringMessage!.content[0]).toMatchObject({ type: 'text', text: '<steering source="user">' })
})
it('replays identically from a seeded event log', () => {
@@ -70,8 +70,8 @@ describe('SessionStore', () => {
session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } })
expect(events).toHaveLength(1)
expect(events[0][0]).toBe(session)
expect(events[0][1].type).toBe('user/message')
expect(events[0]![0]).toBe(session)
expect(events[0]![1].type).toBe('user/message')
expect(ctx.sessions.get(session.id)).toBe(session)
expect(ctx.sessions.list()).toEqual([session])

View File

@@ -223,7 +223,7 @@ export function defineTool<S extends SchemaSpec>(options: DefineToolOptions<S>):
name: options.name,
description: options.description,
parameters: schemaSpecToJsonSchema(options.parameters) as unknown as Record<string, unknown>,
strict: options.strict,
...options.strict !== undefined ? { strict: options.strict } : {},
execute: options.execute as ToolDefinition['execute'],
}
}

View File

@@ -90,13 +90,13 @@ describe('ToolRegistry', () => {
ctx.tools.register(echoTool)
const order: string[] = []
ctx.on('tools/execute', async (exec, next) => {
ctx.on('tools/execute', async (_exec, next) => {
order.push('first:before')
const result = await next()
order.push('first:after')
return result
})
ctx.on('tools/execute', async (exec, next) => {
ctx.on('tools/execute', async (_exec, next) => {
order.push('second:before')
const result = await next()
order.push('second:after')
@@ -251,7 +251,7 @@ describe('defineTool / schema DSL', () => {
// Schema round-trip: schemas() returns standard JSON Schema
const schemas = ctx.tools.schemas()
expect(schemas).toHaveLength(1)
expect(schemas[0].parameters).toEqual({
expect(schemas[0]!.parameters).toEqual({
type: 'object',
properties: {
req: { type: 'string' },
@@ -287,7 +287,7 @@ describe('defineTool / schema DSL', () => {
})
const schemas = ctx.tools.schemas()
expect(schemas[0].parameters).toEqual({
expect(schemas[0]!.parameters).toEqual({
type: 'object',
properties: { path: { type: 'string' } },
required: ['path'],

View File

@@ -10,7 +10,14 @@
"skipLibCheck": true,
"esModuleInterop": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": false,
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"types": ["node"]
}
}

View File

@@ -5,10 +5,19 @@
"outDir": "lib",
"noImplicitAny": false,
"noImplicitThis": false,
"strictFunctionTypes": false
"strictFunctionTypes": false,
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" }
{
"path": "../cosmokit"
}
]
}

View File

@@ -2,7 +2,14 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
"outDir": "lib",
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"]
"include": [
"src"
]
}

View File

@@ -2,11 +2,22 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
"outDir": "lib",
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cordis" },
{ "path": "../loader" }
{
"path": "../cordis"
},
{
"path": "../loader"
}
]
}

View File

@@ -2,15 +2,34 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
"outDir": "lib",
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" },
{ "path": "../cordis" },
{ "path": "../loader" },
{ "path": "../include" },
{ "path": "../timer" },
{ "path": "../schemastery" }
{
"path": "../cosmokit"
},
{
"path": "../cordis"
},
{
"path": "../loader"
},
{
"path": "../include"
},
{
"path": "../timer"
},
{
"path": "../schemastery"
}
]
}

View File

@@ -3,12 +3,25 @@
"compilerOptions": {
"rootDir": "src",
"outDir": "lib",
"noImplicitAny": false
"noImplicitAny": false,
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" },
{ "path": "../cordis" },
{ "path": "../loader" }
{
"path": "../cosmokit"
},
{
"path": "../cordis"
},
{
"path": "../loader"
}
]
}

View File

@@ -3,11 +3,22 @@
"compilerOptions": {
"rootDir": "src",
"outDir": "lib",
"noImplicitAny": false
"noImplicitAny": false,
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" },
{ "path": "../cordis" }
{
"path": "../cosmokit"
},
{
"path": "../cordis"
}
]
}

View File

@@ -2,12 +2,25 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
"outDir": "lib",
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" },
{ "path": "../cordis" },
{ "path": "../schemastery" }
{
"path": "../cosmokit"
},
{
"path": "../cordis"
},
{
"path": "../schemastery"
}
]
}

View File

@@ -3,10 +3,19 @@
"compilerOptions": {
"rootDir": "src",
"outDir": "lib",
"module": "preserve"
"module": "preserve",
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" }
{
"path": "../cosmokit"
}
]
}

View File

@@ -2,11 +2,22 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
"outDir": "lib",
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": false,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"],
"include": [
"src"
],
"references": [
{ "path": "../cosmokit" },
{ "path": "../cordis" }
{
"path": "../cosmokit"
},
{
"path": "../cordis"
}
]
}