@deepseek-ai/dsh-tool-workflow 0.0.1-rc.1 → 0.0.1-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/README.i18n.yaml +2 -2
- package/README.md +7 -2
- package/README.zh.md +9 -4
- package/lib/index.js +82 -5
- package/lib/invariant.js +121 -15
- package/lib/types/index.d.ts +1 -1
- package/lib/types/index.js +278 -0
- package/lib/types/invariant.d.ts +3 -10
- package/lib/types/invariant.js +151 -0
- package/lib/types/types.d.ts +57 -0
- package/lib/types/types.js +8 -0
- package/package.json +23 -17
package/README.i18n.yaml
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
|
3
3
|
# after editing either side, bring the other along and re-record with:
|
|
4
4
|
# pnpm run verify-translation-pairing --write packages/workflow/tool-workflow/README.md
|
|
5
|
-
README.md:
|
|
6
|
-
README.zh.md:
|
|
5
|
+
README.md: 918fe5b9aff74b3b959107ec1eebfd7966afe6d1
|
|
6
|
+
README.zh.md: f7e62560a1b581cf64d78dc379b821d17f29b3aa
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
English | [中文](README.zh.md)
|
|
4
4
|
|
|
5
|
-
The model-facing **`workflow` tool**: run a JavaScript orchestration script that fans out subagents, and return the script's final value. This package owns the model-facing schema and run lifecycle over [`ctx.
|
|
5
|
+
The model-facing **`workflow` tool**: run a JavaScript orchestration script that fans out subagents, and return the script's final value. This package owns the model-facing schema and run lifecycle over [`ctx.workflowEngine`](../workflow/README.md); script parsing, execution, caps, and cancellation live behind the seam, while the consumer retains ownership of the parent-facing schema and result envelope.
|
|
6
6
|
|
|
7
7
|
## What the model sees
|
|
8
8
|
|
|
@@ -12,6 +12,10 @@ Three parameters: `meta` (required identity data: `name`, `description`, and opt
|
|
|
12
12
|
|
|
13
13
|
Collection is synchronous (like [`dsh-tool-subagent`](../../subagent/tool-subagent/README.md)): `execute` starts a run and awaits `run.result` inside a `try/finally` that always disposes the run, so the script and its children reach quiescence on every path. `exec.signal` is bridged to `run.cancel()` (including the already-aborted-before-start case). A non-`completed` stop reason maps to an `isError` result reporting the reason—never partial output as success; a parse/meta failure thrown synchronously by `start()` becomes an `isError` the model can correct from. Completion returns canonical `{ runId, agentsStarted, result }`; the Native renderer preserves the meta name, agent count, and JSON value, truncating only that projection at `maxResultChars`.
|
|
14
14
|
|
|
15
|
+
For a root transport execution (`exec.parent` absent), the tool also projects the run into the calling Agent's Session: run-start after `start()` returns, matching member starts and endings filtered by `run.id`, then run-end only after `run.result` is available and `dispose()` has reached quiescence. Nested transport calls execute normally but write no workflow record. The first failed Session append disables later recording for that run, emits one warning, and leaves either no record or a legal continuous prefix without changing the tool result or cleanup.
|
|
16
|
+
|
|
17
|
+
The browser-safe `@deepseek-ai/dsh-tool-workflow/types` subpath owns these four log-only event payloads and their `SessionEventMap` declaration. The package invariant rejects duplicate starts, unpaired members, terminal events with open members, and updates after run-end on both cold load and live append while accepting missing terminal suffixes.
|
|
18
|
+
|
|
15
19
|
## Render intent
|
|
16
20
|
|
|
17
21
|
Decided up front (per the [render-intent Agent Note](../../../.agents/notes/implemented/architecture/2026-07-02-tool-render-intent-union.md)): a `generic` card titled `workflow: <meta.name>`, read directly from `args.meta.name` (presentation is a pure function of args and does not ask the engine to parse); the script text rides as `rawInput`. The result keeps the generic card.
|
|
@@ -75,6 +79,7 @@ Append-only; newly visible content follows the reusable request prefix and does
|
|
|
75
79
|
|
|
76
80
|
## Known Limitations and Deferred Work
|
|
77
81
|
|
|
78
|
-
- **The parent turn blocks until the whole workflow settles** — there is no background start/poll
|
|
82
|
+
- **The parent turn blocks until the whole workflow settles** — there is no background start/poll API, and cancellation discards partial output as an error.
|
|
79
83
|
- **`args` must be an object and Native result text is bounded** — callers wrap top-level arrays/scalars in a field; the canonical workflow result remains complete, while JSON beyond `maxResultChars` is truncated in the model-facing projection rather than stored behind a retrieval handle.
|
|
80
84
|
- **Workflow policy is fixed per tool registration** — provider selection, caps, and tool name are deployment config, not model-call arguments.
|
|
85
|
+
- **Durable records are top-level and observational** — nested Code Mode dispatches are not recorded, and a recording failure intentionally degrades to an incomplete prefix rather than changing execution.
|
package/README.zh.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[English](README.md) | 中文
|
|
4
4
|
|
|
5
|
-
面向模型的 **`workflow` 工具**:运行一段扇出 subagent 的 JavaScript 编排脚本,并返回脚本的最终值。本包负责基于 [`ctx.
|
|
5
|
+
面向模型的 **`workflow` 工具**:运行一段扇出 subagent 的 JavaScript 编排脚本,并返回脚本的最终值。本包负责基于 [`ctx.workflowEngine`](../workflow/README.md) 定义面向模型的 schema 和运行生命周期;脚本解析、执行、上限与取消位于 seam 之后,消费方仍负责面向父级的 schema 和结果包络。
|
|
6
6
|
|
|
7
7
|
## 模型看到的内容
|
|
8
8
|
|
|
@@ -10,7 +10,11 @@
|
|
|
10
10
|
|
|
11
11
|
## 生命周期
|
|
12
12
|
|
|
13
|
-
收集是同步的(类似 [`dsh-tool-subagent`](../../subagent/tool-subagent/README.md)):`execute` 启动运行并等待 `run.result`;这些操作位于 `try/finally` 中,该结构总会 dispose(资源释放)运行,使脚本及其子 agent(智能体)在每条路径上完全停稳。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果,绝不会把局部输出当作成功;`start()`
|
|
13
|
+
收集是同步的(类似 [`dsh-tool-subagent`](../../subagent/tool-subagent/README.md)):`execute` 启动运行并等待 `run.result`;这些操作位于 `try/finally` 中,该结构总会 dispose(资源释放)运行,使脚本及其子 agent(智能体)在每条路径上完全停稳。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果,绝不会把局部输出当作成功;`start()` 同步抛出的解析/meta 失败会变成模型可据以修正的 `isError`。完成时返回规范值 `{ runId, agentsStarted, result }`;Native 渲染器保留 meta 名称、agent 数量和 JSON 值,只会在 `maxResultChars` 处截断该投影。
|
|
14
|
+
|
|
15
|
+
对于根 transport 执行(`exec.parent` 缺省),工具还会把运行投影到调用 Agent 的 Session:`start()` 返回后写 run-start,只记录 `run.id` 匹配的成员开始与结束,并且只在 `run.result` 已取得且 `dispose()` 完全停稳后写 run-end。嵌套 transport 调用照常执行,但不写工作流记录。任一次 Session append 首次失败后,本运行会停止后续记录并只告警一次,留下空记录或合法连续前缀,同时不改变工具结果和清理。
|
|
16
|
+
|
|
17
|
+
浏览器安全的 `@deepseek-ai/dsh-tool-workflow/types` 子路径拥有这四类 log-only 事件 payload 及其 `SessionEventMap` 声明。包 invariant 会在冷加载和实时追加时拒绝重复 start、未配对成员、仍有开放成员的终点和 run-end 后更新,同时允许缺失终态后缀的连续前缀。
|
|
14
18
|
|
|
15
19
|
## 渲染意图
|
|
16
20
|
|
|
@@ -75,6 +79,7 @@ Use the <toolName> tool ONLY when the user explicitly asks for a workflow or for
|
|
|
75
79
|
|
|
76
80
|
## 已知限制与暂缓事项
|
|
77
81
|
|
|
78
|
-
-
|
|
79
|
-
- **`args` 必须是对象,Native
|
|
82
|
+
- **父级轮次会阻塞到整个工作流结算**:没有后台启动/轮询接口,取消会丢弃局部输出并返回错误。
|
|
83
|
+
- **`args` 必须是对象,Native 结果文本有界**:调用方把顶层数组/标量包装到字段中;规范工作流结果保持完整,超过 `maxResultChars` 的 JSON 会在面向模型的投影中截断,而不是存储在检索句柄背后。
|
|
80
84
|
- **每次工具注册的工作流策略固定**:提供方选择、上限和工具名称属于部署配置,不是模型调用参数。
|
|
85
|
+
- **持久记录只覆盖顶层且只供观察**:嵌套 Code Mode dispatch 不记录;记录故障会刻意退化为不完整前缀,而不改变执行。
|
package/lib/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
|
4
4
|
/**
|
|
5
5
|
* The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
|
|
6
6
|
* subagents, and return the script's final value. It owns the model-facing schema and run lifecycle; script
|
|
7
|
-
* parsing, execution, caps, and cancellation live behind `ctx.
|
|
7
|
+
* parsing, execution, caps, and cancellation live behind `ctx.workflowEngine`
|
|
8
8
|
* (`@deepseek-ai/dsh-workflow`), so a hardened engine swaps in without touching what the model
|
|
9
9
|
* sees. Execution awaits `run.result` and always disposes the run; non-completed reasons become tool
|
|
10
10
|
* errors, and background collection remains deferred. Presentation is an args-only generic card
|
|
@@ -15,13 +15,77 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
|
15
15
|
const name = "tool-workflow";
|
|
16
16
|
const inject = [
|
|
17
17
|
"tools",
|
|
18
|
-
"
|
|
18
|
+
"workflowEngine",
|
|
19
19
|
"systemPrompt"
|
|
20
20
|
];
|
|
21
21
|
const Config = z.object({
|
|
22
22
|
toolName: z.string().default("workflow"),
|
|
23
23
|
maxResultChars: z.natural().min(1).default(5e4)
|
|
24
24
|
});
|
|
25
|
+
/** Render a contained recording failure without trusting the thrown value. */
|
|
26
|
+
function renderRecordingError(error) {
|
|
27
|
+
try {
|
|
28
|
+
return String(error);
|
|
29
|
+
} catch {
|
|
30
|
+
return "[unrenderable thrown value]";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Project active top-level workflow runs into their parent Sessions without
|
|
35
|
+
* letting recording failure affect tool execution.
|
|
36
|
+
*/
|
|
37
|
+
function createWorkflowRecorder(ctx) {
|
|
38
|
+
const active = /* @__PURE__ */ new Map();
|
|
39
|
+
const append = (session, type, data) => {
|
|
40
|
+
const appendRecord = session.append.bind(session);
|
|
41
|
+
try {
|
|
42
|
+
appendRecord(type, data);
|
|
43
|
+
return true;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
ctx.on("workflow/agent-start", (info, agent) => {
|
|
50
|
+
const session = active.get(info.id);
|
|
51
|
+
if (session === void 0) return;
|
|
52
|
+
if (!append(session, "tool-workflow/agent-start", {
|
|
53
|
+
runId: info.id,
|
|
54
|
+
seq: agent.seq,
|
|
55
|
+
label: agent.label,
|
|
56
|
+
...agent.phase === void 0 ? {} : { phase: agent.phase },
|
|
57
|
+
childId: agent.childId
|
|
58
|
+
})) active.delete(info.id);
|
|
59
|
+
});
|
|
60
|
+
ctx.on("workflow/agent-end", (info, agent) => {
|
|
61
|
+
const session = active.get(info.id);
|
|
62
|
+
if (session === void 0) return;
|
|
63
|
+
if (!append(session, "tool-workflow/agent-end", {
|
|
64
|
+
runId: info.id,
|
|
65
|
+
seq: agent.seq,
|
|
66
|
+
outcome: agent.outcome
|
|
67
|
+
})) active.delete(info.id);
|
|
68
|
+
});
|
|
69
|
+
return {
|
|
70
|
+
start(session, run) {
|
|
71
|
+
if (append(session, "tool-workflow/run-start", {
|
|
72
|
+
runId: run.id,
|
|
73
|
+
name: run.meta.name
|
|
74
|
+
})) active.set(run.id, session);
|
|
75
|
+
},
|
|
76
|
+
finish(runId, stopReason) {
|
|
77
|
+
const session = active.get(runId);
|
|
78
|
+
if (session !== void 0) append(session, "tool-workflow/run-end", {
|
|
79
|
+
runId,
|
|
80
|
+
stopReason
|
|
81
|
+
});
|
|
82
|
+
active.delete(runId);
|
|
83
|
+
},
|
|
84
|
+
abandon: (runId) => {
|
|
85
|
+
active.delete(runId);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
25
89
|
/**
|
|
26
90
|
* The script-authoring contract, embedded in the tool description. This IS the
|
|
27
91
|
* model-facing spec: the meta block, the hooks and their exact semantics, and
|
|
@@ -70,6 +134,7 @@ function renderResult(name, agentsStarted, value, maxChars) {
|
|
|
70
134
|
}
|
|
71
135
|
function apply(ctx, config) {
|
|
72
136
|
const { toolName, maxResultChars } = config;
|
|
137
|
+
const recorder = createWorkflowRecorder(ctx);
|
|
73
138
|
ctx.systemPrompt.section({
|
|
74
139
|
name: `tool:${toolName}`,
|
|
75
140
|
order: 115,
|
|
@@ -166,19 +231,22 @@ function apply(ctx, config) {
|
|
|
166
231
|
async execute(args, exec) {
|
|
167
232
|
const parent = exec.agent;
|
|
168
233
|
if (!parent) throw new Error("workflow tool requires a calling agent (exec.agent was undefined)");
|
|
169
|
-
const run = ctx.
|
|
234
|
+
const run = ctx.workflowEngine.start({
|
|
170
235
|
script: args.script,
|
|
171
236
|
meta: args.meta,
|
|
172
237
|
...args.args !== void 0 ? { args: args.args } : {},
|
|
173
238
|
parent,
|
|
174
239
|
signal: exec.signal
|
|
175
240
|
});
|
|
241
|
+
const recordsRun = exec.parent === void 0;
|
|
242
|
+
if (recordsRun) recorder.start(parent.session, run);
|
|
176
243
|
const onAbort = () => {
|
|
177
244
|
run.cancel("parent step aborted");
|
|
178
245
|
};
|
|
179
246
|
exec.signal.addEventListener("abort", onAbort, { once: true });
|
|
247
|
+
let result;
|
|
180
248
|
try {
|
|
181
|
-
|
|
249
|
+
result = await run.result;
|
|
182
250
|
const error = stopReasonError(result);
|
|
183
251
|
if (error !== void 0) throw new Error(error);
|
|
184
252
|
return {
|
|
@@ -188,7 +256,16 @@ function apply(ctx, config) {
|
|
|
188
256
|
};
|
|
189
257
|
} finally {
|
|
190
258
|
exec.signal.removeEventListener("abort", onAbort);
|
|
191
|
-
|
|
259
|
+
try {
|
|
260
|
+
await run.dispose();
|
|
261
|
+
if (recordsRun) {
|
|
262
|
+
/* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
|
|
263
|
+
if (result === void 0) throw new Error("workflow run settled without a result");
|
|
264
|
+
recorder.finish(run.id, result.stopReason);
|
|
265
|
+
}
|
|
266
|
+
} finally {
|
|
267
|
+
if (recordsRun) recorder.abandon(run.id);
|
|
268
|
+
}
|
|
192
269
|
}
|
|
193
270
|
},
|
|
194
271
|
presentCall: (args) => presentWorkflowCall(args),
|
package/lib/invariant.js
CHANGED
|
@@ -1,23 +1,129 @@
|
|
|
1
1
|
//#region lib/types/invariant.js
|
|
2
|
-
/**
|
|
3
|
-
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-workflow`.
|
|
4
|
-
* @module @deepseek-ai/dsh-tool-workflow/invariant
|
|
5
|
-
*/
|
|
2
|
+
/** Package-owned durable workflow-record invariants. @module @deepseek-ai/dsh-tool-workflow/invariant */
|
|
6
3
|
const PACKAGE_NAME = "@deepseek-ai/dsh-tool-workflow";
|
|
7
4
|
/** Cordis companion plugin name. */
|
|
8
5
|
const name = "tool-workflow-invariant";
|
|
9
|
-
/**
|
|
6
|
+
/** Services required to validate existing and newly appended Session logs. */
|
|
10
7
|
const inject = ["invariants"];
|
|
11
|
-
/**
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
*/
|
|
8
|
+
/** Whether this package owns the candidate Session event. */
|
|
9
|
+
function isWorkflowRecordEvent(event) {
|
|
10
|
+
return event.type.startsWith("tool-workflow/");
|
|
11
|
+
}
|
|
12
|
+
/** Require a durable opaque identity to be a non-empty string. */
|
|
13
|
+
function stringId(value, label, fail) {
|
|
14
|
+
if (typeof value !== "string" || value.length === 0) fail(`${label} must be a non-empty string`);
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
/** Require one workflow member's 1-based sequence identity. */
|
|
18
|
+
function memberSeq(value, fail) {
|
|
19
|
+
if (!Number.isSafeInteger(value) || value < 1) fail("tool-workflow member seq must be a positive safe integer");
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
/** Read one plain payload field without trusting restored plugin data. */
|
|
23
|
+
function recordOf(event, fail) {
|
|
24
|
+
const data = event.data;
|
|
25
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) fail(`${event.type} data must be a JSON object`);
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
/** Copy only the run one candidate can mutate; other committed states stay shared. */
|
|
29
|
+
function cloneTraceForEvent(source, event, fail) {
|
|
30
|
+
const trace = new Map(source);
|
|
31
|
+
if (event.type === "tool-workflow/run-start") return trace;
|
|
32
|
+
const runId = stringId(recordOf(event, fail).runId, `${event.type} runId`, fail);
|
|
33
|
+
const run = source.get(runId);
|
|
34
|
+
if (run !== void 0) trace.set(runId, {
|
|
35
|
+
ended: run.ended,
|
|
36
|
+
members: new Map(run.members)
|
|
37
|
+
});
|
|
38
|
+
return trace;
|
|
39
|
+
}
|
|
40
|
+
/** Require the named run to exist and remain open. */
|
|
41
|
+
function openRun(trace, runId, eventType, fail) {
|
|
42
|
+
const run = trace.get(runId);
|
|
43
|
+
if (run === void 0) fail(`${eventType} has no matching tool-workflow/run-start for run ${runId}`);
|
|
44
|
+
if (run.ended) fail(`${eventType} appears after tool-workflow/run-end for run ${runId}`);
|
|
45
|
+
return run;
|
|
46
|
+
}
|
|
47
|
+
/** Advance the workflow-record fold with one relevant Session event. */
|
|
48
|
+
function applyEvent(trace, event, fail) {
|
|
49
|
+
const data = recordOf(event, fail);
|
|
50
|
+
const runId = stringId(data.runId, `${event.type} runId`, fail);
|
|
51
|
+
switch (event.type) {
|
|
52
|
+
case "tool-workflow/run-start":
|
|
53
|
+
if (typeof data.name !== "string" || data.name.length === 0) fail("tool-workflow/run-start name must be a non-empty string");
|
|
54
|
+
if (trace.has(runId)) fail(`tool-workflow/run-start repeats run ${runId}`);
|
|
55
|
+
trace.set(runId, {
|
|
56
|
+
ended: false,
|
|
57
|
+
members: /* @__PURE__ */ new Map()
|
|
58
|
+
});
|
|
59
|
+
return;
|
|
60
|
+
case "tool-workflow/agent-start": {
|
|
61
|
+
const run = openRun(trace, runId, event.type, fail);
|
|
62
|
+
const seq = memberSeq(data.seq, fail);
|
|
63
|
+
if (typeof data.label !== "string") fail("tool-workflow/agent-start label must be a string");
|
|
64
|
+
if (data.phase !== void 0 && typeof data.phase !== "string") fail("tool-workflow/agent-start phase must be a string when present");
|
|
65
|
+
stringId(data.childId, "tool-workflow/agent-start childId", fail);
|
|
66
|
+
if (run.members.has(seq)) fail(`tool-workflow/agent-start repeats member seq ${seq} in run ${runId}`);
|
|
67
|
+
run.members.set(seq, false);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
case "tool-workflow/agent-end": {
|
|
71
|
+
const run = openRun(trace, runId, event.type, fail);
|
|
72
|
+
const seq = memberSeq(data.seq, fail);
|
|
73
|
+
if (data.outcome !== "completed" && data.outcome !== "failed" && data.outcome !== "cancelled") fail(`tool-workflow/agent-end outcome ${String(data.outcome)} is invalid`);
|
|
74
|
+
const ended = run.members.get(seq);
|
|
75
|
+
if (ended === void 0) fail(`tool-workflow/agent-end has no matching member seq ${seq} in run ${runId}`);
|
|
76
|
+
if (ended) fail(`tool-workflow/agent-end repeats member seq ${seq} in run ${runId}`);
|
|
77
|
+
run.members.set(seq, true);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
case "tool-workflow/run-end": {
|
|
81
|
+
const run = openRun(trace, runId, event.type, fail);
|
|
82
|
+
if (data.stopReason !== "completed" && data.stopReason !== "cancelled" && data.stopReason !== "error") fail(`tool-workflow/run-end stopReason ${String(data.stopReason)} is invalid`);
|
|
83
|
+
const openMembers = [...run.members].filter(([, ended]) => !ended).map(([seq]) => seq);
|
|
84
|
+
if (openMembers.length > 0) fail(`tool-workflow/run-end leaves member seq ${openMembers.join(", ")} open in run ${runId}`);
|
|
85
|
+
run.ended = true;
|
|
86
|
+
run.members.clear();
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
default: fail(`unknown tool-workflow event type ${event.type}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Install an independent incremental fold over every attached Session. */
|
|
93
|
+
const install = Object.assign((ctx, fail) => {
|
|
94
|
+
const traces = /* @__PURE__ */ new WeakMap();
|
|
95
|
+
const staged = /* @__PURE__ */ new WeakMap();
|
|
96
|
+
const seed = (session) => {
|
|
97
|
+
const trace = /* @__PURE__ */ new Map();
|
|
98
|
+
for (const event of session.events.filter(isWorkflowRecordEvent)) applyEvent(trace, event, fail);
|
|
99
|
+
traces.set(session, trace);
|
|
100
|
+
return trace;
|
|
101
|
+
};
|
|
102
|
+
ctx.sessions.list().forEach(seed);
|
|
103
|
+
ctx.on("session/created", (session) => {
|
|
104
|
+
seed(session);
|
|
105
|
+
}, { global: true });
|
|
106
|
+
ctx.on("internal/dispatch", (_mode, eventName, args) => {
|
|
107
|
+
if (eventName !== "session/event") return;
|
|
108
|
+
const [session, event] = args;
|
|
109
|
+
if (!isWorkflowRecordEvent(event)) return;
|
|
110
|
+
const trace = cloneTraceForEvent(traces.get(session), event, fail);
|
|
111
|
+
applyEvent(trace, event, fail);
|
|
112
|
+
staged.set(event, {
|
|
113
|
+
session,
|
|
114
|
+
trace
|
|
115
|
+
});
|
|
116
|
+
}, { global: true });
|
|
117
|
+
ctx.on("session/event", (session, event) => {
|
|
118
|
+
if (!isWorkflowRecordEvent(event)) return;
|
|
119
|
+
const candidate = staged.get(event);
|
|
120
|
+
/* v8 ignore next 2 -- internal/dispatch stages the exact session/event callback arguments. */
|
|
121
|
+
if (candidate === void 0 || candidate.session !== session) return fail("session/event reached publication without matching workflow-record validation");
|
|
122
|
+
staged.delete(event);
|
|
123
|
+
traces.set(session, candidate.trace);
|
|
124
|
+
}, { global: true });
|
|
125
|
+
}, { inject: ["sessions"] });
|
|
126
|
+
/** Register this package's invariant companion. */
|
|
21
127
|
const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
22
128
|
//#endregion
|
|
23
129
|
export { apply, inject, name };
|
package/lib/types/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
|
|
3
3
|
* subagents, and return the script's final value. It owns the model-facing schema and run lifecycle; script
|
|
4
|
-
* parsing, execution, caps, and cancellation live behind `ctx.
|
|
4
|
+
* parsing, execution, caps, and cancellation live behind `ctx.workflowEngine`
|
|
5
5
|
* (`@deepseek-ai/dsh-workflow`), so a hardened engine swaps in without touching what the model
|
|
6
6
|
* sees. Execution awaits `run.result` and always disposes the run; non-completed reasons become tool
|
|
7
7
|
* errors, and background collection remains deferred. Presentation is an args-only generic card
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
|
|
3
|
+
* subagents, and return the script's final value. It owns the model-facing schema and run lifecycle; script
|
|
4
|
+
* parsing, execution, caps, and cancellation live behind `ctx.workflowEngine`
|
|
5
|
+
* (`@deepseek-ai/dsh-workflow`), so a hardened engine swaps in without touching what the model
|
|
6
|
+
* sees. Execution awaits `run.result` and always disposes the run; non-completed reasons become tool
|
|
7
|
+
* errors, and background collection remains deferred. Presentation is an args-only generic card
|
|
8
|
+
* titled from `meta.name`. Explicit-ask usage guidance is registered as the tool's own prompt
|
|
9
|
+
* section rather than deployment persona prose.
|
|
10
|
+
* @module @deepseek-ai/dsh-tool-workflow
|
|
11
|
+
*/
|
|
12
|
+
import z from '@deepseek-ai/schemastery';
|
|
13
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
14
|
+
export const name = 'tool-workflow';
|
|
15
|
+
export const inject = ['tools', 'workflowEngine', 'systemPrompt'];
|
|
16
|
+
export const Config = z.object({
|
|
17
|
+
toolName: z.string().default('workflow'),
|
|
18
|
+
maxResultChars: z.natural().min(1).default(50_000),
|
|
19
|
+
});
|
|
20
|
+
/** Render a contained recording failure without trusting the thrown value. */
|
|
21
|
+
function renderRecordingError(error) {
|
|
22
|
+
try {
|
|
23
|
+
return String(error);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return '[unrenderable thrown value]';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Project active top-level workflow runs into their parent Sessions without
|
|
31
|
+
* letting recording failure affect tool execution.
|
|
32
|
+
*/
|
|
33
|
+
function createWorkflowRecorder(ctx) {
|
|
34
|
+
const active = new Map();
|
|
35
|
+
const append = (session, type, data) => {
|
|
36
|
+
// These four package-owned events are all log-only. Narrowing the generic
|
|
37
|
+
// append face here discharges Session.append's conditional options tuple.
|
|
38
|
+
const appendRecord = session.append.bind(session);
|
|
39
|
+
try {
|
|
40
|
+
appendRecord(type, data);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`);
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
ctx.on('workflow/agent-start', (info, agent) => {
|
|
49
|
+
const session = active.get(info.id);
|
|
50
|
+
if (session === undefined)
|
|
51
|
+
return;
|
|
52
|
+
const data = {
|
|
53
|
+
runId: info.id,
|
|
54
|
+
seq: agent.seq,
|
|
55
|
+
label: agent.label,
|
|
56
|
+
...agent.phase === undefined ? {} : { phase: agent.phase },
|
|
57
|
+
childId: agent.childId,
|
|
58
|
+
};
|
|
59
|
+
if (!append(session, 'tool-workflow/agent-start', data))
|
|
60
|
+
active.delete(info.id);
|
|
61
|
+
});
|
|
62
|
+
ctx.on('workflow/agent-end', (info, agent) => {
|
|
63
|
+
const session = active.get(info.id);
|
|
64
|
+
if (session === undefined)
|
|
65
|
+
return;
|
|
66
|
+
const data = {
|
|
67
|
+
runId: info.id,
|
|
68
|
+
seq: agent.seq,
|
|
69
|
+
outcome: agent.outcome,
|
|
70
|
+
};
|
|
71
|
+
if (!append(session, 'tool-workflow/agent-end', data))
|
|
72
|
+
active.delete(info.id);
|
|
73
|
+
});
|
|
74
|
+
return {
|
|
75
|
+
start(session, run) {
|
|
76
|
+
if (append(session, 'tool-workflow/run-start', { runId: run.id, name: run.meta.name })) {
|
|
77
|
+
active.set(run.id, session);
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
finish(runId, stopReason) {
|
|
81
|
+
const session = active.get(runId);
|
|
82
|
+
if (session !== undefined)
|
|
83
|
+
append(session, 'tool-workflow/run-end', { runId, stopReason });
|
|
84
|
+
active.delete(runId);
|
|
85
|
+
},
|
|
86
|
+
abandon: (runId) => { active.delete(runId); },
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The script-authoring contract, embedded in the tool description. This IS the
|
|
91
|
+
* model-facing spec: the meta block, the hooks and their exact semantics, and
|
|
92
|
+
* the supported schema subset.
|
|
93
|
+
*/
|
|
94
|
+
const DESCRIPTION = `Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.
|
|
95
|
+
|
|
96
|
+
The workflow's identity rides the \`meta\` parameter as JSON: required \`name\` (short kebab-case) and \`description\` strings, optional \`whenToUse\` string and \`phases\` array (\`{title, detail?, provider?, model?}\`). The \`script\` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO \`export const meta\` statement — meta is a parameter, not code), running with top-level await; end with \`return <value>\` — the value must be JSON-serializable and is this tool's result.
|
|
97
|
+
|
|
98
|
+
Script-body hooks:
|
|
99
|
+
- \`agent(prompt, opts?): Promise<any>\` — run one subagent to completion. Without \`opts.schema\` it resolves to the child's final text; with \`opts.schema\` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves \`null\` when the child fails (filter with \`.filter(Boolean)\`). Other opts: \`label\` (display), \`phase\` (progress group), and independent \`provider\`/\`model\` LLM target overrides (either may be provided alone). Anything else (\`effort\`/\`isolation\`/\`agentType\`) is rejected loudly.
|
|
100
|
+
- \`pipeline(items, ...stages): Promise<any[]>\` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives \`(prev, item, index)\`. An ordinary stage throw drops that ITEM to \`null\` and skips its remaining stages.
|
|
101
|
+
- \`parallel(thunks): Promise<any[]>\` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to \`null\`.
|
|
102
|
+
- \`phase(title)\` — start a progress phase; \`log(message)\` — narrate progress; \`args\` — the tool call's \`args\` input, verbatim.
|
|
103
|
+
|
|
104
|
+
Misused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item \`null\`.
|
|
105
|
+
|
|
106
|
+
Constraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.`;
|
|
107
|
+
/** The pending-state card: a generic card titled by the workflow's meta name. */
|
|
108
|
+
function presentWorkflowCall(args) {
|
|
109
|
+
return {
|
|
110
|
+
card: 'generic',
|
|
111
|
+
title: `workflow: ${args.meta.name}`,
|
|
112
|
+
rawInput: args.script,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** The completed-state card: keep the pending title; render the result content as-is. */
|
|
116
|
+
function presentWorkflowResult(args, result) {
|
|
117
|
+
void args;
|
|
118
|
+
void result;
|
|
119
|
+
return { card: 'generic' };
|
|
120
|
+
}
|
|
121
|
+
/** A non-`completed` stop reason means the script did not finish cleanly. */
|
|
122
|
+
function stopReasonError(result) {
|
|
123
|
+
switch (result.stopReason) {
|
|
124
|
+
case 'completed':
|
|
125
|
+
return undefined;
|
|
126
|
+
case 'cancelled':
|
|
127
|
+
return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`;
|
|
128
|
+
case 'error':
|
|
129
|
+
return `workflow run failed: ${result.error ?? 'unknown error'}`;
|
|
130
|
+
/* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
|
|
131
|
+
default:
|
|
132
|
+
return `workflow run ended abnormally (${String(result.stopReason)})`;
|
|
133
|
+
/* v8 ignore stop */
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** Render the run's outcome text: the meta name, agent count, and the JSON value (capped). */
|
|
137
|
+
function renderResult(name, agentsStarted, value, maxChars) {
|
|
138
|
+
// The engine returns JSON data (null for a valueless script), so stringify never yields undefined.
|
|
139
|
+
const rendered = JSON.stringify(value, null, 2);
|
|
140
|
+
const clipped = rendered.length > maxChars
|
|
141
|
+
? `${rendered.slice(0, maxChars)}\n… [truncated: ${rendered.length - maxChars} more characters]`
|
|
142
|
+
: rendered;
|
|
143
|
+
return `workflow "${name}" completed (${agentsStarted} agent${agentsStarted === 1 ? '' : 's'}).\nReturn value:\n${clipped}`;
|
|
144
|
+
}
|
|
145
|
+
export function apply(ctx, config) {
|
|
146
|
+
// schemastery (the exported Config schema) has already filled the defaulted
|
|
147
|
+
// fields; the assertion records that resolution, not a hidden fallback.
|
|
148
|
+
const { toolName, maxResultChars } = config;
|
|
149
|
+
const recorder = createWorkflowRecorder(ctx);
|
|
150
|
+
// Usage policy ships with the tool (the master convention: tool guidance
|
|
151
|
+
// lives in tool plugins as prompt sections, not in the deployment persona).
|
|
152
|
+
ctx.systemPrompt.section({
|
|
153
|
+
name: `tool:${toolName}`,
|
|
154
|
+
order: 115,
|
|
155
|
+
text: `Use the ${toolName} tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.`,
|
|
156
|
+
});
|
|
157
|
+
ctx.tools.register(defineTool({
|
|
158
|
+
name: toolName,
|
|
159
|
+
description: DESCRIPTION,
|
|
160
|
+
parameters: {
|
|
161
|
+
script: {
|
|
162
|
+
type: 'string',
|
|
163
|
+
required: true,
|
|
164
|
+
description: 'The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`).',
|
|
165
|
+
},
|
|
166
|
+
meta: {
|
|
167
|
+
type: 'object',
|
|
168
|
+
additionalProperties: true,
|
|
169
|
+
required: true,
|
|
170
|
+
description: 'The workflow identity block (plain JSON — never code).',
|
|
171
|
+
properties: {
|
|
172
|
+
name: { type: 'string', required: true, description: 'Short kebab-case workflow name.' },
|
|
173
|
+
description: { type: 'string', required: true, description: 'One-line description of what the workflow does.' },
|
|
174
|
+
whenToUse: { type: 'string', description: 'Optional guidance on when this workflow applies.' },
|
|
175
|
+
phases: {
|
|
176
|
+
type: 'array',
|
|
177
|
+
description: 'Optional phase declarations matched by phase() calls.',
|
|
178
|
+
items: {
|
|
179
|
+
type: 'object',
|
|
180
|
+
additionalProperties: true,
|
|
181
|
+
properties: {
|
|
182
|
+
title: { type: 'string', required: true, description: 'The phase title phase() calls match by exact string.' },
|
|
183
|
+
detail: { type: 'string', description: 'Optional one-line description of the phase.' },
|
|
184
|
+
provider: { type: 'string', description: 'Optional provider override this phase is expected to use.' },
|
|
185
|
+
model: { type: 'string', description: 'Optional model override this phase is expected to use.' },
|
|
186
|
+
},
|
|
187
|
+
},
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
args: {
|
|
192
|
+
type: 'object',
|
|
193
|
+
additionalProperties: true,
|
|
194
|
+
description: 'Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {"files": [...]}).',
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
output: {
|
|
198
|
+
schema: {
|
|
199
|
+
type: 'object',
|
|
200
|
+
additionalProperties: false,
|
|
201
|
+
properties: {
|
|
202
|
+
runId: { type: 'string', required: true },
|
|
203
|
+
agentsStarted: { type: 'integer', required: true },
|
|
204
|
+
result: { type: 'json', required: true },
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
render: (args, value) => [{
|
|
208
|
+
type: 'text',
|
|
209
|
+
text: renderResult(args.meta.name, value.agentsStarted, value.result, maxResultChars),
|
|
210
|
+
}],
|
|
211
|
+
},
|
|
212
|
+
async execute(args, exec) {
|
|
213
|
+
const parent = exec.agent;
|
|
214
|
+
if (!parent) {
|
|
215
|
+
// The loop sets `exec.agent` for every model-driven call; its absence
|
|
216
|
+
// means a non-agent caller invoked the tool directly, which has no
|
|
217
|
+
// parent to attribute the children to. Fail loud rather than guess.
|
|
218
|
+
throw new Error('workflow tool requires a calling agent (exec.agent was undefined)');
|
|
219
|
+
}
|
|
220
|
+
// Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
|
|
221
|
+
// synchronously here and become isError results via the registry — the
|
|
222
|
+
// model sees the violation list and can correct the call.
|
|
223
|
+
const run = ctx.workflowEngine.start({
|
|
224
|
+
script: args.script,
|
|
225
|
+
meta: args.meta,
|
|
226
|
+
...args.args !== undefined ? { args: args.args } : {},
|
|
227
|
+
parent,
|
|
228
|
+
signal: exec.signal,
|
|
229
|
+
});
|
|
230
|
+
const recordsRun = exec.parent === undefined;
|
|
231
|
+
// The shipped worker-thread engine publishes member events from later
|
|
232
|
+
// worker messages, after start() returns and this run record is active.
|
|
233
|
+
if (recordsRun)
|
|
234
|
+
recorder.start(parent.session, run);
|
|
235
|
+
// Bridge the tool's abort signal to the run: if the parent step is aborted while the
|
|
236
|
+
// script is in flight, cancel the whole run. The signal also enters the engine directly, but
|
|
237
|
+
// this local bridge preserves the tool contract even if an implementation ignores it.
|
|
238
|
+
const onAbort = () => { run.cancel('parent step aborted'); };
|
|
239
|
+
exec.signal.addEventListener('abort', onAbort, { once: true });
|
|
240
|
+
let result;
|
|
241
|
+
try {
|
|
242
|
+
result = await run.result;
|
|
243
|
+
const error = stopReasonError(result);
|
|
244
|
+
if (error !== undefined) {
|
|
245
|
+
// Map a non-clean finish to an isError result (the registry turns a
|
|
246
|
+
// throw into an isError). Report the reason, not partial output.
|
|
247
|
+
throw new Error(error);
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
runId: run.id,
|
|
251
|
+
agentsStarted: result.agentsStarted,
|
|
252
|
+
result: result.value,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
exec.signal.removeEventListener('abort', onAbort);
|
|
257
|
+
try {
|
|
258
|
+
// Keep member listeners alive through disposal: an engine may
|
|
259
|
+
// synthesize cancelled member endings while reaching quiescence.
|
|
260
|
+
await run.dispose();
|
|
261
|
+
if (recordsRun) {
|
|
262
|
+
/* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
|
|
263
|
+
if (result === undefined)
|
|
264
|
+
throw new Error('workflow run settled without a result');
|
|
265
|
+
recorder.finish(run.id, result.stopReason);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
finally {
|
|
269
|
+
if (recordsRun)
|
|
270
|
+
recorder.abandon(run.id);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
},
|
|
274
|
+
presentCall: args => presentWorkflowCall(args),
|
|
275
|
+
presentResult: (args, result) => presentWorkflowResult(args, result),
|
|
276
|
+
}));
|
|
277
|
+
}
|
|
278
|
+
//# sourceMappingURL=index.js.map
|
package/lib/types/invariant.d.ts
CHANGED
|
@@ -1,16 +1,9 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Package-owned invariant companion for `@deepseek-ai/dsh-tool-workflow`.
|
|
3
|
-
* @module @deepseek-ai/dsh-tool-workflow/invariant
|
|
4
|
-
*/
|
|
1
|
+
/** Package-owned durable workflow-record invariants. @module @deepseek-ai/dsh-tool-workflow/invariant */
|
|
5
2
|
import type { Context } from '@deepseek-ai/cordis';
|
|
6
3
|
/** Cordis companion plugin name. */
|
|
7
4
|
export declare const name = "tool-workflow-invariant";
|
|
8
|
-
/**
|
|
5
|
+
/** Services required to validate existing and newly appended Session logs. */
|
|
9
6
|
export declare const inject: string[];
|
|
10
|
-
/**
|
|
11
|
-
* Register this package's invariant companion.
|
|
12
|
-
* @param ctx - Cordis context carrying the invariant service.
|
|
13
|
-
* @returns the installed registration's disposer after setup succeeds.
|
|
14
|
-
*/
|
|
7
|
+
/** Register this package's invariant companion. */
|
|
15
8
|
export declare const apply: (ctx: Context) => Promise<() => void>;
|
|
16
9
|
//# sourceMappingURL=invariant.d.ts.map
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/** Package-owned durable workflow-record invariants. @module @deepseek-ai/dsh-tool-workflow/invariant */
|
|
2
|
+
const PACKAGE_NAME = '@deepseek-ai/dsh-tool-workflow';
|
|
3
|
+
/** Cordis companion plugin name. */
|
|
4
|
+
export const name = 'tool-workflow-invariant';
|
|
5
|
+
/** Services required to validate existing and newly appended Session logs. */
|
|
6
|
+
export const inject = ['invariants'];
|
|
7
|
+
/** Whether this package owns the candidate Session event. */
|
|
8
|
+
function isWorkflowRecordEvent(event) {
|
|
9
|
+
return event.type.startsWith('tool-workflow/');
|
|
10
|
+
}
|
|
11
|
+
/** Require a durable opaque identity to be a non-empty string. */
|
|
12
|
+
function stringId(value, label, fail) {
|
|
13
|
+
if (typeof value !== 'string' || value.length === 0)
|
|
14
|
+
fail(`${label} must be a non-empty string`);
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
/** Require one workflow member's 1-based sequence identity. */
|
|
18
|
+
function memberSeq(value, fail) {
|
|
19
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
20
|
+
fail('tool-workflow member seq must be a positive safe integer');
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
/** Read one plain payload field without trusting restored plugin data. */
|
|
25
|
+
function recordOf(event, fail) {
|
|
26
|
+
const data = event.data;
|
|
27
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
|
|
28
|
+
fail(`${event.type} data must be a JSON object`);
|
|
29
|
+
}
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
|
+
/** Copy only the run one candidate can mutate; other committed states stay shared. */
|
|
33
|
+
function cloneTraceForEvent(source, event, fail) {
|
|
34
|
+
const trace = new Map(source);
|
|
35
|
+
if (event.type === 'tool-workflow/run-start')
|
|
36
|
+
return trace;
|
|
37
|
+
const data = recordOf(event, fail);
|
|
38
|
+
const runId = stringId(data.runId, `${event.type} runId`, fail);
|
|
39
|
+
const run = source.get(runId);
|
|
40
|
+
if (run !== undefined) {
|
|
41
|
+
trace.set(runId, { ended: run.ended, members: new Map(run.members) });
|
|
42
|
+
}
|
|
43
|
+
return trace;
|
|
44
|
+
}
|
|
45
|
+
/** Require the named run to exist and remain open. */
|
|
46
|
+
function openRun(trace, runId, eventType, fail) {
|
|
47
|
+
const run = trace.get(runId);
|
|
48
|
+
if (run === undefined)
|
|
49
|
+
fail(`${eventType} has no matching tool-workflow/run-start for run ${runId}`);
|
|
50
|
+
if (run.ended)
|
|
51
|
+
fail(`${eventType} appears after tool-workflow/run-end for run ${runId}`);
|
|
52
|
+
return run;
|
|
53
|
+
}
|
|
54
|
+
/** Advance the workflow-record fold with one relevant Session event. */
|
|
55
|
+
function applyEvent(trace, event, fail) {
|
|
56
|
+
const data = recordOf(event, fail);
|
|
57
|
+
const runId = stringId(data.runId, `${event.type} runId`, fail);
|
|
58
|
+
switch (event.type) {
|
|
59
|
+
case 'tool-workflow/run-start': {
|
|
60
|
+
if (typeof data.name !== 'string' || data.name.length === 0) {
|
|
61
|
+
fail('tool-workflow/run-start name must be a non-empty string');
|
|
62
|
+
}
|
|
63
|
+
if (trace.has(runId))
|
|
64
|
+
fail(`tool-workflow/run-start repeats run ${runId}`);
|
|
65
|
+
trace.set(runId, { ended: false, members: new Map() });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
case 'tool-workflow/agent-start': {
|
|
69
|
+
const run = openRun(trace, runId, event.type, fail);
|
|
70
|
+
const seq = memberSeq(data.seq, fail);
|
|
71
|
+
if (typeof data.label !== 'string')
|
|
72
|
+
fail('tool-workflow/agent-start label must be a string');
|
|
73
|
+
if (data.phase !== undefined && typeof data.phase !== 'string') {
|
|
74
|
+
fail('tool-workflow/agent-start phase must be a string when present');
|
|
75
|
+
}
|
|
76
|
+
stringId(data.childId, 'tool-workflow/agent-start childId', fail);
|
|
77
|
+
if (run.members.has(seq))
|
|
78
|
+
fail(`tool-workflow/agent-start repeats member seq ${seq} in run ${runId}`);
|
|
79
|
+
run.members.set(seq, false);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
case 'tool-workflow/agent-end': {
|
|
83
|
+
const run = openRun(trace, runId, event.type, fail);
|
|
84
|
+
const seq = memberSeq(data.seq, fail);
|
|
85
|
+
if (data.outcome !== 'completed' && data.outcome !== 'failed' && data.outcome !== 'cancelled') {
|
|
86
|
+
fail(`tool-workflow/agent-end outcome ${String(data.outcome)} is invalid`);
|
|
87
|
+
}
|
|
88
|
+
const ended = run.members.get(seq);
|
|
89
|
+
if (ended === undefined)
|
|
90
|
+
fail(`tool-workflow/agent-end has no matching member seq ${seq} in run ${runId}`);
|
|
91
|
+
if (ended)
|
|
92
|
+
fail(`tool-workflow/agent-end repeats member seq ${seq} in run ${runId}`);
|
|
93
|
+
run.members.set(seq, true);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
case 'tool-workflow/run-end': {
|
|
97
|
+
const run = openRun(trace, runId, event.type, fail);
|
|
98
|
+
if (data.stopReason !== 'completed' && data.stopReason !== 'cancelled' && data.stopReason !== 'error') {
|
|
99
|
+
fail(`tool-workflow/run-end stopReason ${String(data.stopReason)} is invalid`);
|
|
100
|
+
}
|
|
101
|
+
const openMembers = [...run.members].filter(([, ended]) => !ended).map(([seq]) => seq);
|
|
102
|
+
if (openMembers.length > 0) {
|
|
103
|
+
fail(`tool-workflow/run-end leaves member seq ${openMembers.join(', ')} open in run ${runId}`);
|
|
104
|
+
}
|
|
105
|
+
run.ended = true;
|
|
106
|
+
run.members.clear();
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
default:
|
|
110
|
+
fail(`unknown tool-workflow event type ${event.type}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Install an independent incremental fold over every attached Session. */
|
|
114
|
+
const install = Object.assign((ctx, fail) => {
|
|
115
|
+
const traces = new WeakMap();
|
|
116
|
+
const staged = new WeakMap();
|
|
117
|
+
const seed = (session) => {
|
|
118
|
+
const trace = new Map();
|
|
119
|
+
for (const event of session.events.filter(isWorkflowRecordEvent))
|
|
120
|
+
applyEvent(trace, event, fail);
|
|
121
|
+
traces.set(session, trace);
|
|
122
|
+
return trace;
|
|
123
|
+
};
|
|
124
|
+
ctx.sessions.list().forEach(seed);
|
|
125
|
+
ctx.on('session/created', (session) => { seed(session); }, { global: true });
|
|
126
|
+
ctx.on('internal/dispatch', (_mode, eventName, args) => {
|
|
127
|
+
if (eventName !== 'session/event')
|
|
128
|
+
return;
|
|
129
|
+
const [session, event] = args;
|
|
130
|
+
if (!isWorkflowRecordEvent(event))
|
|
131
|
+
return;
|
|
132
|
+
// session/event dispatch follows list() or session/created seeding.
|
|
133
|
+
const trace = cloneTraceForEvent(traces.get(session), event, fail);
|
|
134
|
+
applyEvent(trace, event, fail);
|
|
135
|
+
staged.set(event, { session, trace });
|
|
136
|
+
}, { global: true });
|
|
137
|
+
ctx.on('session/event', (session, event) => {
|
|
138
|
+
if (!isWorkflowRecordEvent(event))
|
|
139
|
+
return;
|
|
140
|
+
const candidate = staged.get(event);
|
|
141
|
+
/* v8 ignore next 2 -- internal/dispatch stages the exact session/event callback arguments. */
|
|
142
|
+
if (candidate === undefined || candidate.session !== session) {
|
|
143
|
+
return fail('session/event reached publication without matching workflow-record validation');
|
|
144
|
+
}
|
|
145
|
+
staged.delete(event);
|
|
146
|
+
traces.set(session, candidate.trace);
|
|
147
|
+
}, { global: true });
|
|
148
|
+
}, { inject: ['sessions'] });
|
|
149
|
+
/** Register this package's invariant companion. */
|
|
150
|
+
export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
|
|
151
|
+
//# sourceMappingURL=invariant.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-safe durable workflow-record events written by the model-facing
|
|
3
|
+
* workflow tool into its calling parent Session.
|
|
4
|
+
*
|
|
5
|
+
* @module @deepseek-ai/dsh-tool-workflow/types
|
|
6
|
+
*/
|
|
7
|
+
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
|
8
|
+
import type { WorkflowAgentOutcome, WorkflowRunId, WorkflowStopReason } from '@deepseek-ai/dsh-workflow/types';
|
|
9
|
+
/** Opens one durable top-level workflow run record. */
|
|
10
|
+
export interface ToolWorkflowRunStartData {
|
|
11
|
+
readonly runId: WorkflowRunId;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
}
|
|
14
|
+
/** Records one workflow member after its child Session is published. */
|
|
15
|
+
export interface ToolWorkflowAgentStartData {
|
|
16
|
+
readonly runId: WorkflowRunId;
|
|
17
|
+
readonly seq: number;
|
|
18
|
+
readonly label: string;
|
|
19
|
+
readonly phase?: string;
|
|
20
|
+
readonly childId: SessionId;
|
|
21
|
+
}
|
|
22
|
+
/** Settles one previously started workflow member. */
|
|
23
|
+
export interface ToolWorkflowAgentEndData {
|
|
24
|
+
readonly runId: WorkflowRunId;
|
|
25
|
+
readonly seq: number;
|
|
26
|
+
readonly outcome: WorkflowAgentOutcome;
|
|
27
|
+
}
|
|
28
|
+
/** Settles one workflow run after its live resources reach quiescence. */
|
|
29
|
+
export interface ToolWorkflowRunEndData {
|
|
30
|
+
readonly runId: WorkflowRunId;
|
|
31
|
+
readonly stopReason: WorkflowStopReason;
|
|
32
|
+
}
|
|
33
|
+
declare module '@deepseek-ai/dsh-session/types' {
|
|
34
|
+
interface SessionEventMap {
|
|
35
|
+
/**
|
|
36
|
+
* Opens one top-level workflow record.
|
|
37
|
+
* @param data - stable run identity and display name.
|
|
38
|
+
*/
|
|
39
|
+
'tool-workflow/run-start': ToolWorkflowRunStartData;
|
|
40
|
+
/**
|
|
41
|
+
* Records one published workflow member.
|
|
42
|
+
* @param data - run identity, member sequence, display identity, and child Session.
|
|
43
|
+
*/
|
|
44
|
+
'tool-workflow/agent-start': ToolWorkflowAgentStartData;
|
|
45
|
+
/**
|
|
46
|
+
* Records one member settlement.
|
|
47
|
+
* @param data - run identity, paired member sequence, and outcome.
|
|
48
|
+
*/
|
|
49
|
+
'tool-workflow/agent-end': ToolWorkflowAgentEndData;
|
|
50
|
+
/**
|
|
51
|
+
* Closes one workflow record after cleanup.
|
|
52
|
+
* @param data - stable run identity and terminal reason.
|
|
53
|
+
*/
|
|
54
|
+
'tool-workflow/run-end': ToolWorkflowRunEndData;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=types.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepseek-ai/dsh-tool-workflow",
|
|
3
|
-
"description": "Model-facing workflow tool: run a JavaScript orchestration script over ctx.
|
|
4
|
-
"version": "0.0.1-rc.
|
|
3
|
+
"description": "Model-facing workflow tool: run a JavaScript orchestration script over ctx.workflowEngine",
|
|
4
|
+
"version": "0.0.1-rc.3",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "restricted"
|
|
7
7
|
},
|
|
@@ -22,37 +22,43 @@
|
|
|
22
22
|
"types": "./lib/types/invariant.d.ts",
|
|
23
23
|
"default": "./lib/invariant.js"
|
|
24
24
|
},
|
|
25
|
+
"./types": {
|
|
26
|
+
"types": "./lib/types/types.d.ts",
|
|
27
|
+
"default": "./lib/types/types.js"
|
|
28
|
+
},
|
|
25
29
|
"./src/*": "./src/*",
|
|
26
30
|
"./package.json": "./package.json"
|
|
27
31
|
},
|
|
28
32
|
"files": [
|
|
29
33
|
"lib/index.js",
|
|
30
34
|
"lib/invariant.js",
|
|
35
|
+
"lib/types/**/*.js",
|
|
31
36
|
"lib/types/**/*.d.ts"
|
|
32
37
|
],
|
|
33
38
|
"license": "BSD-3-Clause",
|
|
34
39
|
"peerDependencies": {
|
|
35
|
-
"@deepseek-ai/dsh-
|
|
36
|
-
"@deepseek-ai/dsh-
|
|
37
|
-
"@deepseek-ai/dsh-
|
|
38
|
-
"@deepseek-ai/dsh-
|
|
40
|
+
"@deepseek-ai/dsh-invariants": "^0.0.1-rc.3",
|
|
41
|
+
"@deepseek-ai/dsh-agent": "^0.0.1-rc.3",
|
|
42
|
+
"@deepseek-ai/dsh-llm": "^0.0.1-rc.3",
|
|
43
|
+
"@deepseek-ai/dsh-session": "^0.0.1-rc.3",
|
|
44
|
+
"@deepseek-ai/dsh-system-prompt": "^0.0.1-rc.3",
|
|
45
|
+
"@deepseek-ai/dsh-tools": "^0.0.1-rc.3",
|
|
39
46
|
"@deepseek-ai/cordis": "^4.0.1-rc.1",
|
|
40
|
-
"@deepseek-ai/dsh-
|
|
41
|
-
"@deepseek-ai/dsh-invariants": "^0.0.1-rc.1"
|
|
47
|
+
"@deepseek-ai/dsh-workflow": "^0.0.1-rc.3"
|
|
42
48
|
},
|
|
43
49
|
"dependencies": {
|
|
44
50
|
"@deepseek-ai/schemastery": "^3.18.1-rc.1"
|
|
45
51
|
},
|
|
46
52
|
"devDependencies": {
|
|
47
|
-
"@deepseek-ai/dsh-
|
|
48
|
-
"@deepseek-ai/dsh-
|
|
49
|
-
"@deepseek-ai/dsh-
|
|
50
|
-
"@deepseek-ai/dsh-
|
|
51
|
-
"@deepseek-ai/dsh-
|
|
52
|
-
"@deepseek-ai/dsh-system-prompt": "^0.0.1-rc.
|
|
53
|
-
"@deepseek-ai/dsh-tools": "^0.0.1-rc.
|
|
54
|
-
"@deepseek-ai/dsh-workflow": "^0.0.1-rc.
|
|
55
|
-
"@deepseek-ai/dsh-workflow-
|
|
53
|
+
"@deepseek-ai/dsh-agent": "^0.0.1-rc.3",
|
|
54
|
+
"@deepseek-ai/dsh-invariants": "^0.0.1-rc.3",
|
|
55
|
+
"@deepseek-ai/dsh-session": "^0.0.1-rc.3",
|
|
56
|
+
"@deepseek-ai/dsh-llm": "^0.0.1-rc.3",
|
|
57
|
+
"@deepseek-ai/dsh-subagent": "^0.0.1-rc.3",
|
|
58
|
+
"@deepseek-ai/dsh-system-prompt": "^0.0.1-rc.3",
|
|
59
|
+
"@deepseek-ai/dsh-tools": "^0.0.1-rc.3",
|
|
60
|
+
"@deepseek-ai/dsh-workflow": "^0.0.1-rc.3",
|
|
61
|
+
"@deepseek-ai/dsh-workflow-worker-thread": "^0.0.1-rc.3",
|
|
56
62
|
"@deepseek-ai/cordis": "^4.0.1-rc.1"
|
|
57
63
|
}
|
|
58
64
|
}
|