@deepseek-ai/dsh-workflow 0.0.1-rc.1

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/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, DeepSeek
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/workflow/workflow/README.md
5
+ README.md: 0de661423206cc71eb4669bc8ddb2419202bcb4a
6
+ README.zh.md: 62abd00c013d054f4111a2db2ce72c58d3514087
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @deepseek-ai/dsh-workflow
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ The workflow seam (`ctx.workflows`) executes a model-written orchestration script that can fan out subagents. The seam defines the script, run, result, error, and event contracts; an engine decides how to isolate and execute the script.
6
+
7
+ `@deepseek-ai/dsh-workflow-workerthread` is the current engine and `@deepseek-ai/dsh-tool-workflow` is the model-facing consumer. A future process or sandbox engine can replace the implementation without changing the tool.
8
+
9
+ ## Service and run contract
10
+
11
+ `WorkflowService.start(request): WorkflowRun` validates enough synchronously to reject a malformed meta block, unparseable script, unavailable provider route, or unsupported per-run limit before a run exists. Once returned, `WorkflowRun.result` never rejects: execution failures resolve with `stopReason: 'error'`, and cancellation resolves with `cancelled` within the engine's bounded grace.
12
+
13
+ A run is holder-owned. Engine-plugin unload prevents new starts but does not revoke accepted runs. The holder must call `dispose()` on every path; disposal cancels remaining work and reaches or abandons quiescence within the documented bound.
14
+
15
+ `WorkflowStartRequest` contains `{ meta, script, args?, subagentProvider?, maxTotalAgents?, parent, signal? }`. `parent` attributes every child agent to the invoking agent. `subagentProvider` optionally routes every child in that run without exposing provider choice to the script; omission uses the engine's configured provider. `maxTotalAgents` optionally lowers the engine's deployment ceiling for one run and is likewise invisible to the script. An implementation rejects invalid routes and limits synchronously. `meta` and `args` are plain data, not script fragments.
16
+
17
+ `WorkflowRun` exposes `{ id, meta, result, cancel(reason?), dispose() }`. `WorkflowResult` contains `{ value, stopReason, error?, agentsStarted }`; `value` is plain JSON data or `null`.
18
+
19
+ ## Events
20
+
21
+ Workflow events are observe-only. They carry `WorkflowRunInfo` (`id` plus `meta`) rather than the live run, so listeners cannot acquire cancellation or disposal authority.
22
+
23
+ - `workflow/start` / `workflow/end` pair the run.
24
+ - `workflow/phase` and `workflow/log` expose script narration.
25
+ - `workflow/agent-start` / `workflow/agent-end` pair each child call by `seq`; a child whose async provider start rejects emits neither.
26
+
27
+ Same-process event payloads are borrowed immutable values. Every listener is independently contained: a synchronous throw or rejected returned promise is logged without starving peers or changing execution.
28
+
29
+ ## Failure discipline
30
+
31
+ `WorkflowError` carries a code and a `fatal` flag. Fatal errors always escape `parallel()` and `pipeline()` instead of becoming an ordinary per-item `null`:
32
+
33
+ - `SCRIPT_PARSE` / `META_INVALID` — the workflow cannot start.
34
+ - `INVALID_ARGUMENT` / `UNSUPPORTED_OPTION` / `UNSUPPORTED_SCHEMA` — a hook call violates the engine contract.
35
+ - `AGENT_CAP` / `ITEM_CAP` — configured safety limits were exceeded.
36
+ - `AGENT_START` — the provider's async start rejected.
37
+ - `AGENT_RESULT` — a published child's result rejected with an infrastructure fault.
38
+ - `RESULT_UNSERIALIZABLE` — a script/worker value is not plain JSON data.
39
+ - `CANCELLED` — cancellation owns the run and pending/future hooks reject.
40
+
41
+ A child that resolves normally with a non-completed stop reason is not an infrastructure exception: `agent()` returns `null`, allowing the script to handle an ordinary child failure.
42
+
43
+ ## Model Experience
44
+
45
+ Indirectly, through `dsh-tool-workflow` and a workflow engine, which create child-agent requests and return a retained parent tool result.
46
+
47
+ #### KV Cache effect
48
+
49
+ No direct invalidation; the named consumer owns any request-prefix changes.
50
+
51
+ ## Known Limitations and Deferred Work
52
+
53
+ - **Foreground collection only** — the caller owns one live run and awaits it; background start/poll, spill handles, and detached collection are deferred.
54
+ - **No journaling or resume** — scripts, child progress, and intermediate values are not checkpointed, so a process restart cannot continue a run.
55
+ - **No saved or nested workflows** — the seam starts caller-supplied scripts only, and a workflow script receives no `workflow()` hook for recursive orchestration.
56
+ - **No token-budget vocabulary** — engines cap concurrency, items, and children, but neither the request nor result accounts for model tokens across children.
57
+ - **Runs are holder-owned, not service-tracked** — unloading the engine does not discover independent live handles; every consumer must dispose the run it started.
58
+
59
+ See the [dynamic-workflows Agent Note](../../../.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md) for the deferred workflow surface.
package/README.zh.md ADDED
@@ -0,0 +1,59 @@
1
+ # @deepseek-ai/dsh-workflow
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 工作流 seam(`ctx.workflows`)执行由模型编写、可扇出 subagent 的编排脚本。该 seam 定义脚本、运行、结果、错误和事件约定;引擎负责决定如何隔离并执行脚本。
6
+
7
+ `@deepseek-ai/dsh-workflow-workerthread` 是当前引擎,`@deepseek-ai/dsh-tool-workflow` 是面向模型的消费方。未来的进程或沙箱引擎可以替换实现,而无需更改工具。
8
+
9
+ ## 服务与运行约定
10
+
11
+ `WorkflowService.start(request): WorkflowRun` 会同步完成足够多的校验,在运行创建前拒绝格式错误的 meta 块、无法解析的脚本、不可用的提供方路由或不受支持的单次运行限制。返回后,`WorkflowRun.result` 绝不拒绝:执行失败以 `stopReason: 'error'` 兑现,取消则在引擎有限的宽限时间内以 `cancelled` 兑现。
12
+
13
+ 运行由持有方负责。引擎插件卸载会阻止新的启动,但不会撤销已接受的运行。持有方必须在每条路径上调用 `dispose()`;dispose(资源释放)会取消剩余工作,并在文档规定的期限内达到或放弃完全停稳。
14
+
15
+ `WorkflowStartRequest` 包含 `{ meta, script, args?, subagentProvider?, maxTotalAgents?, parent, signal? }`。`parent` 把每个子 agent(智能体)归属于调用 agent。`subagentProvider` 可以为该次运行的所有子 agent 指定路由,同时不向脚本公开提供方选择;省略时使用引擎配置的提供方。`maxTotalAgents` 可以为一次运行降低引擎的部署上限,同样对脚本不可见。实现会同步拒绝无效路由和限制。`meta` 与 `args` 是普通数据,不是脚本片段。
16
+
17
+ `WorkflowRun` 公开 `{ id, meta, result, cancel(reason?), dispose() }`。`WorkflowResult` 包含 `{ value, stopReason, error?, agentsStarted }`;`value` 是普通 JSON 数据或 `null`。
18
+
19
+ ## 事件
20
+
21
+ 工作流事件只供观察。它们携带 `WorkflowRunInfo`(`id` 加 `meta`),而不是活动运行,因此监听器无法取得取消或 dispose 权限。
22
+
23
+ - `workflow/start` / `workflow/end` 为运行配对;
24
+ - `workflow/phase` 和 `workflow/log` 公开脚本叙述;
25
+ - `workflow/agent-start` / `workflow/agent-end` 按 `seq` 为每次子 agent 调用配对;提供方的异步启动调用被拒绝时,该子 agent 不会发出其中任何一个事件。
26
+
27
+ 同进程事件 payload 是借用的不可变值。每个监听器都独立隔离:同步抛出异常或返回的 promise 被拒绝时,只会记录日志,不会阻塞同级监听器或改变执行。
28
+
29
+ ## 失败纪律
30
+
31
+ `WorkflowError` 携带一个代码和 `fatal` 标志。致命错误总会逸出 `parallel()` 和 `pipeline()`,而不会变成普通的逐项 `null`:
32
+
33
+ - `SCRIPT_PARSE` / `META_INVALID`:工作流无法启动;
34
+ - `INVALID_ARGUMENT` / `UNSUPPORTED_OPTION` / `UNSUPPORTED_SCHEMA`:钩子调用违反引擎约定;
35
+ - `AGENT_CAP` / `ITEM_CAP`:超过已配置的安全上限;
36
+ - `AGENT_START`:提供方的异步启动调用被拒绝;
37
+ - `AGENT_RESULT`:已发布子 agent 的结果因基础设施故障而被拒绝;
38
+ - `RESULT_UNSERIALIZABLE`:脚本/worker 值不是普通 JSON 数据;
39
+ - `CANCELLED`:取消会接管该运行,待处理和后续的钩子调用都会被拒绝。
40
+
41
+ 子 agent 若以非完成的结束原因正常兑现,并不属于基础设施异常:`agent()` 返回 `null`,使脚本可以处理普通的子 agent 失败。
42
+
43
+ ## 模型体验
44
+
45
+ 通过 `dsh-tool-workflow` 和工作流引擎间接产生影响;两者创建子 agent 请求,并返回保留在父级的工具结果。
46
+
47
+ #### KV Cache 影响
48
+
49
+ 不会直接导致 KV Cache 失效;请求前缀的任何变化均由上述消费方负责。
50
+
51
+ ## 已知限制与暂缓事项
52
+
53
+ - **仅支持前台收集**:调用方负责一个活动运行并等待它;后台启动/轮询、spill 句柄和分离收集均暂缓处理。
54
+ - **没有日志化或恢复**:脚本、子 agent 进度和中间值均不设检查点,因此进程重启后无法继续运行。
55
+ - **没有已保存或嵌套工作流**:该 seam 只启动调用方提供的脚本,工作流脚本不会收到用于递归编排的 `workflow()` 钩子。
56
+ - **没有 token 预算词汇**:引擎会限制并发、条目和子 agent,但请求与结果都不会统计跨子 agent 的模型 token。
57
+ - **运行由持有方负责,不由服务跟踪**:卸载引擎不会发现独立的活动句柄;每个消费方都必须 dispose 自己启动的运行。
58
+
59
+ 暂缓实现的工作流接口见[动态工作流 Agent Note](../../../.agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md)。
package/lib/index.js ADDED
@@ -0,0 +1,92 @@
1
+ import { Service } from "@deepseek-ai/cordis";
2
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
3
+ //#region lib/types/types.js
4
+ /**
5
+ * Workflow seam vocabulary: the request/run/result types a workflow engine
6
+ * consumes and produces, plus the fields in the `workflow/*` event payloads.
7
+ * Types only (plus the id-brand factory), per the package convention.
8
+ *
9
+ * @module @deepseek-ai/dsh-workflow/types
10
+ */
11
+ /**
12
+ * Brand a string as a {@link WorkflowRunId}.
13
+ * @param id - the raw id string (the engine mints UUIDs; tests may pass fixtures).
14
+ * @returns the same string, branded.
15
+ */
16
+ function WorkflowRunId(id) {
17
+ return id;
18
+ }
19
+ //#endregion
20
+ //#region lib/types/index.js
21
+ /**
22
+ * Service Definition for the workflow capability seam. Service providers execute orchestration scripts;
23
+ * observe-only lifecycle events never expose run control.
24
+ * @module @deepseek-ai/dsh-workflow
25
+ */
26
+ /**
27
+ * Typed error for workflow-seam failures. Extends {@link HarnessError}, so the
28
+ * `code` is machine-routable taxonomy. `fatal` drives the combinator
29
+ * discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd
30
+ * option or a tripped cap must kill the script loudly), and reserve the
31
+ * per-item `null` for child-run failures and ordinary in-stage script errors.
32
+ * Every {@link WorkflowErrorCode} is fatal; the flag exists so the
33
+ * distinction is explicit at every catch site rather than implied.
34
+ */
35
+ var WorkflowError = class extends HarnessError {
36
+ /** Whether combinators must propagate this error instead of nulling the item. */
37
+ fatal;
38
+ constructor(message, code, options) {
39
+ super(message, code, options);
40
+ this.name = "WorkflowError";
41
+ this.fatal = options?.fatal ?? true;
42
+ }
43
+ };
44
+ /**
45
+ * Whether combinators must re-throw `error` instead of mapping the item to `null`.
46
+ * @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).
47
+ * @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.
48
+ */
49
+ function isFatalWorkflowError(error) {
50
+ return error instanceof WorkflowError && error.fatal;
51
+ }
52
+ /**
53
+ * Workflow Service Definition contract. Invalid requests throw before publication; a live
54
+ * run is holder-owned, its result never rejects, cancellation and disposal are
55
+ * bounded, and disposal waits for child cleanup within that bound. Lifecycle
56
+ * listener failures are contained, and `workflow/end` fires exactly once as the
57
+ * result settles.
58
+ */
59
+ var WorkflowService = class extends Service {
60
+ constructor(ctx) {
61
+ super(ctx, "workflows");
62
+ }
63
+ /**
64
+ * Emit a lifecycle event while containing and logging each listener failure.
65
+ * @param name - the `workflow/*` event to dispatch.
66
+ * @param args - the event's payload, matching its declared signature.
67
+ */
68
+ emitWorkflowEvent(name, ...args) {
69
+ for (const callback of this.ctx.events.dispatch("emit", [name, ...args])) try {
70
+ const returned = callback(...args);
71
+ Promise.resolve(returned).catch((error) => {
72
+ this.ctx.logger.warn(`workflow: ${name} listener rejected: ${renderListenerError(error)}`);
73
+ });
74
+ } catch (error) {
75
+ this.ctx.logger.warn(`workflow: ${name} listener threw: ${renderListenerError(error)}`);
76
+ }
77
+ }
78
+ };
79
+ /**
80
+ * Render any thrown value without violating listener containment.
81
+ * @param error - any thrown value.
82
+ * @returns `String(error)`, or a fixed label when even coercion throws.
83
+ */
84
+ function renderListenerError(error) {
85
+ try {
86
+ return String(error);
87
+ } catch {
88
+ return "[unrenderable thrown value]";
89
+ }
90
+ }
91
+ //#endregion
92
+ export { WorkflowError, WorkflowRunId, WorkflowService, WorkflowService as default, isFatalWorkflowError };
@@ -0,0 +1,100 @@
1
+ //#region lib/types/invariant.js
2
+ /** Package-owned workflow lifecycle invariants. @module @deepseek-ai/dsh-workflow/invariant */
3
+ const PACKAGE_NAME = "@deepseek-ai/dsh-workflow";
4
+ /** Cordis companion plugin name. */
5
+ const name = "workflow-invariant";
6
+ /** Service required before the companion can reserve package ownership. */
7
+ const inject = ["invariants"];
8
+ /** Require every event for a run to retain its validated identity snapshot. */
9
+ function traceFor(traces, info, fail) {
10
+ const trace = traces.get(info.id);
11
+ if (trace === void 0) fail(`workflow event has no matching workflow/start for run ${JSON.stringify(info.id)}`);
12
+ if (trace.meta !== JSON.stringify(info.meta)) fail(`workflow event meta diverges from workflow/start for run ${JSON.stringify(info.id)}`);
13
+ return trace;
14
+ }
15
+ /** Assert the immutable identity fields shared by an agent pair. */
16
+ function validateAgentEnd(start, end, fail) {
17
+ if (start.label !== end.label || start.phase !== end.phase || start.childId !== end.childId) fail(`workflow/agent-end identity diverges from workflow/agent-start for seq ${end.seq}`);
18
+ const outcome = end.outcome;
19
+ if (outcome !== "completed" && outcome !== "failed" && outcome !== "cancelled") fail(`workflow/agent-end carries unknown outcome ${JSON.stringify(outcome)}`);
20
+ }
21
+ /** Validate a terminal result against the accumulated run trace. */
22
+ function validateWorkflowEnd(trace, result, fail) {
23
+ if (trace.agents.size > 0) fail(`workflow/end has ${trace.agents.size} agent call(s) without workflow/agent-end`);
24
+ if (!Number.isSafeInteger(result.agentsStarted) || result.agentsStarted < trace.starts) fail("workflow/end agentsStarted must be a safe integer covering every observed agent start");
25
+ if (result.stopReason === "completed" ? result.error !== void 0 : typeof result.error !== "string") fail("workflow/end error must be absent exactly for completed runs");
26
+ }
27
+ /** Install workflow start/end and child-call pairing checks. */
28
+ const install = (ctx, fail) => {
29
+ const traces = /* @__PURE__ */ new Map();
30
+ const stagedStarts = /* @__PURE__ */ new WeakSet();
31
+ const stagedAgentStarts = /* @__PURE__ */ new WeakSet();
32
+ const stagedAgentEnds = /* @__PURE__ */ new WeakSet();
33
+ const stagedEnds = /* @__PURE__ */ new WeakSet();
34
+ ctx.on("internal/dispatch", (_mode, eventName, args) => {
35
+ if (eventName === "workflow/start") {
36
+ const info = args[0];
37
+ if (String(info.id).length === 0 || info.meta.name.length === 0 || info.meta.description.length === 0) fail("workflow/start id, meta.name, and meta.description must be non-empty");
38
+ if (traces.has(info.id)) fail(`workflow/start repeated run id ${JSON.stringify(info.id)}`);
39
+ stagedStarts.add(info);
40
+ return;
41
+ }
42
+ if (!eventName.startsWith("workflow/")) return;
43
+ const info = args[0];
44
+ const trace = traceFor(traces, info, fail);
45
+ if (eventName === "workflow/agent-start") {
46
+ const agent = args[1];
47
+ if (!Number.isSafeInteger(agent.seq) || agent.seq < 1 || String(agent.childId).length === 0) fail("workflow/agent-start seq must be positive and childId must be non-empty");
48
+ if (trace.agents.has(agent.seq)) fail(`workflow/agent-start repeated seq ${agent.seq}`);
49
+ stagedAgentStarts.add(agent);
50
+ return;
51
+ }
52
+ if (eventName === "workflow/agent-end") {
53
+ const agent = args[1];
54
+ const start = trace.agents.get(agent.seq);
55
+ if (start === void 0) return fail(`workflow/agent-end has no matching start for seq ${agent.seq}`);
56
+ validateAgentEnd(start, agent, fail);
57
+ stagedAgentEnds.add(agent);
58
+ return;
59
+ }
60
+ if (eventName === "workflow/end") {
61
+ const result = args[1];
62
+ validateWorkflowEnd(trace, result, fail);
63
+ stagedEnds.add(result);
64
+ }
65
+ }, { global: true });
66
+ ctx.on("workflow/start", (info) => {
67
+ /* v8 ignore next -- internal/dispatch stages the same run-info object */
68
+ if (!stagedStarts.delete(info)) return;
69
+ traces.set(info.id, {
70
+ meta: JSON.stringify(info.meta),
71
+ agents: /* @__PURE__ */ new Map(),
72
+ starts: 0
73
+ });
74
+ }, { global: true });
75
+ ctx.on("workflow/agent-start", (info, agent) => {
76
+ /* v8 ignore next -- internal/dispatch stages the same agent object */
77
+ if (!stagedAgentStarts.delete(agent)) return;
78
+ const trace = traceFor(traces, info, fail);
79
+ trace.agents.set(agent.seq, agent);
80
+ trace.starts += 1;
81
+ }, { global: true });
82
+ ctx.on("workflow/agent-end", (info, agent) => {
83
+ /* v8 ignore next -- internal/dispatch stages the same agent object */
84
+ if (!stagedAgentEnds.delete(agent)) return;
85
+ traceFor(traces, info, fail).agents.delete(agent.seq);
86
+ }, { global: true });
87
+ ctx.on("workflow/end", (info, result) => {
88
+ /* v8 ignore next -- internal/dispatch stages the same result object */
89
+ if (!stagedEnds.delete(result)) return;
90
+ traces.delete(info.id);
91
+ }, { global: true });
92
+ };
93
+ /**
94
+ * Register the workflow invariant companion.
95
+ * @param ctx - Cordis context carrying the invariant service.
96
+ * @returns the installed registration's disposer after setup succeeds.
97
+ */
98
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
99
+ //#endregion
100
+ export { apply, inject, name };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Service Definition for the workflow capability seam. Service providers execute orchestration scripts;
3
+ * observe-only lifecycle events never expose run control.
4
+ * @module @deepseek-ai/dsh-workflow
5
+ */
6
+ import { Context, Service } from '@deepseek-ai/cordis';
7
+ import { HarnessError } from '@deepseek-ai/dsh-llm';
8
+ import type { WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowResultInfo, WorkflowRun, WorkflowRunInfo, WorkflowStartRequest } from './types.ts';
9
+ export { WorkflowRunId } from './types.ts';
10
+ export type { WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowAgentOutcome, WorkflowMeta, WorkflowPhase, WorkflowResult, WorkflowResultInfo, WorkflowRun, WorkflowRunInfo, WorkflowStartRequest, WorkflowStopReason, } from './types.ts';
11
+ declare module '@deepseek-ai/cordis' {
12
+ interface Context {
13
+ workflows: WorkflowService;
14
+ }
15
+ interface Events {
16
+ /**
17
+ * A workflow run started — the script's meta block validated, the body
18
+ * about to execute. Paired with {@link Events['workflow/end']}.
19
+ * @param info - the run's identity snapshot (id + meta).
20
+ * @mode emit
21
+ */
22
+ 'workflow/start'(info: WorkflowRunInfo): void;
23
+ /**
24
+ * The script entered a phase (a `phase(title)` call) — progress grouping
25
+ * for observers; no execution semantics.
26
+ * @param info - the run's identity snapshot.
27
+ * @param title - the phase title, verbatim.
28
+ * @mode emit
29
+ */
30
+ 'workflow/phase'(info: WorkflowRunInfo, title: string): void;
31
+ /**
32
+ * The script emitted a narration line (a `log(message)` call).
33
+ * @param info - the run's identity snapshot.
34
+ * @param message - the logged message, verbatim.
35
+ * @mode emit
36
+ */
37
+ 'workflow/log'(info: WorkflowRunInfo, message: string): void;
38
+ /**
39
+ * One `agent()` call established a published child run. Paired with
40
+ * {@link Events['workflow/agent-end']} by `agent.seq`. A call that never
41
+ * receives a published run from the provider emits neither
42
+ * event in this pair.
43
+ * @param info - the run's identity snapshot.
44
+ * @param agent - the call's sequence number, label, phase, and child id.
45
+ * @mode emit
46
+ */
47
+ 'workflow/agent-start'(info: WorkflowRunInfo, agent: WorkflowAgentInfo): void;
48
+ /**
49
+ * One `agent()` call settled (clean result, child failure, or run
50
+ * cancellation). Paired with {@link Events['workflow/agent-start']} by
51
+ * `agent.seq`, exactly once per started call on every stop path — on an
52
+ * engine termination path (a worker killed past its grace) the end is
53
+ * engine-synthesized with outcome `'cancelled'`.
54
+ * @param info - the run's identity snapshot.
55
+ * @param agent - the call identity plus its outcome.
56
+ * @mode emit
57
+ */
58
+ 'workflow/agent-end'(info: WorkflowRunInfo, agent: WorkflowAgentEndInfo): void;
59
+ /**
60
+ * A workflow run settled (any stop reason). Fired when
61
+ * {@link WorkflowRun.result} resolves. Paired with
62
+ * {@link Events['workflow/start']}.
63
+ * @param info - the run's identity snapshot.
64
+ * @param result - the outcome data (stop reason, error, agent count) —
65
+ * deliberately WITHOUT the result value (see {@link WorkflowResultInfo}).
66
+ * @mode emit
67
+ */
68
+ 'workflow/end'(info: WorkflowRunInfo, result: WorkflowResultInfo): void;
69
+ }
70
+ }
71
+ /** The full set of `workflow/*` event names {@link WorkflowService.emitWorkflowEvent} dispatches. */
72
+ export type WorkflowEventName = 'workflow/start' | 'workflow/phase' | 'workflow/log' | 'workflow/agent-start' | 'workflow/agent-end' | 'workflow/end';
73
+ /**
74
+ * Machine-routable fatal workflow failures: parse/meta/argument/schema errors,
75
+ * resource caps, subagent infrastructure failures, unserializable boundary
76
+ * values, and cancellation. An ordinary child failure resolves its item to
77
+ * `null` and is not one of these fatal codes.
78
+ */
79
+ export type WorkflowErrorCode = 'SCRIPT_PARSE' | 'META_INVALID' | 'INVALID_ARGUMENT' | 'UNSUPPORTED_OPTION' | 'UNSUPPORTED_SCHEMA' | 'AGENT_CAP' | 'ITEM_CAP' | 'AGENT_START' | 'AGENT_RESULT' | 'RESULT_UNSERIALIZABLE' | 'CANCELLED';
80
+ /**
81
+ * Typed error for workflow-seam failures. Extends {@link HarnessError}, so the
82
+ * `code` is machine-routable taxonomy. `fatal` drives the combinator
83
+ * discipline: `parallel()`/`pipeline()` re-throw a fatal error (a typo'd
84
+ * option or a tripped cap must kill the script loudly), and reserve the
85
+ * per-item `null` for child-run failures and ordinary in-stage script errors.
86
+ * Every {@link WorkflowErrorCode} is fatal; the flag exists so the
87
+ * distinction is explicit at every catch site rather than implied.
88
+ */
89
+ export declare class WorkflowError extends HarnessError {
90
+ /** Whether combinators must propagate this error instead of nulling the item. */
91
+ readonly fatal: boolean;
92
+ constructor(message: string, code: WorkflowErrorCode, options?: ErrorOptions & {
93
+ fatal?: boolean;
94
+ });
95
+ }
96
+ /**
97
+ * Whether combinators must re-throw `error` instead of mapping the item to `null`.
98
+ * @param error - any thrown value; fatality is host `instanceof` (unforgeable from a script realm).
99
+ * @returns true iff `error` is a {@link WorkflowError} whose `fatal` flag is set.
100
+ */
101
+ export declare function isFatalWorkflowError(error: unknown): boolean;
102
+ /**
103
+ * Workflow Service Definition contract. Invalid requests throw before publication; a live
104
+ * run is holder-owned, its result never rejects, cancellation and disposal are
105
+ * bounded, and disposal waits for child cleanup within that bound. Lifecycle
106
+ * listener failures are contained, and `workflow/end` fires exactly once as the
107
+ * result settles.
108
+ */
109
+ export declare abstract class WorkflowService extends Service {
110
+ constructor(ctx: Context);
111
+ /**
112
+ * Parse and execute a workflow script.
113
+ * @param request - the script, its `args`, the parent agent, and an
114
+ * optional cancel signal.
115
+ * @returns the live run; its `result` resolves when the script settles.
116
+ */
117
+ abstract start(request: WorkflowStartRequest): WorkflowRun;
118
+ /**
119
+ * Emit a lifecycle event while containing and logging each listener failure.
120
+ * @param name - the `workflow/*` event to dispatch.
121
+ * @param args - the event's payload, matching its declared signature.
122
+ */
123
+ protected emitWorkflowEvent(name: WorkflowEventName, ...args: unknown[]): void;
124
+ }
125
+ export default WorkflowService;
126
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,13 @@
1
+ /** Package-owned workflow lifecycle invariants. @module @deepseek-ai/dsh-workflow/invariant */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ /** Cordis companion plugin name. */
4
+ export declare const name = "workflow-invariant";
5
+ /** Service required before the companion can reserve package ownership. */
6
+ export declare const inject: string[];
7
+ /**
8
+ * Register the workflow invariant companion.
9
+ * @param ctx - Cordis context carrying the invariant service.
10
+ * @returns the installed registration's disposer after setup succeeds.
11
+ */
12
+ export declare const apply: (ctx: Context) => Promise<() => void>;
13
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Workflow seam vocabulary: the request/run/result types a workflow engine
3
+ * consumes and produces, plus the fields in the `workflow/*` event payloads.
4
+ * Types only (plus the id-brand factory), per the package convention.
5
+ *
6
+ * @module @deepseek-ai/dsh-workflow/types
7
+ */
8
+ import type { Branded } from '@deepseek-ai/dsh-brand';
9
+ import type { Agent } from '@deepseek-ai/dsh-agent';
10
+ import type { SessionId } from '@deepseek-ai/dsh-session';
11
+ /** Identifies one workflow run. */
12
+ export type WorkflowRunId = Branded<'WorkflowRunId'>;
13
+ /**
14
+ * Brand a string as a {@link WorkflowRunId}.
15
+ * @param id - the raw id string (the engine mints UUIDs; tests may pass fixtures).
16
+ * @returns the same string, branded.
17
+ */
18
+ export declare function WorkflowRunId(id: string): WorkflowRunId;
19
+ /**
20
+ * One phase declared in a script's `meta.phases` (progress vocabulary only —
21
+ * phases group agents in observers/UIs; they impose no execution structure).
22
+ */
23
+ export interface WorkflowPhase {
24
+ /** The phase title; `phase()` calls match against it by exact string. */
25
+ title: string;
26
+ /** Optional one-line description of what the phase does. */
27
+ detail?: string;
28
+ /** Optional provider override this phase is expected to use (informational). */
29
+ provider?: string;
30
+ /** Optional model override this phase is expected to use (informational). */
31
+ model?: string;
32
+ }
33
+ /**
34
+ * The script's identity block, provided as plain JSON data alongside the
35
+ * script body (the model-facing tool carries it as its `meta` parameter) and
36
+ * validated by the engine before the body runs. `name`/`description` are
37
+ * required; the rest is optional annotation. The field vocabulary matches the
38
+ * Claude Code dynamic-workflows meta block.
39
+ */
40
+ export interface WorkflowMeta {
41
+ /** Short kebab-case workflow name (display + persistence key). */
42
+ name: string;
43
+ /** One-line description of what the workflow does. */
44
+ description: string;
45
+ /** Optional guidance on when this workflow applies (shown in listings). */
46
+ whenToUse?: string;
47
+ /** Optional phase declarations matched by `phase()` calls. */
48
+ phases?: WorkflowPhase[];
49
+ }
50
+ /**
51
+ * What a caller asks for when starting a workflow run. `meta` and `args` are
52
+ * plain JSON DATA by the seam contract (the tool builds both from the model's schema-validated call;
53
+ * the engine validates `meta` against its schema and rejects loud
54
+ * before anything runs) — an engine never evaluates script text to obtain
55
+ * them. `parent` is REQUIRED — every `agent()` the script spawns is
56
+ * attributed to it (cwd, lineage, depth flow through the subagent seam).
57
+ */
58
+ export interface WorkflowStartRequest {
59
+ /** The plain-JS script body (top-level await allowed; ends with `return <json-value>`). */
60
+ script: string;
61
+ /** The workflow's identity fields as plain JSON data, validated by the engine. */
62
+ meta: WorkflowMeta;
63
+ /** Optional input exposed verbatim to the script as the `args` global. */
64
+ args?: unknown;
65
+ /**
66
+ * Optional engine-wide child-provider override for this run. The workflow
67
+ * script cannot observe or replace it; omission uses the engine's configured
68
+ * provider.
69
+ */
70
+ subagentProvider?: string;
71
+ /**
72
+ * Optional per-run total-child ceiling. Implementations reject values above
73
+ * their deployment ceiling before publishing the run.
74
+ */
75
+ maxTotalAgents?: number;
76
+ /** The agent on whose behalf the run executes (parent of every child). */
77
+ parent: Agent;
78
+ /** Cancels the run when aborted (the tool's `exec.signal`). */
79
+ signal?: AbortSignal;
80
+ }
81
+ /**
82
+ * Why a run settled. CLOSED union (engine-owned, consumers may exhaust):
83
+ * `completed` = the script ran to its final `return`; `cancelled` = the run
84
+ * was cancelled (caller `cancel()`/signal); `error` = the script threw, a
85
+ * fatal `WorkflowError` propagated, or the result failed materialization.
86
+ */
87
+ export type WorkflowStopReason = 'completed' | 'cancelled' | 'error';
88
+ /**
89
+ * The outcome of one run, resolved by {@link WorkflowRun.result}. `value` is
90
+ * the script's materialized return value (plain host-realm JSON data; `null`
91
+ * when the script returned `undefined`) — meaningful only for `completed`.
92
+ * A non-`completed` reason carries the failure in `error`; the consumer maps
93
+ * it to an `isError` tool result rather than reporting partial output.
94
+ */
95
+ export interface WorkflowResult {
96
+ /** The script's return value (host JSON data; `null` for no return). */
97
+ value: unknown;
98
+ /** Why the run settled. */
99
+ stopReason: WorkflowStopReason;
100
+ /** The failure message (present iff `stopReason` is not `completed`). */
101
+ error?: string;
102
+ /**
103
+ * How many `agent()` calls the run accepted over its whole lifetime. On a
104
+ * graceful settlement this is the script-side count (calls still queued for
105
+ * a concurrency slot included); on a termination path (grace force-settle,
106
+ * worker death) it degrades to the host-observed count — calls queued
107
+ * inside a terminated script are unknowable then.
108
+ */
109
+ agentsStarted: number;
110
+ }
111
+ /**
112
+ * Holder-owned live workflow. `result` never rejects and settles within the
113
+ * engine's cancellation grace; failures resolve through `stopReason`. Consumers
114
+ * may cancel and must call idempotent `dispose()` on every path to await bounded
115
+ * script settlement and child quiescence.
116
+ */
117
+ export interface WorkflowRun {
118
+ readonly id: WorkflowRunId;
119
+ /** The validated meta block (available before the body runs). */
120
+ readonly meta: WorkflowMeta;
121
+ readonly result: Promise<WorkflowResult>;
122
+ /** Cancel the run: children abort, pending hooks reject, the script dies at its next await (or is force-settled at the grace). */
123
+ cancel(reason?: string): void;
124
+ /** Cancel + bounded-grace settle; safe to call on every path (idempotent). */
125
+ dispose(): Promise<void>;
126
+ }
127
+ /** Identifying detail for a run, carried by every `workflow/*` event as borrowed immutable data, never the live run. */
128
+ export interface WorkflowRunInfo {
129
+ /** The run's id. */
130
+ id: WorkflowRunId;
131
+ /** The run's validated meta block. */
132
+ meta: WorkflowMeta;
133
+ }
134
+ /** One `agent()` call's identity within a run (the `workflow/agent-start` payload). */
135
+ export interface WorkflowAgentInfo {
136
+ /** 1-based sequence number of this `agent()` call within the run. */
137
+ seq: number;
138
+ /** The display label (the `label` option, or a prompt snippet). */
139
+ label: string;
140
+ /** The phase this agent belongs to (the `phase` option, else the current `phase()` title). */
141
+ phase?: string;
142
+ /** The child agent's id on the subagent seam. */
143
+ childId: SessionId;
144
+ }
145
+ /** How one `agent()` call settled: clean result, child failure (script sees `null`), or run cancellation. */
146
+ export type WorkflowAgentOutcome = 'completed' | 'failed' | 'cancelled';
147
+ /** One `agent()` call's settlement (the `workflow/agent-end` payload). */
148
+ export interface WorkflowAgentEndInfo extends WorkflowAgentInfo {
149
+ /** How the call settled. */
150
+ outcome: WorkflowAgentOutcome;
151
+ }
152
+ /**
153
+ * A settled run's outcome as event data (the `workflow/end` payload): the
154
+ * {@link WorkflowResult} minus `value` (a listener observing outcomes must not
155
+ * receive a mutable alias of the caller's result value; a consumer that needs
156
+ * the value holds the run and awaits `result`).
157
+ */
158
+ export interface WorkflowResultInfo {
159
+ /** Why the run settled. */
160
+ stopReason: WorkflowStopReason;
161
+ /** The failure message (present iff `stopReason` is not `completed`). */
162
+ error?: string;
163
+ /** How many `agent()` calls the run accepted (see {@link WorkflowResult.agentsStarted}). */
164
+ agentsStarted: number;
165
+ }
166
+ //# sourceMappingURL=types.d.ts.map
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@deepseek-ai/dsh-workflow",
3
+ "description": "Workflow capability seam: ctx.workflows service, run vocabulary, and workflow/* events",
4
+ "version": "0.0.1-rc.1",
5
+ "publishConfig": {
6
+ "access": "restricted"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
11
+ "directory": "packages/workflow/workflow"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./invariant": {
22
+ "types": "./lib/types/invariant.d.ts",
23
+ "default": "./lib/invariant.js"
24
+ },
25
+ "./src/*": "./src/*",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "lib/index.js",
30
+ "lib/invariant.js",
31
+ "lib/types/**/*.d.ts"
32
+ ],
33
+ "license": "BSD-3-Clause",
34
+ "peerDependencies": {
35
+ "@deepseek-ai/dsh-agent": "^0.0.1-rc.1",
36
+ "@deepseek-ai/dsh-brand": "^0.0.1-rc.1",
37
+ "@deepseek-ai/dsh-invariants": "^0.0.1-rc.1",
38
+ "@deepseek-ai/dsh-llm": "^0.0.1-rc.1",
39
+ "@deepseek-ai/dsh-session": "^0.0.1-rc.1",
40
+ "@deepseek-ai/cordis": "^4.0.1-rc.1"
41
+ },
42
+ "devDependencies": {
43
+ "@deepseek-ai/dsh-agent": "^0.0.1-rc.1",
44
+ "@deepseek-ai/dsh-brand": "^0.0.1-rc.1",
45
+ "@deepseek-ai/dsh-llm": "^0.0.1-rc.1",
46
+ "@deepseek-ai/dsh-session": "^0.0.1-rc.1",
47
+ "@deepseek-ai/cordis": "^4.0.1-rc.1",
48
+ "@deepseek-ai/dsh-invariants": "^0.0.1-rc.1"
49
+ }
50
+ }