@kkelly-offical/kkcode 0.1.2 → 0.1.6

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 (58) hide show
  1. package/README.md +120 -178
  2. package/package.json +46 -46
  3. package/src/agent/agent.mjs +41 -0
  4. package/src/agent/prompt/frontend-designer.txt +58 -0
  5. package/src/agent/prompt/longagent-blueprint-agent.txt +83 -0
  6. package/src/agent/prompt/longagent-coding-agent.txt +37 -0
  7. package/src/agent/prompt/longagent-debugging-agent.txt +46 -0
  8. package/src/agent/prompt/longagent-preview-agent.txt +63 -0
  9. package/src/config/defaults.mjs +260 -195
  10. package/src/config/schema.mjs +71 -6
  11. package/src/core/constants.mjs +91 -46
  12. package/src/index.mjs +1 -1
  13. package/src/knowledge/frontend-aesthetics.txt +39 -0
  14. package/src/knowledge/loader.mjs +2 -1
  15. package/src/knowledge/tailwind.txt +12 -3
  16. package/src/mcp/client-http.mjs +141 -157
  17. package/src/mcp/client-sse.mjs +288 -286
  18. package/src/mcp/client-stdio.mjs +533 -451
  19. package/src/mcp/constants.mjs +2 -0
  20. package/src/mcp/registry.mjs +479 -394
  21. package/src/mcp/stdio-framing.mjs +133 -127
  22. package/src/mcp/tool-result.mjs +24 -0
  23. package/src/observability/index.mjs +42 -0
  24. package/src/observability/metrics.mjs +137 -0
  25. package/src/observability/tracer.mjs +137 -0
  26. package/src/orchestration/background-manager.mjs +372 -358
  27. package/src/orchestration/background-worker.mjs +305 -245
  28. package/src/orchestration/longagent-manager.mjs +171 -116
  29. package/src/orchestration/stage-scheduler.mjs +728 -489
  30. package/src/permission/exec-policy.mjs +9 -11
  31. package/src/provider/anthropic.mjs +1 -0
  32. package/src/provider/openai.mjs +340 -339
  33. package/src/provider/retry-policy.mjs +68 -68
  34. package/src/provider/router.mjs +241 -228
  35. package/src/provider/sse.mjs +104 -91
  36. package/src/repl.mjs +1 -1
  37. package/src/session/checkpoint.mjs +66 -3
  38. package/src/session/engine.mjs +227 -225
  39. package/src/session/longagent-4stage.mjs +460 -0
  40. package/src/session/longagent-hybrid.mjs +1081 -0
  41. package/src/session/longagent-plan.mjs +365 -329
  42. package/src/session/longagent-project-memory.mjs +53 -0
  43. package/src/session/longagent-scaffold.mjs +291 -100
  44. package/src/session/longagent-task-bus.mjs +54 -0
  45. package/src/session/longagent-utils.mjs +472 -0
  46. package/src/session/longagent.mjs +884 -1462
  47. package/src/session/project-context.mjs +30 -0
  48. package/src/session/store.mjs +510 -503
  49. package/src/session/task-validator.mjs +4 -3
  50. package/src/skill/builtin/design.mjs +76 -0
  51. package/src/skill/builtin/frontend.mjs +8 -0
  52. package/src/skill/registry.mjs +390 -336
  53. package/src/storage/ghost-commit-store.mjs +18 -8
  54. package/src/tool/executor.mjs +11 -0
  55. package/src/tool/git-auto.mjs +0 -19
  56. package/src/tool/registry.mjs +71 -37
  57. package/src/ui/activity-renderer.mjs +664 -410
  58. package/src/util/git.mjs +23 -0
@@ -1,410 +1,664 @@
1
- import { EventBus } from "../core/events.mjs"
2
- import { EVENT_TYPES } from "../core/constants.mjs"
3
- import { paint } from "../theme/color.mjs"
4
-
5
- let _theme = null
6
- function diffAdd() { return _theme?.components?.diff_add || "green" }
7
- function diffDel() { return _theme?.components?.diff_del || "red" }
8
-
9
- // ── Symbols ──────────────────────────────────────────────
10
- export const SYM = {
11
- dot: "●",
12
- dotHollow: "○",
13
- toolOk: "✓",
14
- toolErr: "✗",
15
- stage: "◆",
16
- iteration: "↻",
17
- phase: "●",
18
- plan: "☐",
19
- planDone: "☑",
20
- recovery: "⟳",
21
- alert: "!",
22
- thinking: "▶",
23
- thinkingOpen: "▼",
24
- search: "*",
25
- arrow: "→",
26
- write: "◇"
27
- }
28
-
29
- // ── Helpers ──────────────────────────────────────────────
30
-
31
- function clipText(text, max) {
32
- const s = String(text || "").trim()
33
- if (s.length <= max) return s
34
- return s.slice(0, max - 3) + "..."
35
- }
36
-
37
- function shortPath(p) {
38
- const s = String(p || "").trim()
39
- // Show last 2-3 segments for readability
40
- const parts = s.replace(/\\/g, "/").split("/")
41
- if (parts.length <= 3) return s
42
- return ".../" + parts.slice(-3).join("/")
43
- }
44
-
45
- // ── Tool Display Formatters ──────────────────────────────
46
-
47
- export function formatToolStart(toolName, args) {
48
- // Compact single-line dim format (OpenCode style)
49
- const sym = toolName === "grep" || toolName === "glob" || toolName === "websearch"
50
- ? SYM.search
51
- : toolName === "write" || toolName === "edit" || toolName === "notebookedit"
52
- ? SYM.write
53
- : SYM.arrow
54
- const prefix = paint(sym, "#666666")
55
- const name = paint(toolName.charAt(0).toUpperCase() + toolName.slice(1), null, { dim: true })
56
-
57
- switch (toolName) {
58
- case "bash": {
59
- const desc = clipText(args?.description || args?.command, 80)
60
- return ` ${prefix} ${name} ${paint(desc, null, { dim: true })}`
61
- }
62
- case "write":
63
- case "edit":
64
- return ` ${prefix} ${name} ${paint(shortPath(args?.path), null, { dim: true })}`
65
- case "notebookedit":
66
- return ` ${prefix} ${name} ${paint(shortPath(args?.path), null, { dim: true })} ${paint(`cell ${args?.cell_number ?? 0}`, null, { dim: true })}`
67
- case "read":
68
- case "list":
69
- return ` ${prefix} ${name} ${paint(shortPath(args?.path || "."), null, { dim: true })}`
70
- case "grep":
71
- case "glob":
72
- return ` ${prefix} ${name} ${paint(clipText(args?.pattern, 60), null, { dim: true })}`
73
- case "task":
74
- return ` ${prefix} ${name} ${paint(clipText(args?.description || args?.prompt, 60), null, { dim: true })}`
75
- case "todowrite":
76
- return null // handled by result preview only
77
- case "webfetch":
78
- return ` ${prefix} ${name} ${paint(clipText(args?.url, 60), null, { dim: true })}`
79
- case "websearch":
80
- return ` ${prefix} ${name} ${paint(clipText(args?.query, 60), null, { dim: true })}`
81
- case "question":
82
- return ` ~ ${paint("Asking questions...", null, { dim: true })}`
83
- case "enter_plan":
84
- return ` ${paint(SYM.plan, "magenta")} ${paint("Enter Plan", "magenta")}`
85
- case "exit_plan":
86
- return ` ${paint(SYM.planDone, "green")} ${paint("Submit Plan", "green")}`
87
- default:
88
- return ` ${prefix} ${name} ${paint(clipText(args ? Object.keys(args).slice(0, 3).join(", ") : "", 40), null, { dim: true })}`
89
- }
90
- }
91
-
92
- export function formatToolFinish(toolName, status, durationMs, args) {
93
- if (status === "error") {
94
- return ` ${paint(SYM.toolErr, "red")} ${paint(toolName, null, { dim: true })} ${paint("error", "red")}${durationMs ? paint(` ${durationMs}ms`, null, { dim: true }) : ""}`
95
- }
96
- // For completed tools, return null — the start line + result preview is enough
97
- return null
98
- }
99
-
100
- export function formatToolResultPreview(toolName, output, status, args) {
101
- if (status !== "completed") return null
102
- const text = String(output || "").trim()
103
-
104
- switch (toolName) {
105
- case "bash": {
106
- const lines = text.split("\n").filter(Boolean)
107
- if (!lines.length) return null
108
- const first = clipText(lines[0], 90)
109
- const suffix = lines.length > 1 ? paint(` (+${lines.length - 1} lines)`, null, { dim: true }) : ""
110
- return ` ${paint(first, null, { dim: true })}${suffix}`
111
- }
112
- case "write": {
113
- const n = String(args?.content || "").split("\n").filter(Boolean).length
114
- return ` ${paint(`+${n} lines`, diffAdd(), { dim: true })}`
115
- }
116
- case "edit": {
117
- const added = String(args?.new_string || "").split("\n").filter(Boolean).length
118
- const removed = String(args?.old_string || "").split("\n").filter(Boolean).length
119
- const parts = []
120
- if (added > 0) parts.push(paint(`+${added}`, diffAdd()))
121
- if (removed > 0) parts.push(paint(`-${removed}`, diffDel()))
122
- return parts.length ? ` ${parts.join(" ")} ${paint("lines", null, { dim: true })}` : null
123
- }
124
- case "grep": {
125
- const lines = text.split("\n").filter(Boolean)
126
- if (text === "no matches" || !lines.length) return ` ${paint("no matches", null, { dim: true })}`
127
- return ` ${paint(`${lines.length} matches`, null, { dim: true })}`
128
- }
129
- case "read":
130
- return ` ${paint(`${text.split("\n").length} lines`, null, { dim: true })}`
131
- case "glob": {
132
- const lines = text.split("\n").filter(Boolean)
133
- if (!lines.length) return ` ${paint("no files", null, { dim: true })}`
134
- return ` ${paint(`${lines.length} files`, null, { dim: true })}`
135
- }
136
- case "todowrite": {
137
- const todos = Array.isArray(args?.todos) ? args.todos : []
138
- if (!todos.length) return null
139
- const result = []
140
- for (const t of todos.slice(0, 8)) {
141
- const s = t.status || "pending"
142
- const dot = s === "completed" ? paint(SYM.toolOk, "green")
143
- : s === "in_progress" ? paint(SYM.dot, "yellow")
144
- : paint(SYM.dotHollow, "#666666")
145
- const color = s === "completed" ? "green" : s === "in_progress" ? "yellow" : null
146
- const label = s === "in_progress" && t.activeForm ? t.activeForm : t.content
147
- result.push(` ${dot} ${paint(label || "", color, { dim: s === "completed" })}`)
148
- }
149
- if (todos.length > 8) result.push(paint(` ... +${todos.length - 8} more`, null, { dim: true }))
150
- return result
151
- }
152
- default:
153
- return null
154
- }
155
- }
156
-
157
- function formatToolError(error) {
158
- if (!error) return null
159
- return ` ${paint(clipText(error, 120), "red", { dim: true })}`
160
- }
161
-
162
- // ── Thinking Formatter ──────────────────────────────────
163
-
164
- export function formatThinkingHeader() {
165
- return `${paint(SYM.dot, "#666666")} ${paint("Thinking", null, { italic: true, dim: true })} ${paint("∨", null, { dim: true })}`
166
- }
167
-
168
- // ── LongAgent Display Formatters ─────────────────────────
169
-
170
- export function formatPhaseChange(prevPhase, nextPhase, reason) {
171
- const arrow = paint("→", null, { dim: true })
172
- const reasonText = reason ? paint(reason, null, { dim: true }) : ""
173
- return `${paint(SYM.phase, "magenta")} ${paint("phase", "magenta", { bold: true })} ${paint(prevPhase, null, { dim: true })} ${arrow} ${paint(nextPhase, "magenta", { bold: true })} ${reasonText}`
174
- }
175
-
176
- export function formatStageStarted(stageId, taskCount) {
177
- return `${paint(SYM.stage, "#fb923c", { bold: true })} ${paint("stage", "#fb923c", { bold: true })} ${paint(stageId, "white", { bold: true })} ${paint(`(${taskCount} tasks)`, null, { dim: true })}`
178
- }
179
-
180
- export function formatStageFinished(stageId, successCount, failCount) {
181
- const status = failCount === 0
182
- ? paint("PASS", "green", { bold: true })
183
- : paint(`FAIL (${failCount})`, "red", { bold: true })
184
- return `${paint(SYM.stage, "#fb923c")} ${paint("stage", "#fb923c")} ${paint(stageId, "white")} ${status} ${paint(`(${successCount} ok)`, null, { dim: true })}`
185
- }
186
-
187
- export function formatTaskDispatched(_stageId, taskId, attempt) {
188
- const attemptLabel = attempt > 1 ? paint(` retry#${attempt}`, "yellow") : ""
189
- return ` ${paint(SYM.dot, "#666666")} ${paint("task", "cyan")} ${paint(taskId, null, { dim: true })}${attemptLabel}`
190
- }
191
-
192
- export function formatTaskFinished(taskId, status) {
193
- const dot = status === "completed" ? paint(SYM.dot, "green") : paint(SYM.dot, "red")
194
- const color = status === "completed" ? "green" : "red"
195
- return ` ${dot} ${paint(taskId, null, { dim: true })} ${paint(status, color)}`
196
- }
197
-
198
- export function formatHeartbeat(iteration, maxIterations, phase, gate, progress, elapsed) {
199
- const iterLabel = maxIterations > 0 ? `${iteration}/${maxIterations}` : String(iteration)
200
- const progressLabel = progress?.percentage !== null && progress?.percentage !== undefined
201
- ? paint(`${progress.percentage}%`, "green")
202
- : paint("...", null, { dim: true })
203
- const elapsedLabel = elapsed !== undefined ? paint(`${elapsed}s`, null, { dim: true }) : ""
204
- return `${paint(SYM.iteration, "#fb923c")} ${paint("iter", "#fb923c")} ${paint(iterLabel, "white", { bold: true })} phase=${paint(phase || "-", "magenta")} gate=${paint(gate || "-", "cyan")} progress=${progressLabel} ${elapsedLabel}`
205
- }
206
-
207
- export function formatPlanFrozen(planId, stageCount) {
208
- return `${paint(SYM.planDone, "green", { bold: true })} ${paint("plan frozen", "green", { bold: true })} ${paint(planId || "", null, { dim: true })} ${paint(`${stageCount} stage(s)`, null, { dim: true })}`
209
- }
210
-
211
- export function formatRecovery(reason, recoveryCount) {
212
- return `${paint(SYM.recovery, "yellow", { bold: true })} ${paint("recovery", "yellow", { bold: true })} #${recoveryCount} ${paint(reason || "", null, { dim: true })}`
213
- }
214
-
215
- export function formatAlert(kind, message) {
216
- return `${paint(SYM.alert, "red", { bold: true })} ${paint("alert", "red", { bold: true })} [${kind}] ${paint(message || "", null, { dim: true })}`
217
- }
218
-
219
- export function formatIntakeStarted(objective) {
220
- const preview = clipText(objective, 80)
221
- return `${paint(SYM.phase, "magenta")} ${paint("intake", "magenta", { bold: true })} ${paint(preview, null, { dim: true })}`
222
- }
223
-
224
- export function formatGateChecked(gate, status) {
225
- const dot = status === "pass" ? paint(SYM.dot, "green") : paint(SYM.dot, "yellow")
226
- return ` ${dot} gate=${paint(gate || "-", "cyan")} ${paint(status || "-", status === "pass" ? "green" : "yellow")}`
227
- }
228
-
229
- // ── Plan Progress Formatter ──────────────────────────────
230
-
231
- export function formatPlanProgress(taskProgress) {
232
- if (!taskProgress || typeof taskProgress !== "object") return []
233
- const entries = Object.entries(taskProgress)
234
- if (!entries.length) return []
235
-
236
- const lines = [paint("Plan Progress:", "cyan", { bold: true })]
237
- for (const [taskId, tp] of entries) {
238
- const status = tp?.status || "pending"
239
- const dot = status === "completed"
240
- ? paint(SYM.dot, "green")
241
- : status === "error"
242
- ? paint(SYM.dot, "red")
243
- : paint(SYM.dotHollow, "#666666")
244
- const color = status === "completed" ? "green" : status === "error" ? "red" : "white"
245
- lines.push(` ${dot} ${taskId} ${paint(status, color)}`)
246
- }
247
- return lines
248
- }
249
-
250
- // ── Renderer ─────────────────────────────────────────────
251
-
252
- export function createActivityRenderer({ output, theme = null }) {
253
- _theme = theme
254
- const log = typeof output?.appendLog === "function"
255
- ? output.appendLog
256
- : (text) => console.log(text)
257
-
258
- const toolTimers = new Map()
259
- let timerCounter = 0
260
- let unsubscribe = null
261
-
262
- function timerKey(sessionId, turnId, toolName) {
263
- return `${sessionId || ""}:${turnId || ""}:${toolName}:${timerCounter++}`
264
- }
265
-
266
- // Track the latest timer key per tool invocation
267
- const activeToolKeys = new Map()
268
- // Track tool args for finish formatting
269
- const activeToolArgs = new Map()
270
-
271
- function handleEvent(event) {
272
- const { type, payload, sessionId, turnId } = event
273
-
274
- switch (type) {
275
- case EVENT_TYPES.TOOL_START: {
276
- const key = timerKey(sessionId, turnId, payload.tool)
277
- const lookupKey = `${sessionId}:${turnId}:${payload.tool}`
278
- toolTimers.set(key, Date.now())
279
- activeToolKeys.set(lookupKey, key)
280
- activeToolArgs.set(lookupKey, payload.args)
281
- // Show tool call inline (compact dim line)
282
- const startLine = formatToolStart(payload.tool, payload.args)
283
- if (startLine) log(startLine)
284
- break
285
- }
286
-
287
- case EVENT_TYPES.TOOL_FINISH: {
288
- const lookupKey = `${sessionId}:${turnId}:${payload.tool}`
289
- const key = activeToolKeys.get(lookupKey)
290
- const savedArgs = activeToolArgs.get(lookupKey) || payload.args
291
- if (key) {
292
- toolTimers.delete(key)
293
- activeToolKeys.delete(lookupKey)
294
- activeToolArgs.delete(lookupKey)
295
- }
296
- const finishLine = formatToolFinish(payload.tool, payload.status, 0, savedArgs)
297
- if (finishLine) log(finishLine)
298
- const preview = formatToolResultPreview(payload.tool, payload.output, payload.status, savedArgs)
299
- if (preview) {
300
- if (Array.isArray(preview)) {
301
- for (const line of preview) log(line)
302
- } else {
303
- log(preview)
304
- }
305
- }
306
- // Blank line after tool for visual spacing
307
- if (payload.tool !== "todowrite") log("")
308
- break
309
- }
310
-
311
- case EVENT_TYPES.TOOL_ERROR: {
312
- const lookupKey = `${sessionId}:${turnId}:${payload.tool}`
313
- const key = activeToolKeys.get(lookupKey)
314
- const savedArgs = activeToolArgs.get(lookupKey) || payload.args
315
- if (key) {
316
- toolTimers.delete(key)
317
- activeToolKeys.delete(lookupKey)
318
- activeToolArgs.delete(lookupKey)
319
- }
320
- log(formatToolFinish(payload.tool, payload.status || "error", 0, savedArgs))
321
- const errLine = formatToolError(payload.error)
322
- if (errLine) log(errLine)
323
- break
324
- }
325
-
326
- case EVENT_TYPES.LONGAGENT_PHASE_CHANGED: {
327
- log(formatPhaseChange(payload.prevPhase, payload.nextPhase, payload.reason))
328
- break
329
- }
330
-
331
- case EVENT_TYPES.LONGAGENT_STAGE_STARTED: {
332
- log(formatStageStarted(payload.stageId, payload.taskCount))
333
- break
334
- }
335
-
336
- case EVENT_TYPES.LONGAGENT_STAGE_FINISHED: {
337
- log(formatStageFinished(payload.stageId, payload.successCount, payload.failCount))
338
- break
339
- }
340
-
341
- case EVENT_TYPES.LONGAGENT_STAGE_TASK_DISPATCHED: {
342
- log(formatTaskDispatched(payload.stageId, payload.taskId, payload.attempt))
343
- break
344
- }
345
-
346
- case EVENT_TYPES.LONGAGENT_STAGE_TASK_FINISHED: {
347
- log(formatTaskFinished(payload.taskId, payload.status))
348
- break
349
- }
350
-
351
- case EVENT_TYPES.LONGAGENT_HEARTBEAT: {
352
- log(formatHeartbeat(
353
- payload.iteration,
354
- payload.maxIterations,
355
- payload.phase,
356
- payload.gate,
357
- payload.progress,
358
- payload.elapsed
359
- ))
360
- break
361
- }
362
-
363
- case EVENT_TYPES.LONGAGENT_PLAN_FROZEN: {
364
- log(formatPlanFrozen(payload.planId, payload.stageCount))
365
- break
366
- }
367
-
368
- case EVENT_TYPES.LONGAGENT_RECOVERY_ENTERED: {
369
- log(formatRecovery(payload.reason, payload.recoveryCount))
370
- break
371
- }
372
-
373
- case EVENT_TYPES.LONGAGENT_ALERT: {
374
- log(formatAlert(payload.kind, payload.message))
375
- break
376
- }
377
-
378
- case EVENT_TYPES.LONGAGENT_INTAKE_STARTED: {
379
- log(formatIntakeStarted(payload.objective))
380
- break
381
- }
382
-
383
- case EVENT_TYPES.LONGAGENT_GATE_CHECKED: {
384
- log(formatGateChecked(payload.gate, payload.status))
385
- break
386
- }
387
-
388
- case EVENT_TYPES.SESSION_COMPACTED: {
389
- log(`${paint(SYM.phase, "magenta")} ${paint("context compacted", "magenta", { dim: true })}`)
390
- break
391
- }
392
- }
393
- }
394
-
395
- return {
396
- start() {
397
- if (unsubscribe) return
398
- unsubscribe = EventBus.subscribe(handleEvent)
399
- },
400
- stop() {
401
- if (unsubscribe) {
402
- unsubscribe()
403
- unsubscribe = null
404
- }
405
- toolTimers.clear()
406
- activeToolKeys.clear()
407
- activeToolArgs.clear()
408
- }
409
- }
410
- }
1
+ import { EventBus } from "../core/events.mjs"
2
+ import { EVENT_TYPES } from "../core/constants.mjs"
3
+ import { paint } from "../theme/color.mjs"
4
+
5
+ let _theme = null
6
+ function diffAdd() { return _theme?.components?.diff_add || "green" }
7
+ function diffDel() { return _theme?.components?.diff_del || "red" }
8
+
9
+ // ── Symbols ──────────────────────────────────────────────
10
+ export const SYM = {
11
+ dot: "●",
12
+ dotHollow: "○",
13
+ toolOk: "✓",
14
+ toolErr: "✗",
15
+ stage: "◆",
16
+ iteration: "↻",
17
+ phase: "●",
18
+ plan: "☐",
19
+ planDone: "☑",
20
+ recovery: "⟳",
21
+ alert: "!",
22
+ thinking: "▶",
23
+ thinkingOpen: "▼",
24
+ search: "*",
25
+ arrow: "→",
26
+ write: "◇"
27
+ }
28
+
29
+ // ── Helpers ──────────────────────────────────────────────
30
+
31
+ function clipText(text, max) {
32
+ const s = String(text || "").trim()
33
+ if (s.length <= max) return s
34
+ return s.slice(0, max - 3) + "..."
35
+ }
36
+
37
+ function shortPath(p) {
38
+ const s = String(p || "").trim()
39
+ // Show last 2-3 segments for readability
40
+ const parts = s.replace(/\\/g, "/").split("/")
41
+ if (parts.length <= 3) return s
42
+ return ".../" + parts.slice(-3).join("/")
43
+ }
44
+
45
+ // ── Tool Display Formatters ──────────────────────────────
46
+
47
+ export function formatToolStart(toolName, args) {
48
+ // Compact single-line dim format (OpenCode style)
49
+ const sym = toolName === "grep" || toolName === "glob" || toolName === "websearch"
50
+ ? SYM.search
51
+ : toolName === "write" || toolName === "edit" || toolName === "notebookedit"
52
+ ? SYM.write
53
+ : SYM.arrow
54
+ const prefix = paint(sym, "#666666")
55
+ const name = paint(toolName.charAt(0).toUpperCase() + toolName.slice(1), null, { dim: true })
56
+
57
+ switch (toolName) {
58
+ case "bash": {
59
+ const desc = clipText(args?.description || args?.command, 80)
60
+ return ` ${prefix} ${name} ${paint(desc, null, { dim: true })}`
61
+ }
62
+ case "write":
63
+ case "edit":
64
+ return ` ${prefix} ${name} ${paint(shortPath(args?.path), null, { dim: true })}`
65
+ case "notebookedit":
66
+ return ` ${prefix} ${name} ${paint(shortPath(args?.path), null, { dim: true })} ${paint(`cell ${args?.cell_number ?? 0}`, null, { dim: true })}`
67
+ case "read":
68
+ case "list":
69
+ return ` ${prefix} ${name} ${paint(shortPath(args?.path || "."), null, { dim: true })}`
70
+ case "grep":
71
+ case "glob":
72
+ return ` ${prefix} ${name} ${paint(clipText(args?.pattern, 60), null, { dim: true })}`
73
+ case "task":
74
+ return ` ${prefix} ${name} ${paint(clipText(args?.description || args?.prompt, 60), null, { dim: true })}`
75
+ case "todowrite":
76
+ return null // handled by result preview only
77
+ case "webfetch":
78
+ return ` ${prefix} ${name} ${paint(clipText(args?.url, 60), null, { dim: true })}`
79
+ case "websearch":
80
+ return ` ${prefix} ${name} ${paint(clipText(args?.query, 60), null, { dim: true })}`
81
+ case "question":
82
+ return ` ~ ${paint("Asking questions...", null, { dim: true })}`
83
+ case "enter_plan":
84
+ return ` ${paint(SYM.plan, "magenta")} ${paint("Enter Plan", "magenta")}`
85
+ case "exit_plan":
86
+ return ` ${paint(SYM.planDone, "green")} ${paint("Submit Plan", "green")}`
87
+ default:
88
+ return ` ${prefix} ${name} ${paint(clipText(args ? Object.keys(args).slice(0, 3).join(", ") : "", 40), null, { dim: true })}`
89
+ }
90
+ }
91
+
92
+ export function formatToolFinish(toolName, status, durationMs, args) {
93
+ if (status === "error") {
94
+ return ` ${paint(SYM.toolErr, "red")} ${paint(toolName, null, { dim: true })} ${paint("error", "red")}${durationMs ? paint(` ${durationMs}ms`, null, { dim: true }) : ""}`
95
+ }
96
+ // For completed tools, return null — the start line + result preview is enough
97
+ return null
98
+ }
99
+
100
+ export function formatToolResultPreview(toolName, output, status, args) {
101
+ if (status !== "completed") return null
102
+ const text = String(output || "").trim()
103
+
104
+ switch (toolName) {
105
+ case "bash": {
106
+ const lines = text.split("\n").filter(Boolean)
107
+ if (!lines.length) return null
108
+ const first = clipText(lines[0], 90)
109
+ const suffix = lines.length > 1 ? paint(` (+${lines.length - 1} lines)`, null, { dim: true }) : ""
110
+ return ` ${paint(first, null, { dim: true })}${suffix}`
111
+ }
112
+ case "write": {
113
+ const n = String(args?.content || "").split("\n").filter(Boolean).length
114
+ return ` ${paint(`+${n} lines`, diffAdd(), { dim: true })}`
115
+ }
116
+ case "edit": {
117
+ const added = String(args?.new_string || "").split("\n").filter(Boolean).length
118
+ const removed = String(args?.old_string || "").split("\n").filter(Boolean).length
119
+ const parts = []
120
+ if (added > 0) parts.push(paint(`+${added}`, diffAdd()))
121
+ if (removed > 0) parts.push(paint(`-${removed}`, diffDel()))
122
+ return parts.length ? ` ${parts.join(" ")} ${paint("lines", null, { dim: true })}` : null
123
+ }
124
+ case "grep": {
125
+ const lines = text.split("\n").filter(Boolean)
126
+ if (text === "no matches" || !lines.length) return ` ${paint("no matches", null, { dim: true })}`
127
+ return ` ${paint(`${lines.length} matches`, null, { dim: true })}`
128
+ }
129
+ case "read":
130
+ return ` ${paint(`${text.split("\n").length} lines`, null, { dim: true })}`
131
+ case "glob": {
132
+ const lines = text.split("\n").filter(Boolean)
133
+ if (!lines.length) return ` ${paint("no files", null, { dim: true })}`
134
+ return ` ${paint(`${lines.length} files`, null, { dim: true })}`
135
+ }
136
+ case "todowrite": {
137
+ const todos = Array.isArray(args?.todos) ? args.todos : []
138
+ if (!todos.length) return null
139
+ const result = []
140
+ for (const t of todos.slice(0, 8)) {
141
+ const s = t.status || "pending"
142
+ const dot = s === "completed" ? paint(SYM.toolOk, "green")
143
+ : s === "in_progress" ? paint(SYM.dot, "yellow")
144
+ : paint(SYM.dotHollow, "#666666")
145
+ const color = s === "completed" ? "green" : s === "in_progress" ? "yellow" : null
146
+ const label = s === "in_progress" && t.activeForm ? t.activeForm : t.content
147
+ result.push(` ${dot} ${paint(label || "", color, { dim: s === "completed" })}`)
148
+ }
149
+ if (todos.length > 8) result.push(paint(` ... +${todos.length - 8} more`, null, { dim: true }))
150
+ return result
151
+ }
152
+ default:
153
+ return null
154
+ }
155
+ }
156
+
157
+ function formatToolError(error) {
158
+ if (!error) return null
159
+ return ` ${paint(clipText(error, 120), "red", { dim: true })}`
160
+ }
161
+
162
+ // ── Thinking Formatter ──────────────────────────────────
163
+
164
+ export function formatThinkingHeader() {
165
+ return `${paint(SYM.dot, "#666666")} ${paint("Thinking", null, { italic: true, dim: true })} ${paint("∨", null, { dim: true })}`
166
+ }
167
+
168
+ // ── LongAgent Display Formatters ─────────────────────────
169
+
170
+ export function formatPhaseChange(prevPhase, nextPhase, reason) {
171
+ const arrow = paint("→", null, { dim: true })
172
+ const reasonText = reason ? paint(reason, null, { dim: true }) : ""
173
+ return `${paint(SYM.phase, "magenta")} ${paint("phase", "magenta", { bold: true })} ${paint(prevPhase, null, { dim: true })} ${arrow} ${paint(nextPhase, "magenta", { bold: true })} ${reasonText}`
174
+ }
175
+
176
+ export function formatStageStarted(stageId, taskCount) {
177
+ return `${paint(SYM.stage, "#fb923c", { bold: true })} ${paint("stage", "#fb923c", { bold: true })} ${paint(stageId, "white", { bold: true })} ${paint(`(${taskCount} tasks)`, null, { dim: true })}`
178
+ }
179
+
180
+ export function formatStageFinished(stageId, successCount, failCount) {
181
+ const status = failCount === 0
182
+ ? paint("PASS", "green", { bold: true })
183
+ : paint(`FAIL (${failCount})`, "red", { bold: true })
184
+ return `${paint(SYM.stage, "#fb923c")} ${paint("stage", "#fb923c")} ${paint(stageId, "white")} ${status} ${paint(`(${successCount} ok)`, null, { dim: true })}`
185
+ }
186
+
187
+ export function formatTaskDispatched(_stageId, taskId, attempt) {
188
+ const attemptLabel = attempt > 1 ? paint(` retry#${attempt}`, "yellow") : ""
189
+ return ` ${paint(SYM.dot, "#666666")} ${paint("task", "cyan")} ${paint(taskId, null, { dim: true })}${attemptLabel}`
190
+ }
191
+
192
+ export function formatTaskFinished(taskId, status) {
193
+ const dot = status === "completed" ? paint(SYM.dot, "green") : paint(SYM.dot, "red")
194
+ const color = status === "completed" ? "green" : "red"
195
+ return ` ${dot} ${paint(taskId, null, { dim: true })} ${paint(status, color)}`
196
+ }
197
+
198
+ export function formatHeartbeat(iteration, maxIterations, phase, gate, progress, elapsed) {
199
+ const iterLabel = maxIterations > 0 ? `${iteration}/${maxIterations}` : String(iteration)
200
+ const progressLabel = progress?.percentage !== null && progress?.percentage !== undefined
201
+ ? paint(`${progress.percentage}%`, "green")
202
+ : paint("...", null, { dim: true })
203
+ const elapsedLabel = elapsed !== undefined ? paint(`${elapsed}s`, null, { dim: true }) : ""
204
+ return `${paint(SYM.iteration, "#fb923c")} ${paint("iter", "#fb923c")} ${paint(iterLabel, "white", { bold: true })} phase=${paint(phase || "-", "magenta")} gate=${paint(gate || "-", "cyan")} progress=${progressLabel} ${elapsedLabel}`
205
+ }
206
+
207
+ export function formatPlanFrozen(planId, stageCount) {
208
+ return `${paint(SYM.planDone, "green", { bold: true })} ${paint("plan frozen", "green", { bold: true })} ${paint(planId || "", null, { dim: true })} ${paint(`${stageCount} stage(s)`, null, { dim: true })}`
209
+ }
210
+
211
+ export function formatRecovery(reason, recoveryCount) {
212
+ return `${paint(SYM.recovery, "yellow", { bold: true })} ${paint("recovery", "yellow", { bold: true })} #${recoveryCount} ${paint(reason || "", null, { dim: true })}`
213
+ }
214
+
215
+ export function formatAlert(kind, message) {
216
+ return `${paint(SYM.alert, "red", { bold: true })} ${paint("alert", "red", { bold: true })} [${kind}] ${paint(message || "", null, { dim: true })}`
217
+ }
218
+
219
+ export function formatIntakeStarted(objective) {
220
+ const preview = clipText(objective, 80)
221
+ return `${paint(SYM.phase, "magenta")} ${paint("intake", "magenta", { bold: true })} ${paint(preview, null, { dim: true })}`
222
+ }
223
+
224
+ export function formatGateChecked(gate, status) {
225
+ const dot = status === "pass" ? paint(SYM.dot, "green") : paint(SYM.dot, "yellow")
226
+ return ` ${dot} gate=${paint(gate || "-", "cyan")} ${paint(status || "-", status === "pass" ? "green" : "yellow")}`
227
+ }
228
+
229
+ // ── Hybrid Stage Formatters ──────────────────────────────
230
+
231
+ function hybridBanner(label, color) {
232
+ const line = paint("━".repeat(40), color, { dim: true })
233
+ return `${line}\n${paint(label, color, { bold: true })}`
234
+ }
235
+
236
+ export function formatHybridPreviewStart(objective) {
237
+ const preview = clipText(objective, 70)
238
+ return `${hybridBanner("H1 Preview", "#3b82f6")}\n ${paint(preview, null, { dim: true })}`
239
+ }
240
+
241
+ export function formatHybridPreviewComplete(findingsLength) {
242
+ return ` ${paint(SYM.toolOk, "green")} ${paint("preview complete", "green")} ${paint(`(${findingsLength} chars)`, null, { dim: true })}`
243
+ }
244
+
245
+ export function formatHybridBlueprintStart() {
246
+ return hybridBanner("H2 Blueprint", "#a855f7")
247
+ }
248
+
249
+ export function formatHybridBlueprintComplete(planId, stageCount) {
250
+ return ` ${paint(SYM.toolOk, "green")} ${paint("blueprint complete", "green")} ${paint(planId || "", null, { dim: true })} ${paint(`${stageCount} stage(s)`, null, { dim: true })}`
251
+ }
252
+
253
+ export function formatHybridBlueprintReview(planId) {
254
+ return ` ${paint("⏳", "yellow")} ${paint("awaiting blueprint review", "yellow")} ${paint(planId || "", null, { dim: true })}`
255
+ }
256
+
257
+ export function formatHybridBlueprintValidated(totalTasks, totalFiles, valid) {
258
+ const status = valid ? paint("PASS", "green") : paint("WARN", "yellow")
259
+ return ` ${paint(SYM.dot, valid ? "green" : "yellow")} ${paint("blueprint validation", null, { dim: true })} ${status} ${paint(`${totalTasks} tasks, ${totalFiles} files`, null, { dim: true })}`
260
+ }
261
+
262
+ // ── Hybrid Debugging/Rollback Formatters ─────────────────
263
+
264
+ export function formatHybridDebuggingStart(codingRollbackCount) {
265
+ const suffix = codingRollbackCount > 0 ? ` ${paint(`(rollback #${codingRollbackCount})`, "yellow")}` : ""
266
+ return `${hybridBanner("H5 Debugging", "#fb923c")}${suffix}`
267
+ }
268
+
269
+ export function formatHybridDebuggingComplete(debugIter, rollback) {
270
+ const status = rollback
271
+ ? paint("ROLLBACK", "yellow", { bold: true })
272
+ : paint("PASS", "green", { bold: true })
273
+ return ` ${paint(SYM.dot, rollback ? "yellow" : "green")} ${paint("debugging", null, { dim: true })} ${status} ${paint(`(${debugIter} iters)`, null, { dim: true })}`
274
+ }
275
+
276
+ export function formatHybridReturnToCoding(rollbackCount, failedTaskIds) {
277
+ const tasks = failedTaskIds?.length ? paint(` [${failedTaskIds.join(", ")}]`, null, { dim: true }) : ""
278
+ return ` ${paint(SYM.recovery, "yellow")} ${paint(`rollback to coding #${rollbackCount}`, "yellow")}${tasks}`
279
+ }
280
+
281
+ export function formatHybridCrossReview(fileCount) {
282
+ return ` ${paint(SYM.dot, "cyan")} ${paint("cross-review", "cyan")} ${paint(`${fileCount} file(s)`, null, { dim: true })}`
283
+ }
284
+
285
+ // ── Hybrid Incremental/Budget/Context Formatters ─────────
286
+
287
+ export function formatHybridIncrementalGate(stageId, passed) {
288
+ const dot = passed ? paint(SYM.dot, "green") : paint(SYM.dot, "yellow")
289
+ const status = passed ? paint("pass", "green") : paint("warn", "yellow")
290
+ return ` ${dot} ${paint("gate", null, { dim: true })} ${paint(stageId, "cyan")} ${status}`
291
+ }
292
+
293
+ export function formatHybridContextCompressed(newLength) {
294
+ return ` ${paint(SYM.dot, "#666666")} ${paint(`context compressed → ${newLength} chars`, null, { dim: true })}`
295
+ }
296
+
297
+ export function formatHybridBudgetWarning(totalTokens, budgetLimit, percentage) {
298
+ const color = percentage >= 100 ? "red" : "yellow"
299
+ return ` ${paint(SYM.alert, color)} ${paint("budget", color, { bold: true })} ${paint(`${percentage}%`, color)} ${paint(`(${totalTokens}/${budgetLimit})`, null, { dim: true })}`
300
+ }
301
+
302
+ export function formatHybridCheckpointResumed(stageIndex, iteration) {
303
+ return ` ${paint(SYM.dot, "cyan")} ${paint("checkpoint resumed", "cyan")} ${paint(`stage ${stageIndex}, iter ${iteration}`, null, { dim: true })}`
304
+ }
305
+
306
+ export function formatHybridReplan(newStageCount) {
307
+ return ` ${paint(SYM.dot, "#a855f7")} ${paint("replan", "#a855f7", { bold: true })} ${paint(`→ ${newStageCount} stage(s)`, null, { dim: true })}`
308
+ }
309
+
310
+ // ── Hybrid Memory Formatters ─────────────────────────────
311
+
312
+ export function formatHybridMemoryLoaded(techStack) {
313
+ const items = Array.isArray(techStack) ? techStack.slice(0, 5).join(", ") : ""
314
+ return ` ${paint(SYM.dot, "#666666")} ${paint("memory loaded", null, { dim: true })} ${paint(items, null, { dim: true })}`
315
+ }
316
+
317
+ export function formatHybridMemorySaved(techStackCount) {
318
+ return ` ${paint(SYM.dot, "#666666")} ${paint(`memory saved (${techStackCount} items)`, null, { dim: true })}`
319
+ }
320
+
321
+ // ── Git Formatters ───────────────────────────────────────
322
+
323
+ export function formatGitBranchCreated(branch, baseBranch) {
324
+ return ` ${paint(SYM.dot, "green")} ${paint("git branch", "green")} ${paint(branch, "white", { bold: true })} ${paint(`← ${baseBranch}`, null, { dim: true })}`
325
+ }
326
+
327
+ export function formatGitStageCommitted(stageId, message) {
328
+ return ` ${paint(SYM.dot, "#666666")} ${paint("commit", null, { dim: true })} ${paint(clipText(message || stageId, 60), null, { dim: true })}`
329
+ }
330
+
331
+ export function formatGitMerged(branch, baseBranch) {
332
+ return ` ${paint(SYM.toolOk, "green")} ${paint("git merged", "green", { bold: true })} ${paint(branch, null, { dim: true })} ${paint("→", null, { dim: true })} ${paint(baseBranch, "white")}`
333
+ }
334
+
335
+ // ── Plan Progress Formatter ──────────────────────────────
336
+
337
+ export function formatPlanProgress(taskProgress) {
338
+ if (!taskProgress || typeof taskProgress !== "object") return []
339
+ const entries = Object.entries(taskProgress)
340
+ if (!entries.length) return []
341
+
342
+ const lines = [paint("Plan Progress:", "cyan", { bold: true })]
343
+ for (const [taskId, tp] of entries) {
344
+ const status = tp?.status || "pending"
345
+ const dot = status === "completed"
346
+ ? paint(SYM.dot, "green")
347
+ : status === "error"
348
+ ? paint(SYM.dot, "red")
349
+ : paint(SYM.dotHollow, "#666666")
350
+ const color = status === "completed" ? "green" : status === "error" ? "red" : "white"
351
+ lines.push(` ${dot} ${taskId} ${paint(status, color)}`)
352
+ }
353
+ return lines
354
+ }
355
+
356
+ // ── Recovery Suggestions Formatter ───────────────────────
357
+
358
+ export function formatRecoverySuggestions(recovery) {
359
+ if (!recovery) return []
360
+ const lines = []
361
+ lines.push(paint("Recovery Suggestions:", "yellow", { bold: true }))
362
+
363
+ if (recovery.summary) {
364
+ lines.push(` ${paint(recovery.summary, null, { dim: true })}`)
365
+ }
366
+
367
+ if (recovery.suggestions?.length) {
368
+ for (const s of recovery.suggestions) {
369
+ lines.push(` ${paint(SYM.alert, "yellow")} ${paint(s, "yellow")}`)
370
+ }
371
+ }
372
+
373
+ if (recovery.failedTasks?.length) {
374
+ lines.push(paint(" Failed Tasks:", "red"))
375
+ for (const t of recovery.failedTasks.slice(0, 5)) {
376
+ lines.push(` ${paint(SYM.dot, "red")} ${t.taskId} [${t.category}]: ${paint(t.error || "", null, { dim: true })}`)
377
+ }
378
+ }
379
+
380
+ if (recovery.manualSteps?.length) {
381
+ lines.push(paint(" Manual Steps:", "cyan"))
382
+ for (const step of recovery.manualSteps.slice(0, 5)) {
383
+ lines.push(` ${paint(SYM.arrow, "cyan")} ${paint(step, null, { dim: true })}`)
384
+ }
385
+ }
386
+
387
+ if (recovery.resumeHint) {
388
+ lines.push(` ${paint(SYM.dot, "green")} ${paint(recovery.resumeHint, "green")}`)
389
+ }
390
+
391
+ return lines
392
+ }
393
+
394
+ // ── Renderer ─────────────────────────────────────────────
395
+
396
+ export function createActivityRenderer({ output, theme = null }) {
397
+ _theme = theme
398
+ const log = typeof output?.appendLog === "function"
399
+ ? output.appendLog
400
+ : (text) => console.log(text)
401
+
402
+ const toolTimers = new Map()
403
+ let timerCounter = 0
404
+ let unsubscribe = null
405
+
406
+ function timerKey(sessionId, turnId, toolName) {
407
+ return `${sessionId || ""}:${turnId || ""}:${toolName}:${timerCounter++}`
408
+ }
409
+
410
+ // Track the latest timer key per tool invocation
411
+ const activeToolKeys = new Map()
412
+ // Track tool args for finish formatting
413
+ const activeToolArgs = new Map()
414
+
415
+ function handleEvent(event) {
416
+ const { type, payload, sessionId, turnId } = event
417
+
418
+ switch (type) {
419
+ case EVENT_TYPES.TOOL_START: {
420
+ const key = timerKey(sessionId, turnId, payload.tool)
421
+ const lookupKey = `${sessionId}:${turnId}:${payload.tool}`
422
+ toolTimers.set(key, Date.now())
423
+ activeToolKeys.set(lookupKey, key)
424
+ activeToolArgs.set(lookupKey, payload.args)
425
+ // Show tool call inline (compact dim line)
426
+ const startLine = formatToolStart(payload.tool, payload.args)
427
+ if (startLine) log(startLine)
428
+ break
429
+ }
430
+
431
+ case EVENT_TYPES.TOOL_FINISH: {
432
+ const lookupKey = `${sessionId}:${turnId}:${payload.tool}`
433
+ const key = activeToolKeys.get(lookupKey)
434
+ const savedArgs = activeToolArgs.get(lookupKey) || payload.args
435
+ if (key) {
436
+ toolTimers.delete(key)
437
+ activeToolKeys.delete(lookupKey)
438
+ activeToolArgs.delete(lookupKey)
439
+ }
440
+ const finishLine = formatToolFinish(payload.tool, payload.status, 0, savedArgs)
441
+ if (finishLine) log(finishLine)
442
+ const preview = formatToolResultPreview(payload.tool, payload.output, payload.status, savedArgs)
443
+ if (preview) {
444
+ if (Array.isArray(preview)) {
445
+ for (const line of preview) log(line)
446
+ } else {
447
+ log(preview)
448
+ }
449
+ }
450
+ // Blank line after tool for visual spacing
451
+ if (payload.tool !== "todowrite") log("")
452
+ break
453
+ }
454
+
455
+ case EVENT_TYPES.TOOL_ERROR: {
456
+ const lookupKey = `${sessionId}:${turnId}:${payload.tool}`
457
+ const key = activeToolKeys.get(lookupKey)
458
+ const savedArgs = activeToolArgs.get(lookupKey) || payload.args
459
+ if (key) {
460
+ toolTimers.delete(key)
461
+ activeToolKeys.delete(lookupKey)
462
+ activeToolArgs.delete(lookupKey)
463
+ }
464
+ log(formatToolFinish(payload.tool, payload.status || "error", 0, savedArgs))
465
+ const errLine = formatToolError(payload.error)
466
+ if (errLine) log(errLine)
467
+ break
468
+ }
469
+
470
+ case EVENT_TYPES.LONGAGENT_PHASE_CHANGED: {
471
+ log(formatPhaseChange(payload.prevPhase, payload.nextPhase, payload.reason))
472
+ break
473
+ }
474
+
475
+ case EVENT_TYPES.LONGAGENT_STAGE_STARTED: {
476
+ log(formatStageStarted(payload.stageId, payload.taskCount))
477
+ break
478
+ }
479
+
480
+ case EVENT_TYPES.LONGAGENT_STAGE_FINISHED: {
481
+ log(formatStageFinished(payload.stageId, payload.successCount, payload.failCount))
482
+ break
483
+ }
484
+
485
+ case EVENT_TYPES.LONGAGENT_STAGE_TASK_DISPATCHED: {
486
+ log(formatTaskDispatched(payload.stageId, payload.taskId, payload.attempt))
487
+ break
488
+ }
489
+
490
+ case EVENT_TYPES.LONGAGENT_STAGE_TASK_FINISHED: {
491
+ log(formatTaskFinished(payload.taskId, payload.status))
492
+ break
493
+ }
494
+
495
+ case EVENT_TYPES.LONGAGENT_HEARTBEAT: {
496
+ log(formatHeartbeat(
497
+ payload.iteration,
498
+ payload.maxIterations,
499
+ payload.phase,
500
+ payload.gate,
501
+ payload.progress,
502
+ payload.elapsed
503
+ ))
504
+ break
505
+ }
506
+
507
+ case EVENT_TYPES.LONGAGENT_PLAN_FROZEN: {
508
+ log(formatPlanFrozen(payload.planId, payload.stageCount))
509
+ break
510
+ }
511
+
512
+ case EVENT_TYPES.LONGAGENT_RECOVERY_ENTERED: {
513
+ log(formatRecovery(payload.reason, payload.recoveryCount))
514
+ break
515
+ }
516
+
517
+ case EVENT_TYPES.LONGAGENT_ALERT: {
518
+ log(formatAlert(payload.kind, payload.message))
519
+ break
520
+ }
521
+
522
+ case EVENT_TYPES.LONGAGENT_INTAKE_STARTED: {
523
+ log(formatIntakeStarted(payload.objective))
524
+ break
525
+ }
526
+
527
+ case EVENT_TYPES.LONGAGENT_GATE_CHECKED: {
528
+ log(formatGateChecked(payload.gate, payload.status))
529
+ break
530
+ }
531
+
532
+ // ── Hybrid Events ──────────────────────────────
533
+ case EVENT_TYPES.LONGAGENT_HYBRID_PREVIEW_START: {
534
+ log(formatHybridPreviewStart(payload.objective))
535
+ break
536
+ }
537
+ case EVENT_TYPES.LONGAGENT_HYBRID_PREVIEW_COMPLETE: {
538
+ log(formatHybridPreviewComplete(payload.findingsLength))
539
+ break
540
+ }
541
+ case EVENT_TYPES.LONGAGENT_HYBRID_BLUEPRINT_START: {
542
+ log(formatHybridBlueprintStart())
543
+ break
544
+ }
545
+ case EVENT_TYPES.LONGAGENT_HYBRID_BLUEPRINT_COMPLETE: {
546
+ log(formatHybridBlueprintComplete(payload.planId, payload.stageCount))
547
+ break
548
+ }
549
+ case EVENT_TYPES.LONGAGENT_HYBRID_BLUEPRINT_REVIEW: {
550
+ log(formatHybridBlueprintReview(payload.planId))
551
+ break
552
+ }
553
+ case EVENT_TYPES.LONGAGENT_HYBRID_BLUEPRINT_VALIDATED: {
554
+ log(formatHybridBlueprintValidated(payload.totalTasks, payload.totalFiles, payload.valid))
555
+ break
556
+ }
557
+ case EVENT_TYPES.LONGAGENT_HYBRID_DEBUGGING_START: {
558
+ log(formatHybridDebuggingStart(payload.codingRollbackCount))
559
+ break
560
+ }
561
+ case EVENT_TYPES.LONGAGENT_HYBRID_DEBUGGING_COMPLETE: {
562
+ log(formatHybridDebuggingComplete(payload.debugIter, payload.rollback))
563
+ break
564
+ }
565
+ case EVENT_TYPES.LONGAGENT_HYBRID_RETURN_TO_CODING: {
566
+ log(formatHybridReturnToCoding(payload.rollbackCount, payload.failedTaskIds))
567
+ break
568
+ }
569
+ case EVENT_TYPES.LONGAGENT_HYBRID_CROSS_REVIEW: {
570
+ log(formatHybridCrossReview(payload.fileCount))
571
+ break
572
+ }
573
+ case EVENT_TYPES.LONGAGENT_HYBRID_INCREMENTAL_GATE: {
574
+ log(formatHybridIncrementalGate(payload.stageId, payload.passed))
575
+ break
576
+ }
577
+ case EVENT_TYPES.LONGAGENT_HYBRID_CONTEXT_COMPRESSED: {
578
+ log(formatHybridContextCompressed(payload.newLength))
579
+ break
580
+ }
581
+ case EVENT_TYPES.LONGAGENT_HYBRID_BUDGET_WARNING: {
582
+ log(formatHybridBudgetWarning(payload.totalTokens, payload.budgetLimit, payload.percentage))
583
+ break
584
+ }
585
+ case EVENT_TYPES.LONGAGENT_HYBRID_CHECKPOINT_RESUMED: {
586
+ log(formatHybridCheckpointResumed(payload.stageIndex, payload.iteration))
587
+ break
588
+ }
589
+ case EVENT_TYPES.LONGAGENT_HYBRID_REPLAN: {
590
+ log(formatHybridReplan(payload.newStageCount))
591
+ break
592
+ }
593
+ case EVENT_TYPES.LONGAGENT_HYBRID_MEMORY_LOADED: {
594
+ log(formatHybridMemoryLoaded(payload.techStack))
595
+ break
596
+ }
597
+ case EVENT_TYPES.LONGAGENT_HYBRID_MEMORY_SAVED: {
598
+ log(formatHybridMemorySaved(payload.techStackCount))
599
+ break
600
+ }
601
+
602
+ // ── New Fault Recovery Events ──────────────────
603
+ case EVENT_TYPES.LONGAGENT_DEGRADATION_APPLIED: {
604
+ log(formatAlert("degradation", `${payload.strategy} applied in ${payload.phase}${payload.reason ? ` (${payload.reason})` : ""}`))
605
+ break
606
+ }
607
+ case EVENT_TYPES.LONGAGENT_WRITE_LOOP_DETECTED: {
608
+ log(formatAlert("write_loop", payload.message || "write loop detected"))
609
+ break
610
+ }
611
+ case EVENT_TYPES.LONGAGENT_SEMANTIC_ERROR_REPEATED: {
612
+ log(formatAlert("semantic_error", `repeated ${payload.count}x: ${(payload.error || "").slice(0, 80)}`))
613
+ break
614
+ }
615
+ case EVENT_TYPES.LONGAGENT_PHASE_TIMEOUT: {
616
+ log(formatAlert("phase_timeout", `${payload.phase} timed out after ${Math.round((payload.elapsed || 0) / 1000)}s`))
617
+ break
618
+ }
619
+ case EVENT_TYPES.LONGAGENT_GIT_CONFLICT_RESOLUTION: {
620
+ log(formatAlert("git_conflict", `resolving conflicts in ${(payload.files || []).length} file(s)`))
621
+ break
622
+ }
623
+ case EVENT_TYPES.LONGAGENT_CHECKPOINT_CLEANED: {
624
+ log(` ${paint(SYM.dot, "#666666")} ${paint(`checkpoints cleaned (${payload.removed} removed)`, null, { dim: true })}`)
625
+ break
626
+ }
627
+
628
+ // ── Git Events ─────────────────────────────────
629
+ case EVENT_TYPES.LONGAGENT_GIT_BRANCH_CREATED: {
630
+ log(formatGitBranchCreated(payload.branch, payload.baseBranch))
631
+ break
632
+ }
633
+ case EVENT_TYPES.LONGAGENT_GIT_STAGE_COMMITTED: {
634
+ log(formatGitStageCommitted(payload.stageId, payload.message))
635
+ break
636
+ }
637
+ case EVENT_TYPES.LONGAGENT_GIT_MERGED: {
638
+ log(formatGitMerged(payload.branch, payload.baseBranch))
639
+ break
640
+ }
641
+
642
+ case EVENT_TYPES.SESSION_COMPACTED: {
643
+ log(`${paint(SYM.phase, "magenta")} ${paint("context compacted", "magenta", { dim: true })}`)
644
+ break
645
+ }
646
+ }
647
+ }
648
+
649
+ return {
650
+ start() {
651
+ if (unsubscribe) return
652
+ unsubscribe = EventBus.subscribe(handleEvent)
653
+ },
654
+ stop() {
655
+ if (unsubscribe) {
656
+ unsubscribe()
657
+ unsubscribe = null
658
+ }
659
+ toolTimers.clear()
660
+ activeToolKeys.clear()
661
+ activeToolArgs.clear()
662
+ }
663
+ }
664
+ }