@blackbelt-technology/pi-dashboard-flows-plugin 0.11.0 → 0.12.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.
Files changed (71) hide show
  1. package/README.md +5 -1
  2. package/package.json +23 -4
  3. package/src/bridge/flow-catalog-publisher.ts +138 -0
  4. package/src/bridge/flow-event-forward.ts +132 -0
  5. package/src/bridge/flow-files-reporter.ts +16 -14
  6. package/src/bridge/flow-open-tool.ts +124 -0
  7. package/src/bridge/flow-probe.ts +20 -0
  8. package/src/bridge/flow-tool-registry.ts +298 -0
  9. package/src/bridge/flow-tools-guideline.ts +52 -0
  10. package/src/bridge/index.ts +67 -10
  11. package/src/bridge/run-snapshot-reporter.ts +146 -0
  12. package/src/catalog-timings.ts +70 -0
  13. package/src/client/AskSession.tsx +82 -0
  14. package/src/client/FlowActionDialogs.tsx +143 -0
  15. package/src/client/FlowActivityBadge.tsx +42 -4
  16. package/src/client/FlowAgentCard.tsx +63 -8
  17. package/src/client/FlowAgentDetail.tsx +3 -5
  18. package/src/client/FlowDashboard.tsx +381 -273
  19. package/src/client/FlowEditMenu.tsx +69 -0
  20. package/src/client/FlowEditPopover.tsx +130 -0
  21. package/src/client/FlowGraph.tsx +127 -44
  22. package/src/client/FlowHeaderActions.tsx +83 -0
  23. package/src/client/FlowInputWiring.tsx +1 -1
  24. package/src/client/FlowOpenListener.tsx +82 -0
  25. package/src/client/FlowQuestionBlock.tsx +226 -0
  26. package/src/client/FlowStepCards.tsx +189 -0
  27. package/src/client/FlowSummary.tsx +72 -240
  28. package/src/client/FlowWriteToolRenderer.tsx +46 -17
  29. package/src/client/FlowYamlPopoverButton.tsx +2 -2
  30. package/src/client/FlowsContextGroup.tsx +156 -0
  31. package/src/client/FlowsSessionStateContext.tsx +202 -54
  32. package/src/client/FlowsSettings.tsx +145 -17
  33. package/src/client/SessionFlowActions.tsx +65 -10
  34. package/src/client/SessionFlowMenuClaim.tsx +48 -241
  35. package/src/client/ask-session-store.ts +243 -0
  36. package/src/client/flow-attach-store.ts +2 -0
  37. package/src/client/flow-card-grid.ts +2 -2
  38. package/src/client/flow-collapse-storage.ts +36 -6
  39. package/src/client/flow-edges.ts +91 -35
  40. package/src/client/flow-files.ts +16 -4
  41. package/src/client/flow-idle-state.ts +93 -37
  42. package/src/client/flowsActionsGate.ts +1 -1
  43. package/src/client/flowsAvailability.ts +8 -2
  44. package/src/client/index.tsx +13 -11
  45. package/src/client/shouldRender.ts +1 -1
  46. package/src/client/useEditModeState.ts +78 -0
  47. package/src/client/useFlowActions.tsx +191 -0
  48. package/src/client/useFlowCatalog.ts +69 -0
  49. package/src/client/useMinuteClock.ts +21 -0
  50. package/src/client/useRunReattach.ts +50 -0
  51. package/src/configSchema.json +37 -2
  52. package/src/flow-catalog-contract.ts +65 -0
  53. package/src/flow-questions.ts +138 -0
  54. package/src/flow-reducer.ts +434 -13
  55. package/src/flow-state-serialize.ts +132 -0
  56. package/src/i18n.ts +144 -6
  57. package/src/server/automation-actions.ts +4 -3
  58. package/src/server/edit-mode.ts +307 -0
  59. package/src/server/flow-catalog.ts +127 -0
  60. package/src/server/flow-control.ts +263 -0
  61. package/src/server/flow-files.ts +140 -14
  62. package/src/server/flow-open.ts +385 -0
  63. package/src/server/index.ts +112 -34
  64. package/src/server/render-actions.ts +3 -2
  65. package/src/server/state-store.ts +11 -5
  66. package/src/types.ts +180 -0
  67. package/src/bridge/flow-question-adapter.ts +0 -93
  68. package/src/client/FlowQuestionCard.tsx +0 -218
  69. package/src/client/FlowQuestionTranscriptPill.tsx +0 -58
  70. package/src/client/FlowsCommandRoutes.tsx +0 -245
  71. package/src/client/flow-yaml-parse.ts +0 -140
@@ -0,0 +1,132 @@
1
+ /**
2
+ * `FlowState` ↔ JSON for the bridge's active-run snapshot (`flow_run_snapshot`),
3
+ * plus the byte budget that keeps a snapshot under the store's per-event ceiling.
4
+ *
5
+ * - `serializeFlowState`: `agents` Map → entry array; every string capped at
6
+ * {@link SNAPSHOT_STRING_CAP} (the cap live events already get).
7
+ * - `deserializeFlowState`: the inverse; `null` for a missing / malformed state
8
+ * (e.g. the store's `__truncated` placeholder) so the client ignores it.
9
+ * - `trimToBudget`: shrinks an over-budget snapshot `data` envelope in order —
10
+ * oldest tool bodies, then oldest non-log entries, then all but code-step logs
11
+ * — and sets `historyTrimmed`. Cards, statuses, DAG steps, groups and questions
12
+ * are never trimmed.
13
+ *
14
+ * Pure; shared by the bridge (build) and the client (seed).
15
+ * See change: fix-flow-reattach-per-run-state (D4).
16
+ */
17
+ import type { FlowDetailEntry } from "@blackbelt-technology/pi-dashboard-shared/types.js";
18
+ import type { FlowAgentState, FlowState } from "./types.js";
19
+
20
+ /** Dashboard event type of a bridge run snapshot (bus channel `flow:run-snapshot`). */
21
+ export const FLOW_RUN_SNAPSHOT_EVENT = "flow_run_snapshot";
22
+
23
+ /** Per-string cap (same as the store's generic string cap). */
24
+ const SNAPSHOT_STRING_CAP = 4000;
25
+ /** Snapshot `data` budget: min(192 KiB, default 256 KiB ceiling − 8 KiB). */
26
+ export const SNAPSHOT_BUDGET_BYTES = 192 * 1024;
27
+
28
+ /** JSON shape of a `FlowState` (agents as an entry array). */
29
+ export type SerializedFlowState = Omit<FlowState, "agents"> & { agents: Array<[string, FlowAgentState]> };
30
+
31
+ /** `flow_run_snapshot` event data. */
32
+ export interface RunSnapshotData {
33
+ runId: string;
34
+ flowName: string;
35
+ /** Epoch ms of the run's `flow_started`. */
36
+ startedAt: number;
37
+ state: SerializedFlowState;
38
+ }
39
+
40
+ function capStrings<T>(value: T): T {
41
+ if (typeof value === "string") return (value.length > SNAPSHOT_STRING_CAP ? value.slice(0, SNAPSHOT_STRING_CAP) : value) as T;
42
+ if (Array.isArray(value)) return value.map(capStrings) as T;
43
+ if (value && typeof value === "object") {
44
+ const out: Record<string, unknown> = {};
45
+ for (const [k, v] of Object.entries(value)) if (v !== undefined) out[k] = capStrings(v);
46
+ return out as T;
47
+ }
48
+ return value;
49
+ }
50
+
51
+ export function serializeFlowState(state: FlowState): SerializedFlowState {
52
+ return capStrings({ ...state, agents: [...state.agents] }) as SerializedFlowState;
53
+ }
54
+
55
+ /** Inverse of {@link serializeFlowState}; `null` when `raw` is not a state. */
56
+ export function deserializeFlowState(raw: unknown): FlowState | null {
57
+ if (!raw || typeof raw !== "object") return null;
58
+ const s = raw as Partial<SerializedFlowState>;
59
+ if (typeof s.flowName !== "string" || typeof s.status !== "string" || !Array.isArray(s.agents)) return null;
60
+ const agents = new Map<string, FlowAgentState>();
61
+ for (const entry of s.agents) {
62
+ if (!Array.isArray(entry) || typeof entry[0] !== "string" || !entry[1] || typeof entry[1] !== "object") return null;
63
+ const a = entry[1] as FlowAgentState;
64
+ agents.set(entry[0], {
65
+ ...a,
66
+ blockedBy: Array.isArray(a.blockedBy) ? a.blockedBy : [],
67
+ recentTools: Array.isArray(a.recentTools) ? a.recentTools : [],
68
+ detailHistory: Array.isArray(a.detailHistory) ? a.detailHistory : [],
69
+ });
70
+ }
71
+ return { ...(s as SerializedFlowState), agents };
72
+ }
73
+
74
+ const encoder = new TextEncoder();
75
+ const byteLen = (v: unknown): number => encoder.encode(JSON.stringify(v)).length;
76
+
77
+ const isCodeStep = (a: FlowAgentState): boolean => a.nodeKind === "code" || a.nodeKind === "code-decision";
78
+ /** A code / code-decision step's `flow_assistant_text` log line — never trimmed. */
79
+ const isLog = (a: FlowAgentState, e: FlowDetailEntry): boolean => isCodeStep(a) && e.kind === "text";
80
+
81
+ /** Every card (step cards, then fan-out item cards) holding a detail history. */
82
+ function cards(state: SerializedFlowState): FlowAgentState[] {
83
+ const out = state.agents.map(([, a]) => a);
84
+ for (const items of Object.values(state.groups ?? {})) for (const i of items) if (i) out.push(i);
85
+ return out;
86
+ }
87
+
88
+ /** D4 step 1: empty the oldest tool bodies (keep `toolName`; keep a recorded
89
+ * output as "" so a later live result never attaches to a trimmed call) until
90
+ * the size estimate fits. */
91
+ function emptyToolBodies(all: FlowAgentState[], size: number, budget: number): void {
92
+ for (const card of all) {
93
+ for (let i = 0; i < card.detailHistory.length && size > budget; i++) {
94
+ const e = card.detailHistory[i];
95
+ if (e.kind !== "tool") continue;
96
+ const trimmed: FlowDetailEntry = { ...e, input: "", ...(e.output !== undefined ? { output: "" } : {}) };
97
+ size -= byteLen(e) - byteLen(trimmed);
98
+ card.detailHistory[i] = trimmed;
99
+ }
100
+ }
101
+ }
102
+
103
+ /** D4 steps 2–3: drop the oldest non-log entries until the size estimate fits
104
+ * (run to the end, only code-step logs remain). Returns whether any dropped. */
105
+ function dropOldestEntries(all: FlowAgentState[], size: number, budget: number): boolean {
106
+ let dropped = false;
107
+ for (const card of all) {
108
+ card.detailHistory = card.detailHistory.filter((e) => {
109
+ if (size <= budget || isLog(card, e)) return true;
110
+ size -= byteLen(e) + 1;
111
+ dropped = true;
112
+ return false;
113
+ });
114
+ }
115
+ return dropped;
116
+ }
117
+
118
+ /**
119
+ * Bound a snapshot `data` envelope to `budget` bytes (UTF-8 JSON). Returns `data`
120
+ * unchanged when it fits; otherwise a trimmed copy with `state.historyTrimmed`.
121
+ * Running sizes are estimates (separator commas), so each pass re-measures.
122
+ */
123
+ export function trimToBudget(data: RunSnapshotData, budget: number = SNAPSHOT_BUDGET_BYTES): RunSnapshotData {
124
+ if (byteLen(data) <= budget) return data;
125
+ const copy = JSON.parse(JSON.stringify(data)) as RunSnapshotData;
126
+ copy.state.historyTrimmed = true;
127
+ const all = cards(copy.state);
128
+ emptyToolBodies(all, byteLen(copy), budget);
129
+ let size = byteLen(copy);
130
+ while (size > budget && dropOldestEntries(all, size, budget)) size = byteLen(copy);
131
+ return copy;
132
+ }
package/src/i18n.ts CHANGED
@@ -27,7 +27,15 @@ export const catalog = {
27
27
  editModeLabel: "编辑模式",
28
28
  settingsIntro: "多智能体工作流。这是所有会话的默认设置。",
29
29
  editModeHintPre: "允许主会话创建和修改流程与智能体。启用",
30
- editModeHintPost: "以及 edit-flow 技能。默认关闭。",
30
+ editModeHintPost: "以及 manage-flows 技能。默认关闭。",
31
+ editModeHintGlobal: "保存到 ~/.pi/agent/settings.json;不会修改项目文件。项目自身的设置优先于此设置。",
32
+ editModeSaveError: "无法保存:{error}",
33
+ projectEditModeOn: "为此项目开启编辑模式",
34
+ projectEditModeOff: "为此项目关闭编辑模式",
35
+ projectEditModeHint: "将 flows.editFlow 写入此项目的 .pi/settings.json。之后项目值将覆盖全局默认值。",
36
+ editModeErrorTitle: "编辑模式未更改",
37
+ editModeErrorNotDelivered: "无法连接到该会话。此项目的编辑模式未更改。",
38
+ editModeErrorTimeout: "pi-flows 未及时确认更改。菜单显示的是当前值。",
31
39
  runFlowTitle: "运行流程:{flowName}",
32
40
  taskPlaceholder: "描述任务(可选)…",
33
41
  summary: "摘要",
@@ -37,7 +45,6 @@ export const catalog = {
37
45
  viewAgentDetail: "查看 {name} 详情",
38
46
  details: "详情",
39
47
  stepsCount: "{done}/{total} 个步骤",
40
- toggleAutonomousMode: "切换自主模式",
41
48
  abortFlow: "中止流程",
42
49
  newFlowOption: "+ 新建流程",
43
50
  newFlowOptionDesc: "使用 edit-flow 技能创建新流程",
@@ -50,6 +57,8 @@ export const catalog = {
50
57
  closeAttachedFlow: "关闭",
51
58
  flowDefinitionLoadError: "流程定义文件不可用",
52
59
  flowNoLongerAvailable: "已不可用",
60
+ flowViewOnlyLabel: "仅查看 - 未注册",
61
+ flowViewOnlyReopenHint: "请让智能体重新打开它",
53
62
  flowLoading: "加载中…",
54
63
  flowRunRejected: "启动被拒绝",
55
64
  flowRunSendFailed: "无法启动流程",
@@ -61,10 +70,70 @@ export const catalog = {
61
70
  searchFlows: "搜索流程…",
62
71
  noFlowsAvailable: "没有可用的流程",
63
72
  newEditFlowTitle: "新建 / 编辑流程",
64
- pickFlowToEdit: "选择要编辑的流程,或 + 新建流程…",
73
+ pickFlowToEdit: "选择要编辑的流程…",
65
74
  noFlowsYet: "还没有流程 — 选择 + 新建流程",
66
75
  deleteFlowTitle: "删除流程",
67
76
  deleteFlowConfirm: '删除流程 "{name}"?这将移除流程文件及所有关联的代理。',
77
+ // See change: flows-dock-chip-and-panel-actions.
78
+ flowsChipLabel: "流程",
79
+ chipRunning: "运行中 {done}/{total}",
80
+ chipFailed: "失败 · {steps} 步",
81
+ chipDone: "完成",
82
+ chipAborted: "已中止",
83
+ runAgainButton: "再次运行",
84
+ editFlowsButton: "编辑…",
85
+ editModeLoading: "正在检查编辑模式…",
86
+ editFlowItem: "编辑…",
87
+ newFlowItem: "新建流程…",
88
+ editFlowTitle: "编辑流程",
89
+ advancedGroup: "高级",
90
+ catalogTimingsIntro: "仪表盘如何向会话请求其流程列表。",
91
+ catalogAskLimitLabel: "每个会话的目录请求间隔",
92
+ catalogReaskIntervalLabel: "未知时的重新请求间隔",
93
+ catalogReaskAttemptsLabel: "每次查看的重新请求次数",
94
+ catalogServerStartIntervalLabel: "服务器启动后的重新请求间隔",
95
+ catalogServerStartWindowLabel: "服务器启动后的重新请求时间窗口",
96
+ timingRangeError: "请输入 {range} 范围内的值。",
97
+ timingRangeHint: "{range},默认 {def}",
98
+ // Parent-mailbox questions. See change: adopt-flow-parent-mailbox.
99
+ questionHeader: "问题",
100
+ questionBadge: "问题",
101
+ questionsOne: "{n} 个问题",
102
+ questionsMany: "{n} 个问题",
103
+ waitingForAnswer: "等待回答",
104
+ nWaitingForAnswer: "{n} 个等待回答",
105
+ waitingShort: "等待中",
106
+ waitingAria: "等待回答",
107
+ askSession: "询问会话",
108
+ askSessionTitle: "将此问题发送给会话的模型(后续提示)",
109
+ askSessionSent: "已发送",
110
+ askSessionSentTitle: "pi-flows 已将此问题发布到会话中",
111
+ askNoteUnread: "未读",
112
+ askNoteSent: "已发送",
113
+ askNoteNoConfirmation: "未确认",
114
+ nOptions: "{n} 个选项",
115
+ freeAnswer: "自由回答",
116
+ questionsHistory: "问题 ({n})",
117
+ closeCancelled: "已取消",
118
+ closeTimedOut: "已超时",
119
+ closeTimedOutDefault: "已超时,采用默认值:{answer}",
120
+ closeDecider: "已交给分支决策者",
121
+ closeAnswered: "已回答:{answer}",
122
+ closeAnsweredBare: "已回答",
123
+ questionContext: "上下文",
124
+ contextSummary: "{values} 个值 · {files} 个文件 · {upstream} 个上游",
125
+ contextRunValues: "运行上下文",
126
+ contextChangedFiles: "已更改的文件",
127
+ contextUpstream: "上游",
128
+ contextFromAsker: "来自提问者",
129
+ contextNote: "说明",
130
+ showFullQuestion: "显示完整问题",
131
+ hideFullQuestion: "隐藏完整问题",
132
+ remainingDue: "到期",
133
+ remainingUnderMinute: "<1分",
134
+ remainingMinutes: "{m}分",
135
+ remainingHours: "{h}时 {m}分",
136
+ remainingDays: "{d}天 {h}时",
68
137
  },
69
138
  hu: {
70
139
  abort: "Megszakítás",
@@ -81,7 +150,15 @@ export const catalog = {
81
150
  editModeLabel: "Szerkesztő mód",
82
151
  settingsIntro: "Többügynökös munkafolyamatok. Ez az alapértelmezés minden munkamenetre.",
83
152
  editModeHintPre: "Lehetővé teszi, hogy a fő munkamenet folyamatokat és ügynököket hozzon létre és módosítson. Bekapcsolja a",
84
- editModeHintPost: "eszközöket és az edit-flow skillt. Alapértelmezetten kikapcsolva.",
153
+ editModeHintPost: "eszközöket és a manage-flows skillt. Alapértelmezetten kikapcsolva.",
154
+ editModeHintGlobal: "A ~/.pi/agent/settings.json fájlba mentődik; a projektfájlok nem változnak. A projekt saját beállítása felülírja.",
155
+ editModeSaveError: "Nem sikerült menteni: {error}",
156
+ projectEditModeOn: "Szerkesztő mód bekapcsolása ebben a projektben",
157
+ projectEditModeOff: "Szerkesztő mód kikapcsolása ebben a projektben",
158
+ projectEditModeHint: "A flows.editFlow értéket a projekt .pi/settings.json fájljába írja. Ezután a projekt értéke felülírja a globális alapértelmezést.",
159
+ editModeErrorTitle: "A szerkesztő mód nem változott",
160
+ editModeErrorNotDelivered: "A munkamenet nem érhető el. A projekt szerkesztő módja nem változott.",
161
+ editModeErrorTimeout: "A pi-flows nem erősítette meg időben a változást. A menü az aktuális értéket mutatja.",
85
162
  runFlowTitle: "Folyamat futtatása: {flowName}",
86
163
  taskPlaceholder: "Írd le a feladatot (opcionális)…",
87
164
  summary: "Összefoglaló",
@@ -91,7 +168,6 @@ export const catalog = {
91
168
  viewAgentDetail: "{name} részleteinek megtekintése",
92
169
  details: "Részletek",
93
170
  stepsCount: "{done}/{total} lépés",
94
- toggleAutonomousMode: "Autonóm mód váltása",
95
171
  abortFlow: "Folyamat megszakítása",
96
172
  newFlowOption: "+ Új folyamat",
97
173
  newFlowOptionDesc: "Új folyamat készítése az edit-flow készséggel",
@@ -104,6 +180,8 @@ export const catalog = {
104
180
  closeAttachedFlow: "Bezárás",
105
181
  flowDefinitionLoadError: "A folyamatdefiníciós fájl nem érhető el",
106
182
  flowNoLongerAvailable: "már nem érhető el",
183
+ flowViewOnlyLabel: "csak megtekintés - nincs regisztrálva",
184
+ flowViewOnlyReopenHint: "kérd meg az ágenst, hogy nyissa meg újra",
107
185
  flowLoading: "betöltés…",
108
186
  flowRunRejected: "Az indítás elutasítva",
109
187
  flowRunSendFailed: "A folyamat nem indítható el",
@@ -115,10 +193,70 @@ export const catalog = {
115
193
  searchFlows: "Folyamatok keresése…",
116
194
  noFlowsAvailable: "Nincs elérhető folyamat",
117
195
  newEditFlowTitle: "Új / Folyamat szerkesztése",
118
- pickFlowToEdit: "Válassz folyamatot szerkesztésre, vagy + Új folyamat…",
196
+ pickFlowToEdit: "Válassz folyamatot szerkesztésre…",
119
197
  noFlowsYet: "Még nincs folyamat — válaszd a + Új folyamat lehetőséget",
120
198
  deleteFlowTitle: "Folyamat törlése",
121
199
  deleteFlowConfirm:
122
200
  'Törlöd a(z) "{name}" folyamatot? Ez eltávolítja a folyamatfájlt és a hozzá tartozó ügynököket.',
201
+ // See change: flows-dock-chip-and-panel-actions.
202
+ flowsChipLabel: "FOLYAMATOK",
203
+ chipRunning: "fut {done}/{total}",
204
+ chipFailed: "sikertelen · {steps} lépés",
205
+ chipDone: "kész",
206
+ chipAborted: "megszakítva",
207
+ runAgainButton: "Futtatás újra",
208
+ editFlowsButton: "Szerkesztés…",
209
+ editModeLoading: "Szerkesztési mód ellenőrzése…",
210
+ editFlowItem: "Szerkesztés…",
211
+ newFlowItem: "Új folyamat…",
212
+ editFlowTitle: "Folyamat szerkesztése",
213
+ advancedGroup: "Speciális",
214
+ catalogTimingsIntro: "Hogyan kéri le az irányítópult a munkamenetek folyamatlistáját.",
215
+ catalogAskLimitLabel: "Katalóguskérés korlátja munkamenetenként",
216
+ catalogReaskIntervalLabel: "Újrakérési időköz, amíg ismeretlen",
217
+ catalogReaskAttemptsLabel: "Újrakérések száma nézetenként",
218
+ catalogServerStartIntervalLabel: "Újrakérési időköz szerverindítás után",
219
+ catalogServerStartWindowLabel: "Újrakérési időablak szerverindítás után",
220
+ timingRangeError: "Adj meg egy értéket ebben a tartományban: {range}.",
221
+ timingRangeHint: "{range}, alapértelmezés: {def}",
222
+ // Parent-mailbox questions. See change: adopt-flow-parent-mailbox.
223
+ questionHeader: "KÉRDÉS",
224
+ questionBadge: "kérdés",
225
+ questionsOne: "{n} kérdés",
226
+ questionsMany: "{n} kérdés",
227
+ waitingForAnswer: "válaszra vár",
228
+ nWaitingForAnswer: "{n} válaszra vár",
229
+ waitingShort: "vár",
230
+ waitingAria: "válaszra vár",
231
+ askSession: "Munkamenet kérdezése",
232
+ askSessionTitle: "A kérdés elküldése a munkamenet modelljének (követő üzenet)",
233
+ askSessionSent: "Elküldve",
234
+ askSessionSentTitle: "A pi-flows elküldte a kérdést a munkamenetbe",
235
+ askNoteUnread: "olvasatlan",
236
+ askNoteSent: "elküldve",
237
+ askNoteNoConfirmation: "nincs visszaigazolás",
238
+ nOptions: "{n} lehetőség",
239
+ freeAnswer: "szabad válasz",
240
+ questionsHistory: "Kérdések ({n})",
241
+ closeCancelled: "megszakítva",
242
+ closeTimedOut: "lejárt",
243
+ closeTimedOutDefault: "lejárt, alapértelmezés: {answer}",
244
+ closeDecider: "elágazás-döntőnek átadva",
245
+ closeAnswered: "megválaszolva: {answer}",
246
+ closeAnsweredBare: "megválaszolva",
247
+ questionContext: "Kontextus",
248
+ contextSummary: "{values} érték · {files} fájl · {upstream} előzmény",
249
+ contextRunValues: "Futási kontextus",
250
+ contextChangedFiles: "Módosított fájlok",
251
+ contextUpstream: "Előzmény lépések",
252
+ contextFromAsker: "A kérdezőtől",
253
+ contextNote: "Megjegyzés",
254
+ showFullQuestion: "Teljes kérdés megjelenítése",
255
+ hideFullQuestion: "Teljes kérdés elrejtése",
256
+ remainingDue: "lejárt",
257
+ remainingUnderMinute: "<1p",
258
+ remainingMinutes: "{m}p",
259
+ remainingHours: "{h}ó {m}p",
260
+ remainingDays: "{d}n {h}ó",
123
261
  },
124
262
  };
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * Flow availability + the `flow` enum options come from the LIVE per-session
14
14
  * flows list the server already holds (`stateStore`, populated by the
15
- * bridge-forwarded `flows_list`), resolved by mapping a cwd to its running
15
+ * plugin flow catalog fed by forwarded `flow_catalog` events), resolved by mapping a cwd to its running
16
16
  * session(s). NOT a static `.pi/flows/flows/` scan — so package-bundled and
17
17
  * event-registered flows (which pi-flows discovers at runtime) are reflected.
18
18
  * See change: fix-automation-flow-detection.
@@ -121,8 +121,9 @@ export function flowsActionContributions(flowsForCwd: FlowsForCwd): ActionContri
121
121
  // not a slash-command prompt. A flows.run run produces NO agent turn in
122
122
  // the host session (pi-flows consumes flow:run headlessly), so it emits
123
123
  // no `agent_end`. Declare `completion` so the automation engine finalizes
124
- // it on the forwarded `flow_complete` event instead (the extension's
125
- // FLOW_EVENT_MAP forwards pi-flows' `flow:complete` → `flow_complete`).
124
+ // it on the forwarded `flow_complete` event instead (the
125
+ // flows plugin bridge declares pi-flows' `flow:complete` → `flow_complete`,
126
+ // stream keyed `flowName`; see bridge/flow-event-forward.ts).
126
127
  // All flows knowledge — the event name and the FlowResult shape — stays
127
128
  // here; the automation plugin stays generic.
128
129
  //
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Flows edit mode: resolver, guarded routes, per-project action and the
3
+ * one-time legacy migration. The dashboard NEVER writes a repo's
4
+ * `.pi/settings.json` on its own; only the explicit per-project action sends
5
+ * `flow:set-edit-mode` (pi-flows then writes that repo's file).
6
+ *
7
+ * - `resolveEditMode(cwd)` mirrors pi-flows `isEditFlowEnabled`
8
+ * (`edit-flow-config.ts`): project ?? global ?? false; each file holds
9
+ * `flows.editFlow` (boolean) or the legacy top-level `flowsEditFlow`;
10
+ * an absent / unparseable file counts as unset. READ-ONLY.
11
+ * - Global file = `<os.homedir()>/.pi/agent/settings.json`, deliberately
12
+ * ignoring `PI_CODING_AGENT_DIR` (pi-flows reads `homedir()` only).
13
+ * - `GET|PUT /api/plugins/flows/edit-mode-default` and
14
+ * `GET /api/plugins/flows/edit-mode-state?sessionId` sit in an
15
+ * encapsulated scope behind `networkGuard` + `@fastify/rate-limit`.
16
+ * PUT accepts `{ enabled: boolean }` only and writes `flows.editFlow` only,
17
+ * under pi's settings lock (merge-preserving).
18
+ * - Push frame `{ type: "flows_edit_mode_state", sessionId, enabled, error? }`,
19
+ * one per active session in each affected cwd.
20
+ *
21
+ * See change: stop-flows-edit-mode-project-writes (D2, D4, D5, D6).
22
+ */
23
+ import fs from "node:fs";
24
+ import os from "node:os";
25
+ import path from "node:path";
26
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
27
+ import {
28
+ asObject,
29
+ type FsDeps,
30
+ formatJson,
31
+ readPiSettings,
32
+ withPiSettingsLock,
33
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-agent-settings-lock.js";
34
+ import rateLimit from "@fastify/rate-limit";
35
+
36
+ const EDIT_MODE_STATE_FRAME = "flows_edit_mode_state";
37
+ const SET_EDIT_MODE_EVENT = "flow:set-edit-mode";
38
+ /** Per-project action: poll the project file until pi-flows has written it. */
39
+ export const SET_EDIT_MODE_POLL = { attempts: 10, intervalMs: 200 } as const;
40
+
41
+ export type EditModeError = "not-delivered" | "timeout";
42
+
43
+ interface EditModeStateFrame {
44
+ type: typeof EDIT_MODE_STATE_FRAME;
45
+ sessionId: string;
46
+ enabled: boolean;
47
+ error?: EditModeError;
48
+ }
49
+
50
+ // ── Resolver (mirror of pi-flows `edit-flow-config.ts`) ──────────────
51
+
52
+ /** The global file pi-flows reads: `<home>/.pi/agent/settings.json` (env ignored). */
53
+ export function globalSettingsPath(home: string = os.homedir()): string {
54
+ return path.join(home, ".pi", "agent", "settings.json");
55
+ }
56
+
57
+ function projectSettingsPath(cwd: string): string {
58
+ return path.join(cwd, ".pi", "settings.json");
59
+ }
60
+
61
+ /** pi-flows `readEditFlowFlag`: `flows.editFlow` first, then `flowsEditFlow`; booleans only. */
62
+ function readEditFlowFlag(settings: unknown): boolean | undefined {
63
+ if (!settings || typeof settings !== "object") return undefined;
64
+ const s = settings as Record<string, unknown>;
65
+ const flows = s.flows;
66
+ if (flows && typeof flows === "object" && "editFlow" in flows) {
67
+ const v = (flows as Record<string, unknown>).editFlow;
68
+ if (typeof v === "boolean") return v;
69
+ }
70
+ if (typeof s.flowsEditFlow === "boolean") return s.flowsEditFlow;
71
+ return undefined;
72
+ }
73
+
74
+ /** Absent / unreadable / unparseable → undefined (pi-flows `readSettingsFile`). */
75
+ function readFlagFile(file: string): boolean | undefined {
76
+ try {
77
+ return readEditFlowFlag(JSON.parse(fs.readFileSync(file, "utf-8")));
78
+ } catch {
79
+ return undefined;
80
+ }
81
+ }
82
+
83
+ export interface ResolveOptions {
84
+ /** Defaults to `os.homedir()`. */
85
+ home?: string;
86
+ }
87
+
88
+ /** Effective edit mode for `cwd`: project ?? global ?? false. Never writes. */
89
+ export function resolveEditMode(cwd: string, opts: ResolveOptions = {}): boolean {
90
+ const project = readFlagFile(projectSettingsPath(cwd));
91
+ if (project !== undefined) return project;
92
+ return readFlagFile(globalSettingsPath(opts.home)) ?? false;
93
+ }
94
+
95
+ /** Resolve many cwds reading the global file once and each project file once. */
96
+ function resolveEditModeMany(cwds: Iterable<string>, opts: ResolveOptions): Map<string, boolean> {
97
+ const global = readFlagFile(globalSettingsPath(opts.home)) ?? false;
98
+ const out = new Map<string, boolean>();
99
+ for (const cwd of cwds) {
100
+ if (!out.has(cwd)) out.set(cwd, readFlagFile(projectSettingsPath(cwd)) ?? global);
101
+ }
102
+ return out;
103
+ }
104
+
105
+ // ── Session registry helpers ─────────────────────────────────────────
106
+
107
+ interface ActiveSession {
108
+ id: string;
109
+ cwd: string;
110
+ }
111
+
112
+ function activeSessions(sm: { listActive(): unknown[] }): ActiveSession[] {
113
+ const out: ActiveSession[] = [];
114
+ for (const s of sm.listActive()) {
115
+ const r = s as { id?: unknown; cwd?: unknown; status?: unknown; originDeviceId?: unknown } | null;
116
+ // A remote-origin session's cwd is not on this filesystem: never resolve it locally.
117
+ if (r && typeof r.id === "string" && typeof r.cwd === "string" && r.cwd !== "" && r.status !== "ended" && !r.originDeviceId) {
118
+ out.push({ id: r.id, cwd: r.cwd });
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+
124
+ export interface EditModeDeps {
125
+ sessionManager: { listActive(): unknown[] };
126
+ broadcastToSubscribers: (msg: unknown) => void;
127
+ /** Test seam for `os.homedir()`. */
128
+ home?: string;
129
+ /** Test seam for the locked write's fs calls. */
130
+ lockFs?: FsDeps["fs"];
131
+ }
132
+
133
+ const lockDeps = (deps: Pick<EditModeDeps, "home" | "lockFs">): FsDeps => ({
134
+ settingsPath: globalSettingsPath(deps.home),
135
+ ...(deps.lockFs ? { fs: deps.lockFs } : {}),
136
+ });
137
+
138
+ /**
139
+ * Push the effective state to every active session whose cwd is in `cwds`
140
+ * (all active sessions when omitted). One read per distinct cwd.
141
+ */
142
+ export function broadcastEditModeState(
143
+ deps: EditModeDeps,
144
+ cwds?: ReadonlySet<string>,
145
+ extra?: { sessionId: string; error: EditModeError },
146
+ ): void {
147
+ const sessions = activeSessions(deps.sessionManager).filter((s) => !cwds || cwds.has(s.cwd));
148
+ const resolved = resolveEditModeMany(
149
+ sessions.map((s) => s.cwd),
150
+ { home: deps.home },
151
+ );
152
+ for (const s of sessions) {
153
+ const frame: EditModeStateFrame = { type: EDIT_MODE_STATE_FRAME, sessionId: s.id, enabled: resolved.get(s.cwd) ?? false };
154
+ if (extra && extra.sessionId === s.id) frame.error = extra.error;
155
+ deps.broadcastToSubscribers(frame);
156
+ }
157
+ }
158
+
159
+ // ── Routes (D2, D4) ──────────────────────────────────────────────────
160
+
161
+ export interface EditModeRouteDeps extends EditModeDeps {
162
+ fastify: ServerPluginContext["fastify"];
163
+ networkGuard: ServerPluginContext["networkGuard"];
164
+ }
165
+
166
+ /** Write `flows.editFlow` to the global file under pi's lock. */
167
+ async function writeGlobalEditMode(
168
+ enabled: boolean,
169
+ deps: Pick<EditModeDeps, "home" | "lockFs">,
170
+ ): Promise<{ ok: true } | { ok: false; status: number; parseError?: string; error: string }> {
171
+ const r = await withPiSettingsLock<null, { parseError: string }>(
172
+ (state) => {
173
+ if (state.parseError) return { fail: { parseError: state.parseError } };
174
+ const next = { ...state.settings, flows: { ...asObject(state.settings.flows), editFlow: enabled } };
175
+ return { value: null, write: formatJson(next) };
176
+ },
177
+ {},
178
+ lockDeps(deps),
179
+ );
180
+ if (r.ok) return { ok: true };
181
+ if (r.error === "fn") return { ok: false, status: 400, error: "unparseable settings", parseError: r.fail.parseError };
182
+ if (r.error === "busy") return { ok: false, status: 503, error: "settings locked" };
183
+ return { ok: false, status: 500, error: "write failed" };
184
+ }
185
+
186
+ export async function registerEditModeRoutes(deps: EditModeRouteDeps): Promise<void> {
187
+ await deps.fastify.register(async (scope) => {
188
+ await scope.register(rateLimit, { global: true, max: 600, timeWindow: "1 minute", allowList: ["127.0.0.1", "::1"] });
189
+
190
+ scope.get("/api/plugins/flows/edit-mode-default", { preHandler: deps.networkGuard }, async () => {
191
+ const state = readPiSettings(lockDeps(deps));
192
+ return {
193
+ enabled: readEditFlowFlag(state.settings) ?? false,
194
+ ...(state.parseError ? { parseError: state.parseError } : {}),
195
+ };
196
+ });
197
+
198
+ scope.put("/api/plugins/flows/edit-mode-default", { preHandler: deps.networkGuard }, async (req, reply) => {
199
+ const enabled = (req.body as { enabled?: unknown } | null)?.enabled;
200
+ if (typeof enabled !== "boolean") return reply.code(400).send({ error: "body must be { enabled: boolean }" });
201
+ const r = await writeGlobalEditMode(enabled, deps);
202
+ if (!r.ok) {
203
+ return reply.code(r.status).send({ error: r.error, ...(r.parseError ? { parseError: r.parseError } : {}) });
204
+ }
205
+ broadcastEditModeState(deps);
206
+ return { enabled };
207
+ });
208
+
209
+ scope.get("/api/plugins/flows/edit-mode-state", { preHandler: deps.networkGuard }, async (req, reply) => {
210
+ const id = (req.query as { sessionId?: unknown } | null)?.sessionId;
211
+ const session = typeof id === "string" && id ? activeSessions(deps.sessionManager).find((s) => s.id === id) : undefined;
212
+ if (!session) return reply.code(404).send({ error: "session not found" });
213
+ return { enabled: resolveEditMode(session.cwd, { home: deps.home }) };
214
+ });
215
+ });
216
+ }
217
+
218
+ // ── Per-project action (D5) ──────────────────────────────────────────
219
+
220
+ export interface SetEditModeDeps extends EditModeDeps {
221
+ emitEventToSession: (sessionId: string, eventType: string, data: Record<string, unknown>) => boolean;
222
+ logger?: { info(m: string): void; warn(m: string): void };
223
+ }
224
+
225
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
226
+
227
+ /**
228
+ * `flow.set-edit-mode { enabled }` — `enabled` is the DESIRED value (the
229
+ * label the user clicked). Emits `flow:set-edit-mode` only when it differs
230
+ * from the current effective value, then waits for pi-flows' project write
231
+ * and pushes the result to every session in the cwd.
232
+ */
233
+ export async function handleSetEditMode(deps: SetEditModeDeps, sessionId: string, payload: Record<string, unknown>): Promise<void> {
234
+ const enabled = payload.enabled;
235
+ if (typeof enabled !== "boolean") {
236
+ deps.logger?.warn(`flow.set-edit-mode session=${sessionId}: enabled must be boolean`);
237
+ return;
238
+ }
239
+ const session = activeSessions(deps.sessionManager).find((s) => s.id === sessionId);
240
+ if (!session) {
241
+ deps.logger?.warn(`flow.set-edit-mode session=${sessionId}: session not active`);
242
+ return;
243
+ }
244
+ const cwds = new Set([session.cwd]);
245
+ const current = () => resolveEditMode(session.cwd, { home: deps.home });
246
+
247
+ if (current() === enabled) {
248
+ broadcastEditModeState(deps, cwds);
249
+ return;
250
+ }
251
+ const delivered = deps.emitEventToSession(sessionId, SET_EDIT_MODE_EVENT, { enabled });
252
+ deps.logger?.info(`flow.set-edit-mode enabled=${enabled} session=${sessionId} delivered=${delivered}`);
253
+ if (!delivered) {
254
+ broadcastEditModeState(deps, cwds, { sessionId, error: "not-delivered" });
255
+ return;
256
+ }
257
+ for (let i = 0; i < SET_EDIT_MODE_POLL.attempts; i++) {
258
+ await sleep(SET_EDIT_MODE_POLL.intervalMs);
259
+ if (current() === enabled) {
260
+ broadcastEditModeState(deps, cwds);
261
+ return;
262
+ }
263
+ }
264
+ broadcastEditModeState(deps, cwds, { sessionId, error: "timeout" });
265
+ }
266
+
267
+ // ── Legacy migration (D6) ────────────────────────────────────────────
268
+
269
+ export interface MigrationCtx {
270
+ getPluginConfig<T = Record<string, unknown>>(): T;
271
+ updatePluginConfig<T = Record<string, unknown>>(partial: Partial<T>): Promise<void>;
272
+ }
273
+
274
+ /**
275
+ * One-time: a legacy plugin-config `editFlow: true` becomes the global
276
+ * `flows.editFlow: true` when the global file has no edit-mode value (checked
277
+ * inside the lock). The key is then dropped. Failure keeps the key so the
278
+ * next start retries. Never writes a project file.
279
+ */
280
+ export async function migrateLegacyEditFlow(
281
+ ctx: MigrationCtx,
282
+ deps: Pick<EditModeDeps, "home" | "lockFs"> & { logger?: { info(m: string): void; warn(m: string): void } } = {},
283
+ ): Promise<"none" | "migrated" | "cleared" | "deferred"> {
284
+ const config = ctx.getPluginConfig<{ editFlow?: unknown }>() ?? {};
285
+ if (!("editFlow" in config) || config.editFlow === undefined) return "none";
286
+ let outcome: "migrated" | "cleared" = "cleared";
287
+ if (config.editFlow === true) {
288
+ const r = await withPiSettingsLock<boolean, { parseError: string }>(
289
+ (state) => {
290
+ if (state.parseError) return { fail: { parseError: state.parseError } };
291
+ if (readEditFlowFlag(state.settings) !== undefined) return { value: false };
292
+ const next = { ...state.settings, flows: { ...asObject(state.settings.flows), editFlow: true } };
293
+ return { value: true, write: formatJson(next) };
294
+ },
295
+ {},
296
+ lockDeps(deps),
297
+ );
298
+ if (!r.ok) {
299
+ deps.logger?.warn(`flows: legacy editFlow migration deferred (${r.error})`);
300
+ return "deferred";
301
+ }
302
+ if (r.value) outcome = "migrated";
303
+ }
304
+ await ctx.updatePluginConfig({ editFlow: undefined });
305
+ deps.logger?.info(`flows: legacy editFlow ${outcome}`);
306
+ return outcome;
307
+ }