ralphflow-dsh 2.1.0 → 2.2.0

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/lib/engine.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { WorkflowStatus } from "./status-contract.js";
2
+ import type { WorkflowUiRef } from "./message-source.js";
1
3
  import { MAX_VOTERS, formatVotingFailureReason, formatVotingInfraReason, formatVotingPassReason, voterProgressLine, voterStatusLabel } from "./voting.js";
2
4
  export { MAX_VOTERS };
3
5
  export { formatVotingFailureReason, formatVotingPassReason, formatVotingInfraReason, voterProgressLine, voterStatusLabel };
@@ -564,7 +566,10 @@ export interface EnginePorts {
564
566
  */
565
567
  deliverNotice: (sessionId: string, text: string, summary?: string, opts?: {
566
568
  dedupe?: boolean;
569
+ uiRef?: WorkflowUiRef;
567
570
  }) => boolean;
571
+ /** Observe committed facts only; failures of this observer never affect the engine. */
572
+ statusChanged?: () => void;
568
573
  /**
569
574
  * 把该会话**挂起的播报**在安全边界补齐(可见面尾部工具配对平衡时才落)。
570
575
  *
@@ -673,7 +678,17 @@ export declare function formatDuration(ms: number): string;
673
678
  * slug 为空(任务全是空白/被剥字符)→ 直接回退整个 `instId`(保证目录名非空且唯一)。
674
679
  */
675
680
  export declare function makeArtifactsDirName(task: string, instId: string): string;
676
- /** 内置工作流文件(不落盘,只存在于插件目录;lib/engine.js → ../workflows/<name>.yaml) */
681
+ /**
682
+ * 内置工作流文件(不落盘,只存在于插件目录;lib/engine.js → ../workflows/<name>.yaml)。
683
+ *
684
+ * 取模块目录**必须**用 `fileURLToPath`:`new URL(import.meta.url).pathname` 不做百分号解码,
685
+ * Windows 上还给出 `/C:/…`(盘符前多一个 `/`,`path.resolve` 之后盘符变成一个**字面目录名**)。
686
+ * 两者都让 `statSync` 必然失败 → 内置工作流回落不到 → 全新安装时一个可用工作流都没有
687
+ * (`listWorkflows` 无条件列出 `loop`/`spec`,于是表现为「(无描述)(定义无效)」)。
688
+ *
689
+ * 这条路径在纯 ASCII 的 Linux/macOS 上**静默正常**,所以只有 Windows、或安装路径带空格/非
690
+ * ASCII 字符时才会暴露 —— 回归见 `scripts/builtin-workflow-path-test.mjs`。
691
+ */
677
692
  export declare function builtinWorkflowPath(name: string): string | undefined;
678
693
  /** 全局工作流目录:`<DSH_HOME|~/.dsh>/ralph-flow/workflows` */
679
694
  export declare function globalWorkflowsDirOf(): string;
@@ -733,6 +748,11 @@ export declare function createEngine(projectDir: string, ports: EnginePorts): {
733
748
  restore: () => void;
734
749
  diagnose: () => ToolResult;
735
750
  activeInstanceOfSession: (sessionId: string) => InstanceInfo | undefined;
751
+ uiStatus: (sessionId: string) => {
752
+ status: WorkflowStatus | null;
753
+ error: string | null;
754
+ };
755
+ uiReport: (ref: WorkflowUiRef) => WorkflowStatus | null;
736
756
  };
737
757
  export type Engine = ReturnType<typeof createEngine>;
738
758
  export declare const BUILTIN_WORKFLOWS: string[];
package/lib/engine.js CHANGED
@@ -11,6 +11,7 @@
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import os from "node:os";
14
+ import { fileURLToPath } from "node:url";
14
15
  import yaml from "js-yaml";
15
16
  import { MAX_VOTERS, decideVotingOutcome, formatVotingFailureReason, formatVotingInfraReason, formatVotingPassReason, voterProgressLine, voterStatusLabel, } from "./voting.js";
16
17
  // 纯函数层(聚合优先级与三份文案)的唯一实现在 voting.ts;这里只把常量与展示标签转出去,
@@ -656,9 +657,19 @@ export function makeArtifactsDirName(task, instId) {
656
657
  const suffix = String(instId).split("-").pop() || "0";
657
658
  return slug ? `${slug}-${suffix}` : String(instId);
658
659
  }
659
- /** 内置工作流文件(不落盘,只存在于插件目录;lib/engine.js → ../workflows/<name>.yaml) */
660
+ /**
661
+ * 内置工作流文件(不落盘,只存在于插件目录;lib/engine.js → ../workflows/<name>.yaml)。
662
+ *
663
+ * 取模块目录**必须**用 `fileURLToPath`:`new URL(import.meta.url).pathname` 不做百分号解码,
664
+ * Windows 上还给出 `/C:/…`(盘符前多一个 `/`,`path.resolve` 之后盘符变成一个**字面目录名**)。
665
+ * 两者都让 `statSync` 必然失败 → 内置工作流回落不到 → 全新安装时一个可用工作流都没有
666
+ * (`listWorkflows` 无条件列出 `loop`/`spec`,于是表现为「(无描述)(定义无效)」)。
667
+ *
668
+ * 这条路径在纯 ASCII 的 Linux/macOS 上**静默正常**,所以只有 Windows、或安装路径带空格/非
669
+ * ASCII 字符时才会暴露 —— 回归见 `scripts/builtin-workflow-path-test.mjs`。
670
+ */
660
671
  export function builtinWorkflowPath(name) {
661
- const here = path.dirname(new URL(import.meta.url).pathname);
672
+ const here = path.dirname(fileURLToPath(import.meta.url));
662
673
  const candidates = [
663
674
  path.resolve(here, "..", "workflows", `${name}.yaml`),
664
675
  path.resolve(here, "..", "..", "workflows", `${name}.yaml`),
@@ -1571,6 +1582,14 @@ export function createEngine(projectDir, ports) {
1571
1582
  // ─── 状态 I/O(原子写)─────────────────────────────────────────────────────
1572
1583
  function instanceDir(instId) { return path.join(instancesDir, instId); }
1573
1584
  function statePath(instId) { return path.join(instanceDir(instId), "state.json"); }
1585
+ const stateIds = new WeakMap();
1586
+ const statusErrors = new Map();
1587
+ function publishStatus() {
1588
+ try {
1589
+ ports.statusChanged?.();
1590
+ }
1591
+ catch { }
1592
+ }
1574
1593
  function readState(instId) {
1575
1594
  try {
1576
1595
  const s = JSON.parse(fs.readFileSync(statePath(instId), "utf-8"));
@@ -1587,6 +1606,7 @@ export function createEngine(projectDir, ports) {
1587
1606
  }
1588
1607
  // 派生当前步失败轮数(不落盘)
1589
1608
  s.fail_count = typeof s.fail_counts[s.current_step] === "number" ? s.fail_counts[s.current_step] : 0;
1609
+ stateIds.set(s, instId);
1590
1610
  return s;
1591
1611
  }
1592
1612
  catch {
@@ -1594,6 +1614,7 @@ export function createEngine(projectDir, ports) {
1594
1614
  }
1595
1615
  }
1596
1616
  function writeState(state, instId) {
1617
+ stateIds.set(state, instId);
1597
1618
  state.updated_at = new Date().toISOString();
1598
1619
  // 落盘前剔除派生量 fail_count(宪法 §10.4:状态不存派生量)。
1599
1620
  // 每次读取都由 fail_counts[current_step] 重算,故不可能出现两个写入者不一致。
@@ -1605,10 +1626,13 @@ export function createEngine(projectDir, ports) {
1605
1626
  const tmp = path.join(dir, `.state.${process.pid}.tmp`);
1606
1627
  fs.writeFileSync(tmp, JSON.stringify(persisted, null, 2), "utf-8");
1607
1628
  fs.renameSync(tmp, statePath(instId));
1629
+ statusErrors.delete(instId);
1608
1630
  }
1609
1631
  catch (e) {
1632
+ statusErrors.set(instId, "状态写盘失败,当前显示最后确认值。请检查工作区权限或磁盘空间。");
1610
1633
  log("error", "state_write_failed", { instId, error: msg(e) });
1611
1634
  }
1635
+ publishStatus();
1612
1636
  }
1613
1637
  /** 某步当前的失败轮数(按步计数;缺省 0) */
1614
1638
  function failCountOf(state, stepId) {
@@ -1815,8 +1839,10 @@ export function createEngine(projectDir, ports) {
1815
1839
  /**
1816
1840
  * DO prompt:宣告本步任务(交卷 = 调用 ralphflow_submit 工具,dsh 原生方式)。
1817
1841
  *
1818
- * §1.7:每个 DO 提示词**各注入一行**「产出目录」(工作区相对路径)。
1819
- * 由此 `do`/`output` 里写裸文件名即落到该目录,跨任务不再串味;内置 loop/spec 不用改。
1842
+ * §1.7:每个 DO 提示词**各注入一节**「产出目录」(工作区相对路径),写明**过程文档**与
1843
+ * **产物**的落点边界(过程文档裸文件名 → 该目录;明确路径 → 按写的路径;工作目录只放产物、
1844
+ * 不留副本)。`## 交付物` 一节随后补一句「落点由产出目录决定」,保证**拼装后**两节不打架 ——
1845
+ * 仅靠「各文件单独看没错」会漏掉这种跨节矛盾(loop 曾经的 `+ summary.md` 正是如此)。
1820
1846
  *
1821
1847
  * 「## 任务」= {@link effectiveTaskOf}:子工作流调用点写了 `do` 时,这里给的是**那段子工作流
1822
1848
  * 要做什么**(加载期下沉到 `step.task`);否则仍是发起会话的任务描述(向后兼容)。
@@ -1843,10 +1869,17 @@ export function createEngine(projectDir, ports) {
1843
1869
  (step.do || step.desc || step.id).trim(),
1844
1870
  "",
1845
1871
  `## 产出目录`,
1846
- `\`${rel}/\` —— 本步的文档产出(清单、方案、报告、摘要等)统一放这里:\`do\`/\`output\` 里只写文件名的(如 \`summary.md\`)落到这个目录,写了其它路径的按写的路径来。`,
1872
+ `\`${rel}/\` —— 本步的**过程文档**(清单、方案、报告、摘要、草稿等)只落这里:\`do\`/\`output\` 里写**裸文件名**的(如 \`summary.md\`)落到这个目录;写了**明确路径**的(如 \`docs/x.md\`)按写的路径来。`,
1873
+ "",
1874
+ `工作目录只放本步的**产物**(代码、资源、可执行文件);过程文档除「写了明确路径」外不进工作目录,同一份过程文档只写一处、不要留副本(例如产出目录已有 \`summary.md\`、工作目录根又出现一份,那是落点错误)。`,
1847
1875
  ];
1848
- if (step.output)
1849
- parts.push("", `## 交付物`, String(step.output).trim());
1876
+ // 「交付物」与「产出目录」必须拼装后自洽:`output` 说的是**产出什么**,落点由上面
1877
+ // 「产出目录」一节决定。少了这句,`output` 里写进过程文档名(如 loop 曾经的
1878
+ // `+ summary.md(执行摘要)`)就会被读成「和代码并列的工作目录交付物」,
1879
+ // 与紧邻的「产出目录」直接打架 —— 模型两边都写、并行维护、开始漂移。
1880
+ if (step.output) {
1881
+ parts.push("", `## 交付物`, String(step.output).trim(), "", `(这一节说的是本步**产出什么**;它们落在**哪里**由「产出目录」一节决定 —— 过程文档写裸文件名就落产出目录,不因为列在这一节就改写进工作目录。)`);
1882
+ }
1850
1883
  if (rework) {
1851
1884
  parts.push("", `## 上一轮验证未通过,请针对性修复`, rework.trim());
1852
1885
  }
@@ -2368,7 +2401,11 @@ export function createEngine(projectDir, ports) {
2368
2401
  function deliverNotice(state, text, summary) {
2369
2402
  if (!state.owner_session)
2370
2403
  return;
2371
- const ok = ports.deliverNotice(state.owner_session, text, summary, { dedupe: false });
2404
+ const instId = stateIds.get(state);
2405
+ const ended = state.history.some((h) => h.event === "cancelled") ? "cancelled" : "done";
2406
+ const uiRef = !state.active && instId && fs.existsSync(path.join(reportsDir, `${instId}.md`))
2407
+ ? { v: 1, runId: instId, reportRef: reportRelPathOf(instId), ended } : undefined;
2408
+ const ok = ports.deliverNotice(state.owner_session, text, summary, { dedupe: false, ...(uiRef ? { uiRef } : {}) });
2372
2409
  if (!ok)
2373
2410
  log("warn", "deliver_notice_failed", { instId: state.owner_session });
2374
2411
  }
@@ -2577,7 +2614,8 @@ export function createEngine(projectDir, ports) {
2577
2614
  req.canProceed = stillLive; // 载体在 append 之前同步复查一次(关掉「等窗口期间被取消」的竞态)
2578
2615
  // 从这一刻起「本步 DO 还没送达」——期间 turn-stopping 的「忘了交卷」提醒必须闭嘴
2579
2616
  pendingDoDelivery.add(instId);
2580
- const releasePending = () => { pendingDoDelivery.delete(instId); };
2617
+ publishStatus();
2618
+ const releasePending = () => { pendingDoDelivery.delete(instId); publishStatus(); };
2581
2619
  void Promise.resolve()
2582
2620
  .then(() => ports.resetSurface(sid, req))
2583
2621
  .then((outcome) => {
@@ -3832,13 +3870,70 @@ export function createEngine(projectDir, ports) {
3832
3870
  log("warn", "orphan_delegation_recovered", { instId: id });
3833
3871
  }
3834
3872
  }
3873
+ /** Read-only UI projection; never persists derived phase or advances an instance. */
3874
+ function uiStatus(sessionId) {
3875
+ let info = listInstances().find((i) => i.state.owner_session === sessionId);
3876
+ if (!info) {
3877
+ // An archive failure retains an inactive state; keep that failure visible to its owner.
3878
+ try {
3879
+ for (const entry of fs.readdirSync(instancesDir, { withFileTypes: true })) {
3880
+ if (!entry.isDirectory())
3881
+ continue;
3882
+ const state = readState(entry.name);
3883
+ if (state && !state.active && state.owner_session === sessionId && (!info || state.started_at > info.state.started_at)) {
3884
+ info = { id: entry.name, state };
3885
+ }
3886
+ }
3887
+ }
3888
+ catch { }
3889
+ }
3890
+ if (!info)
3891
+ return { status: null, error: null };
3892
+ const { id, state } = info;
3893
+ const wf = loadWorkflow(state.workflow_name).def;
3894
+ const step = wf?.steps.find((s) => s.id === state.current_step);
3895
+ const stage = !state.active || !wf || !step ? "unavailable" : state.paused ? "paused" : pendingDoDelivery.has(id) ? "switching"
3896
+ : state.delegations.length > 0 ? "verifying"
3897
+ : state.do_submitted && step && wf && atOpenGate(wf, state, step) ? "gate"
3898
+ : state.do_submitted ? "switching" : "executing";
3899
+ const total = step ? Math.max(voterCountOf(step), stepHasVerification(step) ? 1 : 0) : 0;
3900
+ const votes = state.do_submitted ? Array.from({ length: total }, (_, index) => {
3901
+ const verdict = state.verdicts.find((v) => verdictBelongsToStep(v, state.current_step) && (total === 1 || v.check_index === index));
3902
+ const running = state.delegations.some((d) => total === 1 || d.check_index === index);
3903
+ return { index: index + 1, status: verdict?.status ?? (running ? "running" : "pending"), reason: verdict?.reason.slice(0, 500) ?? "" };
3904
+ }) : [];
3905
+ const hint = stage === "unavailable" ? "状态或报告不可用,请用 /ralphflow-doctor 检查。" : stage === "switching" ? "正在切换步骤或准备本步上下文。" : stage === "executing" ? "执行阶段,等待本步交卷。"
3906
+ : (nextActionHint(state, id, step) ?? "").replace(/\*\*/g, "");
3907
+ return { status: { id, workflow: state.workflow_name, task: state.user_task.slice(0, 2000), step: state.current_step,
3908
+ stage, hint, failures: state.fail_count, maxFailures: step?.max_fail_count ?? 0, updatedAt: state.updated_at, report: null,
3909
+ steps: (wf?.steps ?? []).map((s) => ({ id: s.id, description: s.desc ?? "", current: s.id === state.current_step, failures: failCountOf(state, s.id) })),
3910
+ votes, recent: state.history.slice(-5).map((h) => ({ step: h.step ?? "", event: h.event, detail: h.detail ?? "" })),
3911
+ }, error: statusErrors.get(id) ?? (!wf ? "工作流定义暂不可读取。" : !step ? "当前步骤已不在工作流定义中。" : null) };
3912
+ }
3913
+ /** Resolve only an exact trusted report id, never a browser-supplied filesystem path. */
3914
+ function uiReport(ref) {
3915
+ if (!/^[a-zA-Z0-9_-]+$/.test(ref.runId) || ref.reportRef !== reportRelPathOf(ref.runId))
3916
+ return null;
3917
+ let report;
3918
+ try {
3919
+ report = parseReportHeader(ref.reportRef, ref.runId, fs.readFileSync(path.join(reportsDir, `${ref.runId}.md`), "utf-8"));
3920
+ }
3921
+ catch {
3922
+ return null;
3923
+ }
3924
+ if (!report.parsed || report.id !== ref.runId || report.statusLabel !== (ref.ended === "done" ? "完成" : "取消"))
3925
+ return null;
3926
+ return { id: ref.runId, workflow: report.workflow ?? "Ralph Flow", task: report.task ?? "", step: "",
3927
+ stage: ref.ended, hint: "运行已结束,报告与产出已归档。", failures: 0, maxFailures: 0,
3928
+ updatedAt: report.endedAt ?? "", report: report.relPath, steps: [], votes: [], recent: [] };
3929
+ }
3835
3930
  return {
3836
3931
  root, instancesDir, workflowsDir, reportsDir, projectDir,
3837
3932
  ensureLayout, listWorkflows, loadWorkflow,
3838
3933
  readState, listInstances, listHistory, instanceDir,
3839
3934
  artifactsDirOf, artifactsRelDirOf, reportRelPathOf, destroyInstance,
3840
3935
  start, onSubmit, noteAssistantText, remindToSubmit, continueInstance, resetCurrent, rewindTo, cancelInstance, statusOf, listAll, restore, diagnose,
3841
- activeInstanceOfSession,
3936
+ activeInstanceOfSession, uiStatus, uiReport,
3842
3937
  };
3843
3938
  }
3844
3939
  function msg(e) { return e instanceof Error ? e.message : String(e); }
package/lib/index.js CHANGED
@@ -7,6 +7,7 @@
7
7
  import fs from "node:fs";
8
8
  import { toolPairingBalancedAfter } from "@deepseek-ai/dsh-compaction";
9
9
  import { createUserMessage, boundContextSummary } from "@deepseek-ai/dsh-llm";
10
+ import { WorkflowStatusService } from "./status-service.js";
10
11
  import { RALPHFLOW_SOURCE_KIND } from "./message-source.js";
11
12
  import { createEngine, listWorkflowsIn } from "./engine.js";
12
13
  import { createResetSurface } from "./reset.js";
@@ -128,22 +129,18 @@ export function apply(ctx) {
128
129
  * · {@link deliverDirective} **指令** = 要模型干活(DO / 命令转达 / 交卷提醒)→ `agent.steer`;
129
130
  * · {@link deliverNotice} **播报** = 给人看的记录(验证进度、判定、暂停/完成)→ 直接 append。
130
131
  *
131
- * 两类都必须注意 dsh 客户端的渲染契约:客户端按 `source.form` 决定怎么渲染 plugin 注入的
132
- * user 消息(`dsh-client-ui-chat` 的 `contextBody`/`contextForm`):
133
- * · 带 `form:"notice"` + `summary` → 渲染为 **notice 行**(summary 不展开就能读,用户看得见);
134
- * · **没有 form** → `case null: return opaque` → 退化成 `OpaqueBody`(不显眼的上下文注入行)。
135
- * 这正是 dsh 自己的做法:`dsh-agent` 的 modelSwitchNotice 就用
136
- * `{kind:"plugin", plugin:"model-selection", form:"notice", summary: boundContextSummary(...)}`。
137
- *
138
- * 所以:**凡是要让用户看见的播报,都必须带 summary**;不带 summary 的只适合纯内部管道。
132
+ * `source.form` 决定 context 内容的展开方式,不决定 Chat 是否收录这一行:
133
+ * 非 user 来源的普通 context 会整行过滤。本包客户端把带 notice + summary 的 append
134
+ * 日志另投影为会话级 `ralphflow-notice` 节点,才让人类看到记录。
135
+ * summary 是默认可读的摘要;没有 summary 的内部指令不匹配该客户端 Definition。
139
136
  * {@link buildMessage} 就是这个 source 的唯一构造点。
140
137
  */
141
- const buildMessage = (text, summary) => {
138
+ const buildMessage = (text, summary, uiRef) => {
142
139
  const brief = typeof summary === "string" ? summary.trim() : "";
143
140
  const source = brief
144
141
  ? { kind: RALPHFLOW_SOURCE_KIND, form: "notice", summary: boundContextSummary(brief) }
145
142
  : { kind: RALPHFLOW_SOURCE_KIND };
146
- return createUserMessage({ content: [{ type: "text", text }], source });
143
+ return createUserMessage({ content: [{ type: "text", text }], source: { ...source, ...(uiRef ? { uiRef } : {}) } });
147
144
  };
148
145
  /**
149
146
  * 去重护栏(只给**命令指令**路径用;引擎自驱投递传 `dedupe:false` 跳过)。命中返回 true。
@@ -253,8 +250,8 @@ export function apply(ctx) {
253
250
  * `dsh-agent-loop` 的回合循环在 `turnEnds && inbox.nextStep.length > 0` 时**继续跑下一步**,
254
251
  * 所以它照样把正在收尾的回合续上 —— 而且收件箱里的东西在**被 claim 之前不进可见面**
255
252
  * (客户端 `inbox-definition` 的 `publication: () => "none"`),用户时间线上不会立刻多一行。
256
- * · 直接 append 则两件事同时成立:立刻成为可见面节点(客户端按 `form:"notice"` 渲染成
257
- * notice 行),且**完全不碰驱动器**(不唤醒、不续回合)。它还天然满足「模型在下一回合
253
+ * · 直接 append 则两件事同时成立:立刻成为模型可见面节点(本包客户端另外投影为
254
+ * 用户可见的私有 Chat 节点),且**完全不碰驱动器**(不唤醒、不续回合)。它还天然满足「模型在下一回合
258
255
  * 能看到它」与「仍被 reset 整段遮蔽」(reset 的 `sourceEventSeqs` 取的是可见面全部节点)。
259
256
  */
260
257
  const deliverNotice = (sessionId, text, summary, opts) => {
@@ -265,7 +262,7 @@ export function apply(ctx) {
265
262
  if (deduped(sessionId, text, opts))
266
263
  return true;
267
264
  const session = sessionOf(sessionId, agent);
268
- const msg = buildMessage(text, summary);
265
+ const msg = buildMessage(text, summary, opts?.uiRef);
269
266
  if (canAppendNoticeNow(session)) {
270
267
  // 先落挂起的历史播报,再落这一条 —— 保持时间线顺序
271
268
  flushNotices(sessionId);
@@ -305,12 +302,29 @@ export function apply(ctx) {
305
302
  * 不到 / 历史列表永远空 / doctor 看不见残留」的同一个根因。
306
303
  */
307
304
  const engines = new Map();
305
+ const statusListeners = new Set();
306
+ let statusQueued = false;
307
+ const statusChanged = () => {
308
+ if (statusQueued)
309
+ return;
310
+ statusQueued = true;
311
+ queueMicrotask(() => {
312
+ statusQueued = false;
313
+ for (const listener of statusListeners) {
314
+ try {
315
+ listener();
316
+ }
317
+ catch { }
318
+ }
319
+ });
320
+ };
308
321
  const ports = {
309
322
  // 投递分两类(判据 1):指令 = 唤醒(DO / 命令转达 / 交卷提醒),播报 = 只记录不唤醒。
310
323
  // 每个调用点都必须显式选一个 —— 端口名就是分类,代码里一眼看得出(见 docs/v2/delivery-classification.md
311
324
  // 与 scripts/delivery-classification-test.mjs 的静态审计)。
312
325
  deliverDirective,
313
326
  deliverNotice,
327
+ statusChanged,
314
328
  /** 把挂起的播报在**安全边界**补齐(reset 门在整段替换前先调一次:让替换把它们一并遮蔽) */
315
329
  flushNotices,
316
330
  verify: (req) => runVerifier({ ctx }, req),
@@ -363,6 +377,48 @@ export function apply(ctx) {
363
377
  }
364
378
  return e;
365
379
  };
380
+ // Optional outside web: headless/test compositions keep the same workflow behavior.
381
+ ctx.inject(["typert"], (remoteCtx) => {
382
+ const terminalRefs = new WeakMap();
383
+ new WorkflowStatusService(remoteCtx, {
384
+ subscribe(listener) { statusListeners.add(listener); return () => statusListeners.delete(listener); },
385
+ async read(session) {
386
+ // Viewing status never runs restore or registers skills / sends a notice.
387
+ const key = session.header.cwd || workspace;
388
+ const engine = engines.get(key) ?? createEngine(key, ports);
389
+ const active = engine.uiStatus(session.id);
390
+ if (active.status && engine.readState(active.status.id)?.active)
391
+ return active;
392
+ let cached = terminalRefs.get(session);
393
+ if (!cached || cached.seq !== session.seq) {
394
+ const query = ctx.get("sessionQuery");
395
+ if (!query)
396
+ return active;
397
+ const observedSeq = session.seq;
398
+ const log = await query.readSession(session.id);
399
+ let ref;
400
+ for (const event of log.events) {
401
+ if (event.seq < log.inheritedEventCount || event.type !== "user/message" || event.surfaceOp !== "append"
402
+ || event.data.source.kind !== RALPHFLOW_SOURCE_KIND)
403
+ continue;
404
+ const candidate = event.data.source.uiRef;
405
+ if (candidate?.v === 1 && (candidate.ended === "done" || candidate.ended === "cancelled"))
406
+ ref = candidate;
407
+ }
408
+ cached = { seq: observedSeq, ref };
409
+ terminalRefs.set(session, cached);
410
+ }
411
+ // A new active run may have landed while the cold read awaited persistence.
412
+ const current = engine.uiStatus(session.id);
413
+ const terminal = cached.ref ? engine.uiReport(cached.ref) : null;
414
+ // A residual from an older archive failure must not cover a newer completed run.
415
+ if (current.status && (engine.readState(current.status.id)?.active || !terminal
416
+ || Date.parse(current.status.updatedAt) >= Date.parse(terminal.updatedAt)))
417
+ return current;
418
+ return { status: terminal, error: current.error ?? (cached.ref && !terminal ? "本次运行的报告暂不可读取,请检查报告文件。" : null) };
419
+ },
420
+ });
421
+ });
366
422
  /**
367
423
  * 只查**已存在**的引擎:会话事件是高频路径,不能为了它给每个会话凭空建引擎
368
424
  * (没有引擎 = 该工作区没有活跃实例,也就没有需要提醒/捕获的东西)。
@@ -382,6 +438,8 @@ export function apply(ctx) {
382
438
  const sid = s?.id;
383
439
  if (!sid || !e || typeof e !== "object")
384
440
  return;
441
+ if (e.type === "user/message" && e.data?.source?.uiRef)
442
+ statusChanged();
385
443
  if (deferredNotices.has(sid))
386
444
  queueMicrotask(() => { try {
387
445
  flushNotices(sid);
@@ -426,7 +484,7 @@ export function apply(ctx) {
426
484
  log("warn", "turn_stopping_failed", { sessionId: sid, error: e instanceof Error ? e.message : String(e) });
427
485
  return;
428
486
  }
429
- // 带 summary 才会渲染成用户可见的 notice 行(否则是 opaque 注入行,用户看不到)
487
+ // 本包客户端以 notice + summary 匹配播报,再由私有节点绕过普通 context 的过滤
430
488
  if (!verdict.message)
431
489
  return;
432
490
  if (!verdict.remind) {
@@ -9,17 +9,26 @@
9
9
  * 只按**当前** dsh 的这套写法写,不为任何更老的 dsh 留分支 —— dsh 的破坏性改动是常态,
10
10
  * 我们的立场是跟着最新版走(作者定案)。
11
11
  *
12
- * 可见性不受影响:客户端按 `source.form === "notice"` + 非空 `summary` 渲染成折叠的
13
- * notice 行,**不看 `kind`**;未知 kind 回落为 opaque 内容(见 `scripts/visibility-test.mjs`
14
- * 头部记的那次缺陷)。改名换掉的是日志里的来源标记,不是渲染。
12
+ * Chat 可见性受 kind 过滤控制:非 user 来源先成为 context,普通 context 整行丢弃。
13
+ * `form: "notice"` + summary 只控制已可见 context 的展开,不能绕过过滤。
14
+ * 本包客户端另注册 `ralphflow-notice` 私有节点与渲染器,读取 append 日志并显式定位
15
+ * 会话级;它决定播报在 Chat 可见,reset 的模型面替换不会抹掉这条人类记录。
15
16
  */
16
17
  import type { ContextFormed } from "@deepseek-ai/dsh-llm";
17
18
  declare module "@deepseek-ai/dsh-llm" {
18
19
  interface MessageSourceMap {
19
20
  ralphflow: {
20
21
  kind: "ralphflow";
22
+ uiRef?: WorkflowUiRef;
21
23
  } & ContextFormed;
22
24
  }
23
25
  }
24
26
  /** 本插件消息的来源 kind。用户可见的播报另带 `form: "notice"` + `summary`。 */
25
27
  export declare const RALPHFLOW_SOURCE_KIND: "ralphflow";
28
+ /** Index on existing terminal notices; never changes model content or sends another event. */
29
+ export interface WorkflowUiRef {
30
+ v: 1;
31
+ runId: string;
32
+ reportRef: string;
33
+ ended: "done" | "cancelled";
34
+ }
@@ -0,0 +1,46 @@
1
+ import type { InvocationDescriptor, RemoteStream, TypertRemoteContribution } from "@deepseek-ai/dsh-typert-protocol";
2
+ export type WorkflowStage = "executing" | "verifying" | "gate" | "paused" | "switching" | "done" | "cancelled" | "unavailable";
3
+ export interface WorkflowStatus {
4
+ id: string;
5
+ workflow: string;
6
+ task: string;
7
+ step: string;
8
+ stage: WorkflowStage;
9
+ hint: string;
10
+ failures: number;
11
+ maxFailures: number;
12
+ updatedAt: string;
13
+ report: string | null;
14
+ steps: Array<{
15
+ id: string;
16
+ description: string;
17
+ current: boolean;
18
+ failures: number;
19
+ }>;
20
+ votes: Array<{
21
+ index: number;
22
+ status: "pending" | "running" | "passed" | "failed" | "infra";
23
+ reason: string;
24
+ }>;
25
+ recent: Array<{
26
+ step: string;
27
+ event: string;
28
+ detail: string;
29
+ }>;
30
+ }
31
+ export interface StatusFrame {
32
+ kind: "snapshot" | "update";
33
+ sessionId: string;
34
+ status: WorkflowStatus | null;
35
+ error: string | null;
36
+ }
37
+ export declare function parseStatusFrame(value: unknown): StatusFrame;
38
+ export declare const statusDescriptors: readonly InvocationDescriptor[];
39
+ export declare const statusRemote: TypertRemoteContribution;
40
+ declare module "@deepseek-ai/dsh-typert-protocol" {
41
+ interface TypertRemoteNamespaceMap {
42
+ ralphflowStatus: {
43
+ watch(sessionId: string, signal?: AbortSignal): RemoteStream<StatusFrame>;
44
+ };
45
+ }
46
+ }
@@ -0,0 +1,58 @@
1
+ /** One explicit, strict public Typert contract shared by both faces. No SRC fallback. */
2
+ function record(value) {
3
+ if (!value || typeof value !== "object" || Array.isArray(value))
4
+ throw new TypeError("expected status object");
5
+ return value;
6
+ }
7
+ function string(value) {
8
+ if (typeof value !== "string")
9
+ throw new TypeError("expected status string");
10
+ return value;
11
+ }
12
+ function count(value) {
13
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
14
+ throw new TypeError("expected status count");
15
+ return value;
16
+ }
17
+ function array(value, parse) {
18
+ if (!Array.isArray(value) || value.length > 2000)
19
+ throw new TypeError("expected bounded status list");
20
+ return value.map(parse);
21
+ }
22
+ function bool(value) {
23
+ if (typeof value !== "boolean")
24
+ throw new TypeError("expected status boolean");
25
+ return value;
26
+ }
27
+ function choice(value, values) {
28
+ if (!values.includes(value))
29
+ throw new TypeError("unknown status variant");
30
+ return value;
31
+ }
32
+ export function parseStatusFrame(value) {
33
+ const frame = record(value);
34
+ let status = null;
35
+ if (frame.status !== null) {
36
+ const s = record(frame.status);
37
+ status = {
38
+ id: string(s.id), workflow: string(s.workflow), task: string(s.task), step: string(s.step),
39
+ stage: choice(s.stage, ["executing", "verifying", "gate", "paused", "switching", "done", "cancelled", "unavailable"]),
40
+ hint: string(s.hint), failures: count(s.failures), maxFailures: count(s.maxFailures), updatedAt: string(s.updatedAt),
41
+ report: s.report === null ? null : string(s.report),
42
+ steps: array(s.steps, (v) => { const x = record(v); return { id: string(x.id), description: string(x.description), current: bool(x.current), failures: count(x.failures) }; }),
43
+ votes: array(s.votes, (v) => { const x = record(v); return { index: count(x.index), status: choice(x.status, ["pending", "running", "passed", "failed", "infra"]), reason: string(x.reason) }; }),
44
+ recent: array(s.recent, (v) => { const x = record(v); return { step: string(x.step), event: string(x.event), detail: string(x.detail) }; }),
45
+ };
46
+ }
47
+ return { kind: choice(frame.kind, ["snapshot", "update"]), sessionId: string(frame.sessionId), status,
48
+ error: frame.error === null ? null : string(frame.error) };
49
+ }
50
+ const sessionCodec = { mode: "strict", typeSymbol: "@deepseek-ai/dsh-session/types#SessionId", create: () => ({ parse: string }) };
51
+ const frameCodec = { mode: "strict", typeSymbol: "ralphflow-dsh#StatusFrame", create: () => ({ parse: parseStatusFrame }) };
52
+ export const statusDescriptors = [{
53
+ id: "ralphflow-dsh#ralphflowStatus/watch", service: "ralphflowStatus", namespace: "ralphflowStatus", method: "watch",
54
+ mode: "stream", invocation: { kind: "direct" },
55
+ parameters: [{ name: "session", wire: "sessionId", source: "lookup", lookup: "session", codec: sessionCodec }],
56
+ cancellation: { parameter: "signal" }, result: frameCodec,
57
+ }];
58
+ export const statusRemote = { package: "ralphflow-dsh", descriptors: statusDescriptors };
@@ -0,0 +1,18 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type { Session } from "@deepseek-ai/dsh-session";
3
+ import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
4
+ import type { StatusFrame, WorkflowStatus } from "./status-contract.js";
5
+ export interface StatusReader {
6
+ read(session: Session): Promise<{
7
+ status: WorkflowStatus | null;
8
+ error: string | null;
9
+ }>;
10
+ subscribe(listener: () => void): () => void;
11
+ }
12
+ /** The existing session lookup owns admission/resume. This face only observes that Session. */
13
+ export declare class WorkflowStatusService extends TypertRemoteService {
14
+ private readonly reader;
15
+ private readonly lifetime;
16
+ constructor(ctx: Context, reader: StatusReader);
17
+ watch(session: Session, signal: AbortSignal): AsyncGenerator<StatusFrame>;
18
+ }
@@ -0,0 +1,86 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
36
+ /** The existing session lookup owns admission/resume. This face only observes that Session. */
37
+ let WorkflowStatusService = (() => {
38
+ let _classSuper = TypertRemoteService;
39
+ let _instanceExtraInitializers = [];
40
+ let _watch_decorators;
41
+ return class WorkflowStatusService extends _classSuper {
42
+ static {
43
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
44
+ _watch_decorators = [Remote({ mode: "stream" })];
45
+ __esDecorate(this, null, _watch_decorators, { kind: "method", name: "watch", static: false, private: false, access: { has: obj => "watch" in obj, get: obj => obj.watch }, metadata: _metadata }, null, _instanceExtraInitializers);
46
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
47
+ }
48
+ reader = __runInitializers(this, _instanceExtraInitializers);
49
+ lifetime = new AbortController();
50
+ constructor(ctx, reader) {
51
+ super(ctx, "ralphflowStatus");
52
+ this.reader = reader;
53
+ ctx.effect(() => () => this.lifetime.abort(), "ralphflow status stream lifetime");
54
+ }
55
+ async *watch(session, signal) {
56
+ signal = AbortSignal.any([signal, this.lifetime.signal]);
57
+ let pending = true;
58
+ let wake;
59
+ const changed = () => { pending = true; wake?.(); };
60
+ const unsubscribe = this.reader.subscribe(changed);
61
+ signal.addEventListener("abort", changed);
62
+ let first = true;
63
+ try {
64
+ while (!signal.aborted) {
65
+ if (!pending)
66
+ await new Promise((resolve) => { wake = resolve; if (pending || signal.aborted)
67
+ resolve(); });
68
+ wake = undefined;
69
+ if (signal.aborted)
70
+ return;
71
+ pending = false;
72
+ const next = await this.reader.read(session);
73
+ if (signal.aborted)
74
+ return;
75
+ yield { kind: first ? "snapshot" : "update", sessionId: session.id, ...next };
76
+ first = false;
77
+ }
78
+ }
79
+ finally {
80
+ unsubscribe();
81
+ signal.removeEventListener("abort", changed);
82
+ }
83
+ }
84
+ };
85
+ })();
86
+ export { WorkflowStatusService };