@deepseek-ai/dsh-workflow-ptc 0.2.2-rc.1 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/host.ts ADDED
@@ -0,0 +1,322 @@
1
+ /** Workflow child ownership and progress over the shared sandboxed PTC executor. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { Agent } from '@deepseek-ai/dsh-agent'
4
+ import type {} from '@deepseek-ai/dsh-working-directory'
5
+ import type { PtcBindingFunction, PtcJsonValue, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
6
+ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
7
+ import { SessionId } from '@deepseek-ai/dsh-session'
8
+ import type SubagentRuntime from '@deepseek-ai/dsh-subagent'
9
+ import type { SubagentActivation } from '@deepseek-ai/dsh-subagent'
10
+ import { assertObjectJsonSchema } from '@deepseek-ai/dsh-tools'
11
+ import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
12
+ import { assertNever, snapshotJsonValue } from '@deepseek-ai/dsh-util-values'
13
+ import type { WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowMeta, WorkflowResult, WorkflowRun, WorkflowRunId } from '@deepseek-ai/dsh-workflow'
14
+ import { WORKFLOW_GUEST_SOURCE } from './guest-source.ts'
15
+ import type { WorkflowProgress } from './guest-types.ts'
16
+ import { renderThrown } from './realm.ts'
17
+ import type { ExecutionObserver } from './runtime.ts'
18
+ import type { ChildStartRequest, WorkerInit } from './types.ts'
19
+
20
+ interface ChildRecord {
21
+ readonly callId: number
22
+ readonly run: SubagentActivation
23
+ disposal?: Promise<void>
24
+ }
25
+
26
+ const GUEST_URL = `data:text/javascript,${encodeURIComponent(WORKFLOW_GUEST_SOURCE)}`
27
+ const PROGRAM = `const { runWorkflowGuest } = await import(${JSON.stringify(GUEST_URL)}); return await runWorkflowGuest(workflowHost);`
28
+
29
+ function object(value: unknown): Record<string, unknown> {
30
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('workflow binding requires an object')
31
+ return value as Record<string, unknown>
32
+ }
33
+
34
+ function text(value: unknown, name: string): string {
35
+ if (typeof value !== 'string') throw new Error(`workflow ${name} must be a string`)
36
+ return value
37
+ }
38
+
39
+ function json(value: unknown): PtcJsonValue {
40
+ const result = snapshotJsonValue(value)
41
+ if (result === undefined) throw new Error('workflow binding value must be lossless JSON')
42
+ return result as PtcJsonValue
43
+ }
44
+
45
+ function childRequest(value: unknown): ChildStartRequest {
46
+ const request = object(value)
47
+ const prompt = text(request.prompt, 'prompt')
48
+ const provider = request.provider === undefined ? undefined : text(request.provider, 'provider')
49
+ const model = request.model === undefined ? undefined : text(request.model, 'model')
50
+ let schema: ObjectJsonSchema | undefined
51
+ if (request.schema !== undefined) {
52
+ const candidate = object(request.schema)
53
+ assertObjectJsonSchema(candidate)
54
+ schema = candidate
55
+ }
56
+ return {
57
+ prompt,
58
+ ...provider === undefined ? {} : { provider },
59
+ ...model === undefined ? {} : { model },
60
+ ...schema === undefined ? {} : { schema },
61
+ }
62
+ }
63
+
64
+ function agentInfo(value: unknown): WorkflowAgentInfo {
65
+ const info = object(value)
66
+ if (!Number.isSafeInteger(info.seq) || (info.seq as number) < 1) throw new Error('workflow agent sequence must be a positive integer')
67
+ return {
68
+ seq: info.seq as number,
69
+ label: text(info.label, 'agent label'),
70
+ childId: SessionId(text(info.childId, 'child id')),
71
+ ...info.phase === undefined ? {} : { phase: text(info.phase, 'agent phase') },
72
+ }
73
+ }
74
+
75
+ function progress(value: unknown): WorkflowProgress {
76
+ const event = object(value)
77
+ switch (event.type) {
78
+ case 'phase': return { type: 'phase', title: text(event.title, 'phase') }
79
+ case 'log': return { type: 'log', message: text(event.message, 'log') }
80
+ case 'agent-start': return { type: 'agent-start', info: agentInfo(event.info) }
81
+ case 'agent-end': {
82
+ const info = object(event.info)
83
+ if (info.outcome !== 'completed' && info.outcome !== 'failed' && info.outcome !== 'cancelled') throw new Error('invalid workflow agent outcome')
84
+ return { type: 'agent-end', info: { ...agentInfo(info), outcome: info.outcome } }
85
+ }
86
+ default: throw new Error('invalid workflow progress event')
87
+ }
88
+ }
89
+
90
+ function progressBatch(value: unknown): WorkflowProgress[] {
91
+ if (!Array.isArray(value)) throw new Error('workflow progress requires an array of events')
92
+ return value.map(progress)
93
+ }
94
+
95
+ function workflowResult(value: unknown): WorkflowResult {
96
+ const result = object(value)
97
+ if (result.stopReason !== 'completed' && result.stopReason !== 'error' && result.stopReason !== 'cancelled') throw new Error('invalid workflow stop reason')
98
+ if (!Number.isSafeInteger(result.agentsStarted) || (result.agentsStarted as number) < 0) throw new Error('invalid workflow agent count')
99
+ if (!Object.hasOwn(result, 'value')) throw new Error('workflow result is missing its value')
100
+ return {
101
+ value: result.value,
102
+ stopReason: result.stopReason,
103
+ agentsStarted: result.agentsStarted as number,
104
+ ...result.error === undefined ? {} : { error: text(result.error, 'error') },
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Holder-owned workflow. Cancellation stops the program immediately; settlement waits for
110
+ * its managed process and every admitted child startup/disposal. Engine unload does not
111
+ * invalidate the captured runtime or subagent handles.
112
+ */
113
+ export class PtcWorkflowRun implements WorkflowRun {
114
+ readonly result: Promise<WorkflowResult>
115
+ private readonly controller = new AbortController()
116
+ private readonly children = new Map<number, ChildRecord>()
117
+ private readonly pending = new Set<Promise<unknown>>()
118
+ private readonly liveAgents = new Map<number, WorkflowAgentInfo>()
119
+ private started = 0
120
+ private terminal = false
121
+ private cancelReason: string | undefined
122
+ private disposed: Promise<void> | undefined
123
+ private readonly externalAbort: () => void
124
+ private readonly cwd: Promise<string>
125
+
126
+ constructor(
127
+ private readonly ctx: Context,
128
+ private readonly subagents: SubagentRuntime,
129
+ private readonly runtime: PtcRuntime,
130
+ readonly id: WorkflowRunId,
131
+ readonly meta: WorkflowMeta,
132
+ private readonly parent: Agent,
133
+ private readonly init: WorkerInit,
134
+ private readonly provider: string,
135
+ private readonly policy: SandboxExecutionPolicy,
136
+ private readonly observer: ExecutionObserver,
137
+ private readonly signal?: AbortSignal,
138
+ ) {
139
+ this.externalAbort = () => { this.cancel('workflow signal aborted') }
140
+ if (signal?.aborted) this.externalAbort()
141
+ else signal?.addEventListener('abort', this.externalAbort, { once: true })
142
+ this.cwd = ctx.workingDirectory.ensure(parent, this.controller.signal)
143
+ // Consumers attach durable run recording after start() returns.
144
+ this.result = Promise.resolve().then(() => this.drive())
145
+ }
146
+
147
+ /**
148
+ * Stop the script and abort pending and published children.
149
+ * @param reason - Human-readable cancellation cause; the first request wins.
150
+ */
151
+ cancel(reason = 'workflow cancelled'): void {
152
+ if (this.terminal || this.cancelReason !== undefined) return
153
+ this.cancelReason = reason
154
+ this.controller.abort(reason)
155
+ for (const record of this.children.values()) void this.disposeChild(record)
156
+ }
157
+
158
+ /**
159
+ * Cancel unfinished work and await the program and child cleanup.
160
+ * @returns One shared completion promise for repeated disposal calls.
161
+ */
162
+ dispose(): Promise<void> {
163
+ this.cancel('workflow disposed')
164
+ this.disposed ??= this.result.then(() => {})
165
+ return this.disposed
166
+ }
167
+
168
+ private requireActive(): void {
169
+ this.controller.signal.throwIfAborted()
170
+ }
171
+
172
+ private track<T>(task: Promise<T>): Promise<T> {
173
+ this.pending.add(task)
174
+ void task.then(() => { this.pending.delete(task) }, () => { this.pending.delete(task) })
175
+ return task
176
+ }
177
+
178
+ private bindings(): Record<string, PtcBindingFunction> {
179
+ return {
180
+ begin: () => { this.requireActive(); return Promise.resolve(json(this.init)) },
181
+ startChild: value => this.track(this.startChild(childRequest(value))),
182
+ childResult: value => this.track(this.childResult(this.child(value))),
183
+ disposeChild: async (value) => { await this.disposeChild(this.child(value)); return null },
184
+ progress: (value) => {
185
+ for (const event of progressBatch(value)) this.onProgress(event)
186
+ return Promise.resolve(null)
187
+ },
188
+ }
189
+ }
190
+
191
+ private child(value: unknown): ChildRecord {
192
+ this.requireActive()
193
+ const callId = object(value).callId
194
+ if (!Number.isSafeInteger(callId)) throw new Error('workflow child call id must be an integer')
195
+ const record = this.children.get(callId as number)
196
+ if (record === undefined) throw new Error('workflow child call is not active')
197
+ return record
198
+ }
199
+
200
+ private async startChild(request: ChildStartRequest): Promise<PtcJsonValue> {
201
+ this.requireActive()
202
+ const callId = ++this.started
203
+ const run = await this.subagents.startActivation({
204
+ provider: this.provider,
205
+ label: `${this.meta.name} child ${callId}`,
206
+ delivery: 'caller',
207
+ signal: this.controller.signal,
208
+ cwd: await this.cwd,
209
+ prompt: [{ type: 'text', text: request.prompt }],
210
+ parent: this.parent,
211
+ ...request.schema === undefined ? {} : { outputSchema: request.schema },
212
+ ...request.provider === undefined && request.model === undefined ? {} : {
213
+ agentOptions: {
214
+ ...request.provider === undefined ? {} : { provider: request.provider },
215
+ ...request.model === undefined ? {} : { model: request.model },
216
+ },
217
+ },
218
+ })
219
+ const record: ChildRecord = { callId, run }
220
+ this.children.set(callId, record)
221
+ // A provider can publish after the signal fired while startup was pending.
222
+ if (this.controller.signal.aborted) {
223
+ await this.disposeChild(record)
224
+ throw new Error('workflow child started after cancellation')
225
+ }
226
+ return { callId, childId: run.childId }
227
+ }
228
+
229
+ private async childResult(record: ChildRecord): Promise<PtcJsonValue> {
230
+ const signal = this.controller.signal
231
+ signal.throwIfAborted()
232
+ const aborted = Promise.withResolvers<never>()
233
+ const onAbort = (): void => { aborted.reject(signal.reason) }
234
+ signal.addEventListener('abort', onAbort, { once: true })
235
+ try {
236
+ const result = await Promise.race([record.run.result, aborted.promise])
237
+ return json({
238
+ output: result.output,
239
+ stopReason: result.stopReason,
240
+ ...result.structured === undefined ? {} : { structured: result.structured },
241
+ })
242
+ } finally {
243
+ signal.removeEventListener('abort', onAbort)
244
+ }
245
+ }
246
+
247
+ private disposeChild(record: ChildRecord): Promise<void> {
248
+ record.disposal ??= Promise.resolve().then(() => record.run.dispose()).catch((error: unknown) => {
249
+ this.ctx.logger.warn(`workflow-ptc: child dispose failed: ${renderThrown(error)}`)
250
+ }).finally(() => {
251
+ this.children.delete(record.callId)
252
+ })
253
+ return record.disposal
254
+ }
255
+
256
+ private onProgress(event: WorkflowProgress): void {
257
+ this.requireActive()
258
+ switch (event.type) {
259
+ case 'phase': this.observer.phase(event.title); break
260
+ case 'log': this.observer.log(event.message); break
261
+ case 'agent-start':
262
+ this.liveAgents.set(event.info.seq, event.info)
263
+ this.observer.agentStart(event.info)
264
+ break
265
+ case 'agent-end': this.endAgent(event.info); break
266
+ /* v8 ignore next -- progress() validates the closed message union before dispatch. */
267
+ default: assertNever(event, 'workflow progress')
268
+ }
269
+ }
270
+
271
+ private endAgent(info: WorkflowAgentEndInfo): void {
272
+ if (!this.liveAgents.delete(info.seq)) return
273
+ this.observer.agentEnd(info)
274
+ }
275
+
276
+ private cancelled(): WorkflowResult {
277
+ return { value: null, stopReason: 'cancelled', error: `workflow run cancelled: ${this.cancelReason}`, agentsStarted: this.started }
278
+ }
279
+
280
+ private async drive(): Promise<WorkflowResult> {
281
+ let result: WorkflowResult
282
+ try {
283
+ const cwd = await this.cwd
284
+ this.requireActive()
285
+ if (this.runtime.sandboxMode === undefined && this.policy.mode !== 'danger-full-access') {
286
+ throw new Error(`workflow runtime cannot enforce the ${this.policy.mode} file policy`)
287
+ }
288
+ const outcome = await this.runtime.run(this.runtime.resolve({
289
+ program: {
290
+ 'function-body': PROGRAM,
291
+ repl: `await (async () => {\n${PROGRAM}\n})()`,
292
+ script: `(async () => {\n${PROGRAM}\n})()`,
293
+ }[this.runtime.programFormat],
294
+ bindings: [{ global: 'workflowHost', functions: this.bindings() }],
295
+ cwd,
296
+ ...this.runtime.sandboxMode === undefined ? {} : { sandboxPolicy: this.policy },
297
+ timeoutMs: null,
298
+ signal: this.controller.signal,
299
+ }))
300
+ this.terminal = true
301
+ if (this.cancelReason !== undefined) result = this.cancelled()
302
+ else if (outcome.error !== undefined) result = { value: null, stopReason: 'error', error: `workflow execution failed (${outcome.error.kind}): ${outcome.error.message}`, agentsStarted: this.started }
303
+ else result = workflowResult(outcome.value)
304
+ } catch (error: unknown) {
305
+ this.terminal = true
306
+ result = this.cancelReason === undefined
307
+ ? { value: null, stopReason: 'error', error: renderThrown(error), agentsStarted: this.started }
308
+ : this.cancelled()
309
+ } finally {
310
+ this.terminal = true
311
+ this.signal?.removeEventListener('abort', this.externalAbort)
312
+ this.controller.abort('workflow settled')
313
+ // Disposing published children releases binding waits; pending starts may publish more.
314
+ for (const record of this.children.values()) void this.disposeChild(record)
315
+ while (this.pending.size > 0) await Promise.allSettled([...this.pending])
316
+ await Promise.all([...this.children.values()].map(record => this.disposeChild(record)))
317
+ this.children.clear()
318
+ for (const info of this.liveAgents.values()) this.endAgent({ ...info, outcome: 'cancelled' })
319
+ }
320
+ return result
321
+ }
322
+ }
package/src/index.ts ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Workflow orchestration through the shared sandboxed Node PTC executor.
3
+ * The VM supplies script helpers; the process applies the calling Session's file policy.
4
+ * @module @deepseek-ai/dsh-workflow-ptc
5
+ */
6
+
7
+ import { randomUUID } from 'node:crypto'
8
+ import { availableParallelism } from 'node:os'
9
+ import * as vm from 'node:vm'
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import type {} from '@deepseek-ai/dsh-ptc-runtime'
12
+ import type {} from '@deepseek-ai/dsh-sandbox-policy'
13
+ import type {} from '@deepseek-ai/dsh-working-directory'
14
+ import z from '@deepseek-ai/schemastery'
15
+ import WorkflowEngine, { WorkflowError, WorkflowRunId } from '@deepseek-ai/dsh-workflow'
16
+ import type { WorkflowRun, WorkflowRunInfo, WorkflowStartRequest } from '@deepseek-ai/dsh-workflow'
17
+ import { PtcWorkflowRun } from './host.ts'
18
+ import { validateMeta } from './meta.ts'
19
+ import type { WorkerInit, WorkerLimits } from './types.ts'
20
+
21
+ export { validateMeta } from './meta.ts'
22
+ export { materializeFromRealm, MaterializeError } from './realm.ts'
23
+ export type {
24
+ ChildHandle,
25
+ ChildPort,
26
+ ChildResult,
27
+ ChildStartRequest,
28
+ WorkerInit,
29
+ WorkerLimits,
30
+ } from './types.ts'
31
+
32
+ /** Plugin config (all optional — `static Config` supplies the defaults). */
33
+ export interface Config {
34
+ /** The `ctx.subagents` provider children run on (default `spawn`). */
35
+ provider?: string
36
+ /** Concurrent `agent()` ceiling; `0` (the default) auto-resolves to `min(16, max(1, cores - 2))`. */
37
+ maxConcurrentAgents?: number
38
+ /** Total `agent()` calls one run may start — the runaway-loop backstop (default 1000). */
39
+ maxTotalAgents?: number
40
+ /** Items accepted by a single `parallel()`/`pipeline()` call (default 4096). */
41
+ maxItemsPerCall?: number
42
+ /** VM timeout for the script's initial synchronous slice (default 5000 ms). */
43
+ syncTimeoutMs?: number
44
+ }
45
+
46
+ type ResolvedConfig = Required<Config>
47
+
48
+ /** A body that still carries the Claude Code-style meta header (meta rides the seam as data here). */
49
+ const META_STATEMENT = /^\s*export\s+const\s+meta\b/
50
+
51
+ /**
52
+ * Reject invalid JavaScript synchronously before publishing a workflow run.
53
+ * The guest compiles the same async wrapper in its own process.
54
+ */
55
+ function assertBodyParses(body: string, name: string): void {
56
+ if (META_STATEMENT.test(body)) {
57
+ throw new WorkflowError('workflow meta rides the `meta` request field, not the script: remove the `export const meta = {...}` statement from the body', 'SCRIPT_PARSE')
58
+ }
59
+ try {
60
+ // Parse only — the script object is discarded, nothing executes.
61
+ void new vm.Script(`(async () => {\n${body}\n})()`, { filename: `workflow:${name}`, lineOffset: -1 })
62
+ } catch (error: unknown) {
63
+ throw new WorkflowError(`workflow script does not parse: ${String(error)}`, 'SCRIPT_PARSE', { cause: error })
64
+ }
65
+ }
66
+
67
+ /** Resolve one run's provider route before publishing work. */
68
+ function resolveSubagentProvider(ctx: Context, configured: string, override: string | undefined): string {
69
+ const provider = override ?? configured
70
+ if (provider.length === 0 || provider !== provider.trim()) {
71
+ throw new WorkflowError(
72
+ 'workflow subagentProvider must be a non-empty normalized string',
73
+ 'INVALID_ARGUMENT',
74
+ )
75
+ }
76
+ if (ctx.subagents.getProvider(provider) === undefined) {
77
+ throw new WorkflowError(`no subagent provider registered for "${provider}"`, 'AGENT_START')
78
+ }
79
+ return provider
80
+ }
81
+
82
+ /** Resolve one run's total-child cap against the engine deployment ceiling. */
83
+ function resolveMaxTotalAgents(requested: number | undefined, ceiling: number): number {
84
+ if (requested === undefined) return ceiling
85
+ if (!Number.isSafeInteger(requested) || requested < 1) {
86
+ throw new WorkflowError('workflow maxTotalAgents must be a positive safe integer', 'INVALID_ARGUMENT')
87
+ }
88
+ if (requested > ceiling) {
89
+ throw new WorkflowError(
90
+ `workflow maxTotalAgents ${requested} exceeds the engine ceiling ${ceiling}`,
91
+ 'INVALID_ARGUMENT',
92
+ )
93
+ }
94
+ return requested
95
+ }
96
+
97
+ /**
98
+ * The PTC-backed workflow engine. `start()` validates the script up front
99
+ * (meta + a host-side body parse) and returns a {@link WorkflowRun} whose
100
+ * `result` never rejects; the `workflow/*` events fire around the run per
101
+ * the seam contract.
102
+ */
103
+ class PtcWorkflowEngine extends WorkflowEngine {
104
+ static inject = ['subagents', 'ptcRuntime', 'sandboxPolicy', 'workingDirectory']
105
+
106
+ static Config: z<Config> = z.object({
107
+ provider: z.string().default('spawn'),
108
+ maxConcurrentAgents: z.natural().default(0),
109
+ maxTotalAgents: z.natural().min(1).default(1000),
110
+ maxItemsPerCall: z.natural().min(1).default(4096),
111
+ syncTimeoutMs: z.natural().min(1).default(5000),
112
+ })
113
+
114
+ private readonly config: ResolvedConfig
115
+
116
+ constructor(ctx: Context, config: Config) {
117
+ super(ctx)
118
+ if (ctx.ptcRuntime.language !== 'typescript') throw new Error('workflow-ptc requires the Node TypeScript PTC runtime')
119
+ // schemastery (static Config) has already filled the defaulted fields;
120
+ // the assertion records that resolution, not a hidden fallback.
121
+ this.config = config as ResolvedConfig
122
+ }
123
+
124
+ /**
125
+ * Validate and execute a workflow script in a sandboxed Node process. Throws
126
+ * {@link WorkflowError} synchronously (`META_INVALID` for a malformed meta
127
+ * block, `SCRIPT_PARSE` for a body that does not compile) for a request
128
+ * that cannot begin; once a run is returned, every failure resolves through
129
+ * `result.stopReason` instead.
130
+ * @param request - the script body, its meta data and `args`, the parent
131
+ * agent, and an optional cancel signal.
132
+ * @returns the live run (its `result` resolves when the script settles).
133
+ */
134
+ start(request: WorkflowStartRequest): WorkflowRun {
135
+ const meta = validateMeta(request.meta)
136
+ assertBodyParses(request.script, meta.name)
137
+ const subagentProvider = resolveSubagentProvider(this.ctx, this.config.provider, request.subagentProvider)
138
+ const maxTotalAgents = resolveMaxTotalAgents(request.maxTotalAgents, this.config.maxTotalAgents)
139
+ const id = WorkflowRunId(randomUUID())
140
+ const info: WorkflowRunInfo = { id, meta }
141
+ const limits: WorkerLimits = {
142
+ maxConcurrentAgents: this.config.maxConcurrentAgents === 0
143
+ ? Math.min(16, Math.max(1, availableParallelism() - 2))
144
+ : this.config.maxConcurrentAgents,
145
+ maxTotalAgents,
146
+ maxItemsPerCall: this.config.maxItemsPerCall,
147
+ syncTimeoutMs: this.config.syncTimeoutMs,
148
+ }
149
+ const init: WorkerInit = {
150
+ meta,
151
+ body: request.script,
152
+ ...request.args !== undefined ? { args: structuredClone(request.args) } : {},
153
+ limits,
154
+ }
155
+ // Captured service handles keep a holder-owned run usable after engine unload.
156
+ const runCtx = this.ctx
157
+ const subagents = runCtx.subagents
158
+ const run = new PtcWorkflowRun(
159
+ runCtx,
160
+ subagents,
161
+ runCtx.ptcRuntime,
162
+ id,
163
+ meta,
164
+ request.parent,
165
+ init,
166
+ subagentProvider,
167
+ runCtx.sandboxPolicy.resolve({ session: request.parent.session }),
168
+ {
169
+ phase: (title) => { this.emitWorkflowEvent('workflow/phase', info, title) },
170
+ log: (message) => { this.emitWorkflowEvent('workflow/log', info, message) },
171
+ agentStart: (agent) => { this.emitWorkflowEvent('workflow/agent-start', info, agent) },
172
+ agentEnd: (agent) => { this.emitWorkflowEvent('workflow/agent-end', info, agent) },
173
+ },
174
+ request.signal,
175
+ )
176
+
177
+ this.emitWorkflowEvent('workflow/start', info)
178
+ // `workflow/end` fires as the (never-rejecting) result settles, with the
179
+ // outcome DATA only — the value stays with the run's holder.
180
+ void run.result.then((settled) => {
181
+ this.emitWorkflowEvent('workflow/end', info, {
182
+ stopReason: settled.stopReason,
183
+ ...settled.error !== undefined ? { error: settled.error } : {},
184
+ agentsStarted: settled.agentsStarted,
185
+ })
186
+ })
187
+
188
+ return run
189
+ }
190
+ }
191
+
192
+ export default PtcWorkflowEngine
package/src/meta.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Meta validation checks caller-provided DATA against the {@link WorkflowMeta}
3
+ * contract and rejects every violation by name. Meta arrives as schema-checked
4
+ * JSON data, never evaluated script text. Model-written JavaScript executes
5
+ * inside the confined PTC process.
6
+ * @module @deepseek-ai/dsh-workflow-ptc/meta
7
+ */
8
+
9
+ import { WorkflowError } from '@deepseek-ai/dsh-workflow'
10
+ import type { WorkflowMeta, WorkflowPhase } from '@deepseek-ai/dsh-workflow'
11
+
12
+ /** Collect shape violations for a meta value (plain JSON data by the seam contract). */
13
+ function validateMetaShape(meta: unknown): { meta?: WorkflowMeta; violations: string[] } {
14
+ const violations: string[] = []
15
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) {
16
+ return { violations: ['meta must be an object'] }
17
+ }
18
+ const record = meta as Record<string, unknown>
19
+ const known = new Set(['name', 'description', 'whenToUse', 'phases'])
20
+ for (const key of Object.keys(record)) {
21
+ if (!known.has(key)) violations.push(`meta.${key} is not a recognized field (name/description/whenToUse/phases)`)
22
+ }
23
+ if (typeof record.name !== 'string' || record.name.length === 0) violations.push('meta.name must be a non-empty string')
24
+ if (typeof record.description !== 'string' || record.description.length === 0) violations.push('meta.description must be a non-empty string')
25
+ if (record.whenToUse !== undefined && typeof record.whenToUse !== 'string') violations.push('meta.whenToUse must be a string')
26
+ const phases: WorkflowPhase[] = []
27
+ if (record.phases !== undefined) {
28
+ if (!Array.isArray(record.phases)) {
29
+ violations.push('meta.phases must be an array')
30
+ } else {
31
+ record.phases.forEach((phase, index) => {
32
+ if (typeof phase !== 'object' || phase === null || Array.isArray(phase)) {
33
+ violations.push(`meta.phases[${index}] must be an object`)
34
+ return
35
+ }
36
+ const entry = phase as Record<string, unknown>
37
+ for (const key of Object.keys(entry)) {
38
+ if (!['title', 'detail', 'provider', 'model'].includes(key)) violations.push(`meta.phases[${index}].${key} is not a recognized field`)
39
+ }
40
+ if (typeof entry.title !== 'string' || entry.title.length === 0) violations.push(`meta.phases[${index}].title must be a non-empty string`)
41
+ if (entry.detail !== undefined && typeof entry.detail !== 'string') violations.push(`meta.phases[${index}].detail must be a string`)
42
+ if (entry.provider !== undefined && typeof entry.provider !== 'string') violations.push(`meta.phases[${index}].provider must be a string`)
43
+ if (entry.model !== undefined && typeof entry.model !== 'string') violations.push(`meta.phases[${index}].model must be a string`)
44
+ if (violations.length === 0) {
45
+ phases.push({
46
+ title: entry.title as string,
47
+ ...entry.detail !== undefined ? { detail: entry.detail as string } : {},
48
+ ...entry.provider !== undefined ? { provider: entry.provider as string } : {},
49
+ ...entry.model !== undefined ? { model: entry.model as string } : {},
50
+ })
51
+ }
52
+ })
53
+ }
54
+ }
55
+ if (violations.length > 0) return { violations }
56
+ return {
57
+ violations,
58
+ meta: {
59
+ name: record.name as string,
60
+ description: record.description as string,
61
+ ...record.whenToUse !== undefined ? { whenToUse: record.whenToUse as string } : {},
62
+ ...record.phases !== undefined ? { phases } : {},
63
+ },
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Validate a caller-provided meta value against the {@link WorkflowMeta}
69
+ * contract. Throws `META_INVALID` naming every violation (unknown fields,
70
+ * missing/mistyped `name`/`description`, malformed `phases`); the returned
71
+ * meta is a NORMALIZED copy built from the validated fields, so the engine
72
+ * never aliases the caller's object.
73
+ * @param value - the meta data from the start request (plain JSON by the seam contract).
74
+ * @returns the validated, normalized meta block.
75
+ */
76
+ export function validateMeta(value: unknown): WorkflowMeta {
77
+ const { meta, violations } = validateMetaShape(value)
78
+ if (meta === undefined) {
79
+ throw new WorkflowError(`invalid meta: ${violations.join('; ')}`, 'META_INVALID')
80
+ }
81
+ return meta
82
+ }