ralphflow-dsh 2.1.1 → 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/client.js ADDED
@@ -0,0 +1,457 @@
1
+ window.__ModuleLoader__.load({id:"ralphflow-dsh",factory:(require)=>{
2
+ var module={exports:{}};var exports=module.exports;
3
+ "use strict";
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/client/index.ts
23
+ var index_exports = {};
24
+ __export(index_exports, {
25
+ NoticeRow: () => NoticeRow,
26
+ apply: () => apply,
27
+ inject: () => inject
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+ var import_react2 = require("react");
31
+
32
+ // src/message-source.ts
33
+ var RALPHFLOW_SOURCE_KIND = "ralphflow";
34
+
35
+ // src/client/definition.ts
36
+ var RALPHFLOW_NOTICE_KIND = "ralphflow-notice";
37
+ var noticeDefinition = {
38
+ kind: RALPHFLOW_NOTICE_KIND,
39
+ target: "chat",
40
+ match(event) {
41
+ if (event.type !== "user/message" || event.surfaceOp !== "append") return null;
42
+ const source = event.data.source;
43
+ if (source.kind !== RALPHFLOW_SOURCE_KIND || source.form !== "notice" || typeof source.summary !== "string" || !source.summary.trim()) return null;
44
+ return { id: String(event.seq), role: "start" };
45
+ },
46
+ start(_context, { event }) {
47
+ if (event.type !== "user/message" || event.data.source.kind !== RALPHFLOW_SOURCE_KIND || event.data.source.form !== "notice" || typeof event.data.source.summary !== "string") throw new Error("ralphflow notice requires user/message notice");
48
+ return {
49
+ summary: event.data.source.summary,
50
+ text: event.data.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")
51
+ };
52
+ },
53
+ update: (context) => context.state,
54
+ buildViewNode(context) {
55
+ if (!context.start || !context.state) return null;
56
+ return {
57
+ key: context.key,
58
+ kind: RALPHFLOW_NOTICE_KIND,
59
+ id: context.id,
60
+ target: "chat",
61
+ anchorSeq: context.start.event.seq,
62
+ // Notices can land before turn/end. Never let the turn-process disclosure swallow them.
63
+ location: { kind: "session" },
64
+ visibility: "visible",
65
+ data: context.state
66
+ };
67
+ }
68
+ };
69
+
70
+ // src/client/status.tsx
71
+ var import_react = require("react");
72
+ var import_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
73
+
74
+ // src/status-contract.ts
75
+ function record(value) {
76
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("expected status object");
77
+ return value;
78
+ }
79
+ function string(value) {
80
+ if (typeof value !== "string") throw new TypeError("expected status string");
81
+ return value;
82
+ }
83
+ function count(value) {
84
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError("expected status count");
85
+ return value;
86
+ }
87
+ function array(value, parse) {
88
+ if (!Array.isArray(value) || value.length > 2e3) throw new TypeError("expected bounded status list");
89
+ return value.map(parse);
90
+ }
91
+ function bool(value) {
92
+ if (typeof value !== "boolean") throw new TypeError("expected status boolean");
93
+ return value;
94
+ }
95
+ function choice(value, values) {
96
+ if (!values.includes(value)) throw new TypeError("unknown status variant");
97
+ return value;
98
+ }
99
+ function parseStatusFrame(value) {
100
+ const frame = record(value);
101
+ let status = null;
102
+ if (frame.status !== null) {
103
+ const s = record(frame.status);
104
+ status = {
105
+ id: string(s.id),
106
+ workflow: string(s.workflow),
107
+ task: string(s.task),
108
+ step: string(s.step),
109
+ stage: choice(s.stage, ["executing", "verifying", "gate", "paused", "switching", "done", "cancelled", "unavailable"]),
110
+ hint: string(s.hint),
111
+ failures: count(s.failures),
112
+ maxFailures: count(s.maxFailures),
113
+ updatedAt: string(s.updatedAt),
114
+ report: s.report === null ? null : string(s.report),
115
+ steps: array(s.steps, (v) => {
116
+ const x = record(v);
117
+ return { id: string(x.id), description: string(x.description), current: bool(x.current), failures: count(x.failures) };
118
+ }),
119
+ votes: array(s.votes, (v) => {
120
+ const x = record(v);
121
+ return { index: count(x.index), status: choice(x.status, ["pending", "running", "passed", "failed", "infra"]), reason: string(x.reason) };
122
+ }),
123
+ recent: array(s.recent, (v) => {
124
+ const x = record(v);
125
+ return { step: string(x.step), event: string(x.event), detail: string(x.detail) };
126
+ })
127
+ };
128
+ }
129
+ return {
130
+ kind: choice(frame.kind, ["snapshot", "update"]),
131
+ sessionId: string(frame.sessionId),
132
+ status,
133
+ error: frame.error === null ? null : string(frame.error)
134
+ };
135
+ }
136
+ var sessionCodec = { mode: "strict", typeSymbol: "@deepseek-ai/dsh-session/types#SessionId", create: () => ({ parse: string }) };
137
+ var frameCodec = { mode: "strict", typeSymbol: "ralphflow-dsh#StatusFrame", create: () => ({ parse: parseStatusFrame }) };
138
+ var statusDescriptors = [{
139
+ id: "ralphflow-dsh#ralphflowStatus/watch",
140
+ service: "ralphflowStatus",
141
+ namespace: "ralphflowStatus",
142
+ method: "watch",
143
+ mode: "stream",
144
+ invocation: { kind: "direct" },
145
+ parameters: [{ name: "session", wire: "sessionId", source: "lookup", lookup: "session", codec: sessionCodec }],
146
+ cancellation: { parameter: "signal" },
147
+ result: frameCodec
148
+ }];
149
+ var statusRemote = { package: "ralphflow-dsh", descriptors: statusDescriptors };
150
+
151
+ // src/client/status-source.ts
152
+ var import_client = require("@deepseek-ai/dsh-api-gateway/client");
153
+ function createStatusSource(ctx, sessionId) {
154
+ let snapshot = { status: null, connection: "connecting", error: null };
155
+ const listeners = /* @__PURE__ */ new Set();
156
+ let stream;
157
+ let token = 0;
158
+ const publish = (next) => {
159
+ if (JSON.stringify(next) === JSON.stringify(snapshot)) return;
160
+ snapshot = next;
161
+ for (const listener of listeners) listener();
162
+ };
163
+ const start = () => {
164
+ const incarnation = ++token;
165
+ publish({ ...snapshot, connection: "connecting" });
166
+ const failed = (_error) => {
167
+ if (incarnation === token) publish({ ...snapshot, connection: "offline", error: "\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u663E\u793A\u6700\u540E\u72B6\u6001\uFF1B\u6B63\u5728\u91CD\u65B0\u540C\u6B65\u3002" });
168
+ };
169
+ const accept = (raw) => {
170
+ if (incarnation !== token) return;
171
+ const frame = parseStatusFrame(raw);
172
+ if (frame.sessionId !== sessionId) throw new Error("status stream crossed Session binding");
173
+ publish({ status: frame.status, connection: "live", error: frame.error });
174
+ };
175
+ const carrier = ctx.remote.$stream({
176
+ name: `ralphflow status ${sessionId}`,
177
+ open: (signal) => ctx.remote.ralphflowStatus.watch(sessionId, signal),
178
+ ended: () => new Error("workflow status stream ended"),
179
+ carrierFailed: failed
180
+ });
181
+ stream = new import_client.RemoteSnapshotStream(carrier, {
182
+ name: "ralphflow status",
183
+ isSnapshot: (frame) => frame.kind === "snapshot",
184
+ replace: accept,
185
+ update: accept,
186
+ failed
187
+ });
188
+ stream.start();
189
+ };
190
+ const stop = () => {
191
+ ++token;
192
+ const current = stream;
193
+ stream = void 0;
194
+ void current?.dispose();
195
+ };
196
+ return {
197
+ getSnapshot: () => snapshot,
198
+ subscribe(listener) {
199
+ listeners.add(listener);
200
+ if (listeners.size === 1) start();
201
+ return () => {
202
+ listeners.delete(listener);
203
+ if (listeners.size === 0) stop();
204
+ };
205
+ },
206
+ dispose() {
207
+ stop();
208
+ listeners.clear();
209
+ }
210
+ };
211
+ }
212
+
213
+ // src/client/status.tsx
214
+ var import_jsx_runtime = require("react/jsx-runtime");
215
+ var labels = {
216
+ executing: "\u5F85\u4EA4\u5377",
217
+ verifying: "\u72EC\u7ACB\u9A8C\u8BC1\u4E2D",
218
+ gate: "\u7B49\u5F85\u4F60\u653E\u884C",
219
+ paused: "\u5DF2\u6682\u505C",
220
+ switching: "\u5207\u6362\u6B65\u9AA4\u4E2D",
221
+ done: "\u5DF2\u5B8C\u6210",
222
+ cancelled: "\u5DF2\u53D6\u6D88",
223
+ unavailable: "\u72B6\u6001\u4E0D\u53EF\u7528"
224
+ };
225
+ var votes = { pending: "\u7B49\u5F85\u9A8C\u8BC1", running: "\u9A8C\u8BC1\u4E2D", passed: "\u901A\u8FC7", failed: "\u672A\u901A\u8FC7", infra: "\u9A8C\u8BC1\u8005\u6545\u969C" };
226
+ var actionStages = /* @__PURE__ */ new Set(["gate", "paused"]);
227
+ var terminalStages = /* @__PURE__ */ new Set(["done", "cancelled"]);
228
+ var whole = (s) => s;
229
+ var css = `
230
+ .ralphflow-status { position: relative; display: inline-flex; align-items: center; gap: 4px; max-width: min(320px, 38vw); min-height: 28px; padding: 3px 2px; border: 0; background: none; color: var(--dsw-alias-label-tertiary); font: inherit; font-size: var(--dsw-font-xxs-12-font-size); line-height: var(--dsw-font-xxs-12-line-height); cursor: pointer; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }
231
+ .ralphflow-status:hover, .ralphflow-status:focus-visible { color: var(--dsw-alias-label-secondary); }
232
+ .ralphflow-status-dot { flex: none; }
233
+ .ralphflow-status-popover { position: absolute; right: 0; top: calc(100% + 8px); width: min(380px, calc(100vw - 32px)); max-height: min(480px, 100vh - 140px); z-index: 100; box-sizing: border-box; display: flex; flex-direction: column; gap: 8px; margin: 0; padding: 12px; overflow: auto; --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); border: 0; border-radius: var(--dsw-radius-lg); background: var(--dsw-alias-bg-layer-2); box-shadow: var(--dsw-elevation-prominent); color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size-secondary); line-height: var(--dsw-font-xs-13-line-height); }
234
+ .ralphflow-status-popover-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
235
+ .ralphflow-status-popover-title { min-width: 0; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
236
+ .ralphflow-status-popover-stage { flex: none; color: var(--dsw-alias-label-tertiary); white-space: nowrap; }
237
+ .ralphflow-status-banner { padding: 6px 8px; border-radius: var(--dsw-radius-sm); background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
238
+ .ralphflow-status-banner[data-kind="error"] { background: var(--dsw-alias-state-error-secondary); color: var(--dsw-alias-label-primary); }
239
+ .ralphflow-status-hint { color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
240
+ .ralphflow-status-task { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
241
+ .ralphflow-status-label { color: var(--dsw-alias-label-tertiary); }
242
+ .ralphflow-status-steps { margin: 4px 0; padding-left: 20px; }
243
+ .ralphflow-status-steps li { overflow-wrap: anywhere; }
244
+ .ralphflow-status-votes { margin: 4px 0; padding-left: 20px; }
245
+ .ralphflow-status-votes li { overflow-wrap: anywhere; }
246
+ .ralphflow-status-recent { margin: 4px 0; padding-left: 20px; }
247
+ .ralphflow-status-recent li { overflow-wrap: anywhere; }
248
+ .ralphflow-status-report { margin: 0; overflow-wrap: anywhere; }
249
+ .ralphflow-status-report code { font-family: var(--dsw-font-mono, monospace); }
250
+ .ralphflow-status-action-dock { width: calc(100% - 2 * var(--dsh-composer-side-clearance) - 4 * var(--dsh-composer-dock-inset)); margin: 0 auto; }
251
+ .ralphflow-status-action { box-sizing: border-box; width: 100%; max-width: calc(var(--dsh-composer-card-max-width) - 4 * var(--dsh-composer-dock-inset)); margin: 0 auto; display: flex; align-items: center; gap: 8px; padding: 4px 12px; border: 0; border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-layer-2); box-shadow: var(--dsw-elevation-panel); color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size-secondary); line-height: var(--dsw-font-xs-13-line-height); min-height: 36px; --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); }
252
+ .ralphflow-status-action-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
253
+ /* The timeline broadcast row keeps its record role; only its radius/font move to tokens. */
254
+ .ralphflow-notice { margin: 8px 0; padding: 8px 12px; border-radius: var(--dsw-radius-sm); background: var(--dsw-alias-bg-module-platform); color: inherit; font-size: var(--dsh-content-font-size-secondary); line-height: 1.6; overflow-wrap: anywhere; }
255
+ .ralphflow-notice > summary { cursor: pointer; }
256
+ .ralphflow-notice-text { padding-top: 8px; white-space: pre-wrap; }
257
+ `;
258
+ function injectStatusCss() {
259
+ if (typeof document === "undefined" || document.querySelector("style[data-ralphflow-status-css]") !== null) return;
260
+ const style = document.createElement("style");
261
+ style.dataset.ralphflowStatusCss = "";
262
+ style.textContent = css;
263
+ document.head.appendChild(style);
264
+ }
265
+ injectStatusCss();
266
+ function StatusDot({ stage }) {
267
+ const state = stage === "done" ? "done" : stage === "gate" || stage === "paused" ? "warning" : stage === "unavailable" ? "error" : stage === "cancelled" ? "idle" : "ongoing";
268
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_dsh_client_ui_primitives.StateDot, { state, className: "ralphflow-status-dot" });
269
+ }
270
+ function WorkflowStatusControl({ useWorkflowStatus }) {
271
+ const { status, connection } = useWorkflowStatus(whole);
272
+ const [opened, setOpened] = (0, import_react.useState)(false);
273
+ const id = (0, import_react.useId)();
274
+ const root = (0, import_react.useRef)(null);
275
+ const trigger = (0, import_react.useRef)(null);
276
+ (0, import_dsh_client_ui_primitives.useDismissOnOutsidePointer)(root, opened, setOpened);
277
+ if (!status) return null;
278
+ const terminal = terminalStages.has(status.stage);
279
+ const label = labels[status.stage];
280
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { ref: root, style: { position: "relative" }, onKeyDown: (e) => {
281
+ if (e.key === "Escape") {
282
+ setOpened(false);
283
+ trigger.current?.focus();
284
+ }
285
+ }, children: [
286
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
287
+ "button",
288
+ {
289
+ ref: trigger,
290
+ type: "button",
291
+ className: "ralphflow-status",
292
+ "data-ralphflow-status": status.id,
293
+ "data-stage": status.stage,
294
+ "data-connection": connection,
295
+ "aria-expanded": opened,
296
+ "aria-controls": opened ? id : void 0,
297
+ "aria-label": "\u67E5\u770B\u5DE5\u4F5C\u6D41\u72B6\u6001",
298
+ onClick: () => setOpened((v) => !v),
299
+ title: `${status.workflow} \xB7 ${status.step} \xB7 ${label}`,
300
+ children: [
301
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusDot, { stage: status.stage }),
302
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
303
+ terminal ? `${label} \xB7 \u62A5\u544A` : `${status.step} \xB7 ${status.stage === "paused" ? `\u5931\u8D25 ${status.failures} \u6B21` : `\u7B2C ${status.failures + 1} \u8F6E`} \xB7 ${label}`,
304
+ connection === "live" ? "" : " \xB7 \u540C\u6B65\u4E2D"
305
+ ] })
306
+ ]
307
+ }
308
+ ),
309
+ opened ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WorkflowStatusPopover, { id, useWorkflowStatus }) : null
310
+ ] });
311
+ }
312
+ function WorkflowStatusPopover({ id, useWorkflowStatus }) {
313
+ const { status, connection, error } = useWorkflowStatus(whole);
314
+ if (!status) return null;
315
+ const terminal = terminalStages.has(status.stage);
316
+ const returned = status.votes.filter((v) => v.status === "passed" || v.status === "failed" || v.status === "infra").length;
317
+ const nearLimit = status.maxFailures > 0 && status.failures > 0 && status.failures >= status.maxFailures * 0.8;
318
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { id, className: "ralphflow-status-popover", "data-ralphflow-status-popover": true, role: "status", children: [
319
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ralphflow-status-popover-head", children: [
320
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "ralphflow-status-popover-title", children: [
321
+ "Ralph Flow \xB7 ",
322
+ status.workflow
323
+ ] }),
324
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "ralphflow-status-popover-stage", children: [
325
+ labels[status.stage],
326
+ connection === "live" ? "" : " \xB7 \u540C\u6B65\u4E2D"
327
+ ] })
328
+ ] }),
329
+ error ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ralphflow-status-banner", "data-kind": "error", role: "status", children: [
330
+ "Ralph Flow \xB7 ",
331
+ error
332
+ ] }) : null,
333
+ connection !== "live" && !error ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ralphflow-status-banner", role: "status", children: "\u6B63\u5728\u91CD\u65B0\u540C\u6B65\uFF0C\u663E\u793A\u6700\u540E\u72B6\u6001\u3002" }) : null,
334
+ !terminal && nearLimit ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ralphflow-status-banner", role: "status", children: [
335
+ "\u672C\u6B65\u5931\u8D25\u63A5\u8FD1\u4E0A\u9650 \xB7 ",
336
+ status.failures,
337
+ "/",
338
+ status.maxFailures
339
+ ] }) : null,
340
+ !terminal && status.hint ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ralphflow-status-hint", children: status.hint }) : null,
341
+ !terminal ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "ralphflow-status-task", children: status.task }) : null,
342
+ !terminal ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ralphflow-status-label", children: [
343
+ "\u672C\u6B65\u5931\u8D25 ",
344
+ status.failures,
345
+ " \u6B21"
346
+ ] }) : null,
347
+ !terminal && status.steps.length ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
348
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ralphflow-status-label", children: "\u6B65\u9AA4" }),
349
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ol", { className: "ralphflow-status-steps", "aria-label": "\u5DE5\u4F5C\u6D41\u6B65\u9AA4", children: status.steps.map((step) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { "aria-current": step.current ? "step" : void 0, children: [
350
+ step.current ? "\u2192 " : "",
351
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: step.id }),
352
+ " \xB7 ",
353
+ step.description,
354
+ step.failures ? ` \xB7 \u5931\u8D25 ${step.failures} \u6B21` : ""
355
+ ] }, step.id)) })
356
+ ] }) : null,
357
+ !terminal && status.votes.length ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
358
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ralphflow-status-label", children: [
359
+ "\u672C\u8F6E\u9A8C\u8BC1 \xB7 ",
360
+ returned,
361
+ "/",
362
+ status.votes.length,
363
+ " \u5DF2\u8FD4\u56DE"
364
+ ] }),
365
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: "ralphflow-status-votes", "aria-label": `\u672C\u8F6E\u9A8C\u8BC1 \xB7 ${returned}/${status.votes.length} \u5DF2\u8FD4\u56DE`, children: status.votes.map((vote) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
366
+ "\u9A8C\u8BC1\u8005 ",
367
+ vote.index,
368
+ "/",
369
+ status.votes.length,
370
+ " \xB7 ",
371
+ votes[vote.status],
372
+ vote.reason ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: vote.reason }) : null
373
+ ] }, vote.index)) })
374
+ ] }) : null,
375
+ !terminal && status.recent.length ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("details", { children: [
376
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("summary", { className: "ralphflow-status-label", children: "\u6700\u8FD1\u8F68\u8FF9" }),
377
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { className: "ralphflow-status-recent", children: status.recent.map((event, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
378
+ event.step,
379
+ " \xB7 ",
380
+ event.event,
381
+ event.detail ? `\uFF1A${event.detail}` : ""
382
+ ] }, index)) })
383
+ ] }) : null,
384
+ status.report ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "ralphflow-status-report", children: [
385
+ "\u62A5\u544A\uFF1A",
386
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: status.report })
387
+ ] }) : null
388
+ ] });
389
+ }
390
+ function WorkflowStatusAction({ useWorkflowStatus }) {
391
+ const { status } = useWorkflowStatus(whole);
392
+ if (!status || !actionStages.has(status.stage)) return null;
393
+ const reason = status.stage === "gate" ? "\u7B49\u5F85\u4F60\u653E\u884C" : status.maxFailures > 0 && status.failures >= status.maxFailures ? "\u5931\u8D25\u5DF2\u5230\u4E0A\u9650" : "\u5DF2\u6682\u505C";
394
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "ralphflow-status-action-dock", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "ralphflow-status-action", "data-ralphflow-status-action": status.id, "data-stage": status.stage, role: "status", children: [
395
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusDot, { stage: status.stage }),
396
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "ralphflow-status-action-text", children: [
397
+ reason,
398
+ " \xB7 \u8F93\u5165 ",
399
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "/ralphflow-continue" }),
400
+ " \u7EE7\u7EED"
401
+ ] })
402
+ ] }) });
403
+ }
404
+ async function registerWorkflowStatus(ctx) {
405
+ await ctx.remote.$mount(statusRemote);
406
+ await ctx.inject(["remote.ralphflowStatus"], registerUi);
407
+ }
408
+ function registerUi(ctx) {
409
+ const sources = /* @__PURE__ */ new Map();
410
+ const sourceOf = (sessionId) => {
411
+ let source = sources.get(sessionId);
412
+ if (!source) {
413
+ source = createStatusSource(ctx, sessionId);
414
+ sources.set(sessionId, source);
415
+ }
416
+ return { hooks: { workflowStatus: source } };
417
+ };
418
+ ctx.effect(() => () => {
419
+ for (const source of sources.values()) source.dispose();
420
+ sources.clear();
421
+ });
422
+ ctx.slots.inject("conversation.input.dock", () => ctx.slots.register({
423
+ name: "conversation.input.dock",
424
+ id: "ralphflow-status",
425
+ order: 5,
426
+ inject: sourceOf
427
+ }, WorkflowStatusAction));
428
+ ctx.slots.inject("conversation.session.header.actions", () => ctx.slots.register({
429
+ name: "conversation.session.header.actions",
430
+ id: "ralphflow-status",
431
+ order: 15,
432
+ inject: sourceOf
433
+ }, WorkflowStatusControl));
434
+ }
435
+
436
+ // src/client/index.ts
437
+ var inject = ["uiConversation", "slots"];
438
+ function NoticeRow({ node }) {
439
+ injectStatusCss();
440
+ return (0, import_react2.createElement)(
441
+ "details",
442
+ { "data-ralphflow-notice": String(node.anchorSeq), className: "ralphflow-notice" },
443
+ (0, import_react2.createElement)("summary", null, node.data.summary),
444
+ (0, import_react2.createElement)("div", { className: "ralphflow-notice-text" }, node.data.text)
445
+ );
446
+ }
447
+ function apply(ctx) {
448
+ ctx.inject(["remote", "sessions"], (child) => registerWorkflowStatus(child));
449
+ ctx.uiConversation.events.register(noticeDefinition);
450
+ ctx.slots.inject("conversation.chat.node", () => ctx.slots.register({
451
+ name: "conversation.chat.node",
452
+ key: RALPHFLOW_NOTICE_KIND
453
+ }, NoticeRow));
454
+ }
455
+
456
+ return module.exports;
457
+ }});
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
  *
@@ -743,6 +748,11 @@ export declare function createEngine(projectDir: string, ports: EnginePorts): {
743
748
  restore: () => void;
744
749
  diagnose: () => ToolResult;
745
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;
746
756
  };
747
757
  export type Engine = ReturnType<typeof createEngine>;
748
758
  export declare const BUILTIN_WORKFLOWS: string[];
package/lib/engine.js CHANGED
@@ -1582,6 +1582,14 @@ export function createEngine(projectDir, ports) {
1582
1582
  // ─── 状态 I/O(原子写)─────────────────────────────────────────────────────
1583
1583
  function instanceDir(instId) { return path.join(instancesDir, instId); }
1584
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
+ }
1585
1593
  function readState(instId) {
1586
1594
  try {
1587
1595
  const s = JSON.parse(fs.readFileSync(statePath(instId), "utf-8"));
@@ -1598,6 +1606,7 @@ export function createEngine(projectDir, ports) {
1598
1606
  }
1599
1607
  // 派生当前步失败轮数(不落盘)
1600
1608
  s.fail_count = typeof s.fail_counts[s.current_step] === "number" ? s.fail_counts[s.current_step] : 0;
1609
+ stateIds.set(s, instId);
1601
1610
  return s;
1602
1611
  }
1603
1612
  catch {
@@ -1605,6 +1614,7 @@ export function createEngine(projectDir, ports) {
1605
1614
  }
1606
1615
  }
1607
1616
  function writeState(state, instId) {
1617
+ stateIds.set(state, instId);
1608
1618
  state.updated_at = new Date().toISOString();
1609
1619
  // 落盘前剔除派生量 fail_count(宪法 §10.4:状态不存派生量)。
1610
1620
  // 每次读取都由 fail_counts[current_step] 重算,故不可能出现两个写入者不一致。
@@ -1616,10 +1626,13 @@ export function createEngine(projectDir, ports) {
1616
1626
  const tmp = path.join(dir, `.state.${process.pid}.tmp`);
1617
1627
  fs.writeFileSync(tmp, JSON.stringify(persisted, null, 2), "utf-8");
1618
1628
  fs.renameSync(tmp, statePath(instId));
1629
+ statusErrors.delete(instId);
1619
1630
  }
1620
1631
  catch (e) {
1632
+ statusErrors.set(instId, "状态写盘失败,当前显示最后确认值。请检查工作区权限或磁盘空间。");
1621
1633
  log("error", "state_write_failed", { instId, error: msg(e) });
1622
1634
  }
1635
+ publishStatus();
1623
1636
  }
1624
1637
  /** 某步当前的失败轮数(按步计数;缺省 0) */
1625
1638
  function failCountOf(state, stepId) {
@@ -2388,7 +2401,11 @@ export function createEngine(projectDir, ports) {
2388
2401
  function deliverNotice(state, text, summary) {
2389
2402
  if (!state.owner_session)
2390
2403
  return;
2391
- 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 } : {}) });
2392
2409
  if (!ok)
2393
2410
  log("warn", "deliver_notice_failed", { instId: state.owner_session });
2394
2411
  }
@@ -2597,7 +2614,8 @@ export function createEngine(projectDir, ports) {
2597
2614
  req.canProceed = stillLive; // 载体在 append 之前同步复查一次(关掉「等窗口期间被取消」的竞态)
2598
2615
  // 从这一刻起「本步 DO 还没送达」——期间 turn-stopping 的「忘了交卷」提醒必须闭嘴
2599
2616
  pendingDoDelivery.add(instId);
2600
- const releasePending = () => { pendingDoDelivery.delete(instId); };
2617
+ publishStatus();
2618
+ const releasePending = () => { pendingDoDelivery.delete(instId); publishStatus(); };
2601
2619
  void Promise.resolve()
2602
2620
  .then(() => ports.resetSurface(sid, req))
2603
2621
  .then((outcome) => {
@@ -3852,13 +3870,70 @@ export function createEngine(projectDir, ports) {
3852
3870
  log("warn", "orphan_delegation_recovered", { instId: id });
3853
3871
  }
3854
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
+ }
3855
3930
  return {
3856
3931
  root, instancesDir, workflowsDir, reportsDir, projectDir,
3857
3932
  ensureLayout, listWorkflows, loadWorkflow,
3858
3933
  readState, listInstances, listHistory, instanceDir,
3859
3934
  artifactsDirOf, artifactsRelDirOf, reportRelPathOf, destroyInstance,
3860
3935
  start, onSubmit, noteAssistantText, remindToSubmit, continueInstance, resetCurrent, rewindTo, cancelInstance, statusOf, listAll, restore, diagnose,
3861
- activeInstanceOfSession,
3936
+ activeInstanceOfSession, uiStatus, uiReport,
3862
3937
  };
3863
3938
  }
3864
3939
  function msg(e) { return e instanceof Error ? e.message : String(e); }