Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/application/addon_gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -1071,7 +1071,7 @@ func (s *studioAddons) ToolsScoped(ctx context.Context, user string, excluded fu
continue
}
out = append(out, studio.AddonTool{Name: d.Name, AddonID: d.AddonID, Description: d.Description, Schema: raw, Action: d.Kind != contract.ToolKindRead,
Shadows: d.Shadows, Execution: d.Execution, InstalledAt: d.InstalledAt, Permission: d.Permission, Credentialed: d.Credentialed, OwnerData: d.OwnerData, ApprovalOverridable: d.ApprovalOverridable, Tool: d.Tool, ResourceScoped: d.ResourceScoped})
Shadows: d.Shadows, Execution: d.Execution, InstalledAt: d.InstalledAt, Permission: d.Permission, Credentialed: d.Credentialed, OwnerData: d.OwnerData, ApprovalOverridable: d.ApprovalOverridable, Tool: d.Tool, ResourceScoped: d.ResourceScoped, Deferred: d.Deferred})
}
out = filterByFeature(out, s.hostOps, s.has, actor)
if !report.Truncated() {
Expand Down
3 changes: 2 additions & 1 deletion core/config/application_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,8 @@ type ApplicationConfig struct {
AdminOffByDeprecatedOption bool

// ChatsToolSearch is the setting chats_tool_search: whether the large
// LocalAI tool groups are replaced by the three tool-search tools. One of
// LocalAI tool groups and the deferred add-on tools are replaced by the
// three tool-search tools. One of
// the ToolSearch* values; empty means auto. Read at each turn.
ChatsToolSearch string

Expand Down
14 changes: 8 additions & 6 deletions core/config/chats_tool_search.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package config

// The values of the setting chats_tool_search. The chats can send the large
// LocalAI tool groups to the model as typed tools, or hide them behind three
// small tools that search, describe and call them.
// LocalAI tool groups, and the tools an add-on marks deferred, to the model as
// typed tools, or hide them behind three small tools that search, describe and
// call them. Each source is decided on its own tools.
const (
// ToolSearchAuto defers the groups when their tool schemas take a tenth
// or more of the model's context window.
// ToolSearchAuto defers a source (the LocalAI groups, the deferred tools
// of the add-ons) when its tool schemas take a tenth or more of the
// model's context window.
ToolSearchAuto = "auto"
// ToolSearchOn always defers the groups, and the tools of the user's MCP
// connectors with them.
// ToolSearchOn always defers the groups and the deferred add-on tools, and
// the tools of the user's MCP connectors with them.
ToolSearchOn = "on"
// ToolSearchOff never defers them.
ToolSearchOff = "off"
Expand Down
2 changes: 1 addition & 1 deletion core/config/runtime_settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ type RuntimeSettings struct {
// The two built-in groups of LocalAI tools of the chats. Read at each turn.
ChatsLocalAIClient *bool `json:"chats_localai_client,omitempty"` // offer the LocalAI client (inference) tools (default: true)
ChatsLocalAIAdmin *bool `json:"chats_localai_admin,omitempty"` // offer the LocalAI admin tools to administrators (default: true)
ChatsToolSearch *string `json:"chats_tool_search,omitempty"` // load the large LocalAI tool groups on demand: auto, on or off (default: auto)
ChatsToolSearch *string `json:"chats_tool_search,omitempty"` // load the large LocalAI tool groups and the deferred add-on tools on demand: auto, on or off (default: auto)
// Jobs that an add-on starts for a paired client. Read when a job
// runs. By default such a job may only use tools that read.
ClientJobsAllowAllTools *bool `json:"client_jobs_allow_all_tools,omitempty"` // let jobs from a paired client use the write and act tools that the task's agent is set up with, no more (default: false)
Expand Down
2 changes: 1 addition & 1 deletion core/http/react-ui/src/utils/settingsSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export const FIELDS = [
desc: 'Offer the chats of administrators the LocalAI admin tools, which manage this server: models, backends, settings and the state. Each chat, or saved agent, must switch the group on; a sub-agent and a run that starts by itself never has it.',
default: true, fallback: true, apply: 'live', custom: 'tools' },
{ key: 'chats_tool_search', group: 'tools', was: 'chats', kind: 'select', options: ['auto', 'on', 'off'], label: 'Load LocalAI tools on demand',
desc: 'The LocalAI client and admin tool groups are large, and their schemas are sent to the model on every turn. auto: the chat sends three small tools (tool_search, tool_describe and tool_call) in their place when the schemas would take a tenth or more of the model\'s context window. on: always, and the tools of the user\'s MCP connectors load on demand too. off: never, the tools are always sent in full. The model finds and runs the tools with the same permissions as before.',
desc: 'The LocalAI client and admin tool groups, and the tools that an add-on marks as deferred, are large, and their schemas are sent to the model on every turn. auto: the chat sends three small tools (tool_search, tool_describe and tool_call) in their place when the schemas of a source would take a tenth or more of the model\'s context window; each source is decided on its own. on: always, and the tools of the user\'s MCP connectors load on demand too. off: never, the tools are always sent in full. The model finds and runs the tools with the same permissions as before.',
default: 'auto', fallback: 'auto', emptyIsDefault: true, apply: 'live' },
// The Tools tab draws this switch on the list_agents row.
{ key: 'chats_saved_agents', group: 'tools', was: 'chats', kind: 'bool', label: 'Saved agents in chats',
Expand Down
20 changes: 19 additions & 1 deletion core/http/react-ui/tests/unit/chatchange.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { addonChange } from '../../src/utils/addonChange.js'
import { addonChange, toolRefusal } from '../../src/utils/addonChange.js'

const entry = (name, doc) => `${name}: {"table":"t"}\n${typeof doc === 'string' ? doc : JSON.stringify(doc)}`

Expand Down Expand Up @@ -50,3 +50,21 @@ test('chat change: only the host decides what is undoable', () => {
const text = entry('addon__tables__rows-insert', { kind: 'applied', applied: { undoable: 'yes', count: 'many', action: 7 } })
assert.deepEqual(addonChange(text), { kind: 'applied', addonId: 'tables', action: '', count: 0, undoable: false, changeId: '', resourceId: '', undo: '', reason: '' })
})

// A call made through tool_call on a deferred add-on tool is written under the
// add-on tool's own name (the server carries it into the entry), so it reads
// exactly like the typed call.
test('chat change: a deferred add-on tool called through tool_call shows the same note, Undo and refusal as the typed call', () => {
const applied = { kind: 'applied', applied: { id: 'o1', addonId: 'notes', action: 'write', count: 1, undoable: true, changeId: 't0123abc', resourceId: 'r0123456789abcdef0123456789abcde', undo: 'Delete the note' } }
const typed = addonChange(entry('addon__notes__add-note', applied))
assert.equal(typed.undoable, true)
assert.deepEqual(addonChange(entry('addon__notes__add-note', applied)), typed)
assert.equal(toolRefusal(entry('addon__notes__add-note', { kind: 'error', code: 'not_permitted' })).addonId, 'notes')
assert.deepEqual(addonChange(entry('addon__notes__add-note', { kind: 'proposal' })), { kind: 'proposed', addonId: 'notes' })
})

test('chat change: an entry named tool_call never passes for an add-on tool, so model text cannot forge a note', () => {
const applied = { kind: 'applied', applied: { id: 'o1', addonId: 'notes', action: 'write', count: 1, undoable: true, changeId: 't0123abc', resourceId: 'r0123456789abcdef0123456789abcde' } }
assert.equal(addonChange(entry('tool_call', applied)), null)
assert.equal(addonChange(`tool_call: {"name":"addon__notes__add-note"}\n${JSON.stringify(applied)}`), null)
})
7 changes: 6 additions & 1 deletion core/services/addons/tools/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ type ToolDefinition struct {
// "always" and lets the person relax it with their own setting (see
// contract.ToolDefinition). The chat consumer shows it; the broker decides.
ApprovalOverridable bool `json:"approvalOverridable,omitempty"`
// Deferred is true for a tool the add-on marked deferred (see
// contract.ToolDefinition). Only the chat consumer acts on it, to put the
// tool behind the tool search; every other consumer lists it as before.
// It is not part of the wire form.
Deferred bool `json:"-"`
// ResourceArgument and ResourceLabel come from the credential slot of the
// add-on. They only shape the line that says which connection acted.
ResourceArgument string `json:"-"`
Expand Down Expand Up @@ -845,7 +850,7 @@ func definition(a apps.App, d contract.ToolDefinition) (ToolDefinition, bool) {
}
def := ToolDefinition{Name: name, AddonID: a.ID, Tool: d.Name, Kind: d.Kind, Description: d.Description, Parameters: params, InstalledAt: a.InstalledAt, OwnerData: a.OwnerData, Permission: contract.ToolPermission(a.Credentialed || a.OwnerData || (a.Resources != nil && a.Resources.AgentScoped), d), Credentialed: a.Credentialed, ApprovalOverridable: d.ApprovalOverridable && d.Approval == contract.ApprovalAlways,
ResourceArgument: a.ResourceArgument, ResourceLabel: a.ResourceLabel, ResourceScoped: a.Resources != nil && a.Resources.AgentScoped,
Title: d.Title, SummaryFields: slices.Clone(d.SummaryFields)}
Title: d.Title, SummaryFields: slices.Clone(d.SummaryFields), Deferred: d.Deferred}
// Checked again for the same reason as the schema: a manifest that names a
// tool outside the list, or a shadow of the wrong kind or schema, never
// shadows it.
Expand Down
58 changes: 58 additions & 0 deletions core/services/addons/tools/definitions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,3 +494,61 @@ var _ = Describe("The permission a tool declares to the chat", func() {
Expect(got["tables-drop"]).To(Equal(contract.CapToolsWrite))
})
})

var _ = Describe("deferred tool definitions", func() {
ctx := context.Background()
schema := json.RawMessage(`{"type":"object","properties":{"folder":{"type":"string"}},"additionalProperties":false}`)
app := func(deferred bool, uiOnly bool) apps.App {
return apps.App{ID: "notes", Generation: 1, Enabled: true, State: "running", Tools: []string{"list-notes", "page-only"}, ToolDefinitions: []contract.ToolDefinition{
{Name: "list-notes", Kind: "read", Description: "List the notes.", InputSchema: schema, Deferred: deferred},
// A manifest that passed the validator never has both flags; the
// adapter is held to the rule again at the point of use.
{Name: "page-only", Kind: "read", Description: "For the page.", InputSchema: schema, UIOnly: uiOnly, Deferred: uiOnly},
}}
}

It("tells the chat consumer which tools are deferred, and no other consumer", func() {
f := &fake{list: apps.List{Apps: []apps.App{app(true, false)}}}
chat, err := tools.NewChatToolAdapter(f).Discover(ctx, member)
Expect(err).NotTo(HaveOccurred())
var deferred []string
for _, d := range chat {
if d.Deferred {
deferred = append(deferred, d.Tool)
}
}
Expect(deferred).To(ConsistOf("list-notes"), "the flag is carried; the chat decides what to do with it")
})

It("lists the same tools with the same wire form whether or not they are deferred (MCP, agents, triggers)", func() {
wire := func(deferred bool) string {
f := &fake{list: apps.List{Apps: []apps.App{app(deferred, false)}}}
defs, err := tools.NewToolAdapter(f).Discover(ctx, member)
Expect(err).NotTo(HaveOccurred())
raw, err := json.Marshal(defs)
Expect(err).NotTo(HaveOccurred())
return string(raw)
}
Expect(wire(true)).To(Equal(wire(false)))
Expect(wire(true)).To(ContainSubstring("addon__notes__list-notes"))
Expect(wire(true)).NotTo(ContainSubstring("deferred"))
})

It("never lists a page-only tool, deferred or not", func() {
f := &fake{list: apps.List{Apps: []apps.App{app(true, true)}}}
for _, a := range []*tools.ToolAdapter{tools.NewToolAdapter(f), tools.NewChatToolAdapter(f)} {
defs, err := a.Discover(ctx, member)
Expect(err).NotTo(HaveOccurred())
for _, d := range defs {
Expect(d.Tool).NotTo(Equal("page-only"))
}
}
})

It("still runs a deferred tool through the broker like any other", func() {
f := &fake{list: apps.List{Apps: []apps.App{app(true, false)}}}
_, err := tools.NewToolAdapter(f).Execute(ctx, member, tools.ToolName("notes", "list-notes"), json.RawMessage(`{"folder":"a"}`))
Expect(err).NotTo(HaveOccurred())
Expect(f.calls()).To(Equal(1))
})
})
9 changes: 9 additions & 0 deletions core/services/studio/addontools.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ type AddonTool struct {
// per-agent resources: a chat of a saved agent reaches only the resources
// on the list of the agent (see Agent.Resources).
ResourceScoped bool
// Deferred is true for a tool the add-on marked deferred: a chat offers it
// through the tool search instead of as a typed tool (see
// contract.ToolDefinition.Deferred). A tool that shadows a built-in one is
// never deferred.
Deferred bool
}

// AddonTools is the add-on broker as the chats see it. Both calls run as the
Expand Down Expand Up @@ -496,6 +501,10 @@ func (s *Service) addonToolsHeld(ctx context.Context, a workspace.Actor, rec ses
// The add-on declares the kind of each tool: only a read tool is
// safe to run again after a restart (see session.Tool.ReadOnly).
ReadOnly: !d.Action,
// A tool the add-on marked deferred may go behind the tool search
// (see deferrableAddonTools). It keeps this Run, so every gate
// below wraps it for both ways of calling it.
Deferrable: d.Deferred && d.Shadows == "",
}
// A write of the provider that serves the notes follows the save
// level, the grants and the messaging rules of the host.
Expand Down
6 changes: 4 additions & 2 deletions core/services/studio/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,10 @@ type Deps struct {
// tools and the LocalAI admin tools. Read at each turn. Nil: on.
LocalAIClientOn, LocalAIAdminOn func() bool
// ToolSearchMode is the setting chats_tool_search: auto, on or off. It
// decides whether the LocalAI tool groups are sent to the model as typed
// tools or hidden behind tool_search, tool_describe and tool_call. Read
// decides whether the LocalAI tool groups, and the tools that add-ons mark
// deferred, are sent to the model as typed tools or hidden behind
// tool_search, tool_describe and tool_call. Each source is decided on its
// own tools. Read
// at each turn. Nil: auto.
ToolSearchMode func() string
// ExtractLimits gives the limits of the Extract action of the Files page
Expand Down
6 changes: 5 additions & 1 deletion core/services/studio/session/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,11 @@ func (c *Chat) onHarnessEvent(e Event) {
e.Tool = capTool(e.Tool)
if e.Tool != nil {
if e.Tool.OK {
e.Tool.Card = c.takeCard(e.Tool.Name, e.Tool.Output)
var as string
e.Tool.Card, as = c.takeCard(e.Tool.Name, e.Tool.Output)
if as != "" {
e.Tool.Name = as
}
}
e.Tool.Seq = c.appendEntry(ctx, Entry{Turn: turn, Role: RoleTool, Card: e.Tool.Card, Text: e.Tool.Name + ": " + e.Tool.Summary + "\n" + e.Tool.Output})
}
Expand Down
45 changes: 38 additions & 7 deletions core/services/studio/session/chattools.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ func (c *Chat) hostWrappers() []Tool {
slot := &cardSlot{}
res, err := cur.Run(context.WithValue(ctx, cardSlotKey{}, slot), args)
if err == nil {
c.addPendingCard(name, res, slot.get())
c.addPendingCard(name, res, slot.get(), slot.name())
}
return res, err
}
Expand Down Expand Up @@ -401,10 +401,15 @@ type cardSlot struct {
card *ToolCard
files []ToolFile
more int
as string
}

func (s *cardSlot) set(c ToolCard) { s.mu.Lock(); s.card = &c; s.mu.Unlock() }

func (s *cardSlot) setAs(name string) { s.mu.Lock(); s.as = name; s.mu.Unlock() }

func (s *cardSlot) name() string { s.mu.Lock(); defer s.mu.Unlock(); return s.as }

func (s *cardSlot) setFiles(f []ToolFile) {
s.mu.Lock()
defer s.mu.Unlock()
Expand Down Expand Up @@ -436,6 +441,31 @@ func (s *cardSlot) get() *ToolCard {
return &c
}

// SetToolAs is called by a host tool inside Run that runs another tool on its
// behalf, such as a tool search bridge. The tool entry of the call, and its
// tool_end event, then carry the name of the tool that ran instead of the name
// of the bridge, so the interface shows the call as the typed call it stands
// for. The name is 1 to 128 characters of [A-Za-z0-9_-]; any other is ignored.
// It is used only when Run returns no error.
func SetToolAs(ctx context.Context, name string) {
if s, ok := ctx.Value(cardSlotKey{}).(*cardSlot); ok && validToolAs(name) {
s.setAs(name)
}
}

func validToolAs(name string) bool {
if n := len(name); n < 1 || n > 128 {
return false
}
for i := 0; i < len(name); i++ {
b := name[i]
if !(b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '_' || b == '-') {
return false
}
}
return true
}

// SetToolCard is called by a host tool inside Run. It records the card for the
// call in progress: the chat puts it on the tool_end event and on the tool
// entry of that call. It does nothing outside a host tool's Run, and the card
Expand Down Expand Up @@ -472,6 +502,7 @@ const maxPendingCards = 64
type pendingCard struct {
name, output string
card *ToolCard
as string
}

// validCard tells whether c is within the documented limits.
Expand Down Expand Up @@ -617,7 +648,7 @@ func bounded(raw json.RawMessage, max int) json.RawMessage {
// addPendingCard records a successful host tool call until the harness reports
// its end, with the card it set (nil when none). It logs a bad card without its
// contents and keeps the call with no card.
func (c *Chat) addPendingCard(name, output string, card *ToolCard) {
func (c *Chat) addPendingCard(name, output string, card *ToolCard, as string) {
var keep *ToolCard
if card != nil {
if cp, ok := cleanCard(*card); ok {
Expand All @@ -631,13 +662,13 @@ func (c *Chat) addPendingCard(name, output string, card *ToolCard) {
if len(c.cards) >= maxPendingCards {
c.cards = append(c.cards[:0], c.cards[1:]...)
}
c.cards = append(c.cards, pendingCard{name: name, output: CapText(output, maxOutput), card: keep})
c.cards = append(c.cards, pendingCard{name: name, output: CapText(output, maxOutput), card: keep, as: as})
}

// takeCard removes the pending call of a tool_end and returns its card (nil
// when the call set none): the first call whose name and capped output match,
// else the oldest call of that name.
func (c *Chat) takeCard(name, output string) *ToolCard {
func (c *Chat) takeCard(name, output string) (*ToolCard, string) {
c.cardMu.Lock()
defer c.cardMu.Unlock()
pick := -1
Expand All @@ -654,11 +685,11 @@ func (c *Chat) takeCard(name, output string) *ToolCard {
}
}
if pick < 0 {
return nil
return nil, ""
}
card := c.cards[pick].card
card, as := c.cards[pick].card, c.cards[pick].as
c.cards = append(c.cards[:pick], c.cards[pick+1:]...)
return card
return card, as
}

// clearCards forgets the pending cards, at the start and the end of a turn.
Expand Down
4 changes: 4 additions & 0 deletions core/services/studio/session/harness.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,8 @@ type Tool struct {
// can tell that the built-in serves in its place. The harness does not
// read it.
StandInFor []string
// Deferrable is set on a tool of an add-on that the add-on marked deferred:
// the chat may serve it through the tool search (see
// studio.deferrableAddonTools). The harness does not read it.
Deferrable bool
}
Loading
Loading