Merge remote-tracking branch 'origin/master' into feat/send-unify

# Conflicts:
#	docs/persistence-catalog.md
#	examples/acp-agent/tests/snapshots/code-mode-workspace-context/session.jsonl
#	examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl
#	examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/stdout.expected.jsonl
#	packages/context/time-context/tests/time-context.spec.ts
#	packages/cordis/tool-cordis/src/api-catalog.ts
This commit is contained in:
Turtle
2026-07-23 20:54:48 +08:00
430 changed files with 20734 additions and 5783 deletions

View File

@@ -10,6 +10,8 @@ The model-facing control surface for `ctx.tasks`: three kind-independent tools,
All three use generic ACP cards: `read` for output and list, `execute` for kill.
Their canonical values are `{ text, task }`, `PublicTaskSnapshot[]`, and `{ outcome: 'cancellation-requested' | 'already-finished', task }`. A public snapshot carries id, kind, label, status/detail, and start/finish times; it deliberately omits `ownerSession` and the internal `reported` notice bit. Native renderers preserve the status and acknowledgement text above.
## Completion notices
An unreported completion injects `background task <id> (<kind>: <label>) finished [status: ...]. Read its output with task_output.` into the exact owner's session. Injection is durable context for the next request, not a wake-up. A kill or terminal read/wait marks delivery reported and suppresses the redundant notice; owner-disposal races are contained.

View File

@@ -30,18 +30,61 @@ export const Config: z<Config> = z.object({
maxWaitTimeoutMs: z.number().min(1).default(600_000),
})
/** Task state safe for model-authored programs; ownership/bookkeeping fields are omitted. */
export interface PublicTaskSnapshot {
id: string
kind: string
label: string
status: TaskSnapshot['status']
detail?: string
startedAt: number
finishedAt?: number
}
/** Shared schema for task-control outputs. */
const PUBLIC_TASK_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
id: { type: 'string', required: true },
kind: { type: 'string', required: true },
label: { type: 'string', required: true },
status: {
type: 'string',
required: true,
enum: ['running', 'stopping', 'completed', 'killed', 'failed'],
},
detail: { type: 'string' },
startedAt: { type: 'integer', required: true },
finishedAt: { type: 'integer' },
},
} as const
/** Remove task ownership and notification bookkeeping from a registry snapshot. */
function publicTask(snapshot: TaskSnapshot): PublicTaskSnapshot {
return {
id: snapshot.id,
kind: snapshot.kind,
label: snapshot.label,
status: snapshot.status,
...snapshot.detail !== undefined ? { detail: snapshot.detail } : {},
startedAt: snapshot.startedAt,
...snapshot.finishedAt !== undefined ? { finishedAt: snapshot.finishedAt } : {},
}
}
/**
* Render generic status with optional producer detail.
* @param snapshot - task state to render.
* @returns a bracketed status line.
*/
export function statusLine(snapshot: TaskSnapshot): string {
export function statusLine(snapshot: Pick<TaskSnapshot, 'status' | 'detail'>): string {
return snapshot.detail !== undefined
? `[status: ${snapshot.status}, ${snapshot.detail}]`
: `[status: ${snapshot.status}]`
}
/** Validate the non-empty constraint that SchemaSpec cannot express. */
/** Validate the non-empty constraint that ParameterSchemaSpec cannot express. */
function validateTaskId(value: string): TaskId {
if (value.length === 0) {
throw new Error(`invalid task_id: expected a non-empty string, got ${JSON.stringify(value)}`)
@@ -98,6 +141,21 @@ export function apply(ctx: Context, config: Config): void {
wait: { type: 'boolean', description: 'Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive.' },
timeout_ms: { type: 'number', description: 'Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum.' },
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
text: { type: 'string', required: true },
task: { ...PUBLIC_TASK_SCHEMA, required: true },
},
},
render: (_args, value) => {
const body = value.text.length > 0 ? value.text : '(no new output)'
const separator = body.endsWith('\n') ? '' : '\n'
return [{ type: 'text', text: `${body}${separator}${statusLine(value.task)}` }]
},
},
async execute(args, exec) {
const id = validateTaskId(args.task_id)
if (args.wait === true) {
@@ -105,9 +163,7 @@ export function apply(ctx: Context, config: Config): void {
await ctx.tasks.wait(id, timeout, exec.agent, exec.signal)
}
const read = ctx.tasks.read(id, exec.agent)
const body = read.text.length > 0 ? read.text : '(no new output)'
const separator = body.endsWith('\n') ? '' : '\n'
return [{ type: 'text', text: `${body}${separator}${statusLine(read.snapshot)}` }]
return { text: read.text, task: publicTask(read.snapshot) }
},
presentCall: args => presentTaskCall(`Read output from background task ${args.task_id}`, 'read', args.task_id),
}))
@@ -116,12 +172,18 @@ export function apply(ctx: Context, config: Config): void {
name: 'task_list',
description: 'List your background tasks (running and finished) with their ids, kinds, and statuses.',
parameters: {},
output: {
schema: { type: 'array', items: PUBLIC_TASK_SCHEMA },
render: (_args, tasks) => [{
type: 'text',
text: tasks.length === 0
? '(no background tasks)'
: tasks.map(t => `${t.id} [${t.kind}] ${t.status}${t.label}`).join('\n'),
}],
},
execute(_args, exec) {
const tasks = ctx.tasks.list(exec.agent)
const text = tasks.length === 0
? '(no background tasks)'
: tasks.map(t => `${t.id} [${t.kind}] ${t.status}${t.label}`).join('\n')
return Promise.resolve([{ type: 'text', text }])
return Promise.resolve(tasks.map(publicTask))
},
presentCall: () => presentTaskCall('List background tasks', 'read'),
}))
@@ -133,15 +195,35 @@ export function apply(ctx: Context, config: Config): void {
task_id: { type: 'string', required: true, description: 'Task id returned by the tool that started the background work.' },
reason: { type: 'string', description: 'Optional short reason, recorded in the log and forwarded to the task.' },
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
outcome: {
type: 'string',
required: true,
enum: ['cancellation-requested', 'already-finished'],
},
task: { ...PUBLIC_TASK_SCHEMA, required: true },
},
},
render: (_args, value) => [{
type: 'text',
text: value.outcome === 'already-finished'
? `task ${value.task.id} had already finished ${statusLine(value.task)}`
: `requested cancellation of task ${value.task.id}`,
}],
},
execute(args, exec) {
const id = validateTaskId(args.task_id)
const result = ctx.tasks.kill(id, exec.agent, args.reason)
if (result === 'already-finished') {
// A snapshot describes terminal state without consuming pending output.
const snapshot = ctx.tasks.get(id, exec.agent)
return Promise.resolve([{ type: 'text', text: `task ${id} had already finished ${statusLine(snapshot)}` }])
}
return Promise.resolve([{ type: 'text', text: `requested cancellation of task ${id}` }])
// A snapshot describes current state without consuming pending output.
const snapshot = publicTask(ctx.tasks.get(id, exec.agent))
return Promise.resolve({
outcome: result === 'already-finished' ? 'already-finished' as const : 'cancellation-requested' as const,
task: snapshot,
})
},
presentCall: args => presentTaskCall(`Kill background task ${args.task_id}`, 'execute', args.task_id),
}))

View File

@@ -116,7 +116,16 @@ describe('task_output', () => {
ctx.tasks.start(producer({ readOutput: () => chunks.shift() ?? '' }).spec)
// A body already ending in a newline gets no doubled separator.
expect(text(await call(ctx, 'task_output', { task_id: 'bash-1' }))).toBe('line one\n[status: running]')
const first = await call(ctx, 'task_output', { task_id: 'bash-1' })
if (first.isError) throw new Error('expected task_output success')
const firstValue = first.value as { text: string; task: Record<string, unknown> }
expect(firstValue).toMatchObject({
text: 'line one\n',
task: { id: 'bash-1', kind: 'bash', label: 'sleep 60', status: 'running' },
})
expect(firstValue.task).not.toHaveProperty('ownerSession')
expect(firstValue.task).not.toHaveProperty('reported')
expect(text(first)).toBe('line one\n[status: running]')
expect(text(await call(ctx, 'task_output', { task_id: 'bash-1' }))).toBe('(no new output)\n[status: running]')
})
@@ -173,7 +182,17 @@ describe('task_list', () => {
p.settle({ status: 'completed', detail: 'exit code: 0' })
await tick()
expect(text(await call(ctx, 'task_list', {}, alice))).toBe([
const listed = await call(ctx, 'task_list', {}, alice)
if (listed.isError) throw new Error('expected task_list success')
const listedValue = listed.value as Array<Record<string, unknown>>
expect(listedValue).toHaveLength(3)
expect(listedValue[0]).toMatchObject({ id: 'bash-1', kind: 'bash', label: 'pnpm test', status: 'running' })
expect(listedValue[2]).toMatchObject({ id: 'bash-2', kind: 'bash', label: 'build', status: 'completed', detail: 'exit code: 0' })
for (const task of listedValue) {
expect(task).not.toHaveProperty('ownerSession')
expect(task).not.toHaveProperty('reported')
}
expect(text(listed)).toBe([
'bash-1 [bash] running — pnpm test',
'subagent-1 [subagent] running — open research',
'bash-2 [bash] completed — build',
@@ -191,6 +210,14 @@ describe('task_kill', () => {
ctx.tasks.start(p.spec)
const result = await call(ctx, 'task_kill', { task_id: 'bash-1', reason: 'superseded' })
if (result.isError) throw new Error('expected task_kill success')
const killValue = result.value as { outcome: string; task: Record<string, unknown> }
expect(killValue).toMatchObject({
outcome: 'cancellation-requested',
task: { id: 'bash-1', kind: 'bash', label: 'sleep 60', status: 'stopping' },
})
expect(killValue.task).not.toHaveProperty('ownerSession')
expect(killValue.task).not.toHaveProperty('reported')
expect(text(result)).toBe('requested cancellation of task bash-1')
expect(p.cancels).toEqual(['superseded'])
})
@@ -203,8 +230,13 @@ describe('task_kill', () => {
p.settle({ status: 'completed', detail: 'exit code: 0' })
await tick()
expect(text(await call(ctx, 'task_kill', { task_id: 'bash-1' })))
.toBe('task bash-1 had already finished [status: completed, exit code: 0]')
const killed = await call(ctx, 'task_kill', { task_id: 'bash-1' })
if (killed.isError) throw new Error('expected task_kill success')
expect(killed.value).toMatchObject({
outcome: 'already-finished',
task: { id: 'bash-1', kind: 'bash', label: 'sleep 60', status: 'completed', detail: 'exit code: 0' },
})
expect(text(killed)).toBe('task bash-1 had already finished [status: completed, exit code: 0]')
// The kill described the task via a non-consuming snapshot: the delta is intact.
expect(text(await call(ctx, 'task_output', { task_id: 'bash-1' }))).toBe('unread tail\n[status: completed, exit code: 0]')
})