package codex import ( "encoding/json" "strings" "git.a-wan.net/alan/pipelines/internal/protocol" ) func rawText(raw json.RawMessage) string { if len(raw) == 0 || string(raw) == "null" { return "" } var text string if json.Unmarshal(raw, &text) == nil { return text } return string(raw) } func boundedToolText(text string) string { const limit = 64 << 10 if len(text) > limit { return text[:limit] + "\n… (tool detail truncated at 64 KiB)" } return text } func (i item) reasoningText() string { if i.Text != "" { return i.Text } var content []string _ = json.Unmarshal(i.Content, &content) return strings.Join(append(append([]string{}, i.Summary...), content...), "\n\n") } func (i item) toolPart(completed bool) protocol.ChatPart { name := i.Type if i.Name != "" { name = i.Name } if i.Tool != "" { name = i.Tool } if i.Server != "" { name = i.Server + "/" + name } else if i.Namespace != "" { name = i.Namespace + "/" + name } var input any = i.Input if len(i.Arguments) > 0 { input = i.Arguments } switch i.Type { case "commandExecution": name = "shell" input = map[string]any{"command": i.Command} case "webSearch": name = "websearch" if i.Query != "" { input = map[string]any{"query": i.Query} } else { input = i.Raw } case "fileChange": input = map[string]any{"changes": i.Changes} } if input == nil { input = map[string]any{"type": i.Type, "detail": i.Raw} } encoded, _ := json.Marshal(input) if len(encoded) > 64<<10 { encoded, _ = json.Marshal(map[string]any{"truncated": true, "preview": boundedToolText(string(encoded))}) } status := protocol.ChatToolRunning if completed { status = protocol.ChatToolCompleted } message := "" if len(i.Error) > 0 && string(i.Error) != "null" { var detail struct { Message string `json:"message"` } if json.Unmarshal(i.Error, &detail) == nil && detail.Message != "" { message = detail.Message } else { message = rawText(i.Error) } } if message != "" || strings.EqualFold(i.Status, "failed") || strings.EqualFold(i.Status, "declined") || (completed && i.ExitCode != nil && *i.ExitCode != 0) { status = protocol.ChatToolError } state := &protocol.ChatToolState{Status: status, Input: encoded} output := i.AggregatedOutput for _, raw := range []json.RawMessage{i.Result, i.Output, i.ContentItems} { if text := rawText(raw); text != "" { if output != "" { output += "\n" } output += text } } if i.Text != "" { if output != "" { output += "\n" } output += i.Text } if output != "" { state.Content = []protocol.ChatToolContent{{Type: "text", Text: boundedToolText(output)}} } if message != "" { state.Error = &protocol.ChatError{Message: boundedToolText(message)} } return protocol.ChatPart{Type: protocol.ChatPartTool, ID: i.ID, Name: name, State: state} } func (i *item) UnmarshalJSON(raw []byte) error { type plain item var value plain if err := json.Unmarshal(raw, &value); err != nil { return err } *i = item(value) i.Raw = append(json.RawMessage(nil), raw...) return nil }