xonecas.io
60255
Zn

Zoea-Nova / commit fb33462

fix(core): reduce MCP drift and document upstream version

xonecas2026-02-05 fb334626a3b7598e066063d4d30207430d0d1512 parent ee557a8

10 files changed

AGENTS.md+21−0
@@ -44,6 +44,8 @@ To run Zoea Nova without connecting to the SpaceMolt MCP server, use the `--offl
4444
4545 This uses a stub MCP client that returns mock data for essential tools (`get_status`, `get_system`, etc.), allowing TUI development and testing without an active game session.
4646
47+See `documentation/OFFLINE_MODE.md` for supported tools and limitations.
48+
4749 ## TUI Testing:
4850
4951 Zoea Nova uses three types of TUI tests:
@@ -177,6 +179,25 @@ The application uses SQLite for persistence.
177179 - **Source**: Origin of a memory—`direct` (single Mysis), `broadcast` (swarm), `system`, `llm`, or `tool`.
178180 - **Context Compression**: Sliding window that sends only recent messages + system prompt to LLM. See [documentation/CONTEXT_COMPRESSION.md](documentation/CONTEXT_COMPRESSION.md).
179181
182+## Architecture
183+
184+```mermaid
185+flowchart LR
186+ TUI["TUI (Bubble Tea)"] -->|events| EventBus["Event Bus"]
187+ EventBus --> Commander
188+ Commander -->|manages| Mysis
189+ Mysis --> Provider
190+ Provider --> LLM
191+ Commander --> Store
192+ Mysis --> Store
193+ Mysis --> MCPProxy["MCP Proxy"]
194+ MCPProxy --> SpaceMolt["SpaceMolt MCP Server"]
195+```
196+
197+## State Machine
198+
199+See `documentation/MYSIS_STATE_MACHINE.md` for valid Mysis transitions and triggers.
200+
180201 ## Workflow:
181202
182203 The user follows a structured development workflow. Respect these phases:
Makefile+7−1
@@ -1,4 +1,4 @@
1-.PHONY: fmt build run test test-integration install clean db-reset-accounts
1+.PHONY: fmt build run test test-integration install clean db-reset-accounts check-upstream-version
22
33 VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
44 LDFLAGS := -ldflags "-X main.Version=$(VERSION)"
@@ -25,6 +25,12 @@ test:
2525 test-integration:
2626 go test -v ./internal/tui -run TestIntegration -count=1
2727
28+check-upstream-version:
29+ @echo "Config upstream version:"
30+ @rg "upstream_version" config.toml
31+ @echo "Remote upstream version:"
32+ @curl -s https://www.spacemolt.com/api.md | rg -o "gameserver v[0-9.]+"
33+
2834 clean:
2935 rm -rf bin/ coverage.out
3036
config.toml+1−0
@@ -17,3 +17,4 @@ rate_burst = 5
1717
1818 [mcp]
1919 upstream = "https://game.spacemolt.com/mcp"
20+upstream_version = "v0.43.0"
documentation/MYSIS_STATE_MACHINE.md+51−0
@@ -0,0 +1,51 @@
1+# Mysis State Machine
2+
3+This document describes the valid Mysis lifecycle states and the transitions between them.
4+
5+## States
6+
7+- `idle`: Created or loaded but not running.
8+- `running`: Processing messages and tool calls.
9+- `stopped`: Explicitly stopped by user action.
10+- `errored`: Entered due to an error during execution or startup.
11+
12+## Diagram
13+
14+```mermaid
15+stateDiagram-v2
16+ [*] --> idle: create or load
17+ idle --> running: start
18+ running --> stopped: stop
19+ running --> errored: error
20+ stopped --> running: relaunch
21+ errored --> running: relaunch
22+```
23+
24+## Transition Triggers
25+
26+### Create or Load
27+
28+- When a Mysis is created in the store, its state is `idle`.
29+- When a Mysis is loaded at startup, the runtime instance starts in `idle` and must be explicitly started.
30+
31+### Start (Relaunch)
32+
33+- Triggered by `Commander.StartMysis` (TUI `r` key).
34+- Transitions to `running` from `idle`, `stopped`, or `errored`.
35+- If the store update fails during start, the Mysis enters `errored`.
36+
37+### Stop
38+
39+- Triggered by `Commander.StopMysis` (TUI `s` key).
40+- Valid only when currently `running`.
41+- Transitions to `stopped` and releases the current account.
42+
43+### Error
44+
45+- Triggered by `setErrorState` on execution failures.
46+- Transitions to `errored` and records `lastError`.
47+
48+## Notes
49+
50+- State updates are persisted via `store.UpdateMysisState`.
51+- `running` is the only state that accepts new messages.
documentation/OFFLINE_MODE.md+33−0
@@ -0,0 +1,33 @@
1+# Offline Mode
2+
3+Offline mode runs Zoea Nova without connecting to the SpaceMolt MCP server. It replaces the MCP client with a stub that returns mock data so the TUI and orchestration flow can be exercised safely.
4+
5+## Run
6+
7+```bash
8+./bin/zoea --offline
9+```
10+
11+## Supported Tools
12+
13+The stub MCP client implements these tools with mock payloads:
14+
15+- `get_status`
16+- `get_system`
17+- `get_ship`
18+- `get_poi`
19+
20+All other MCP tool calls return an error response indicating the tool is not implemented in the stub.
21+
22+## What Works
23+
24+- TUI navigation, focus mode, and command handling
25+- Mysis orchestration (create, start, stop, delete)
26+- Provider calls and LLM prompts
27+- Local orchestration tools (zoea_* tools)
28+
29+## Limitations
30+
31+- No live game actions (mine, travel, trade, etc.)
32+- Tool results are mock data and do not change based on game state
33+- Any MCP tool outside the supported list returns an error
documentation/plans/v1.md+22−11
@@ -98,14 +98,22 @@ Prevents drift when system prompt falls out of context window.
9898
9999 ### 2.4 Captains Log Guidance
100100
101-** NEEDS TO BE REVISED AND FIND EVIDENCE, UPSTREAM GAME SERVER HAS CHANGED**
101+Upstream API doc (gameserver v0.43.0) documents captain’s log limits and behavior.
102+We should reflect these limits in prompts to prevent avoidable errors.
102103
103-Prevents `empty_entry` errors.
104+- [x] **Verify current prompts include limits and examples**
105+ - SystemPrompt: non-empty entry examples + limits
106+ - ContinuePrompt: non-empty reminder + limits
107+ - Limits from https://www.spacemolt.com/api.md:
108+ - Max 20 entries per player (oldest entry evicted when full)
109+ - Max 100KB per entry
110+ - Commands are query-only (not rate-limited)
104111
105-- [ ] **Verify current prompts have examples**
106- - SystemPrompt already has examples (lines 55-59 of mysis.go)
107- - ContinuePrompt has reminder (line 120-121)
108- - Test with fresh mysis to confirm no empty_entry errors
112+- [x] **Verify empty_entry behavior still occurs**
113+ - Test with fresh mysis and empty entry
114+ - If behavior changed, update error handling in mysis tool result formatting
115+
116+**Completed:** 2026-02-05 21:10 UTC
109117
110118 ---
111119
@@ -304,20 +312,23 @@ No cleanup of old memories.
304312 - Update README with installation instructions
305313 - Completed: 2026-02-05 19:10 UTC
306314
307-- [ ] **Document offline mode**
315+- [x] **Document offline mode**
308316 - How to run without game server
309317 - What features are available in offline mode
318+ - Completed: 2026-02-05 20:30 UTC
310319
311320 ### 9.2 Developer Documentation
312321
313-- [ ] **Add architecture diagram**
322+- [x] **Add architecture diagram**
314323 - Use mermaid in AGENTS.md
315324 - Show: Commander -> Mysis -> Provider -> LLM
316325 - Show: TUI -> EventBus -> Commander
326+ - Completed: 2026-02-05 20:30 UTC
317327
318-- [ ] **Document state machine**
328+- [x] **Document state machine**
319329 - Valid Mysis state transitions
320330 - When each transition occurs
331+ - Completed: 2026-02-05 20:30 UTC
321332
322333 ---
323334
@@ -514,11 +525,11 @@ The following data fields exist in structs but lack adequate test coverage:
514525 | 6. Database | 3 | 0 | 0 |
515526 | 7. Configuration | 3 | 0 | 0 |
516527 | 8. Code Quality | 3 | 1 | 0 |
517-| 9. Documentation | 4 | 1 | 0 |
528+| 9. Documentation | 4 | 4 | 0 |
518529 | 10. TODO.md | 4 | 3 | 0 |
519530 | 11. TUI Data Visibility | 19 | 19 | 0 |
520531 | 12. Pre-Release | 5 | 0 | 0 |
521-| **Total** | **67** | **45** | **0** |
532+| **Total** | **67** | **48** | **0** |
522533
523534 ---
524535
internal/constants/constants.go+5−11
@@ -52,6 +52,10 @@ Remember in captain's log:
5252 - Current objectives and plans
5353 - Trade routes and profitable deals
5454
55+Captain's log limits (server enforced):
56+- Max 20 entries per player (oldest is evicted when full)
57+- Max 100KB per entry
58+
5559 ## Timekeeping
5660 - Do not mention real-world time (minutes, hours, dates, UTC)
5761 - Use game ticks from tool results (current_tick, arrival_tick, cooldown_ticks)
@@ -90,6 +94,7 @@ const ContinuePrompt = `Turn complete. What is your next move?
9094 CRITICAL REMINDERS:
9195 - ALWAYS try zoea_claim_account before registering; if registering, use a Crustacean-themed username
9296 - When using captains_log_add, entry field must be non-empty
97+- Captain's log limits: 20 entries max, 100KB per entry (oldest evicted when full)
9398 - Never store or share your password in any in-game tool calls or chat
9499 - Use game ticks only; do not mention real-world time (minutes, hours, dates, UTC)
95100 - Never calculate ticks, use every turn to progress
@@ -147,14 +152,3 @@ const MinEventBusBufferSize = 1000
147152
148153 // EventBusPublishTimeout is the per-subscriber timeout for critical events.
149154 const EventBusPublishTimeout = 200 * time.Millisecond
150-
151-// SnapshotTools defines tools that return state snapshots for context compaction.
152-var SnapshotTools = map[string]bool{
153- "get_ship": true,
154- "get_system": true,
155- "get_poi": true,
156- "get_nearby": true,
157- "get_cargo": true,
158- "zoea_swarm_status": true,
159- "zoea_list_myses": true,
160-}
internal/core/mysis.go+95−36
@@ -451,7 +451,6 @@ func (a *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
451451
452452 // Execute each tool call
453453 for _, tc := range response.ToolCalls {
454- a.updateActivityFromToolCall(tc.Name)
455454 // Signal MCP activity
456455 a.bus.Publish(Event{
457456 Type: EventNetworkMCP,
@@ -461,7 +460,7 @@ func (a *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
461460 })
462461
463462 result, execErr := a.executeToolCall(ctx, mcpProxy, tc)
464- a.updateActivityFromToolResult(tc.Name, result, execErr)
463+ a.updateActivityFromToolResult(result, execErr)
465464
466465 // Store the tool result
467466 resultContent := a.formatToolResult(tc.ID, tc.Name, result, execErr)
@@ -767,7 +766,7 @@ func (a *Mysis) compactSnapshots(memories []*store.Memory) []*store.Memory {
767766 }
768767
769768 // If this is a snapshot tool, track its position
770- if constants.SnapshotTools[toolName] {
769+ if a.isSnapshotTool(toolName) {
771770 latestSnapshot[toolName] = i
772771 }
773772 }
@@ -789,7 +788,7 @@ func (a *Mysis) compactSnapshots(memories []*store.Memory) []*store.Memory {
789788 }
790789
791790 // If this is a snapshot tool, only keep if it's the latest
792- if constants.SnapshotTools[toolName] {
791+ if a.isSnapshotTool(toolName) {
793792 if latestSnapshot[toolName] == i {
794793 result = append(result, m)
795794 }
@@ -835,6 +834,21 @@ func (a *Mysis) toolCallNameIndex(memories []*store.Memory) map[string]string {
835834 return index
836835 }
837836
837+func (a *Mysis) isSnapshotTool(toolName string) bool {
838+ if toolName == "" {
839+ return false
840+ }
841+ if strings.HasPrefix(toolName, "get_") {
842+ return true
843+ }
844+ switch toolName {
845+ case "zoea_swarm_status", "zoea_list_myses":
846+ return true
847+ default:
848+ return false
849+ }
850+}
851+
838852 // run is the mysis main processing loop.
839853 func (a *Mysis) run(ctx context.Context) {
840854 // Ticker to nudge the mysis if it's idle
@@ -950,24 +964,8 @@ func (a *Mysis) shouldNudge(now time.Time) bool {
950964 return true
951965 }
952966
953-func (a *Mysis) updateActivityFromToolCall(toolName string) {
954- switch toolName {
955- case "travel":
956- a.setActivity(ActivityStateTraveling, time.Now().Add(constants.WaitStateNudgeInterval))
957- case "mine":
958- a.setActivity(ActivityStateMining, time.Time{})
959- case "attack", "attack_base":
960- a.setActivity(ActivityStateInCombat, time.Time{})
961- }
962-}
963-
964-func (a *Mysis) updateActivityFromToolResult(toolName string, result *mcp.ToolResult, err error) {
967+func (a *Mysis) updateActivityFromToolResult(result *mcp.ToolResult, err error) {
965968 if err != nil || result == nil || result.IsError {
966- a.clearActivityIf(ActivityStateMining)
967- a.clearActivityIf(ActivityStateInCombat)
968- if toolName == "travel" {
969- a.setActivity(ActivityStateIdle, time.Time{})
970- }
971969 return
972970 }
973971
@@ -982,31 +980,34 @@ func (a *Mysis) updateActivityFromToolResult(toolName string, result *mcp.ToolRe
982980 }
983981 }
984982
985- if toolName == "travel" {
986- arrivalTick, found := findIntField(payload, "arrival_tick")
987- if found {
988- if currentTickOK && arrivalTick <= currentTick {
989- a.setActivity(ActivityStateIdle, time.Time{})
990- return
991- }
992- until := a.estimateTravelUntil(now, arrivalTick, currentTick, currentTickOK)
993- a.setActivity(ActivityStateTraveling, until)
983+ arrivalTick, found := findIntField(payload, "arrival_tick", "travel_arrival_tick")
984+ if found {
985+ if currentTickOK && arrivalTick <= currentTick {
986+ a.setActivity(ActivityStateIdle, time.Time{})
987+ return
994988 }
989+ until := a.estimateTravelUntil(now, arrivalTick, currentTick, currentTickOK)
990+ a.setActivity(ActivityStateTraveling, until)
995991 return
996992 }
997993
994+ if progress, ok := findFloatField(payload, "travel_progress"); ok {
995+ if progress >= 1 {
996+ a.setActivity(ActivityStateIdle, time.Time{})
997+ return
998+ }
999+ if progress > 0 {
1000+ a.setActivity(ActivityStateTraveling, now.Add(constants.WaitStateNudgeInterval))
1001+ return
1002+ }
1003+ }
1004+
9981005 if cooldownTicks, found := findIntField(payload, "cooldown_ticks", "cooldown_remaining"); found && cooldownTicks > 0 {
9991006 until := a.estimateCooldownUntil(now, cooldownTicks)
10001007 a.setActivity(ActivityStateCooldown, until)
10011008 return
10021009 }
10031010
1004- switch toolName {
1005- case "mine":
1006- a.clearActivityIf(ActivityStateMining)
1007- case "attack", "attack_base":
1008- a.clearActivityIf(ActivityStateInCombat)
1009- }
10101011 }
10111012
10121013 func (a *Mysis) setActivity(state ActivityState, until time.Time) {
@@ -1133,6 +1134,39 @@ func findIntField(payload interface{}, keys ...string) (int64, bool) {
11331134 return 0, false
11341135 }
11351136
1137+func findFloatField(payload interface{}, keys ...string) (float64, bool) {
1138+ queue := []interface{}{payload}
1139+
1140+ for len(queue) > 0 {
1141+ current := queue[0]
1142+ queue = queue[1:]
1143+
1144+ switch value := current.(type) {
1145+ case map[string]interface{}:
1146+ for _, key := range keys {
1147+ if raw, ok := value[key]; ok {
1148+ if number, ok := normalizeFloat(raw); ok {
1149+ return number, true
1150+ }
1151+ }
1152+ }
1153+
1154+ childKeys := make([]string, 0, len(value))
1155+ for key := range value {
1156+ childKeys = append(childKeys, key)
1157+ }
1158+ sort.Strings(childKeys)
1159+ for _, key := range childKeys {
1160+ queue = append(queue, value[key])
1161+ }
1162+ case []interface{}:
1163+ queue = append(queue, value...)
1164+ }
1165+ }
1166+
1167+ return 0, false
1168+}
1169+
11361170 func findCurrentTick(payload interface{}) (int64, bool) {
11371171 if number, ok := findIntFieldAtKeys(payload, "current_tick"); ok {
11381172 return number, true
@@ -1217,6 +1251,31 @@ func normalizeInt(value interface{}) (int64, bool) {
12171251 }
12181252 }
12191253
1254+func normalizeFloat(value interface{}) (float64, bool) {
1255+ switch v := value.(type) {
1256+ case int:
1257+ return float64(v), true
1258+ case int64:
1259+ return float64(v), true
1260+ case float64:
1261+ return v, true
1262+ case json.Number:
1263+ number, err := v.Float64()
1264+ if err != nil {
1265+ return 0, false
1266+ }
1267+ return number, true
1268+ case string:
1269+ number, err := strconv.ParseFloat(v, 64)
1270+ if err != nil {
1271+ return 0, false
1272+ }
1273+ return number, true
1274+ default:
1275+ return 0, false
1276+ }
1277+}
1278+
12201279 func (a *Mysis) emitStateChange(oldState, newState MysisState) {
12211280 a.publishCriticalEvent(Event{
12221281 Type: EventMysisStateChanged,
internal/core/mysis_test.go+23−3
@@ -424,12 +424,18 @@ func TestSystemPromptContainsCaptainsLogExamples(t *testing.T) {
424424 if !strings.Contains(constants.SystemPrompt, "non-empty entry field") {
425425 t.Fatal("SystemPrompt missing non-empty entry reminder")
426426 }
427+ if !strings.Contains(constants.SystemPrompt, "Max 20 entries") {
428+ t.Fatal("SystemPrompt missing captain's log limit guidance")
429+ }
427430 }
428431
429432 func TestContinuePromptContainsCriticalReminders(t *testing.T) {
430433 if !strings.Contains(constants.ContinuePrompt, "captains_log_add") {
431434 t.Fatal("ContinuePrompt missing captains_log_add reminder")
432435 }
436+ if !strings.Contains(constants.ContinuePrompt, "100KB") {
437+ t.Fatal("ContinuePrompt missing captain's log limit reminder")
438+ }
433439 }
434440
435441 func TestFormatToolResult_EmptyEntryError(t *testing.T) {
@@ -808,7 +814,7 @@ func TestMysisActivityTravelUntilFromTicks(t *testing.T) {
808814 Content: []mcp.ContentBlock{{Type: "text", Text: `{"current_tick":110,"arrival_tick":120}`}},
809815 }
810816
811- m.updateActivityFromToolResult("travel", result, nil)
817+ m.updateActivityFromToolResult(result, nil)
812818
813819 if m.activityState != ActivityStateTraveling {
814820 t.Fatalf("expected activity state traveling, got %s", m.activityState)
@@ -827,7 +833,7 @@ func TestMysisActivityTravelFallbackWait(t *testing.T) {
827833 Content: []mcp.ContentBlock{{Type: "text", Text: `{"arrival_tick":5000}`}},
828834 }
829835
830- m.updateActivityFromToolResult("travel", result, nil)
836+ m.updateActivityFromToolResult(result, nil)
831837
832838 if m.activityState != ActivityStateTraveling {
833839 t.Fatalf("expected activity state traveling, got %s", m.activityState)
@@ -846,7 +852,7 @@ func TestMysisActivityTravelArrivalTickReached(t *testing.T) {
846852 Content: []mcp.ContentBlock{{Type: "text", Text: `{"current_tick":120,"arrival_tick":120}`}},
847853 }
848854
849- m.updateActivityFromToolResult("travel", result, nil)
855+ m.updateActivityFromToolResult(result, nil)
850856
851857 if m.activityState != ActivityStateIdle {
852858 t.Fatalf("expected activity state idle, got %s", m.activityState)
@@ -856,6 +862,20 @@ func TestMysisActivityTravelArrivalTickReached(t *testing.T) {
856862 }
857863 }
858864
865+func TestMysisActivityTravelArrivalTickField(t *testing.T) {
866+ m := &Mysis{}
867+
868+ result := &mcp.ToolResult{
869+ Content: []mcp.ContentBlock{{Type: "text", Text: `{"current_tick":200,"travel_arrival_tick":210}`}},
870+ }
871+
872+ m.updateActivityFromToolResult(result, nil)
873+
874+ if m.activityState != ActivityStateTraveling {
875+ t.Fatalf("expected activity state traveling, got %s", m.activityState)
876+ }
877+}
878+
859879 func TestFindCurrentTick(t *testing.T) {
860880 tests := []struct {
861881 name string
internal/mcp/proxy.go+102−19
@@ -4,6 +4,7 @@ import (
44 "context"
55 "encoding/json"
66 "fmt"
7+ "strings"
78 "sync"
89
910 "github.com/rs/zerolog/log"
@@ -163,19 +164,14 @@ func (p *Proxy) handleRegisterResponse(arguments json.RawMessage, result *ToolRe
163164 return
164165 }
165166
166- if len(result.Content) == 0 {
167+ payload, ok := parseToolResultPayload(result)
168+ if !ok {
167169 return
168170 }
169171
170- var response struct {
171- Password string `json:"password"`
172- }
173- if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
174- return
175- }
176-
177- if args.Username != "" && response.Password != "" {
178- _, _ = p.accountStore.CreateAccount(args.Username, response.Password)
172+ password, ok := findStringField(payload, "password", "token")
173+ if args.Username != "" && ok && password != "" {
174+ _, _ = p.accountStore.CreateAccount(args.Username, password)
179175 }
180176 }
181177
@@ -193,22 +189,109 @@ func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResul
193189 }
194190
195191 func (p *Proxy) handleLogoutResponse(arguments json.RawMessage, result *ToolResult) {
196- if len(result.Content) == 0 {
192+ payload, ok := parseToolResultPayload(result)
193+ if !ok {
197194 return
198195 }
199196
200- var response struct {
201- Player struct {
202- Username string `json:"username"`
203- } `json:"player"`
197+ username, ok := findStringFieldAtPath(payload, "player", "username")
198+ if !ok {
199+ username, _ = findStringField(payload, "username")
204200 }
205- if err := json.Unmarshal([]byte(result.Content[0].Text), &response); err != nil {
206- return
201+
202+ if username != "" {
203+ _ = p.accountStore.ReleaseAccount(username)
204+ }
205+}
206+
207+func parseToolResultPayload(result *ToolResult) (interface{}, bool) {
208+ if result == nil {
209+ return nil, false
210+ }
211+
212+ content := strings.TrimSpace(joinToolResultText(result))
213+ if content == "" {
214+ return nil, false
215+ }
216+ if !strings.HasPrefix(content, "{") && !strings.HasPrefix(content, "[") {
217+ return nil, false
218+ }
219+
220+ decoder := json.NewDecoder(strings.NewReader(content))
221+ decoder.UseNumber()
222+ var payload interface{}
223+ if err := decoder.Decode(&payload); err != nil {
224+ return nil, false
225+ }
226+
227+ return payload, true
228+}
229+
230+func joinToolResultText(result *ToolResult) string {
231+ if result == nil {
232+ return ""
207233 }
208234
209- if response.Player.Username != "" {
210- _ = p.accountStore.ReleaseAccount(response.Player.Username)
235+ var parts []string
236+ for _, block := range result.Content {
237+ if block.Type == "text" {
238+ parts = append(parts, block.Text)
239+ }
240+ }
241+ return strings.Join(parts, "\n")
242+}
243+
244+func findStringField(payload interface{}, keys ...string) (string, bool) {
245+ queue := []interface{}{payload}
246+
247+ for len(queue) > 0 {
248+ current := queue[0]
249+ queue = queue[1:]
250+
251+ switch value := current.(type) {
252+ case map[string]interface{}:
253+ for _, key := range keys {
254+ if raw, ok := value[key]; ok {
255+ if str, ok := raw.(string); ok {
256+ return str, true
257+ }
258+ }
259+ }
260+
261+ for _, child := range value {
262+ queue = append(queue, child)
263+ }
264+ case []interface{}:
265+ queue = append(queue, value...)
266+ }
267+ }
268+
269+ return "", false
270+}
271+
272+func findStringFieldAtPath(payload interface{}, path ...string) (string, bool) {
273+ current, ok := payload.(map[string]interface{})
274+ if !ok {
275+ return "", false
211276 }
277+
278+ for i, key := range path {
279+ value, exists := current[key]
280+ if !exists {
281+ return "", false
282+ }
283+ if i == len(path)-1 {
284+ str, ok := value.(string)
285+ return str, ok
286+ }
287+ next, ok := value.(map[string]interface{})
288+ if !ok {
289+ return "", false
290+ }
291+ current = next
292+ }
293+
294+ return "", false
212295 }
213296
214297 // Initialize initializes the upstream connection if available.