feat(workflow): show durable run records in Chat
This commit is contained in:
@@ -15,8 +15,15 @@ import z from 'schemastery'
|
||||
import { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
|
||||
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
||||
import type { JsonValue } from '@deepseek-ai/dsh-session'
|
||||
import type { WorkflowResult, WorkflowRun } from '@deepseek-ai/dsh-workflow'
|
||||
import type { JsonValue, Session, SessionEventMap } from '@deepseek-ai/dsh-session'
|
||||
import type {
|
||||
WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowResult, WorkflowRun,
|
||||
WorkflowRunId, WorkflowRunInfo, WorkflowStopReason,
|
||||
} from '@deepseek-ai/dsh-workflow'
|
||||
import type {
|
||||
ToolWorkflowAgentEndData, ToolWorkflowAgentStartData,
|
||||
ToolWorkflowRunEndData, ToolWorkflowRunStartData,
|
||||
} from './types.ts'
|
||||
// Declaration merge only: makes ctx.systemPrompt visible for the section registration.
|
||||
import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
|
||||
@@ -38,6 +45,114 @@ export const Config: z<Config> = z.object({
|
||||
|
||||
type ResolvedConfig = Required<Config>
|
||||
|
||||
type BufferedWorkflowEvent =
|
||||
| { readonly kind: 'agent-start'; readonly info: WorkflowRunInfo; readonly agent: WorkflowAgentInfo }
|
||||
| { readonly kind: 'agent-end'; readonly info: WorkflowRunInfo; readonly agent: WorkflowAgentEndInfo }
|
||||
|
||||
interface WorkflowRecorder {
|
||||
bind(run: WorkflowRun): void
|
||||
finish(stopReason: WorkflowStopReason): void
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
interface ToolWorkflowRecordEventMap {
|
||||
'tool-workflow/run-start': ToolWorkflowRunStartData
|
||||
'tool-workflow/agent-start': ToolWorkflowAgentStartData
|
||||
'tool-workflow/agent-end': ToolWorkflowAgentEndData
|
||||
'tool-workflow/run-end': ToolWorkflowRunEndData
|
||||
}
|
||||
|
||||
/** Render a contained recording failure without trusting the thrown value. */
|
||||
function renderRecordingError(error: unknown): string {
|
||||
try {
|
||||
return String(error)
|
||||
} catch {
|
||||
return '[unrenderable thrown value]'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Project one top-level workflow run into its parent Session without letting
|
||||
* recording failure affect tool execution. Listeners are installed before
|
||||
* `start()` so even a synchronous provider cannot outrun the recorder.
|
||||
*/
|
||||
function createWorkflowRecorder(ctx: Context, session: Session): WorkflowRecorder {
|
||||
let runId: WorkflowRunId | undefined
|
||||
let enabled = true
|
||||
const buffered: BufferedWorkflowEvent[] = []
|
||||
// These four package-owned events are all log-only. Narrowing the generic
|
||||
// append face here lets TypeScript discharge Session.append's conditional
|
||||
// surface-options tuple once for the complete closed event set.
|
||||
const appendRecord = session.append.bind(session) as <Type extends keyof ToolWorkflowRecordEventMap>(
|
||||
type: Type,
|
||||
data: SessionEventMap[Type],
|
||||
) => void
|
||||
|
||||
const append = <Type extends keyof ToolWorkflowRecordEventMap>(
|
||||
type: Type,
|
||||
data: SessionEventMap[Type],
|
||||
): void => {
|
||||
if (!enabled) return
|
||||
try {
|
||||
appendRecord(type, data)
|
||||
} catch (error: unknown) {
|
||||
enabled = false
|
||||
ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const record = (event: BufferedWorkflowEvent): void => {
|
||||
if (runId === undefined) {
|
||||
buffered.push(event)
|
||||
return
|
||||
}
|
||||
if (event.info.id !== runId) return
|
||||
if (event.kind === 'agent-start') {
|
||||
const data: ToolWorkflowAgentStartData = {
|
||||
runId,
|
||||
seq: event.agent.seq,
|
||||
label: event.agent.label,
|
||||
...event.agent.phase === undefined ? {} : { phase: event.agent.phase },
|
||||
childId: event.agent.childId,
|
||||
}
|
||||
append('tool-workflow/agent-start', data)
|
||||
return
|
||||
}
|
||||
const data: ToolWorkflowAgentEndData = {
|
||||
runId,
|
||||
seq: event.agent.seq,
|
||||
outcome: event.agent.outcome,
|
||||
}
|
||||
append('tool-workflow/agent-end', data)
|
||||
}
|
||||
|
||||
const disposeStart = ctx.on('workflow/agent-start', (info, agent) => {
|
||||
record({ kind: 'agent-start', info, agent })
|
||||
})
|
||||
const disposeEnd = ctx.on('workflow/agent-end', (info, agent) => {
|
||||
record({ kind: 'agent-end', info, agent })
|
||||
})
|
||||
|
||||
return {
|
||||
bind(run) {
|
||||
runId = run.id
|
||||
append('tool-workflow/run-start', { runId, name: run.meta.name })
|
||||
for (const event of buffered) record(event)
|
||||
buffered.length = 0
|
||||
},
|
||||
finish(stopReason) {
|
||||
/* v8 ignore next -- execute binds every returned run before result settlement can call finish. */
|
||||
if (runId === undefined) return
|
||||
append('tool-workflow/run-end', { runId, stopReason })
|
||||
},
|
||||
dispose() {
|
||||
disposeStart()
|
||||
disposeEnd()
|
||||
buffered.length = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The script-authoring contract, embedded in the tool description. This IS the
|
||||
* model-facing spec: the meta block, the hooks and their exact semantics, and
|
||||
@@ -188,13 +303,23 @@ export function apply(ctx: Context, config: Config): void {
|
||||
// Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
|
||||
// synchronously here and become isError results via the registry — the
|
||||
// model sees the violation list and can correct the call.
|
||||
const run: WorkflowRun = ctx.workflows.start({
|
||||
script: args.script,
|
||||
meta: args.meta,
|
||||
...args.args !== undefined ? { args: args.args } : {},
|
||||
parent,
|
||||
signal: exec.signal,
|
||||
})
|
||||
const recorder = exec.parent === undefined
|
||||
? createWorkflowRecorder(ctx, parent.session)
|
||||
: undefined
|
||||
let run: WorkflowRun
|
||||
try {
|
||||
run = ctx.workflows.start({
|
||||
script: args.script,
|
||||
meta: args.meta,
|
||||
...args.args !== undefined ? { args: args.args } : {},
|
||||
parent,
|
||||
signal: exec.signal,
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
recorder?.dispose()
|
||||
throw error
|
||||
}
|
||||
recorder?.bind(run)
|
||||
|
||||
// Bridge the tool's abort signal to the run: if the parent step is aborted while the
|
||||
// script is in flight, cancel the whole run. The signal also enters the engine directly, but
|
||||
@@ -202,8 +327,9 @@ export function apply(ctx: Context, config: Config): void {
|
||||
const onAbort = (): void => { run.cancel('parent step aborted') }
|
||||
exec.signal.addEventListener('abort', onAbort, { once: true })
|
||||
|
||||
let result: WorkflowResult | undefined
|
||||
try {
|
||||
const result = await run.result
|
||||
result = await run.result
|
||||
const error = stopReasonError(result)
|
||||
if (error !== undefined) {
|
||||
// Map a non-clean finish to an isError result (the registry turns a
|
||||
@@ -217,8 +343,15 @@ export function apply(ctx: Context, config: Config): void {
|
||||
}
|
||||
} finally {
|
||||
exec.signal.removeEventListener('abort', onAbort)
|
||||
// Always reach run quiescence — never leak a live script or children.
|
||||
await run.dispose()
|
||||
try {
|
||||
// Keep member listeners alive through disposal: an engine may
|
||||
// synthesize cancelled member endings while reaching quiescence.
|
||||
await run.dispose()
|
||||
/* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
|
||||
if (result !== undefined) recorder?.finish(result.stopReason)
|
||||
} finally {
|
||||
recorder?.dispose()
|
||||
}
|
||||
}
|
||||
},
|
||||
presentCall: args => presentWorkflowCall(args),
|
||||
|
||||
@@ -1,30 +1,158 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-workflow`.
|
||||
* @module @deepseek-ai/dsh-tool-workflow/invariant
|
||||
*/
|
||||
/** Package-owned durable workflow-record invariants. @module @deepseek-ai/dsh-tool-workflow/invariant */
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
import type {} from './types.ts'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-tool-workflow'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'tool-workflow-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
/** Services required to validate existing and newly appended Session logs. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this model-facing adapter has no independent lifecycle stream; execution
|
||||
* relations are owned by the capability seam it calls.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
interface RunTrace {
|
||||
ended: boolean
|
||||
readonly members: Map<number, boolean>
|
||||
}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
type WorkflowTrace = Map<string, RunTrace>
|
||||
|
||||
/** Clone the independent fold before validating one candidate append. */
|
||||
function cloneTrace(source: WorkflowTrace): WorkflowTrace {
|
||||
return new Map([...source].map(([runId, run]) => [runId, {
|
||||
ended: run.ended,
|
||||
members: new Map(run.members),
|
||||
}]))
|
||||
}
|
||||
|
||||
/** Require a durable opaque identity to be a non-empty string. */
|
||||
function stringId(value: unknown, label: string, fail: InvariantFailure): string {
|
||||
if (typeof value !== 'string' || value.length === 0) fail(`${label} must be a non-empty string`)
|
||||
return value
|
||||
}
|
||||
|
||||
/** Require one workflow member's 1-based sequence identity. */
|
||||
function memberSeq(value: unknown, fail: InvariantFailure): number {
|
||||
if (!Number.isSafeInteger(value) || (value as number) < 1) {
|
||||
fail('tool-workflow member seq must be a positive safe integer')
|
||||
}
|
||||
return value as number
|
||||
}
|
||||
|
||||
/** Read one plain payload field without trusting restored plugin data. */
|
||||
function recordOf(event: SessionEvent, fail: InvariantFailure): Record<string, unknown> {
|
||||
const data: unknown = event.data
|
||||
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
||||
fail(`${event.type} data must be a JSON object`)
|
||||
}
|
||||
return data as Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Require the named run to exist and remain open. */
|
||||
function openRun(trace: WorkflowTrace, runId: string, eventType: string, fail: InvariantFailure): RunTrace {
|
||||
const run = trace.get(runId)
|
||||
if (run === undefined) fail(`${eventType} has no matching tool-workflow/run-start for run ${runId}`)
|
||||
if (run.ended) fail(`${eventType} appears after tool-workflow/run-end for run ${runId}`)
|
||||
return run
|
||||
}
|
||||
|
||||
/** Advance the workflow-record fold with one relevant Session event. */
|
||||
function applyEvent(trace: WorkflowTrace, event: SessionEvent, fail: InvariantFailure): void {
|
||||
if (!event.type.startsWith('tool-workflow/')) return
|
||||
const data = recordOf(event, fail)
|
||||
const runId = stringId(data.runId, `${event.type} runId`, fail)
|
||||
|
||||
switch (event.type) {
|
||||
case 'tool-workflow/run-start': {
|
||||
if (typeof data.name !== 'string' || data.name.length === 0) {
|
||||
fail('tool-workflow/run-start name must be a non-empty string')
|
||||
}
|
||||
if (trace.has(runId)) fail(`tool-workflow/run-start repeats run ${runId}`)
|
||||
trace.set(runId, { ended: false, members: new Map() })
|
||||
return
|
||||
}
|
||||
case 'tool-workflow/agent-start': {
|
||||
const run = openRun(trace, runId, event.type, fail)
|
||||
const seq = memberSeq(data.seq, fail)
|
||||
if (typeof data.label !== 'string') fail('tool-workflow/agent-start label must be a string')
|
||||
if (data.phase !== undefined && typeof data.phase !== 'string') {
|
||||
fail('tool-workflow/agent-start phase must be a string when present')
|
||||
}
|
||||
stringId(data.childId, 'tool-workflow/agent-start childId', fail)
|
||||
if (run.members.has(seq)) fail(`tool-workflow/agent-start repeats member seq ${seq} in run ${runId}`)
|
||||
run.members.set(seq, false)
|
||||
return
|
||||
}
|
||||
case 'tool-workflow/agent-end': {
|
||||
const run = openRun(trace, runId, event.type, fail)
|
||||
const seq = memberSeq(data.seq, fail)
|
||||
if (data.outcome !== 'completed' && data.outcome !== 'failed' && data.outcome !== 'cancelled') {
|
||||
fail(`tool-workflow/agent-end outcome ${String(data.outcome)} is invalid`)
|
||||
}
|
||||
const ended = run.members.get(seq)
|
||||
if (ended === undefined) fail(`tool-workflow/agent-end has no matching member seq ${seq} in run ${runId}`)
|
||||
if (ended) fail(`tool-workflow/agent-end repeats member seq ${seq} in run ${runId}`)
|
||||
run.members.set(seq, true)
|
||||
return
|
||||
}
|
||||
case 'tool-workflow/run-end': {
|
||||
const run = openRun(trace, runId, event.type, fail)
|
||||
if (data.stopReason !== 'completed' && data.stopReason !== 'cancelled' && data.stopReason !== 'error') {
|
||||
fail(`tool-workflow/run-end stopReason ${String(data.stopReason)} is invalid`)
|
||||
}
|
||||
const openMembers = [...run.members].filter(([, ended]) => !ended).map(([seq]) => seq)
|
||||
if (openMembers.length > 0) {
|
||||
fail(`tool-workflow/run-end leaves member seq ${openMembers.join(', ')} open in run ${runId}`)
|
||||
}
|
||||
run.ended = true
|
||||
return
|
||||
}
|
||||
default:
|
||||
fail(`unknown tool-workflow event type ${event.type}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply one cold-load or live-append candidate through the package reporter. */
|
||||
function applyChecked(trace: WorkflowTrace, event: SessionEvent, fail: InvariantFailure): void {
|
||||
applyEvent(trace, event, fail)
|
||||
}
|
||||
|
||||
/** Install an independent incremental fold over every attached Session. */
|
||||
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
|
||||
const traces = new WeakMap<Session, WorkflowTrace>()
|
||||
const staged = new WeakMap<SessionEvent, { session: Session; trace: WorkflowTrace }>()
|
||||
|
||||
const seed = (session: Session): WorkflowTrace => {
|
||||
const trace: WorkflowTrace = new Map()
|
||||
for (const event of session.events) applyChecked(trace, event, fail)
|
||||
traces.set(session, trace)
|
||||
return trace
|
||||
}
|
||||
/* v8 ignore next -- session/event always follows list() or session/created seeding. */
|
||||
const traceFor = (session: Session): WorkflowTrace => traces.get(session) ?? seed(session)
|
||||
|
||||
for (const session of ctx.sessions.list()) seed(session)
|
||||
ctx.on('session/created', (session) => { seed(session) }, { global: true })
|
||||
ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
||||
if (eventName !== 'session/event') return
|
||||
const [session, event] = args as [Session, SessionEvent]
|
||||
const trace = cloneTrace(traceFor(session))
|
||||
applyChecked(trace, event, fail)
|
||||
staged.set(event, { session, trace })
|
||||
}, { global: true })
|
||||
ctx.on('session/event', (session, event) => {
|
||||
const candidate = staged.get(event)
|
||||
/* v8 ignore next 2 -- internal/dispatch stages the exact session/event callback arguments. */
|
||||
if (candidate === undefined || candidate.session !== session) {
|
||||
return fail('session/event reached publication without matching workflow-record validation')
|
||||
}
|
||||
staged.delete(event)
|
||||
traces.set(session, candidate.trace)
|
||||
}, { global: true })
|
||||
}, { inject: ['sessions'] })
|
||||
|
||||
/** Register this package's invariant companion. */
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
/* jscpd:ignore-end */
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Browser-safe durable workflow-record events written by the model-facing
|
||||
* workflow tool into its calling parent Session.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-tool-workflow/types
|
||||
*/
|
||||
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type {
|
||||
WorkflowAgentOutcome, WorkflowRunId, WorkflowStopReason,
|
||||
} from '@deepseek-ai/dsh-workflow/types'
|
||||
|
||||
/** Opens one durable top-level workflow run record. */
|
||||
export interface ToolWorkflowRunStartData {
|
||||
readonly runId: WorkflowRunId
|
||||
readonly name: string
|
||||
}
|
||||
|
||||
/** Records one workflow member after its child Session is published. */
|
||||
export interface ToolWorkflowAgentStartData {
|
||||
readonly runId: WorkflowRunId
|
||||
readonly seq: number
|
||||
readonly label: string
|
||||
readonly phase?: string
|
||||
readonly childId: SessionId
|
||||
}
|
||||
|
||||
/** Settles one previously started workflow member. */
|
||||
export interface ToolWorkflowAgentEndData {
|
||||
readonly runId: WorkflowRunId
|
||||
readonly seq: number
|
||||
readonly outcome: WorkflowAgentOutcome
|
||||
}
|
||||
|
||||
/** Settles one workflow run after its live resources reach quiescence. */
|
||||
export interface ToolWorkflowRunEndData {
|
||||
readonly runId: WorkflowRunId
|
||||
readonly stopReason: WorkflowStopReason
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-session/types' {
|
||||
interface SessionEventMap {
|
||||
/**
|
||||
* Opens one top-level workflow record.
|
||||
* @param data - stable run identity and display name.
|
||||
*/
|
||||
'tool-workflow/run-start': ToolWorkflowRunStartData
|
||||
/**
|
||||
* Records one published workflow member.
|
||||
* @param data - run identity, member sequence, display identity, and child Session.
|
||||
*/
|
||||
'tool-workflow/agent-start': ToolWorkflowAgentStartData
|
||||
/**
|
||||
* Records one member settlement.
|
||||
* @param data - run identity, paired member sequence, and outcome.
|
||||
*/
|
||||
'tool-workflow/agent-end': ToolWorkflowAgentEndData
|
||||
/**
|
||||
* Closes one workflow record after cleanup.
|
||||
* @param data - stable run identity and terminal reason.
|
||||
*/
|
||||
'tool-workflow/run-end': ToolWorkflowRunEndData
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user