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

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/realm.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Materializes script VM values as plain JSON and renders thrown values.
3
+ * Getters and proxy traps may execute inside the confined Node process;
4
+ * process isolation and cancellation belong to PTC, not the VM.
5
+ * @module @deepseek-ai/dsh-workflow-ptc/realm
6
+ */
7
+
8
+ /** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */
9
+ export class MaterializeError extends Error {
10
+ constructor(public readonly path: string, public readonly reason: string) {
11
+ super(`${path}: ${reason}`)
12
+ this.name = 'MaterializeError'
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Render a thrown value to failure text without ever throwing: prefer the
18
+ * `stack` (host or realm — a realm error's `stack` is a plain string read),
19
+ * fall back to `message`, then `String()`. Reading those properties MAY run
20
+ * script code; if that code itself throws, a fixed label is returned instead.
21
+ * @param error - any value thrown in the host or guest realm.
22
+ * @returns human-readable text for the failure report; prefers the stack.
23
+ */
24
+ export function renderThrown(error: unknown): string {
25
+ try {
26
+ const stack = (error as { stack?: unknown } | null | undefined)?.stack
27
+ if (typeof stack === 'string' && stack.length > 0) return stack
28
+ const message = (error as { message?: unknown } | null | undefined)?.message
29
+ if (typeof message === 'string' && message.length > 0) return message
30
+ return String(error)
31
+ } catch {
32
+ // A throwing accessor/toString on the thrown value — rendering must be
33
+ // total (drive()'s never-reject contract), so fall back to a fixed label.
34
+ return '[unrenderable thrown value]'
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Whether an object's prototype chain represents a plain data object: `null`, or a prototype
40
+ * whose own prototype is `null` (the realm's `Object.prototype` — which we
41
+ * cannot compare by identity across realms). A `Date`/`Map`/class instance
42
+ * has a longer chain and is rejected.
43
+ */
44
+ function hasPlainPrototype(value: object): boolean {
45
+ const proto: unknown = Object.getPrototypeOf(value)
46
+ if (proto === null) return true
47
+ return Object.getPrototypeOf(proto) === null
48
+ }
49
+
50
+ /**
51
+ * Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is
52
+ * returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail
53
+ * with the offending path. Property accessors run normally, and a throwing read is wrapped
54
+ * with its rendered failure.
55
+ *
56
+ * @param value - the realm value to materialize.
57
+ * @param root - the path label for the root value (error messages).
58
+ * @returns the host-realm copy (plain objects/arrays/scalars only).
59
+ * @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic
60
+ * prototypes, or property reads that throw.
61
+ */
62
+ export function materializeFromRealm(value: unknown, root = 'value'): unknown {
63
+ if (value === undefined) return undefined
64
+ try {
65
+ return materialize(value, root, new Set())
66
+ } catch (error: unknown) {
67
+ if (error instanceof MaterializeError) throw error
68
+ // A property read ran script code that threw; total-ize it so callers can
69
+ // keep the narrow MaterializeError contract.
70
+ throw new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`)
71
+ }
72
+ }
73
+
74
+ function materialize(value: unknown, path: string, seen: Set<object>): unknown {
75
+ switch (typeof value) {
76
+ case 'boolean':
77
+ case 'string':
78
+ return value
79
+ case 'number': {
80
+ if (!Number.isFinite(value)) throw new MaterializeError(path, 'non-finite numbers are not JSON data')
81
+ return value
82
+ }
83
+ case 'bigint':
84
+ throw new MaterializeError(path, 'bigints are not JSON data')
85
+ case 'function':
86
+ throw new MaterializeError(path, 'functions are not plain JSON data')
87
+ case 'symbol':
88
+ throw new MaterializeError(path, 'symbols are not plain JSON data')
89
+ case 'undefined':
90
+ throw new MaterializeError(path, 'undefined is not JSON data')
91
+ case 'object':
92
+ break
93
+ }
94
+ if (value === null) return null
95
+ const objectValue: object = value
96
+ if (seen.has(objectValue)) throw new MaterializeError(path, 'circular references are not JSON data')
97
+ seen.add(objectValue)
98
+ try {
99
+ if (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen)
100
+ return materializeObject(objectValue, path, seen)
101
+ } finally {
102
+ seen.delete(objectValue)
103
+ }
104
+ }
105
+
106
+ function materializeArray(value: unknown[], path: string, seen: Set<object>): unknown[] {
107
+ const out: unknown[] = []
108
+ for (let index = 0; index < value.length; index++) {
109
+ if (!(index in value)) throw new MaterializeError(`${path}[${index}]`, 'sparse arrays are not JSON data')
110
+ out.push(materialize(value[index], `${path}[${index}]`, seen))
111
+ }
112
+ // Own enumerable props beyond the indices (e.g. `arr.total = 3`) would be
113
+ // silently dropped by JSON — reject them instead.
114
+ for (const key of Object.keys(value)) {
115
+ const index = Number(key)
116
+ if (!Number.isInteger(index) || index < 0 || index >= value.length) {
117
+ throw new MaterializeError(`${path}.${key}`, 'arrays with non-index properties are not JSON data')
118
+ }
119
+ }
120
+ if (Object.getOwnPropertySymbols(value).length > 0) {
121
+ throw new MaterializeError(path, 'symbol-keyed properties are not plain JSON data')
122
+ }
123
+ return out
124
+ }
125
+
126
+ function materializeObject(value: object, path: string, seen: Set<object>): Record<string, unknown> {
127
+ if (!hasPlainPrototype(value)) {
128
+ throw new MaterializeError(path, 'only plain objects and arrays are JSON data (exotic prototype)')
129
+ }
130
+ if (Object.getOwnPropertySymbols(value).length > 0) {
131
+ throw new MaterializeError(path, 'symbol-keyed properties are not plain JSON data')
132
+ }
133
+ const out: Record<string, unknown> = {}
134
+ // Object.keys = own enumerable string keys, matching JSON.stringify's
135
+ // property selection exactly (non-enumerable props never reach JSON output).
136
+ for (const key of Object.keys(value)) {
137
+ // defineProperty, never assignment: a "__proto__" key must become an OWN
138
+ // data property of the copy, not a prototype mutation.
139
+ Object.defineProperty(out, key, {
140
+ value: materialize((value as Record<string, unknown>)[key], `${path}.${key}`, seen),
141
+ enumerable: true,
142
+ writable: true,
143
+ configurable: true,
144
+ })
145
+ }
146
+ return out
147
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Workflow VM hooks, child callbacks, ordinary concurrency limits and result serialization.
3
+ * PTC owns process confinement and cancellation. Fatal hook and provider failures propagate
4
+ * through combinators; ordinary child failures and stage errors become per-item nulls.
5
+ * @module @deepseek-ai/dsh-workflow-ptc/runtime
6
+ */
7
+
8
+ import * as vm from 'node:vm'
9
+ import { brandString } from '@deepseek-ai/dsh-brand'
10
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
11
+ import type { SessionId } from '@deepseek-ai/dsh-session'
12
+ import { assertObjectJsonSchema, JsonSchemaError } from '@deepseek-ai/dsh-tools'
13
+ import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
14
+ import { isFatalWorkflowError, WorkflowError } from '@deepseek-ai/dsh-workflow'
15
+ import type {
16
+ WorkflowAgentEndInfo,
17
+ WorkflowAgentInfo,
18
+ WorkflowMeta,
19
+ WorkflowResult,
20
+ } from '@deepseek-ai/dsh-workflow'
21
+ import { materializeFromRealm, MaterializeError, renderThrown } from './realm.ts'
22
+ import type { ChildHandle, ChildPort, WorkerLimits } from './types.ts'
23
+
24
+ /** The observers the execution reports progress through (the session posts them to the host). */
25
+ export interface ExecutionObserver {
26
+ phase(title: string): void
27
+ log(message: string): void
28
+ agentStart(info: WorkflowAgentInfo): void
29
+ agentEnd(info: WorkflowAgentEndInfo): void
30
+ }
31
+
32
+ /** The `agent()` options the script may pass; everything else rejects loud. */
33
+ const SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', 'model'])
34
+ /** Deferred Claude Code options we name explicitly in the rejection message. */
35
+ const DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType'])
36
+
37
+ /** Flatten a child's final output blocks to text (the non-schema `agent()` result). */
38
+ function outputText(blocks: ContentBlock[]): string {
39
+ return blocks
40
+ .filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')
41
+ .map(block => block.text)
42
+ .join('')
43
+ }
44
+
45
+ /** A short display label derived from the prompt when the script passes none. */
46
+ function defaultLabel(prompt: string): string {
47
+ const newline = prompt.indexOf('\n')
48
+ const line = newline === -1 ? prompt : prompt.slice(0, newline)
49
+ return line.length <= 48 ? line : `${line.slice(0, 47)}…`
50
+ }
51
+
52
+ /**
53
+ * One script execution inside the confined Node process. The host owns
54
+ * cancellation and cleanup of any dropped child work.
55
+ */
56
+ export class WorkflowExecution {
57
+ /** 1-based count of `agent()` calls started (the `agentsStarted` result field). */
58
+ private started = 0
59
+ private activeSlots = 0
60
+ private readonly slotWaiters: (() => void)[] = []
61
+ private currentPhase: string | undefined
62
+ private readonly context: vm.Context
63
+ private readonly compiled: vm.Script
64
+
65
+ constructor(
66
+ meta: WorkflowMeta,
67
+ body: string,
68
+ args: unknown,
69
+ private readonly limits: WorkerLimits,
70
+ private readonly observer: ExecutionObserver,
71
+ private readonly children: ChildPort,
72
+ ) {
73
+ // The host parses this same wrapper before publishing a run.
74
+ try {
75
+ this.compiled = new vm.Script(`(async () => {\n${body}\n})()`, {
76
+ filename: `workflow:${meta.name}`,
77
+ lineOffset: -1,
78
+ })
79
+ } catch (error: unknown) {
80
+ throw new WorkflowError(`workflow script does not parse: ${String(error)}`, 'SCRIPT_PARSE', { cause: error })
81
+ }
82
+
83
+ this.context = vm.createContext({}, { name: `workflow:${meta.name}` })
84
+
85
+ const globals: Record<string, unknown> = {
86
+ agent: (prompt: unknown, opts?: unknown) => this.contain(this.agent(prompt, opts)),
87
+ parallel: (thunks: unknown) => this.contain(this.parallel(thunks)),
88
+ pipeline: (items: unknown, ...stages: unknown[]) => this.contain(this.pipeline(items, stages)),
89
+ phase: (title: unknown) => { this.phase(title) },
90
+ log: (message: unknown) => { this.log(message) },
91
+ // PTC has already copied these inputs through its JSON channel.
92
+ args,
93
+ }
94
+ for (const [key, value] of Object.entries(globals)) {
95
+ // Data properties on the contextified global; frozen shape not required —
96
+ // a script overwriting its own hooks only sabotages itself.
97
+ ;(this.context as Record<string, unknown>)[key] = typeof value === 'function' ? Object.freeze(value) : value
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Run the script and materialize its JSON return value.
103
+ * @returns A completed or error result; script failures never reject.
104
+ */
105
+ async drive(): Promise<WorkflowResult> {
106
+ try {
107
+ const scriptPromise = this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs }) as Promise<unknown>
108
+ const raw: unknown = await this.contain(Promise.resolve(scriptPromise))
109
+ const value = raw === undefined ? null : this.materializeResult(raw)
110
+ return { value, stopReason: 'completed', agentsStarted: this.started }
111
+ } catch (error: unknown) {
112
+ return { value: null, stopReason: 'error', error: renderThrown(error), agentsStarted: this.started }
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Attach a no-op rejection consumer WITHOUT changing what the caller
118
+ * receives: if the script drops the promise, a host rejection cannot become
119
+ * an unhandled rejection that kills the process; if
120
+ * the script does await it, it still observes the rejection.
121
+ */
122
+ private contain<T>(promise: Promise<T>): Promise<T> {
123
+ promise.catch(() => { /* consumed: see method contract — a dropped hook promise must not surface an unhandled rejection */ })
124
+ return promise
125
+ }
126
+
127
+ /** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */
128
+ private materializeResult(raw: unknown): unknown {
129
+ try {
130
+ return materializeFromRealm(raw, 'workflow result')
131
+ } catch (error: unknown) {
132
+ /* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */
133
+ if (!(error instanceof MaterializeError)) throw error
134
+ throw new WorkflowError(
135
+ `the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`,
136
+ 'RESULT_UNSERIALIZABLE',
137
+ { cause: error },
138
+ )
139
+ }
140
+ }
141
+
142
+ /** Acquire one concurrency slot in FIFO order. */
143
+ private acquireSlot(): Promise<void> {
144
+ if (this.activeSlots < this.limits.maxConcurrentAgents) {
145
+ this.activeSlots += 1
146
+ return Promise.resolve()
147
+ }
148
+ return new Promise<void>((resolve) => {
149
+ this.slotWaiters.push(() => {
150
+ this.activeSlots += 1
151
+ resolve()
152
+ })
153
+ })
154
+ }
155
+
156
+ private releaseSlot(): void {
157
+ this.activeSlots -= 1
158
+ const next = this.slotWaiters.shift()
159
+ if (next) next()
160
+ }
161
+
162
+ /** The `agent(prompt, opts)` hook. */
163
+ private async agent(rawPrompt: unknown, rawOpts: unknown): Promise<unknown> {
164
+ if (typeof rawPrompt !== 'string' || rawPrompt.length === 0) {
165
+ throw new WorkflowError('agent() requires a non-empty prompt string', 'INVALID_ARGUMENT')
166
+ }
167
+ const opts = this.readAgentOptions(rawOpts)
168
+ if (this.started >= this.limits.maxTotalAgents) {
169
+ throw new WorkflowError(
170
+ `this run reached its total agent cap (${this.limits.maxTotalAgents}) — a runaway-loop backstop; raise the applicable maxTotalAgents limit if the scale is intentional`,
171
+ 'AGENT_CAP',
172
+ )
173
+ }
174
+ this.started += 1
175
+ const seq = this.started
176
+ const label = opts.label ?? defaultLabel(rawPrompt)
177
+ const phase = opts.phase ?? this.currentPhase
178
+
179
+ await this.acquireSlot()
180
+ try {
181
+ let run: ChildHandle
182
+ try {
183
+ run = await this.children.startAgent({
184
+ prompt: rawPrompt,
185
+ ...opts.schema !== undefined ? { schema: opts.schema } : {},
186
+ ...opts.provider !== undefined ? { provider: opts.provider } : {},
187
+ ...opts.model !== undefined ? { model: opts.model } : {},
188
+ })
189
+ } catch (error: unknown) {
190
+ throw new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, 'AGENT_START', { cause: error })
191
+ }
192
+ const info: WorkflowAgentInfo = { seq, label, ...phase !== undefined ? { phase } : {}, childId: brandString<SessionId>(run.id) }
193
+ this.observer.agentStart(info)
194
+ try {
195
+ let result
196
+ try {
197
+ result = await run.result
198
+ } catch (error: unknown) {
199
+ // A rejected child result is an INFRASTRUCTURE fault relayed by the
200
+ // host — distinct from a child that failed and resolved. Pair the
201
+ // lifecycle before propagating, and propagate FATAL: an ordinary
202
+ // throw would dissolve to a per-item null inside the combinators,
203
+ // and a broken provider must not read as a failed child.
204
+ this.observer.agentEnd({ ...info, outcome: 'failed' })
205
+ throw new WorkflowError(`child agent run failed: ${renderThrown(error)}`, 'AGENT_RESULT', { cause: error })
206
+ }
207
+ if (result.stopReason === 'completed') {
208
+ if (opts.schema !== undefined) {
209
+ // The provider honored outputSchema (capability-gated at start), so
210
+ // a completed run without a structured value is a child failure.
211
+ if (result.structured === undefined) {
212
+ this.observer.agentEnd({ ...info, outcome: 'failed' })
213
+ return null
214
+ }
215
+ this.observer.agentEnd({ ...info, outcome: 'completed' })
216
+ return result.structured
217
+ }
218
+ this.observer.agentEnd({ ...info, outcome: 'completed' })
219
+ return outputText(result.output)
220
+ }
221
+ this.observer.agentEnd({ ...info, outcome: 'failed' })
222
+ return null
223
+ } finally {
224
+ await run.dispose()
225
+ }
226
+ } finally {
227
+ this.releaseSlot()
228
+ }
229
+ }
230
+
231
+ /** Materialize + validate the `agent()` options bag from the realm. */
232
+ private readAgentOptions(rawOpts: unknown): {
233
+ label?: string
234
+ phase?: string
235
+ provider?: string
236
+ model?: string
237
+ schema?: ObjectJsonSchema
238
+ } {
239
+ if (rawOpts === undefined) return {}
240
+ let opts: unknown
241
+ try {
242
+ opts = materializeFromRealm(rawOpts, 'agent() options')
243
+ } catch (error: unknown) {
244
+ /* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */
245
+ if (!(error instanceof MaterializeError)) throw error
246
+ throw new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, 'INVALID_ARGUMENT', { cause: error })
247
+ }
248
+ if (typeof opts !== 'object' || opts === null || Array.isArray(opts)) {
249
+ throw new WorkflowError('agent() options must be an object', 'INVALID_ARGUMENT')
250
+ }
251
+ const record = opts as Record<string, unknown>
252
+ for (const key of Object.keys(record)) {
253
+ if (SUPPORTED_AGENT_OPTIONS.has(key)) continue
254
+ if (DEFERRED_AGENT_OPTIONS.has(key)) {
255
+ throw new WorkflowError(`agent() option "${key}" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, 'UNSUPPORTED_OPTION')
256
+ }
257
+ throw new WorkflowError(`agent() option "${key}" is not recognized (supported: label, phase, schema, provider, model)`, 'UNSUPPORTED_OPTION')
258
+ }
259
+ for (const key of ['label', 'phase', 'provider', 'model'] as const) {
260
+ if (record[key] !== undefined && typeof record[key] !== 'string') {
261
+ throw new WorkflowError(`agent() option "${key}" must be a string`, 'INVALID_ARGUMENT')
262
+ }
263
+ }
264
+ let schema: ObjectJsonSchema | undefined
265
+ if (record.schema !== undefined) {
266
+ try {
267
+ assertObjectJsonSchema(record.schema)
268
+ schema = record.schema
269
+ } catch (error: unknown) {
270
+ /* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */
271
+ if (!(error instanceof JsonSchemaError)) throw error
272
+ throw new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, 'UNSUPPORTED_SCHEMA', { cause: error })
273
+ }
274
+ }
275
+ return {
276
+ ...record.label !== undefined ? { label: record.label as string } : {},
277
+ ...record.phase !== undefined ? { phase: record.phase as string } : {},
278
+ ...record.provider !== undefined ? { provider: record.provider as string } : {},
279
+ ...record.model !== undefined ? { model: record.model as string } : {},
280
+ ...schema !== undefined ? { schema } : {},
281
+ }
282
+ }
283
+
284
+ /** The `parallel(thunks)` hook: each thunk caught → `null`; fatal errors propagate. */
285
+ private async parallel(rawThunks: unknown): Promise<unknown[]> {
286
+ if (!Array.isArray(rawThunks)) {
287
+ throw new WorkflowError('parallel() requires an array of zero-argument functions', 'INVALID_ARGUMENT')
288
+ }
289
+ this.assertItemCap(rawThunks.length, 'parallel()')
290
+ const thunks = rawThunks.map((thunk, index) => {
291
+ if (typeof thunk !== 'function') {
292
+ throw new WorkflowError(`parallel() item ${index} is not a function`, 'INVALID_ARGUMENT')
293
+ }
294
+ return thunk as () => unknown
295
+ })
296
+ return Promise.all(thunks.map(async (thunk) => {
297
+ try {
298
+ return await thunk()
299
+ } catch (error: unknown) {
300
+ // Hook failures are WorkflowErrors built OUTSIDE the script's realm;
301
+ // fatality is recognized by `instanceof` against this realm's class —
302
+ // a script-built object can never pass it, so fatality cannot be
303
+ // forged (nor accidentally dissolved).
304
+ if (isFatalWorkflowError(error)) throw error
305
+ return null
306
+ }
307
+ }))
308
+ }
309
+
310
+ /** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */
311
+ private async pipeline(rawItems: unknown, rawStages: unknown[]): Promise<unknown[]> {
312
+ if (!Array.isArray(rawItems)) {
313
+ throw new WorkflowError('pipeline() requires an items array', 'INVALID_ARGUMENT')
314
+ }
315
+ this.assertItemCap(rawItems.length, 'pipeline()')
316
+ if (rawStages.length === 0) {
317
+ throw new WorkflowError('pipeline() requires at least one stage function', 'INVALID_ARGUMENT')
318
+ }
319
+ const stages = rawStages.map((stage, index) => {
320
+ if (typeof stage !== 'function') {
321
+ throw new WorkflowError(`pipeline() stage ${index} is not a function`, 'INVALID_ARGUMENT')
322
+ }
323
+ return stage as (previous: unknown, item: unknown, index: number) => unknown
324
+ })
325
+ return Promise.all(rawItems.map(async (item: unknown, index) => {
326
+ let value: unknown = item
327
+ try {
328
+ for (const stage of stages) {
329
+ value = await stage(value, item, index)
330
+ }
331
+ return value
332
+ } catch (error: unknown) {
333
+ // An ordinary stage throw drops the ITEM to null and skips its
334
+ // remaining stages; a fatal WorkflowError (see parallel()) kills the
335
+ // whole script.
336
+ if (isFatalWorkflowError(error)) throw error
337
+ return null
338
+ }
339
+ }))
340
+ }
341
+
342
+ private assertItemCap(length: number, hook: string): void {
343
+ if (length > this.limits.maxItemsPerCall) {
344
+ throw new WorkflowError(
345
+ `${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`,
346
+ 'ITEM_CAP',
347
+ )
348
+ }
349
+ }
350
+
351
+ /** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */
352
+ private phase(title: unknown): void {
353
+ if (typeof title !== 'string' || title.length === 0) {
354
+ throw new WorkflowError('phase() requires a non-empty title string', 'INVALID_ARGUMENT')
355
+ }
356
+ this.currentPhase = title
357
+ this.observer.phase(title)
358
+ }
359
+
360
+ /** The `log(message)` hook: narration to observers. */
361
+ private log(message: unknown): void {
362
+ if (typeof message !== 'string') {
363
+ throw new WorkflowError('log() requires a message string', 'INVALID_ARGUMENT')
364
+ }
365
+ this.observer.log(message)
366
+ }
367
+ }
package/src/types.ts ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Workflow guest inputs and the child callbacks consumed by its VM helpers.
3
+ * PTC transfers initialization data, requests and results as lossless JSON.
4
+ * @module @deepseek-ai/dsh-workflow-ptc/types
5
+ */
6
+
7
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
8
+ import type { ObjectJsonSchema } from '@deepseek-ai/dsh-tools'
9
+ import type { WorkflowMeta } from '@deepseek-ai/dsh-workflow'
10
+
11
+ /**
12
+ * Ordinary script limits enforced by the guest helpers.
13
+ */
14
+ export interface WorkerLimits {
15
+ /** Concurrent `agent()` ceiling (already auto-resolved; ≥ 1). */
16
+ maxConcurrentAgents: number
17
+ /** Total `agent()` calls per run (the runaway-loop backstop). */
18
+ maxTotalAgents: number
19
+ /** Items accepted by one `parallel()`/`pipeline()` call. */
20
+ maxItemsPerCall: number
21
+ /** VM timeout for the script's initial synchronous slice. */
22
+ syncTimeoutMs: number
23
+ }
24
+
25
+ /** The initialization data returned by the host before the script runs. */
26
+ export interface WorkerInit {
27
+ /** The validated meta block (plain data off the start request, validated host-side). */
28
+ meta: WorkflowMeta
29
+ /** The plain-JS script body, exactly as the start request carried it. */
30
+ body: string
31
+ /** The run's `args` value, copied through the PTC JSON channel. */
32
+ args?: unknown
33
+ /** The guest helper limits. */
34
+ limits: WorkerLimits
35
+ }
36
+
37
+ /** One `agent()` child request after the guest validates script options. */
38
+ export interface ChildStartRequest {
39
+ /** The child's prompt text. */
40
+ prompt: string
41
+ /** The structured-output schema, if the call passed one (already subset-checked). */
42
+ schema?: ObjectJsonSchema
43
+ /** The per-child provider override, if the call passed one. */
44
+ provider?: string
45
+ /** The per-child model override, if the call passed one. */
46
+ model?: string
47
+ }
48
+
49
+ /**
50
+ * The JSON projection of a child's `SubagentResult`. The
51
+ * seam's `stopReason` union is merge-extensible, so it degrades to `string`
52
+ * on the wire — the runtime only ever branches on `'completed'`.
53
+ */
54
+ export interface ChildResult {
55
+ /** The child's final assistant output blocks. */
56
+ output: ContentBlock[]
57
+ /** The structured value, present iff the request carried a schema AND the provider honored it. */
58
+ structured?: unknown
59
+ /** Why the child run ended (`'completed'` is the only value the runtime branches on). */
60
+ stopReason: string
61
+ }
62
+
63
+ /**
64
+ * The guest handle for one published child, reduced to what the VM helpers consume.
65
+ */
66
+ export interface ChildHandle {
67
+ /** The child agent's id (minted host-side by the subagent seam). */
68
+ readonly id: string
69
+ /**
70
+ * Resolves with the child's terminal {@link ChildResult}; REJECTS only when
71
+ * the host reports an infrastructure fault; a child that
72
+ * failed for its own reasons resolves with a non-`completed` stop reason.
73
+ */
74
+ readonly result: Promise<ChildResult>
75
+ /** Ask the host to dispose the child; resolves on the host's ack. */
76
+ dispose(): Promise<void>
77
+ }
78
+
79
+ /**
80
+ * Child callbacks independent of the PTC transport.
81
+ */
82
+ export interface ChildPort {
83
+ /**
84
+ * Start one child agent on the host (the `agent()` hook's start half).
85
+ * @param request - the prompt and validated options.
86
+ * @returns the published child handle; rejects when synchronous start or the
87
+ * provider's asynchronous start fails.
88
+ */
89
+ startAgent(request: ChildStartRequest): Promise<ChildHandle>
90
+ }