repoburg 1.3.199 → 1.3.202

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 (136) hide show
  1. package/agent-pane/backend/data.db +0 -0
  2. package/agent-pane/backend/data.db-shm +0 -0
  3. package/agent-pane/backend/data.db-wal +0 -0
  4. package/agent-pane/backend/dist/index.js +1658 -277
  5. package/agent-pane/backend/src/claude/claude-provider.test.ts +393 -3
  6. package/agent-pane/backend/src/claude/claude-provider.ts +53 -50
  7. package/agent-pane/backend/src/db/index.ts +12 -0
  8. package/agent-pane/backend/src/index.ts +5 -2
  9. package/agent-pane/backend/src/integration/threads-claude-fork.test.ts +241 -0
  10. package/agent-pane/backend/src/providers/index.ts +3 -1
  11. package/agent-pane/backend/src/providers/runtime-provider.ts +6 -0
  12. package/agent-pane/backend/src/repoburg/action-mapping.test.ts +122 -0
  13. package/agent-pane/backend/src/repoburg/action-mapping.ts +294 -0
  14. package/agent-pane/backend/src/repoburg/agent-runtime-client.test.ts +271 -0
  15. package/agent-pane/backend/src/repoburg/agent-runtime-client.ts +285 -0
  16. package/agent-pane/backend/src/repoburg/backend-resolver.test.ts +356 -0
  17. package/agent-pane/backend/src/repoburg/backend-resolver.ts +261 -0
  18. package/agent-pane/backend/src/repoburg/repoburg-client.test.ts +180 -0
  19. package/agent-pane/backend/src/repoburg/repoburg-client.ts +194 -0
  20. package/agent-pane/backend/src/repoburg/repoburg-provider.test.ts +780 -0
  21. package/agent-pane/backend/src/repoburg/repoburg-provider.ts +471 -0
  22. package/agent-pane/backend/src/repoburg/turn-projector.test.ts +621 -0
  23. package/agent-pane/backend/src/repoburg/turn-projector.ts +637 -0
  24. package/agent-pane/backend/src/routes/providers.test.ts +18 -1
  25. package/agent-pane/backend/src/routes/providers.ts +19 -1
  26. package/agent-pane/backend/src/routes/sessions.test.ts +215 -1
  27. package/agent-pane/backend/src/routes/sessions.ts +82 -9
  28. package/agent-pane/backend/src/routes/threads.ts +21 -6
  29. package/agent-pane/backend/src/routes/turns.test.ts +45 -1
  30. package/agent-pane/frontend/dist/assets/index-CJxD4YmJ.js +370 -0
  31. package/agent-pane/frontend/dist/assets/{index-Dwwhx7YN.css → index-r-xwfOKQ.css} +1 -1
  32. package/agent-pane/frontend/dist/index.html +2 -2
  33. package/agent-pane/frontend/src/api/sessions.test.ts +1 -0
  34. package/agent-pane/frontend/src/api/websocket.test.ts +2 -2
  35. package/agent-pane/frontend/src/api/websocket.ts +3 -1
  36. package/agent-pane/frontend/src/components/AskUserItem.test.tsx +143 -0
  37. package/agent-pane/frontend/src/components/AskUserItem.tsx +207 -0
  38. package/agent-pane/frontend/src/components/CommentableText.test.tsx +196 -0
  39. package/agent-pane/frontend/src/components/CommentableText.tsx +109 -21
  40. package/agent-pane/frontend/src/components/IdeWorkspace.test.tsx +39 -0
  41. package/agent-pane/frontend/src/components/IdeWorkspace.tsx +28 -2
  42. package/agent-pane/frontend/src/components/ResizeHandle.tsx +29 -0
  43. package/agent-pane/frontend/src/components/TurnContent.test.tsx +79 -0
  44. package/agent-pane/frontend/src/components/TurnContent.tsx +49 -3
  45. package/agent-pane/frontend/src/components/panels/ThreadsPanel.tsx +35 -3
  46. package/agent-pane/frontend/src/components/panels/TurnsPanel.test.tsx +48 -0
  47. package/agent-pane/frontend/src/components/panels/TurnsPanel.tsx +7 -2
  48. package/agent-pane/frontend/src/constants/models.ts +37 -0
  49. package/agent-pane/frontend/src/hooks/useResizable.test.ts +97 -0
  50. package/agent-pane/frontend/src/hooks/useResizable.ts +75 -0
  51. package/agent-pane/frontend/src/store/store.test.ts +54 -0
  52. package/agent-pane/frontend/src/store/uiSlice.ts +50 -0
  53. package/agent-pane/frontend/src/store/wsSlice.ts +10 -3
  54. package/agent-pane/frontend/src/styles/app.css +26 -1
  55. package/agent-pane/frontend/src/test/component-helpers.ts +2 -0
  56. package/agent-pane/frontend/src/test/fixtures.ts +1 -0
  57. package/agent-pane/frontend/src/types/index.ts +2 -0
  58. package/agent-pane/frontend/src/utils/duration.test.ts +1 -0
  59. package/agent-pane/shared/types.ts +17 -0
  60. package/agent-pane-bug-repro-no-agent-reply.png +0 -0
  61. package/askuser-after-step5-postgres-selected.png +0 -0
  62. package/askuser-after-step7-answer-sent.png +0 -0
  63. package/askuser-card-visible.png +0 -0
  64. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.d.ts +36 -0
  65. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js +199 -0
  66. package/backend/dist/src/agent-runtime/agent-runtime-event-emitter.js.map +1 -0
  67. package/backend/dist/src/agent-runtime/agent-runtime.controller.d.ts +11 -0
  68. package/backend/dist/src/agent-runtime/agent-runtime.controller.js +91 -0
  69. package/backend/dist/src/agent-runtime/agent-runtime.controller.js.map +1 -0
  70. package/backend/dist/src/agent-runtime/agent-runtime.module.d.ts +2 -0
  71. package/backend/dist/src/agent-runtime/agent-runtime.module.js +26 -0
  72. package/backend/dist/src/agent-runtime/agent-runtime.module.js.map +1 -0
  73. package/backend/dist/src/agent-runtime/agent-runtime.types.d.ts +92 -0
  74. package/backend/dist/src/agent-runtime/agent-runtime.types.js +3 -0
  75. package/backend/dist/src/agent-runtime/agent-runtime.types.js.map +1 -0
  76. package/backend/dist/src/app.controller.d.ts +1 -0
  77. package/backend/dist/src/app.module.js +4 -0
  78. package/backend/dist/src/app.module.js.map +1 -1
  79. package/backend/dist/src/app.service.d.ts +1 -0
  80. package/backend/dist/src/app.service.js +4 -1
  81. package/backend/dist/src/app.service.js.map +1 -1
  82. package/backend/dist/src/interactive-chat/chat.module.js +4 -0
  83. package/backend/dist/src/interactive-chat/chat.module.js.map +1 -1
  84. package/backend/dist/src/interactive-chat/chat.service.d.ts +7 -1
  85. package/backend/dist/src/interactive-chat/chat.service.js +54 -7
  86. package/backend/dist/src/interactive-chat/chat.service.js.map +1 -1
  87. package/backend/dist/src/llm-orchestration/action-handlers/invoke-subagent.handler.js +12 -1
  88. package/backend/dist/src/llm-orchestration/action-handlers/invoke-subagent.handler.js.map +1 -1
  89. package/backend/dist/src/llm-orchestration/hooks/frontend-notification.hook.d.ts +3 -1
  90. package/backend/dist/src/llm-orchestration/hooks/frontend-notification.hook.js +20 -2
  91. package/backend/dist/src/llm-orchestration/hooks/frontend-notification.hook.js.map +1 -1
  92. package/backend/dist/src/llm-orchestration/llm-orchestration.interfaces.d.ts +1 -0
  93. package/backend/dist/src/llm-orchestration/llm-orchestration.interfaces.js +1 -0
  94. package/backend/dist/src/llm-orchestration/llm-orchestration.interfaces.js.map +1 -1
  95. package/backend/dist/src/llm-orchestration/llm-orchestration.module.js +2 -0
  96. package/backend/dist/src/llm-orchestration/llm-orchestration.module.js.map +1 -1
  97. package/backend/dist/src/llm-orchestration/llm-turn-processor.service.d.ts +4 -1
  98. package/backend/dist/src/llm-orchestration/llm-turn-processor.service.js +37 -2
  99. package/backend/dist/src/llm-orchestration/llm-turn-processor.service.js.map +1 -1
  100. package/backend/dist/src/llm-provider/ollama-llm.provider.d.ts +1 -0
  101. package/backend/dist/src/llm-provider/ollama-llm.provider.js +19 -1
  102. package/backend/dist/src/llm-provider/ollama-llm.provider.js.map +1 -1
  103. package/backend/dist/src/llm-responses/llm-responses.module.js +4 -0
  104. package/backend/dist/src/llm-responses/llm-responses.module.js.map +1 -1
  105. package/backend/dist/src/llm-responses/llm-responses.service.d.ts +4 -1
  106. package/backend/dist/src/llm-responses/llm-responses.service.js +52 -2
  107. package/backend/dist/src/llm-responses/llm-responses.service.js.map +1 -1
  108. package/backend/dist/tsconfig.build.tsbuildinfo +1 -1
  109. package/daemon/dist/api/services.js +4 -0
  110. package/daemon/dist/index.js +0 -0
  111. package/daemon/dist/serviceManager.js +30 -11
  112. package/daemon/dist/serviceManager.spec.js +26 -0
  113. package/daemon/dist/workspace-validation.js +63 -0
  114. package/daemon/dist/workspace-validation.spec.js +63 -0
  115. package/package.json +1 -1
  116. package/r2-step4-apple-banana.png +0 -0
  117. package/r2-step5-after-rewind-apple-last.png +0 -0
  118. package/r2-step7-apple-cherry.png +0 -0
  119. package/r2-step8-cherry-menu-no-restore.png +0 -0
  120. package/r3-step3-live-task-card-running.png +0 -0
  121. package/r3-step4-after-completion.png +0 -0
  122. package/r3-step5-persistence-after-reload.png +0 -0
  123. package/r3-step6-tasks-tab-card.png +0 -0
  124. package/reverify-answered-state-answer-sent.png +0 -0
  125. package/reverify-card-visible-after-completion.png +0 -0
  126. package/rewind-step3-apple-banana-turns.png +0 -0
  127. package/rewind-step5-ui-unchanged-after-confirmed-rewind.png +0 -0
  128. package/rewind-step6-apple-menu-no-restore.png +0 -0
  129. package/rewind-step7-final-turnlist-unchanged.png +0 -0
  130. package/rewind-step7-negative-error-toast.png +0 -0
  131. package/rewind-step7-negative-error-toast2.png +0 -0
  132. package/subagent-r2-step5-turn-after-reload-no-card.png +0 -0
  133. package/subagent-r2-step6-tasks-panel-card.png +0 -0
  134. package/subagent-step3-tasks-tab-done-card.png +0 -0
  135. package/subagent-step4-turn-stuck-no-cards.png +0 -0
  136. package/agent-pane/frontend/dist/assets/index-BYo-lnxm.js +0 -362
@@ -0,0 +1,637 @@
1
+ /**
2
+ * Turn projector — maps the agent-runtime message stream (Claude-Code-style)
3
+ * onto agent-pane items and turn lifecycle.
4
+ *
5
+ * Projection (idempotent upsert by external ids):
6
+ * - stream_event(text/thinking) → agent_message / reasoning items (live deltas)
7
+ * - assistant → completes the round's text/thoughts items
8
+ * - user(tool_result) → file_change / command_execution / mcp_tool_call
9
+ * / web_search items from the action data
10
+ * - result → terminal: turn completed / failed / cancelled
11
+ *
12
+ * Watch-dog (Claude Code stream-watchdog analog): no `result` within
13
+ * RESULT_TIMEOUT after the last MESSAGE (heartbeats do not reset it) →
14
+ * HTTP snapshot reconcile (GET /sessions/:id/inputs incl. aiActions) fills
15
+ * missing rounds; a still-running session re-arms the watchdog up to
16
+ * MAX_RESULT_EXTENSIONS times, then the turn fails with a timeout error.
17
+ */
18
+
19
+ import { getDb } from '../db/index.ts';
20
+ import { broadcast } from '../ws/index.ts';
21
+ import type { Item } from '../db/schema.ts';
22
+ import type { RepoburgRuntimeClient, RepoburgSessionInput } from './repoburg-client.ts';
23
+ import {
24
+ completeItem,
25
+ insertItem,
26
+ mapActionToItem,
27
+ mapUsage,
28
+ setSessionStatus,
29
+ updateItem,
30
+ } from './action-mapping.ts';
31
+ import type {
32
+ AgentRuntimeMessage,
33
+ AssistantMessage,
34
+ ResultMessage,
35
+ StreamEventMessage,
36
+ SubagentMessage,
37
+ UserMessage,
38
+ } from './agent-runtime-client.ts';
39
+
40
+ /** No result message within this window after the last message → reconcile. */
41
+ export const RESULT_TIMEOUT_MS = 15 * 60_000;
42
+ /** Reconcile extensions while the backend reports the session still running. */
43
+ export const MAX_RESULT_EXTENSIONS = 3;
44
+
45
+ /** Per-round projected state. */
46
+ interface RoundInfo {
47
+ messageItemId: string | null;
48
+ reasoningItemId: string | null;
49
+ messageExternalId: string;
50
+ reasoningExternalId: string;
51
+ text: string;
52
+ thoughts: string;
53
+ finalPlain: string | null;
54
+ }
55
+
56
+ export interface ProjectorDeps {
57
+ agentPaneSessionId: string;
58
+ turnId: string;
59
+ repoburgSessionId: string;
60
+ client: RepoburgRuntimeClient;
61
+ /** Optional hook: called once when the turn reaches a terminal state. */
62
+ onFinished?: () => void;
63
+ }
64
+
65
+ export class TurnProjector {
66
+ private readonly rounds = new Map<string, RoundInfo>();
67
+ private done = false;
68
+ private resultTimer: ReturnType<typeof setTimeout> | null = null;
69
+ private extensions = 0;
70
+
71
+ constructor(private readonly deps: ProjectorDeps) {
72
+ this.armResultWatchdog();
73
+ }
74
+
75
+ get isDone(): boolean {
76
+ return this.done;
77
+ }
78
+
79
+ /** Main entry — dispatch one agent-runtime message. */
80
+ handle(message: AgentRuntimeMessage): void {
81
+ if (this.done) return;
82
+ switch (message.type) {
83
+ case 'system':
84
+ break; // init — connection marker only
85
+ case 'stream_event':
86
+ this.handleStreamEvent(message);
87
+ break;
88
+ case 'assistant':
89
+ this.handleAssistant(message);
90
+ break;
91
+ case 'user':
92
+ this.handleUser(message);
93
+ break;
94
+ case 'subagent':
95
+ this.handleSubagent(message);
96
+ break;
97
+ case 'result':
98
+ this.handleResult(message);
99
+ break;
100
+ }
101
+ }
102
+
103
+ /** Reset the result watchdog (any MESSAGE resets it; heartbeats do not). */
104
+ touch(): void {
105
+ if (this.done) return;
106
+ this.armResultWatchdog();
107
+ }
108
+
109
+ /** Stop the projector (turn finalized externally). Clears timers. */
110
+ close(): void {
111
+ this.clearWatchdog();
112
+ this.done = true;
113
+ }
114
+
115
+ // -------------------------------------------------------------------------
116
+ // Message handlers
117
+ // -------------------------------------------------------------------------
118
+
119
+ private round(inputId: string): RoundInfo {
120
+ let info = this.rounds.get(inputId);
121
+ if (!info) {
122
+ info = {
123
+ messageItemId: null,
124
+ reasoningItemId: null,
125
+ messageExternalId: `${inputId}-text`,
126
+ reasoningExternalId: `${inputId}-thoughts`,
127
+ text: '',
128
+ thoughts: '',
129
+ finalPlain: null,
130
+ };
131
+ this.rounds.set(inputId, info);
132
+ this.recordRuntimeInput(inputId);
133
+ }
134
+ return info;
135
+ }
136
+
137
+ /** Append a runtime input id to the turn row's runtime_input_ids column —
138
+ * the rewind anchor mapping (anchor = LAST id of the target turn). */
139
+ private recordRuntimeInput(inputId: string): void {
140
+ try {
141
+ const db = getDb();
142
+ const row = db.prepare('SELECT runtime_input_ids FROM turns WHERE id = ?').get(this.deps.turnId) as
143
+ | { runtime_input_ids: string | null }
144
+ | undefined;
145
+ if (!row) return; // turn row gone (deleted session) — skip silently
146
+ let ids: string[] = [];
147
+ if (row.runtime_input_ids) {
148
+ const parsed = JSON.parse(row.runtime_input_ids);
149
+ if (Array.isArray(parsed)) ids = parsed;
150
+ }
151
+ if (ids.includes(inputId)) return;
152
+ ids.push(inputId);
153
+ db.prepare('UPDATE turns SET runtime_input_ids = ? WHERE id = ?').run(
154
+ JSON.stringify(ids),
155
+ this.deps.turnId,
156
+ );
157
+ } catch {
158
+ // Best-effort recording — rewind only loses anchor precision.
159
+ }
160
+ }
161
+
162
+ private handleStreamEvent(msg: StreamEventMessage): void {
163
+ const db = getDb();
164
+ const info = this.round(msg.inputId);
165
+ const kind = msg.delta.type === 'thinking' ? 'thoughts' : 'text';
166
+
167
+ if (kind === 'text') info.text += msg.delta.text;
168
+ else info.thoughts += msg.delta.text;
169
+
170
+ const externalId = kind === 'text' ? info.messageExternalId : info.reasoningExternalId;
171
+ const type: Item['type'] = kind === 'text' ? 'agent_message' : 'reasoning';
172
+ const itemId = kind === 'text' ? info.messageItemId : info.reasoningItemId;
173
+
174
+ if (!itemId) {
175
+ const item = insertItem(
176
+ db,
177
+ this.deps.agentPaneSessionId,
178
+ this.deps.turnId,
179
+ externalId,
180
+ type,
181
+ { text: kind === 'text' ? info.text : info.thoughts },
182
+ 'in_progress',
183
+ 'item:started',
184
+ );
185
+ if (kind === 'text') info.messageItemId = item.id;
186
+ else info.reasoningItemId = item.id;
187
+ } else {
188
+ // Subsequent chunks stream as deltas (frontend matches by external id).
189
+ broadcast('item:delta', {
190
+ sessionId: this.deps.agentPaneSessionId,
191
+ turnId: this.deps.turnId,
192
+ itemId: externalId,
193
+ delta: msg.delta.text,
194
+ });
195
+ }
196
+ this.touch();
197
+ }
198
+
199
+ private handleAssistant(msg: AssistantMessage): void {
200
+ const info = this.round(msg.inputId);
201
+
202
+ // The assistant message is the AUTHORITATIVE round content — replace the
203
+ // accumulated deltas (they may be partial when deltas were off/missed).
204
+ const text = msg.content
205
+ .filter((b) => b.type === 'text')
206
+ .map((b) => (b as { text: string }).text)
207
+ .join('');
208
+ const thinking = msg.content
209
+ .filter((b) => b.type === 'thinking')
210
+ .map((b) => (b as { thinking: string }).thinking)
211
+ .join('');
212
+ if (text) info.text = text;
213
+ if (thinking) info.thoughts = thinking;
214
+
215
+ // Complete (or create) the round's items — deltas may have been off/missed.
216
+ this.upsertCompletedTextItem(info, 'message', info.text);
217
+ this.upsertCompletedTextItem(info, 'reasoning', info.thoughts);
218
+ this.touch();
219
+ }
220
+
221
+ /** Complete a round's text/thoughts item — creates it when deltas were
222
+ * off or missed, otherwise completes the streamed in_progress item. */
223
+ private upsertCompletedTextItem(
224
+ info: RoundInfo,
225
+ kind: 'message' | 'reasoning',
226
+ text: string,
227
+ ): void {
228
+ if (!text) return;
229
+ const db = getDb();
230
+ const externalId = kind === 'message' ? info.messageExternalId : info.reasoningExternalId;
231
+ const itemId = kind === 'message' ? info.messageItemId : info.reasoningItemId;
232
+ const type: Item['type'] = kind === 'message' ? 'agent_message' : 'reasoning';
233
+
234
+ if (itemId) {
235
+ const itemRow = db.prepare('SELECT * FROM items WHERE id = ?').get(itemId) as
236
+ | Item
237
+ | undefined;
238
+ if (itemRow) {
239
+ completeItem(db, this.deps.agentPaneSessionId, this.deps.turnId, itemRow, { text }, 'completed');
240
+ return;
241
+ }
242
+ }
243
+ // Idempotent: skip when an item with this external id already exists
244
+ // (e.g. replayed after reconnect).
245
+ const existing = db
246
+ .prepare('SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?')
247
+ .get(this.deps.turnId, externalId);
248
+ if (existing) return;
249
+ const item = insertItem(
250
+ db,
251
+ this.deps.agentPaneSessionId,
252
+ this.deps.turnId,
253
+ externalId,
254
+ type,
255
+ { text },
256
+ 'completed',
257
+ 'item:completed',
258
+ );
259
+ if (kind === 'message') info.messageItemId = item.id;
260
+ else info.reasoningItemId = item.id;
261
+ }
262
+
263
+ private handleUser(msg: UserMessage): void {
264
+ const db = getDb();
265
+ for (const block of msg.content) {
266
+ const info = this.round(msg.inputId);
267
+ // Synthesize the RepoburgAction shape from the tool_result payload —
268
+ // failed actions carry their text as the error, successful as output.
269
+ const action = {
270
+ ...block.action,
271
+ executionLogs: [
272
+ {
273
+ output: block.is_error ? '' : block.content,
274
+ error_message: block.is_error ? block.content : null,
275
+ },
276
+ ],
277
+ };
278
+ if (action.action_type === 'final') info.finalPlain = action.plain ?? null;
279
+
280
+ const externalId = `${msg.inputId}-action-${action.id}`;
281
+ const mapped = mapActionToItem(action);
282
+ if (!mapped) continue;
283
+
284
+ // Idempotent upsert — skip when already projected (reconnect replay
285
+ // or snapshot overlap).
286
+ const existing = db
287
+ .prepare('SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?')
288
+ .get(this.deps.turnId, externalId);
289
+ if (existing) continue;
290
+
291
+ insertItem(
292
+ db,
293
+ this.deps.agentPaneSessionId,
294
+ this.deps.turnId,
295
+ externalId,
296
+ mapped.type,
297
+ mapped.data,
298
+ mapped.status,
299
+ 'item:completed',
300
+ );
301
+ }
302
+ this.touch();
303
+ }
304
+
305
+ /** Sub-agent lifecycle → background_task item (Claude data shape),
306
+ * idempotent upsert keyed `<inputId>-action-<actionId>` — the same
307
+ * external id the invoke_subagent tool_result/reconcile uses, so all
308
+ * paths converge on ONE card. */
309
+ private handleSubagent(msg: SubagentMessage): void {
310
+ const db = getDb();
311
+ const externalId = `${msg.input_id}-action-${msg.action_id}`;
312
+ const terminal = msg.event === 'completed' || msg.event === 'failed';
313
+ const itemStatus: Item['status'] = terminal
314
+ ? msg.event === 'completed'
315
+ ? 'completed'
316
+ : 'failed'
317
+ : 'in_progress';
318
+
319
+ const row = db
320
+ .prepare('SELECT * FROM items WHERE turn_id = ? AND external_item_id = ?')
321
+ .get(this.deps.turnId, externalId) as
322
+ | (Omit<Item, 'data'> & { data: string | null })
323
+ | undefined;
324
+
325
+ if (row) {
326
+ const prev = row.data ? (JSON.parse(row.data) as Record<string, unknown>) : {};
327
+ const item: Item = { ...row, data: prev } as unknown as Item;
328
+ updateItem(
329
+ db,
330
+ this.deps.agentPaneSessionId,
331
+ this.deps.turnId,
332
+ item,
333
+ {
334
+ ...prev,
335
+ description: msg.description,
336
+ subagent_type: msg.agent_name,
337
+ status: terminal ? msg.event : 'running',
338
+ last_tool_name: msg.last_tool_name ?? prev.last_tool_name ?? null,
339
+ token_count: msg.token_count ?? prev.token_count ?? null,
340
+ ...(terminal ? { summary: msg.summary ?? '' } : {}),
341
+ },
342
+ itemStatus,
343
+ );
344
+ } else {
345
+ insertItem(
346
+ db,
347
+ this.deps.agentPaneSessionId,
348
+ this.deps.turnId,
349
+ externalId,
350
+ 'background_task',
351
+ {
352
+ task_id: msg.task_id,
353
+ description: msg.description,
354
+ task_type: 'subagent',
355
+ subagent_type: msg.agent_name,
356
+ prompt: null,
357
+ status: terminal ? msg.event : 'running',
358
+ summary: terminal ? msg.summary ?? '' : null,
359
+ output_file: null,
360
+ output: '',
361
+ token_count: msg.token_count ?? null,
362
+ last_tool_name: msg.last_tool_name ?? null,
363
+ },
364
+ itemStatus,
365
+ terminal ? 'item:completed' : 'item:started',
366
+ );
367
+ }
368
+ this.touch();
369
+ }
370
+ private handleResult(msg: ResultMessage): void {
371
+ switch (msg.subtype) {
372
+ case 'success':
373
+ this.finishSuccess(msg);
374
+ break;
375
+ case 'aborted':
376
+ this.finishAborted();
377
+ break;
378
+ case 'error_during_execution':
379
+ default:
380
+ this.finishFailed((msg.errors ?? []).join('; ') || 'Agent turn failed.');
381
+ break;
382
+ }
383
+ }
384
+
385
+ // -------------------------------------------------------------------------
386
+ // Terminal states
387
+ // -------------------------------------------------------------------------
388
+
389
+ private finishSuccess(msg: ResultMessage): void {
390
+ const db = getDb();
391
+ const now = new Date().toISOString();
392
+ const lastRound = [...this.rounds.values()].pop();
393
+
394
+ const responseText = msg.result || lastRound?.text || lastRound?.finalPlain || '';
395
+ const usage = msg.usage
396
+ ? mapUsage({
397
+ input: msg.usage.input_tokens,
398
+ cached: msg.usage.cache_read_input_tokens,
399
+ output: msg.usage.output_tokens,
400
+ })
401
+ : null;
402
+
403
+ this.closeOpenItems('completed');
404
+ db.prepare(
405
+ 'UPDATE turns SET status = ?, agent_response = ?, token_usage = ?, updated_at = ? WHERE id = ?',
406
+ ).run('completed', responseText || null, usage ? JSON.stringify(usage) : null, now, this.deps.turnId);
407
+ setSessionStatus(db, this.deps.agentPaneSessionId, 0, 'active', now, true);
408
+
409
+ broadcast('turn:completed', {
410
+ sessionId: this.deps.agentPaneSessionId,
411
+ turnId: this.deps.turnId,
412
+ ...(usage ? { usage } : {}),
413
+ hasUnreviewed: true,
414
+ // Final text — the FE renders it when the turn has no agent_message
415
+ // item (final-action rounds).
416
+ response: responseText || null,
417
+ });
418
+ void this.syncTitle();
419
+ this.finalize();
420
+ }
421
+
422
+ /** Fire-and-forget: copy the runtime session title once (new sessions). */
423
+ private async syncTitle(): Promise<void> {
424
+ try {
425
+ const db = getDb();
426
+ const session = db.prepare('SELECT title FROM sessions WHERE id = ?').get(
427
+ this.deps.agentPaneSessionId,
428
+ ) as { title: string | null } | undefined;
429
+ if (!session || session.title) return;
430
+
431
+ const runtimeSession = await this.deps.client.getSession(this.deps.repoburgSessionId);
432
+ const title = (runtimeSession.session_title || '').trim();
433
+ if (!title) return;
434
+
435
+ const now = new Date().toISOString();
436
+ db.prepare('UPDATE sessions SET title = ?, updated_at = ? WHERE id = ?').run(
437
+ title,
438
+ now,
439
+ this.deps.agentPaneSessionId,
440
+ );
441
+ broadcast('session:title', { sessionId: this.deps.agentPaneSessionId, title });
442
+ } catch {
443
+ // Title sync is best-effort.
444
+ }
445
+ }
446
+
447
+ private finishFailed(error: string): void {
448
+ const db = getDb();
449
+ const now = new Date().toISOString();
450
+ this.closeOpenItems('failed');
451
+ db.prepare('UPDATE turns SET status = ?, error = ?, updated_at = ? WHERE id = ?').run(
452
+ 'failed',
453
+ error,
454
+ now,
455
+ this.deps.turnId,
456
+ );
457
+ setSessionStatus(db, this.deps.agentPaneSessionId, 0, 'failed', now);
458
+ broadcast('turn:failed', {
459
+ sessionId: this.deps.agentPaneSessionId,
460
+ turnId: this.deps.turnId,
461
+ error,
462
+ });
463
+ this.finalize();
464
+ }
465
+
466
+ private finishAborted(): void {
467
+ const db = getDb();
468
+ const now = new Date().toISOString();
469
+ this.closeOpenItems('completed');
470
+ db.prepare('UPDATE turns SET status = ?, updated_at = ? WHERE id = ?').run(
471
+ 'aborted',
472
+ now,
473
+ this.deps.turnId,
474
+ );
475
+ setSessionStatus(db, this.deps.agentPaneSessionId, 0, 'active', now);
476
+ broadcast('turn:cancelled', {
477
+ sessionId: this.deps.agentPaneSessionId,
478
+ turnId: this.deps.turnId,
479
+ });
480
+ this.finalize();
481
+ }
482
+
483
+ private finalize(): void {
484
+ this.clearWatchdog();
485
+ this.done = true;
486
+ this.deps.onFinished?.();
487
+ }
488
+
489
+ /** Close every still in_progress item of this turn with the given status. */
490
+ private closeOpenItems(status: Item['status']): void {
491
+ const db = getDb();
492
+ const now = new Date().toISOString();
493
+ db.prepare('UPDATE items SET status = ?, updated_at = ? WHERE turn_id = ? AND status = ?').run(
494
+ status,
495
+ now,
496
+ this.deps.turnId,
497
+ 'in_progress',
498
+ );
499
+ }
500
+
501
+ // -------------------------------------------------------------------------
502
+ // Watch-dog + snapshot reconcile
503
+ // -------------------------------------------------------------------------
504
+
505
+ private armResultWatchdog(): void {
506
+ if (this.done) return;
507
+ this.clearWatchdog();
508
+ this.resultTimer = setTimeout(() => {
509
+ void this.reconcileFromSnapshot();
510
+ }, RESULT_TIMEOUT_MS);
511
+ }
512
+
513
+ private clearWatchdog(): void {
514
+ if (this.resultTimer) {
515
+ clearTimeout(this.resultTimer);
516
+ this.resultTimer = null;
517
+ }
518
+ }
519
+
520
+ /** Snapshot reconcile: project missing rounds from the runtime's HTTP
521
+ * snapshot, then complete the turn when the session stopped running. */
522
+ private async reconcileFromSnapshot(): Promise<void> {
523
+ if (this.done) return;
524
+ const { client, repoburgSessionId } = this.deps;
525
+ try {
526
+ const [inputs, session] = await Promise.all([
527
+ client.getSessionInputs(repoburgSessionId),
528
+ client.getSession(repoburgSessionId),
529
+ ]);
530
+ if (this.done) return; // A result arrived while fetching.
531
+
532
+ for (const input of inputs) {
533
+ if (input.role === 'model') this.projectSnapshotRound(input);
534
+ }
535
+
536
+ if (!session.is_running) {
537
+ // The loop is over — finish from the snapshot's last round.
538
+ const modelInputs = inputs.filter((i) => i.role === 'model');
539
+ const last = modelInputs[modelInputs.length - 1];
540
+ const lastRound = [...this.rounds.values()].pop();
541
+ const responseText =
542
+ lastRound?.text ||
543
+ lastRound?.finalPlain ||
544
+ extractFinalPlain(last) ||
545
+ last?.raw_llm_response ||
546
+ '';
547
+ const usage = last
548
+ ? mapUsage({
549
+ input: last.input_token_count ?? 0,
550
+ cached: last.cached_token_count ?? 0,
551
+ output: last.output_token_count ?? 0,
552
+ })
553
+ : null;
554
+ const db = getDb();
555
+ const now = new Date().toISOString();
556
+ this.closeOpenItems('completed');
557
+ db.prepare(
558
+ 'UPDATE turns SET status = ?, agent_response = ?, token_usage = ?, updated_at = ? WHERE id = ?',
559
+ ).run('completed', responseText || null, usage ? JSON.stringify(usage) : null, now, this.deps.turnId);
560
+ setSessionStatus(db, this.deps.agentPaneSessionId, 0, 'active', now, true);
561
+ broadcast('turn:completed', {
562
+ sessionId: this.deps.agentPaneSessionId,
563
+ turnId: this.deps.turnId,
564
+ ...(usage ? { usage } : {}),
565
+ hasUnreviewed: true,
566
+ response: responseText || null,
567
+ });
568
+ void this.syncTitle();
569
+ this.finalize();
570
+ return;
571
+ }
572
+
573
+ // Still running — re-arm or give up.
574
+ if (this.extensions < MAX_RESULT_EXTENSIONS) {
575
+ this.extensions += 1;
576
+ this.armResultWatchdog();
577
+ } else {
578
+ this.finishFailed(
579
+ `No result within ${(RESULT_TIMEOUT_MS / 60_000) * (MAX_RESULT_EXTENSIONS + 1)} minutes — the runtime session is still running. Check repoburg logs.`,
580
+ );
581
+ }
582
+ } catch (err) {
583
+ console.error('[repoburg] snapshot reconcile failed:', err);
584
+ if (this.extensions < MAX_RESULT_EXTENSIONS) {
585
+ this.extensions += 1;
586
+ this.armResultWatchdog();
587
+ } else {
588
+ this.finishFailed(`Snapshot reconcile failed: ${(err as Error).message}`);
589
+ }
590
+ }
591
+ }
592
+
593
+ /** Project one round from the snapshot (idempotent — live-projected
594
+ * rounds already exist and are skipped). */
595
+ private projectSnapshotRound(input: RepoburgSessionInput): void {
596
+ if (!input.raw_llm_response && !input.thoughts && !input.aiActions?.length) return;
597
+ const info = this.round(input.id);
598
+ info.text = info.text || (input.raw_llm_response ?? '');
599
+ info.thoughts = info.thoughts || (input.thoughts ?? '');
600
+
601
+ this.upsertCompletedTextItem(info, 'message', info.text);
602
+ this.upsertCompletedTextItem(info, 'reasoning', info.thoughts);
603
+
604
+ const actions = [...(input.aiActions ?? [])].sort(
605
+ (a, b) => (a.order_of_execution ?? 0) - (b.order_of_execution ?? 0),
606
+ );
607
+ const db = getDb();
608
+ for (const action of actions) {
609
+ if (action.action_type === 'final') info.finalPlain = action.plain ?? null;
610
+ const mapped = mapActionToItem(action);
611
+ if (!mapped) continue;
612
+ const externalId = `${input.id}-action-${action.id}`;
613
+ const existing = db
614
+ .prepare('SELECT id FROM items WHERE turn_id = ? AND external_item_id = ?')
615
+ .get(this.deps.turnId, externalId);
616
+ if (existing) continue;
617
+ insertItem(
618
+ db,
619
+ this.deps.agentPaneSessionId,
620
+ this.deps.turnId,
621
+ externalId,
622
+ mapped.type,
623
+ mapped.data,
624
+ mapped.status,
625
+ 'item:completed',
626
+ );
627
+ }
628
+ }
629
+ }
630
+
631
+ /** Extract the plain text of a final/html_final action from a snapshot input. */
632
+ function extractFinalPlain(input: RepoburgSessionInput | undefined): string | null {
633
+ const action = input?.aiActions?.find(
634
+ (a) => a.action_type === 'final' || a.action_type === 'html_final',
635
+ );
636
+ return action?.plain ?? null;
637
+ }
@@ -15,11 +15,28 @@ describe('Provider routes', () => {
15
15
  const res = await app.inject({ method: 'GET', url: '/api/providers' });
16
16
  expect(res.statusCode).toBe(200);
17
17
  const providers = res.json();
18
- expect(providers).toHaveLength(2);
18
+ expect(providers).toHaveLength(3);
19
19
  expect(providers[0].id).toBe('codex');
20
20
  expect(providers[0].available).toBe(true);
21
21
  expect(providers[1].id).toBe('claude');
22
22
  expect(providers[1].available).toBe(true);
23
+ expect(providers[2].id).toBe('repoburg');
24
+ expect(providers[2].available).toBe(true);
25
+ });
26
+
27
+ it('repoburg provider has correct capabilities', async () => {
28
+ const res = await app.inject({ method: 'GET', url: '/api/providers' });
29
+ const repoburg = res.json().find((p: { id: string }) => p.id === 'repoburg');
30
+ expect(repoburg.label).toBe('Repoburg');
31
+ expect(repoburg.capabilities.dynamicModels).toBe(true);
32
+ expect(repoburg.capabilities.skills).toBe(false);
33
+ expect(repoburg.capabilities.plugins).toBe(false);
34
+ expect(repoburg.capabilities.mcpServers).toBe(false);
35
+ expect(repoburg.capabilities.imageAttachments).toBe(false);
36
+ expect(repoburg.capabilities.sandbox).toBe(false);
37
+ expect(repoburg.capabilities.webSearch).toBe(false);
38
+ expect(repoburg.capabilities.networkAccess).toBe(false);
39
+ expect(repoburg.capabilities.fileReferences).toBe(false);
23
40
  });
24
41
 
25
42
  it('codex provider has all capabilities enabled', async () => {
@@ -38,7 +38,25 @@ const CLAUDE_PROVIDER: ProviderDefinition = {
38
38
  },
39
39
  };
40
40
 
41
- const PROVIDERS: ProviderDefinition[] = [CODEX_PROVIDER, CLAUDE_PROVIDER];
41
+ /** Repoburg provider — the repoburg backend's full agent engine via HTTP/WS. */
42
+ const REPOBURG_PROVIDER: ProviderDefinition = {
43
+ id: 'repoburg',
44
+ label: 'Repoburg',
45
+ available: true,
46
+ capabilities: {
47
+ dynamicModels: true,
48
+ skills: false,
49
+ plugins: false,
50
+ mcpServers: false,
51
+ imageAttachments: false,
52
+ sandbox: false,
53
+ webSearch: false,
54
+ networkAccess: false,
55
+ fileReferences: false,
56
+ },
57
+ };
58
+
59
+ const PROVIDERS: ProviderDefinition[] = [CODEX_PROVIDER, CLAUDE_PROVIDER, REPOBURG_PROVIDER];
42
60
 
43
61
  /** Register provider routes. */
44
62
  export async function registerProviderRoutes(fastify: FastifyInstance): Promise<void> {