Attribute OpenCode code-mode tool calls, keep same-instant shown items in order, and record the chat tools notes
This commit is contained in:
@@ -5,26 +5,35 @@ import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/chattools"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// openCodeCodeTool is OpenCode V2's code-mode tool: the model calls MCP tools
|
||||
// from a script (`tools.pipelines.show_file({...})`) instead of as tool parts
|
||||
// of their own, so the stream shows one running "execute" part.
|
||||
const openCodeCodeTool = "execute"
|
||||
|
||||
// awaitToolCallSession attributes a call on a shared harness endpoint (one
|
||||
// OpenCode service serves every chat, and its MCP requests carry no session)
|
||||
// to the chat whose retained stream shows a running tool part with one of
|
||||
// names and exactly these arguments. The harness reports the part as running
|
||||
// before or while it calls the tool, so this waits up to wait for it. It
|
||||
// returns "" when no chat matches, and ambiguous when several distinct chats
|
||||
// do: a call is never guessed into a chat.
|
||||
func (h *chatHub) awaitToolCallSession(ctx context.Context, names []string, arguments json.RawMessage, wait time.Duration) (string, bool) {
|
||||
var want any
|
||||
// to the chat whose retained stream shows this call running: a tool part with
|
||||
// the tool's harness name and exactly these arguments, or a running code-mode
|
||||
// script that calls the tool. Several scripts are told apart by the argument
|
||||
// values they contain. The harness reports the part as running before or while
|
||||
// it calls the tool, so this waits up to wait for it. It returns "" when no
|
||||
// chat matches, and ambiguous when several distinct chats still do: a call is
|
||||
// never guessed into a chat.
|
||||
func (h *chatHub) awaitToolCallSession(ctx context.Context, tool string, arguments json.RawMessage, wait time.Duration) (string, bool) {
|
||||
var want map[string]any
|
||||
if json.Unmarshal(arguments, &want) != nil {
|
||||
return "", false
|
||||
}
|
||||
deadline := time.Now().Add(wait)
|
||||
for {
|
||||
sessions := h.runningToolCallSessions(names, want)
|
||||
sessions := h.runningToolCallSessions(tool, want)
|
||||
switch {
|
||||
case len(sessions) == 1:
|
||||
return sessions[0], false
|
||||
@@ -42,34 +51,89 @@ func (h *chatHub) awaitToolCallSession(ctx context.Context, names []string, argu
|
||||
}
|
||||
}
|
||||
|
||||
func (h *chatHub) runningToolCallSessions(names []string, want any) []string {
|
||||
func (h *chatHub) runningToolCallSessions(tool string, want map[string]any) []string {
|
||||
names := chattools.HarnessToolNames(tool)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
var sessions []string
|
||||
var exact, scripts, narrowed []string
|
||||
for sessionID, turn := range h.turns {
|
||||
if turnHasToolCall(turn, names, want) {
|
||||
sessions = append(sessions, sessionID)
|
||||
match := turnToolCallMatch(turn, names, tool, want)
|
||||
if match == toolCallExact {
|
||||
exact = append(exact, sessionID)
|
||||
}
|
||||
if match >= toolCallScript {
|
||||
scripts = append(scripts, sessionID)
|
||||
}
|
||||
if match >= toolCallScriptWithArguments {
|
||||
narrowed = append(narrowed, sessionID)
|
||||
}
|
||||
}
|
||||
slices.Sort(sessions)
|
||||
return sessions
|
||||
for _, candidates := range [][]string{exact, scripts, narrowed} {
|
||||
if len(candidates) == 1 {
|
||||
return candidates
|
||||
}
|
||||
}
|
||||
slices.Sort(scripts)
|
||||
return scripts
|
||||
}
|
||||
|
||||
func turnHasToolCall(turn *chatTurn, names []string, want any) bool {
|
||||
type toolCallMatch int
|
||||
|
||||
const (
|
||||
toolCallNone toolCallMatch = iota
|
||||
toolCallScript
|
||||
toolCallScriptWithArguments
|
||||
toolCallExact
|
||||
)
|
||||
|
||||
// turnToolCallMatch is the strongest evidence one chat's running tool parts
|
||||
// give that it is making this call.
|
||||
func turnToolCallMatch(turn *chatTurn, names []string, tool string, want map[string]any) toolCallMatch {
|
||||
best := toolCallNone
|
||||
for _, message := range turn.messages {
|
||||
for _, part := range message.parts {
|
||||
p := part.part
|
||||
if p.Type != "tool" || p.State == nil || !slices.Contains(names, p.Name) {
|
||||
if p.Type != "tool" || p.State == nil || (p.State.Status != protocol.ChatToolRunning && p.State.Status != "pending") {
|
||||
continue
|
||||
}
|
||||
if p.State.Status != protocol.ChatToolRunning && p.State.Status != "pending" {
|
||||
if slices.Contains(names, p.Name) {
|
||||
var got map[string]any
|
||||
if json.Unmarshal(p.State.Input, &got) == nil && reflect.DeepEqual(got, want) {
|
||||
return toolCallExact
|
||||
}
|
||||
continue
|
||||
}
|
||||
var got any
|
||||
if json.Unmarshal(p.State.Input, &got) == nil && reflect.DeepEqual(got, want) {
|
||||
return true
|
||||
if p.Name != openCodeCodeTool {
|
||||
continue
|
||||
}
|
||||
var script struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if json.Unmarshal(p.State.Input, &script) != nil || !strings.Contains(script.Code, chattools.ServerName+"."+tool+"(") {
|
||||
continue
|
||||
}
|
||||
match := toolCallScript
|
||||
if scriptHasArguments(script.Code, want) {
|
||||
match = toolCallScriptWithArguments
|
||||
}
|
||||
best = max(best, match)
|
||||
}
|
||||
}
|
||||
return false
|
||||
return best
|
||||
}
|
||||
|
||||
// scriptHasArguments reports whether every string argument appears in code,
|
||||
// literally or JSON-escaped.
|
||||
func scriptHasArguments(code string, want map[string]any) bool {
|
||||
for _, value := range want {
|
||||
text, ok := value.(string)
|
||||
if !ok || text == "" {
|
||||
continue
|
||||
}
|
||||
escaped, _ := json.Marshal(text)
|
||||
if !strings.Contains(code, text) && !strings.Contains(code, strings.Trim(string(escaped), `"`)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ func (s *chatToolService) session(ctx context.Context, token, tool string, argum
|
||||
return id, ""
|
||||
}
|
||||
if _, ok := strings.CutPrefix(scope, chatToolInstanceScope); ok && s.hub != nil {
|
||||
id, ambiguous := s.hub.awaitToolCallSession(ctx, chattools.HarnessToolNames(tool), arguments, chatToolCorrelationWait)
|
||||
id, ambiguous := s.hub.awaitToolCallSession(ctx, tool, arguments, chatToolCorrelationWait)
|
||||
if ambiguous {
|
||||
return "", "Pipelines could not tell which chat made this call (another chat made an identical one); retry with a different title."
|
||||
}
|
||||
|
||||
@@ -292,3 +292,39 @@ func TestInstanceTokenCallsNeedOneMatchingRunningToolCall(t *testing.T) {
|
||||
t.Fatalf("two chats running the same call must be refused: %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
// OpenCode V2 calls MCP tools from its code-mode "execute" script, so the
|
||||
// stream shows the script, not a tool part of the Pipelines tool's own name.
|
||||
func TestInstanceTokenCallsMatchOpenCodeCodeModeScripts(t *testing.T) {
|
||||
f := newChatToolFixture(t)
|
||||
token := f.token(t, chatToolInstanceScope+"opencode")
|
||||
saved := chatToolCorrelationWait
|
||||
chatToolCorrelationWait = 100 * time.Millisecond
|
||||
t.Cleanup(func() { chatToolCorrelationWait = saved })
|
||||
script := func(sessionID, part, code string) {
|
||||
input, _ := json.Marshal(map[string]string{"code": code})
|
||||
f.hub.apply(protocol.ChatEventFrame{SessionID: sessionID, MessageID: "msg_" + sessionID, Kind: protocol.ChatEventTool,
|
||||
Part: &protocol.ChatPart{Type: "tool", ID: part, Name: "execute", State: &protocol.ChatToolState{Status: protocol.ChatToolRunning, Input: input}}})
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(f.home, "a.png"), []byte("\x89PNG\r\n\x1a\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(f.home, "b.png"), []byte("\x89PNG\r\n\x1a\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script("ses_p", "prt_p", `return tools.pipelines.show_file({ path: "~/a.png", title: "Checker" })`)
|
||||
script("ses_q", "prt_q", `return tools.other.show_file({ path: "~/a.png" })`)
|
||||
if r := f.call(token, "show_file", `{"path":"~/a.png","title":"Checker"}`); r.IsError {
|
||||
t.Fatal(r.Text)
|
||||
}
|
||||
if len(f.items(t, "ses_p")) != 1 || len(f.items(t, "ses_q")) != 0 {
|
||||
t.Fatal("the script calling the Pipelines tool owns the call")
|
||||
}
|
||||
script("ses_q", "prt_q2", `await tools.pipelines.show_file({ path: "~/b.png" })`)
|
||||
if r := f.call(token, "show_file", `{"path":"~/b.png"}`); r.IsError || len(f.items(t, "ses_q")) != 1 {
|
||||
t.Fatalf("two scripts are told apart by their arguments: %v", r)
|
||||
}
|
||||
if r := f.call(token, "show_file", `{"path":"~/c.png"}`); !r.IsError {
|
||||
t.Fatal("arguments neither script contains must not be guessed into a chat")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user