-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool.go
More file actions
649 lines (581 loc) · 22.4 KB
/
Copy pathtool.go
File metadata and controls
649 lines (581 loc) · 22.4 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
package agentgo
import (
"context"
"encoding/json"
"fmt"
"math"
"strings"
)
// ---------------------------------------------------------------------------
// Tool Progress
// ---------------------------------------------------------------------------
// toolProgressKey is the context key for tool progress callbacks.
type toolProgressKey struct{}
// ProgressPayloadKind distinguishes structured progress update semantics.
type ProgressPayloadKind string
const (
ProgressToolStart ProgressPayloadKind = "tool_start"
ProgressToolEnd ProgressPayloadKind = "tool_end"
ProgressToolDelta ProgressPayloadKind = "tool_delta"
ProgressThinking ProgressPayloadKind = "thinking"
ProgressSummary ProgressPayloadKind = "summary"
ProgressToolError ProgressPayloadKind = "tool_error"
ProgressTurnCounter ProgressPayloadKind = "turn_counter"
ProgressRetry ProgressPayloadKind = "retry"
ProgressContext ProgressPayloadKind = "context"
)
// ProgressPayload is the structured progress envelope emitted by tools.
// Message carries complete text; presentation limits belong to consumers.
type ProgressPayload struct {
Kind ProgressPayloadKind `json:"kind"`
Agent string `json:"agent,omitempty"`
Tool string `json:"tool,omitempty"`
Summary string `json:"summary,omitempty"`
Delta string `json:"delta,omitempty"`
Thinking string `json:"thinking,omitempty"`
Message string `json:"message,omitempty"`
Turn int `json:"turn,omitempty"`
Attempt int `json:"attempt,omitempty"`
MaxRetries int `json:"max_retries,omitempty"`
IsError bool `json:"is_error,omitempty"`
Args json.RawMessage `json:"args,omitempty"`
Meta json.RawMessage `json:"meta,omitempty"`
// DeltaKind distinguishes what kind of content Delta carries when Kind is
// ProgressToolDelta. Consumers can use this to filter/render text vs
// tool-call argument JSON differently.
DeltaKind DeltaKind `json:"delta_kind,omitempty"`
}
// ToolProgressFunc is a callback for reporting tool execution progress.
// Tools call ReportToolProgress to emit partial results during long operations.
type ToolProgressFunc func(progress ProgressPayload)
// WithToolProgress injects a progress callback into the context.
func WithToolProgress(ctx context.Context, fn ToolProgressFunc) context.Context {
return context.WithValue(ctx, toolProgressKey{}, fn)
}
// ReportToolProgress reports structured progress during tool execution.
// Silently ignored if no callback is registered in the context.
func ReportToolProgress(ctx context.Context, progress ProgressPayload) {
if progress.Kind == "" {
progress.Kind = ProgressSummary
}
if fn, ok := ctx.Value(toolProgressKey{}).(ToolProgressFunc); ok {
fn(progress)
}
}
// ---------------------------------------------------------------------------
// Tool Calls & Results
// ---------------------------------------------------------------------------
// ToolCall represents a tool invocation request from the LLM.
//
// When the LLM emits args that don't parse as JSON (common cause: stream
// truncation, provider format bug), Args is replaced with "{}" so the
// surrounding Message stays JSON-serializable for persistence; the original
// payload and parser diagnostic are preserved in ArgsRawText / ArgsParseError.
// Downstream schema validation short-circuits on ArgsInvalid and surfaces the
// captured raw text — pointing at the real root cause instead of running
// "missing field" checks against the {} placeholder.
type ToolCall struct {
ID string `json:"id" codec:"id"`
Name string `json:"name" codec:"name"`
Args json.RawMessage `json:"args" codec:"args"`
ArgsInvalid bool `json:"args_invalid,omitempty" codec:"args_invalid,omitempty"`
ArgsRawText string `json:"args_raw_text,omitempty" codec:"args_raw_text,omitempty"`
ArgsParseError string `json:"args_parse_error,omitempty" codec:"args_parse_error,omitempty"`
// ThoughtSignature is an opaque provider reasoning signature (Gemini 3) that
// must be persisted and replayed verbatim across turns. Empty when absent.
ThoughtSignature string `json:"thought_signature,omitempty" codec:"thought_signature,omitempty"`
}
// ToolResult represents a tool execution outcome.
type ToolResult struct {
ToolCallID string `json:"tool_call_id"`
ToolName string `json:"-"` // internal: for toolErrors tracking
Content json.RawMessage `json:"content,omitempty"`
ContentBlocks []ContentBlock `json:"-"` // rich content (images); not serialized
IsError bool `json:"is_error,omitempty"`
Details any `json:"details,omitempty"` // optional metadata for UI display/logging
}
// ---------------------------------------------------------------------------
// Tool Interface
// ---------------------------------------------------------------------------
// Tool defines the minimal tool interface.
// Timeout control goes through context.Context.
// Tools can report execution progress via ReportToolProgress(ctx, payload).
type Tool interface {
Name() string
Description() string
Schema() map[string]any
Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}
// ToolLabeler is an optional interface for tools to provide a human-readable label.
type ToolLabeler interface {
Label() string
}
// StrictSchemaTool is an optional interface for tools that want provider-side
// strict schema enforcement on their arguments (e.g. OpenAI's strict tool
// calling). Returning true forwards `strict: true` and triggers schema
// normalisation in compatible providers; returning false explicitly disables
// strict on providers that default to it (e.g. OpenAI Responses API).
//
// Provider adapters own strict-schema normalization and validation because the
// supported subset differs by provider. Tool authors should consult the
// adapter documentation for provider-specific restrictions.
type StrictSchemaTool interface {
StrictSchema() bool
}
// ContentTool is an optional interface for tools that return rich content
// (e.g., images). When a tool implements ContentTool, the agent loop calls
// ExecuteContent instead of Execute, enabling multi-block responses with
// text + image content blocks.
type ContentTool interface {
ExecuteContent(ctx context.Context, args json.RawMessage) ([]ContentBlock, error)
}
// Previewer is an optional interface for tools that can compute a preview
// (e.g., diff) before execution. The agent loop calls Preview and emits the
// result as EventToolExecUpdate so the UI can display it before the tool runs.
// A preview error is returned to the model and prevents tool execution.
type Previewer interface {
Preview(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}
// ValidationResult is the verdict from a Validator.
//
// A failure (OK=false) is surfaced to the LLM as a normal tool_result with
// IsError=true. The intent is "input is structurally legal but semantically
// wrong" — e.g. write before read, mtime drift, deny rule. The LLM reads
// Message and self-corrects (typically by issuing the right tool first and
// retrying), without prompting the user.
//
// ErrorCode is optional, intended for stable identification by tests and
// prompts; it is not interpreted by the kernel.
type ValidationResult struct {
OK bool
Message string
ErrorCode int
}
// Validator is an optional interface for tools that want to short-circuit
// before Preview / ToolGate / Execute when the input is structurally legal
// but semantically wrong. Validators MUST NOT prompt the user, MUST NOT
// mutate persistent state, and SHOULD be cheap (read-only lookups, stat).
//
// Returning OK=false produces a tool_result the LLM can act on; returning
// OK=true continues the normal pipeline.
type Validator interface {
Validate(ctx context.Context, args json.RawMessage) ValidationResult
}
// ---------------------------------------------------------------------------
// ToolGate — pluggable approval / policy hook
// ---------------------------------------------------------------------------
// GateRequest carries the inputs that a ToolGate sees for one tool call.
// Tool exposes the underlying tool instance so gates can typeswitch against
// any tool-specific marker interfaces they care about (e.g. capability hints)
// without the kernel needing to know those interfaces.
type GateRequest struct {
Tool Tool
Call ToolCall
ToolLabel string // resolved via ToolLabeler when available
Preview json.RawMessage // resolved via Previewer when available; may be nil
}
// GateDecision is the gate's verdict for one tool call.
//
// Allowed=true => execute the tool with Call.Args, or with UpdatedArgs when
// set — the gate's way to return a policy-side rewrite (hook updated_input,
// interactive data backfill) so the tool executes exactly what was approved.
// Allowed=false => return Reason as the tool result error; do not execute.
// UpdatedArgs is ignored on a denial.
//
// A nil decision is treated as Allowed=true (the gate has no opinion).
type GateDecision struct {
Allowed bool
Reason string
UpdatedArgs json.RawMessage
}
// ToolGate is the pluggable hook called once per tool call, after argument
// validation and after the optional Previewer pass, but before tool
// execution. Returning a non-nil error is treated as deny with the error
// message as the reason. The kernel does not perform any permission
// reasoning of its own; install a gate (or leave it nil) to control policy.
type ToolGate func(ctx context.Context, req GateRequest) (*GateDecision, error)
// DeferFilter controls deferred tool loading for the LLM.
// When a tool in the agent's tool list implements DeferFilter:
// - IsDeferred returns true → tool schema is excluded from the API request
// - WasDeferred returns true → tool schema is sent with defer_loading: true
//
// Unactivated deferred tools are excluded entirely. Once activated via
// tool_reference, they are sent with defer_loading: true so the API server
// manages their context loading. Tools remain registered for execution
// regardless — only their API visibility changes.
//
// IsDeferred is also used by the system prompt builder to exclude unactivated
// tools from the tool description section (they appear in
// <available-deferred-tools> by name only).
type DeferFilter interface {
// IsDeferred reports whether the tool is deferred and not yet activated.
// Unactivated deferred tools are excluded from the API request entirely.
IsDeferred(toolName string) bool
// WasDeferred reports whether the tool was originally in the deferred set
// (regardless of activation). Activated deferred tools are sent with
// defer_loading: true.
WasDeferred(toolName string) bool
}
// DeferActivator is an optional extension of DeferFilter that supports
// pre-activating deferred tools (e.g. when restoring a session whose
// history contains tool_reference blocks for previously activated tools).
type DeferActivator interface {
DeferFilter
Activate(names ...string)
}
// ReactivateDeferred scans restored messages for tool_reference blocks and
// pre-activates them via the DeferActivator found in tools. This must be
// called after restoring a session to avoid "Tool reference not found" errors.
func ReactivateDeferred(tools []Tool, msgs []AgentMessage) {
var activator DeferActivator
for _, t := range tools {
if a, ok := t.(DeferActivator); ok {
activator = a
break
}
}
if activator == nil {
return
}
var names []string
for _, am := range msgs {
msg, ok := am.ToMessage()
if !ok {
continue
}
for _, b := range msg.Content {
if b.Type == ContentToolRef && b.ToolName != "" {
names = append(names, b.ToolName)
}
}
}
if len(names) > 0 {
activator.Activate(names...)
}
}
// ---------------------------------------------------------------------------
// Tool Behavior Interfaces (optional)
// ---------------------------------------------------------------------------
// ReadOnlyTool is an optional interface for tools that declare read-only behavior.
// Read-only tools are eligible for concurrent execution by default.
// The args parameter allows input-dependent classification
// (e.g., bash is read-only for "ls" but not for "rm").
type ReadOnlyTool interface {
ReadOnly(args json.RawMessage) bool
}
// ConcurrencySafeTool is an optional interface for tools that declare
// whether they can safely execute concurrently with other tools.
// Takes precedence over ReadOnlyTool for concurrency scheduling.
type ConcurrencySafeTool interface {
ConcurrencySafe(args json.RawMessage) bool
}
// InterruptBehavior controls what happens when a queued user message arrives
// while a tool is still running.
type InterruptBehavior string
const (
InterruptBehaviorBlock InterruptBehavior = "block"
InterruptBehaviorCancel InterruptBehavior = "cancel"
)
// InterruptBehaviorTool is an optional interface for tools that declare whether
// they should be cancelled or allowed to finish when a steering message arrives.
// Defaults to InterruptBehaviorBlock when not implemented.
type InterruptBehaviorTool interface {
InterruptBehavior(args json.RawMessage) InterruptBehavior
}
// ActivityDescriber is an optional interface for tools that provide
// a human-readable activity description for UI display.
type ActivityDescriber interface {
ActivityDescription(args json.RawMessage) string
}
// isToolConcurrencySafe checks whether a tool call is safe for concurrent execution.
// Priority: ConcurrencySafeTool > ReadOnlyTool > false.
func isToolConcurrencySafe(tool Tool, args json.RawMessage) bool {
if cs, ok := tool.(ConcurrencySafeTool); ok {
return cs.ConcurrencySafe(args)
}
if ro, ok := tool.(ReadOnlyTool); ok {
return ro.ReadOnly(args)
}
return false
}
func toolInterruptBehavior(tool Tool, args json.RawMessage) InterruptBehavior {
if ib, ok := tool.(InterruptBehaviorTool); ok {
switch behavior := ib.InterruptBehavior(args); behavior {
case InterruptBehaviorCancel:
return InterruptBehaviorCancel
case InterruptBehaviorBlock:
return InterruptBehaviorBlock
}
}
return InterruptBehaviorBlock
}
// ToolExecution combines the model-issued ToolCall with the Harness execution
// coordinate for one physical attempt. Middleware may adjust Call.Args, but
// must preserve Execution and the call's ID and Name. AgentLoop uses Call.ID as
// Execution.ID so protocol and execution events share one tool-call identity.
type ToolExecution struct {
Execution
Call ToolCall
}
// ToolExecuteFunc advances one complete tool execution through validation,
// authorization and execution. It is the next function in middleware chains.
type ToolExecuteFunc func(context.Context, ToolExecution) (ToolResult, error)
// ToolMiddleware wraps tool execution with cross-cutting concerns.
// Call next to continue the chain; skip next to short-circuit execution.
// Example: logging, timing, argument/result modification, audit.
type ToolMiddleware func(context.Context, ToolExecution, ToolExecuteFunc) (ToolResult, error)
// ---------------------------------------------------------------------------
// FuncTool
// ---------------------------------------------------------------------------
// FuncTool wraps a function as a Tool (convenience helper).
type FuncTool struct {
name string
description string
schema map[string]any
fn func(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}
func NewFuncTool(name, description string, schema map[string]any, fn func(ctx context.Context, args json.RawMessage) (json.RawMessage, error)) *FuncTool {
return &FuncTool{name: name, description: description, schema: schema, fn: fn}
}
func (t *FuncTool) Name() string { return t.name }
func (t *FuncTool) Description() string { return t.description }
func (t *FuncTool) Schema() map[string]any { return t.schema }
func (t *FuncTool) Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error) {
return t.fn(ctx, args)
}
// ---------------------------------------------------------------------------
// Tool Argument Validation
// ---------------------------------------------------------------------------
// validateToolArgs validates a tool call against the schema without changing
// the model's arguments. Validation failures are returned to the model as tool
// results so it can correct the complete set of issues on the next turn.
func validateToolArgs(tool Tool, call ToolCall) error {
if call.ArgsInvalid {
return fmt.Errorf(
"%w: %s received malformed JSON arguments: %s\nraw args: %s",
ErrToolValidation, tool.Name(), call.ArgsParseError, call.ArgsRawText,
)
}
schema := tool.Schema()
if schema == nil {
return nil
}
args := call.Args
if len(args) == 0 {
args = []byte("{}")
}
var value any
if err := json.Unmarshal(args, &value); err != nil {
return fmt.Errorf("%w: %s received invalid JSON arguments: %v",
ErrToolValidation, tool.Name(), err)
}
issues := validateSchemaValue(value, schema, "")
if len(issues) > 0 {
return &ToolValidationError{ToolName: tool.Name(), Issues: issues}
}
return nil
}
func validateSchemaValue(value any, schema map[string]any, path string) []ValidationIssue {
var issues []ValidationIssue
issuePath := path
if issuePath == "" {
issuePath = "arguments"
}
types, hasTypes := schemaTypeNames(schema["type"])
if hasTypes && !matchesSchemaType(value, types) {
return []ValidationIssue{{
Kind: IssueType,
Path: issuePath,
Expected: strings.Join(types, " or "),
Received: jsonTypeName(value),
Hint: mismatchHint(value, types),
}}
}
if values, ok := enumValues(schema["enum"]); ok && !containsJSONValue(values, value) {
issues = append(issues, ValidationIssue{
Kind: IssueValue,
Path: issuePath,
Expected: formatValues(values),
Received: formatValue(value),
})
}
object, isObject := value.(map[string]any)
if isObject && (containsString(types, "object") || schema["properties"] != nil || schema["required"] != nil) {
properties, _ := schema["properties"].(map[string]any)
if required, ok := stringValues(schema["required"]); ok {
for _, name := range required {
if _, exists := object[name]; !exists {
issues = append(issues, ValidationIssue{
Kind: IssueMissing,
Path: propertyPath(path, name),
})
}
}
}
for name, child := range object {
childPath := propertyPath(path, name)
if rawSchema, exists := properties[name]; exists {
if childSchema, ok := rawSchema.(map[string]any); ok {
issues = append(issues, validateSchemaValue(child, childSchema, childPath)...)
}
continue
}
additional := schema["additionalProperties"]
if additional == false {
issues = append(issues, ValidationIssue{Kind: IssueUnknown, Path: childPath})
} else if additionalSchema, ok := additional.(map[string]any); ok {
issues = append(issues, validateSchemaValue(child, additionalSchema, childPath)...)
}
}
}
array, isArray := value.([]any)
if isArray && (containsString(types, "array") || schema["items"] != nil) {
if itemSchema, ok := schema["items"].(map[string]any); ok {
for i, item := range array {
issues = append(issues, validateSchemaValue(item, itemSchema, itemPath(path, i))...)
}
}
}
return issues
}
func schemaTypeNames(value any) ([]string, bool) {
switch value := value.(type) {
case string:
return []string{value}, value != ""
case []string:
return value, len(value) > 0
case []any:
types := make([]string, 0, len(value))
for _, item := range value {
typ, ok := item.(string)
if !ok || typ == "" {
return nil, false
}
types = append(types, typ)
}
return types, len(types) > 0
default:
return nil, false
}
}
func stringValues(value any) ([]string, bool) {
switch value := value.(type) {
case nil:
return nil, false
case []string:
return value, true
case []any:
values := make([]string, 0, len(value))
for _, item := range value {
text, ok := item.(string)
if !ok {
return nil, false
}
values = append(values, text)
}
return values, true
default:
return nil, false
}
}
func enumValues(value any) ([]any, bool) {
switch value := value.(type) {
case []any:
return value, true
case []string:
values := make([]any, len(value))
for i, item := range value {
values[i] = item
}
return values, true
default:
return nil, false
}
}
func matchesSchemaType(value any, types []string) bool {
actual := jsonTypeName(value)
for _, typ := range types {
if typ == actual || typ == "number" && actual == "integer" {
return true
}
}
return false
}
func containsJSONValue(values []any, target any) bool {
targetJSON, err := json.Marshal(target)
if err != nil {
return false
}
for _, value := range values {
valueJSON, err := json.Marshal(value)
if err == nil && string(valueJSON) == string(targetJSON) {
return true
}
}
return false
}
func mismatchHint(value any, types []string) string {
text, ok := value.(string)
if !ok {
return ""
}
trimmed := strings.TrimSpace(text)
if containsString(types, "array") && strings.HasPrefix(trimmed, "[") {
return `Looks like a JSON-encoded array — pass the value directly (e.g. ["a","b"]), not wrapped in quotes.`
}
if containsString(types, "object") && strings.HasPrefix(trimmed, "{") {
return `Looks like a JSON-encoded object — pass the value directly (e.g. {"k":"v"}), not wrapped in quotes.`
}
return ""
}
func jsonTypeName(value any) string {
switch value := value.(type) {
case nil:
return "null"
case bool:
return "boolean"
case string:
return "string"
case float64:
if value == math.Trunc(value) {
return "integer"
}
return "number"
case []any:
return "array"
case map[string]any:
return "object"
default:
return fmt.Sprintf("%T", value)
}
}
func propertyPath(parent, property string) string {
if parent == "" {
return property
}
return parent + "." + property
}
func itemPath(parent string, index int) string {
return fmt.Sprintf("%s[%d]", parent, index)
}
func containsString(values []string, target string) bool {
for _, value := range values {
if value == target {
return true
}
}
return false
}
func formatValues(values []any) string {
formatted := make([]string, len(values))
for i, value := range values {
formatted[i] = formatValue(value)
}
return "[" + strings.Join(formatted, ", ") + "]"
}
func formatValue(value any) string {
if text, ok := value.(string); ok {
return fmt.Sprintf("%q", text)
}
return fmt.Sprint(value)
}