-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathdeepseek_tui.go
More file actions
330 lines (303 loc) · 7.82 KB
/
Copy pathdeepseek_tui.go
File metadata and controls
330 lines (303 loc) · 7.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package parser
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/tidwall/gjson"
)
const deepSeekTUIPrefix = "deepseek-tui:"
func parseDeepSeekTUISession(
path, machine string,
) (*ParsedSession, []ParsedMessage, error) {
info, err := os.Stat(path)
if err != nil {
return nil, nil, fmt.Errorf("stat %s: %w", path, err)
}
data, err := os.ReadFile(path)
if err != nil {
return nil, nil, fmt.Errorf("read %s: %w", path, err)
}
if !gjson.ValidBytes(data) {
return nil, nil, fmt.Errorf("invalid JSON in %s", path)
}
root := gjson.ParseBytes(data)
rawID := root.Get("metadata.id").Str
if !IsValidSessionID(rawID) {
rawID = deepSeekTUISessionIDFromPath(path)
}
if rawID == "" {
return nil, nil, fmt.Errorf("missing or invalid id in %s", path)
}
metadata := root.Get("metadata")
workspace := metadata.Get("workspace").Str
project := ExtractProjectFromCwd(workspace)
if project == "" {
project = "deepseek_tui"
}
model := metadata.Get("model").Str
startedAt := parseTimestamp(metadata.Get("created_at").Str)
endedAt := parseTimestamp(metadata.Get("updated_at").Str)
var (
messages []ParsedMessage
firstMessage string
ordinal int
)
root.Get("messages").ForEach(func(_, msg gjson.Result) bool {
roleStr := msg.Get("role").Str
role, ok := deepSeekTUIRole(roleStr)
if !ok {
return true
}
ts := parseTimestamp(msg.Get("timestamp").Str)
if !ts.IsZero() {
if startedAt.IsZero() || ts.Before(startedAt) {
startedAt = ts
}
if ts.After(endedAt) {
endedAt = ts
}
}
content, thinking, hasThinking, hasToolUse, calls, results :=
extractDeepSeekTUIContent(msg.Get("content"))
if strings.TrimSpace(content) == "" && len(calls) == 0 &&
len(results) == 0 {
return true
}
if role == RoleUser && firstMessage == "" &&
strings.TrimSpace(content) != "" {
firstMessage = truncate(
strings.ReplaceAll(content, "\n", " "),
300,
)
}
msgModel := msg.Get("model").Str
if msgModel == "" {
msgModel = model
}
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: role,
Content: content,
ThinkingText: thinking,
Timestamp: ts,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(content),
ToolCalls: calls,
ToolResults: results,
Model: msgModel,
})
ordinal++
return true
})
if len(messages) == 0 {
return nil, nil, nil
}
sessionName := metadata.Get("title").Str
if firstMessage == "" {
firstMessage = sessionName
}
userCount := 0
for _, msg := range messages {
if msg.Role == RoleUser && strings.TrimSpace(msg.Content) != "" {
userCount++
}
}
sess := &ParsedSession{
ID: deepSeekTUIPrefix + rawID,
Project: project,
Machine: machine,
Agent: AgentDeepSeekTUI,
Cwd: workspace,
FirstMessage: firstMessage,
SessionName: sessionName,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(messages),
UserMessageCount: userCount,
File: FileInfo{
Path: path,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
},
}
return sess, messages, nil
}
func isDeepSeekTUISessionFile(name string) bool {
if name == "latest.json" || name == "offline_queue.json" {
return false
}
stem, ok := strings.CutSuffix(name, ".json")
return ok && IsValidSessionID(stem)
}
func deepSeekTUISessionIDFromPath(path string) string {
name := filepath.Base(path)
stem, ok := strings.CutSuffix(name, ".json")
if !ok || !IsValidSessionID(stem) {
return ""
}
return stem
}
func deepSeekTUIRole(role string) (RoleType, bool) {
switch role {
case "user":
return RoleUser, true
case "assistant":
return RoleAssistant, true
default:
return "", false
}
}
func extractDeepSeekTUIContent(
content gjson.Result,
) (string, string, bool, bool, []ParsedToolCall, []ParsedToolResult) {
if content.Type == gjson.String {
return content.Str, "", false, false, nil, nil
}
if !content.IsArray() {
return "", "", false, false, nil, nil
}
var (
parts []string
thinkingParts []string
calls []ParsedToolCall
results []ParsedToolResult
hasThinking bool
hasToolUse bool
)
content.ForEach(func(_, block gjson.Result) bool {
switch block.Get("type").Str {
case "text":
if text := block.Get("text").Str; text != "" {
parts = append(parts, text)
}
case "thinking":
thinking := block.Get("thinking").Str
if thinking == "" {
thinking = block.Get("text").Str
}
if thinking != "" {
hasThinking = true
thinkingParts = append(thinkingParts, thinking)
parts = append(parts,
"[Thinking]\n"+thinking+"\n[/Thinking]")
}
case "tool_use", "server_tool_use":
if call, ok := deepSeekTUIToolCall(block); ok {
hasToolUse = true
calls = append(calls, call)
parts = append(parts, formatToolUse(block))
}
case "tool_result", "tool_search_tool_result",
"code_execution_tool_result":
if result, ok := deepSeekTUIToolResult(block); ok {
results = append(results, result)
}
}
return true
})
return strings.Join(parts, "\n"),
strings.Join(thinkingParts, "\n\n"),
hasThinking, hasToolUse, calls, results
}
func deepSeekTUIToolCall(block gjson.Result) (ParsedToolCall, bool) {
name := block.Get("name").Str
if name == "" {
name = block.Get("tool_name").Str
}
if name == "" {
return ParsedToolCall{}, false
}
input := block.Get("input")
if !input.Exists() {
input = block.Get("parameters")
}
return ParsedToolCall{
ToolUseID: block.Get("id").Str,
ToolName: name,
Category: NormalizeToolCategory(name),
InputJSON: input.Raw,
}, true
}
func deepSeekTUIToolResult(block gjson.Result) (ParsedToolResult, bool) {
toolUseID := block.Get("tool_use_id").Str
if toolUseID == "" {
toolUseID = block.Get("toolUseID").Str
}
if toolUseID == "" {
toolUseID = block.Get("id").Str
}
if toolUseID == "" {
return ParsedToolResult{}, false
}
content := block.Get("content")
if !content.Exists() {
content = block.Get("result")
}
if !content.Exists() {
content = block.Get("output")
}
return ParsedToolResult{
ToolUseID: toolUseID,
ContentLength: deepSeekTUIContentLength(content),
ContentRaw: deepSeekTUIResultRaw(content),
}, true
}
// deepSeekTUIObjectText extracts the string content from an object-shaped
// tool result such as {"output":"..."}. It reports whether a known field
// holds a string value, treating an empty string as present so a valid
// no-output result is not mistaken for a missing field.
func deepSeekTUIObjectText(content gjson.Result) (string, bool) {
for _, key := range []string{"output", "text", "content"} {
if field := content.Get(key); field.Exists() &&
field.Type == gjson.String {
return field.Str, true
}
}
return "", false
}
func deepSeekTUIResultRaw(content gjson.Result) string {
// Object results such as {"output":"..."} are not recognized by
// DecodeContent's object branch (which handles only the iFlow shape),
// so extract the known string field and store it as a plain string.
if content.IsObject() {
if text, ok := deepSeekTUIObjectText(content); ok {
quoted, _ := json.Marshal(text)
return string(quoted)
}
}
if content.Raw == "" {
return `""`
}
return content.Raw
}
func deepSeekTUIContentLength(content gjson.Result) int {
if content.Type == gjson.String {
return len(content.Str)
}
if content.IsArray() {
total := 0
content.ForEach(func(_, block gjson.Result) bool {
total += len(block.Get("text").Str)
return true
})
return total
}
if content.IsObject() {
if text, ok := deepSeekTUIObjectText(content); ok {
return len(text)
}
}
if content.Raw == "" {
return 0
}
var decoded any
if err := json.Unmarshal([]byte(content.Raw), &decoded); err == nil {
if text, ok := decoded.(string); ok {
return len(text)
}
}
return len(content.Raw)
}