Repository navigation
Expand file tree
/
Copy patherrors.go
More file actions
440 lines (402 loc) · 14 KB
/
Copy patherrors.go
File metadata and controls
440 lines (402 loc) · 14 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
package toolsy
import (
"context"
"errors"
"fmt"
"strings"
"github.com/skosovsky/toolsy/textprocessor"
)
// Sentinel errors for toolsy. Use [errors.Is] to check.
var (
ErrToolNotFound = errors.New("tool not found")
ErrTimeout = errors.New("tool execution timeout")
ErrValidation = errors.New("validation failed")
ErrShutdown = errors.New("registry is shutting down")
ErrRegistryState = errors.New("registry runtime state is not initialized")
ErrStreamAborted = errors.New("stream aborted by caller")
ErrMaxCallsExceeded = errors.New("maximum session calls exceeded")
// ErrAsyncCollectedLimitExceeded is returned when background chunk collection exceeds WithMaxCollectedChunks.
ErrAsyncCollectedLimitExceeded = errors.New("toolsy: async collected chunks limit exceeded")
ErrBudgetExceeded = errors.New("budget exceeded")
)
// ErrorCode is a machine-readable tool execution error category.
type ErrorCode string
const (
CodeSchemaInvalid ErrorCode = "SCHEMA_INVALID"
CodeValidationFailed ErrorCode = "VALIDATION_FAILED"
CodeTimeout ErrorCode = "TIMEOUT"
CodeToolNotFound ErrorCode = "TOOL_NOT_FOUND"
CodeDependencyMissing ErrorCode = "DEPENDENCY_MISSING"
CodeInternal ErrorCode = "INTERNAL"
CodeShutdown ErrorCode = "SHUTDOWN"
CodeMaxCallsExceeded ErrorCode = "MAX_CALLS_EXCEEDED"
CodeRegistryNotReady ErrorCode = "REGISTRY_NOT_READY"
CodeToolsContractMissing ErrorCode = "TOOLS_CONTRACT_MISSING"
CodeBudgetExceeded ErrorCode = "BUDGET_EXCEEDED"
CodeStateCodecMissing ErrorCode = "STATE_CODEC_MISSING"
CodePolicyDenied ErrorCode = "POLICY_DENIED"
CodeCapabilityDenied ErrorCode = "CAPABILITY_DENIED"
CodeRemoteExecution ErrorCode = "REMOTE_EXECUTION"
)
// ToolError is the structured execution error envelope for orchestrator routing.
// Use [AsToolError] and [errors.Is] on [Err] for sentinel checks.
type ToolError struct {
Code ErrorCode
Retryable bool
Reason string
FixableArgs []string
SafeMessage string
Err error
}
// NewValidationError builds a non-retryable validation [ToolError].
func NewValidationError(reason string, fixableFields ...string) *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // SafeMessage optional for LLM-facing copy
Code: CodeValidationFailed,
Reason: reason,
Retryable: false,
FixableArgs: append([]string(nil), fixableFields...),
Err: ErrValidation,
}
}
// NewSchemaError builds a non-retryable schema or parse [ToolError].
func NewSchemaError(reason string) *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeSchemaInvalid,
Reason: reason,
Retryable: false,
}
}
// NewJSONParseError reports invalid tool argument JSON with details in [ToolError.Unwrap].
func NewJSONParseError(err error) *ToolError {
if err == nil {
return nil
}
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeSchemaInvalid,
Reason: "invalid JSON",
Retryable: false,
Err: err,
}
}
// NewInternalError wraps an internal failure as [ToolError].
// Technical details are available via [ToolError.Unwrap]; [ToolError.Reason] is generic.
func NewInternalError(err error) *ToolError {
if err == nil {
return nil
}
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeInternal,
Reason: "internal error",
Retryable: false,
Err: err,
}
}
// WithSafeMessage sets [ToolError.SafeMessage] for user-facing or LLM-safe copy.
func WithSafeMessage(te *ToolError, safe string) *ToolError {
if te == nil {
return nil
}
te.SafeMessage = safe
return te
}
// NewDependencyMissingError reports a missing or nil typed dependency.
func NewDependencyMissingError(key string) *ToolError {
reason := fmt.Sprintf("dependency %q is missing or nil", key)
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeDependencyMissing,
Reason: reason,
Retryable: false,
Err: errors.New(reason),
}
}
// NewToolNotFoundError reports an unknown tool name.
func NewToolNotFoundError() *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeToolNotFound,
Reason: ErrToolNotFound.Error(),
Retryable: false,
Err: ErrToolNotFound,
}
}
// NewTimeoutError reports execution timeout; set retryable when the orchestrator may retry.
func NewTimeoutError(retryable bool) *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeTimeout,
Reason: ErrTimeout.Error(),
Retryable: retryable,
Err: ErrTimeout,
}
}
// NewTimeoutErrorFrom reports execution timeout while preserving cause (e.g. [context.DeadlineExceeded]) in the unwrap chain.
func NewTimeoutErrorFrom(cause error, retryable bool) *ToolError {
if cause == nil {
return NewTimeoutError(retryable)
}
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeTimeout,
Reason: ErrTimeout.Error(),
Retryable: retryable,
Err: fmt.Errorf("%w: %w", ErrTimeout, cause),
}
}
// MapReadLimitError maps [textprocessor.ErrReadLimitExceeded] to [CodeValidationFailed] for LLM-facing tools.
// When maxBytes > 0, Reason includes the limit; otherwise a generic message is used.
// If maxBytes is 0, [textprocessor.ReadLimitMaxBytes] scans the unwrap chain for "exceeds N byte limit".
func MapReadLimitError(err error, maxBytes int) error {
if !textprocessor.IsReadLimitExceeded(err) {
return err
}
if maxBytes <= 0 {
maxBytes = textprocessor.ReadLimitMaxBytes(err)
}
if maxBytes > 0 {
return NewValidationError(fmt.Sprintf("response exceeds %d byte limit", maxBytes))
}
return NewValidationError("response exceeds byte limit")
}
// MapReadLimitErrorFor maps [textprocessor.ErrReadLimitExceeded] to [CodeValidationFailed] with a domain-specific subject.
// Optional hint is appended after the limit message (e.g. "use WithMaxPageBytes to raise the budget").
func MapReadLimitErrorFor(err error, maxBytes int, subject string, hint string) error {
if !textprocessor.IsReadLimitExceeded(err) {
return err
}
subject = strings.TrimSpace(subject)
if subject == "" {
return MapReadLimitError(err, maxBytes)
}
if maxBytes <= 0 {
maxBytes = textprocessor.ReadLimitMaxBytes(err)
}
var msg string
if maxBytes > 0 {
msg = fmt.Sprintf("%s exceeds %d byte limit", subject, maxBytes)
} else {
msg = fmt.Sprintf("%s exceeds byte limit", subject)
}
hint = strings.TrimSpace(hint)
if hint != "" {
msg += "; " + hint
}
return NewValidationError(msg)
}
// MapSandboxReadLimitError maps sandbox [textprocessor.ErrReadLimitExceeded] chains to [CodeValidationFailed].
// Returns nil for bare sentinel or non-sandbox-formatted limits; callers should use [MapReadLimitError].
func MapSandboxReadLimitError(err error) error {
if !textprocessor.IsReadLimitExceeded(err) {
return nil
}
subject := textprocessor.ReadLimitSubject(err)
maxBytes := textprocessor.ReadLimitMaxBytes(err)
if subject == "" && maxBytes <= 0 {
return nil
}
if maxBytes <= 0 {
maxBytes = defaultSandboxReadLimitBytes
}
return MapReadLimitErrorFor(err, maxBytes, subject, "")
}
const (
// defaultSandboxReadLimitBytes matches [sandboxfs.DefaultMaxSandboxOutputBytes] (import cycle).
defaultSandboxReadLimitBytes = 256 * 1024
)
// isContextInterrupt reports ctx cancel/deadline/timeout in err's unwrap chain.
func isContextInterrupt(err error) bool {
return errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, ErrTimeout)
}
// IsContextInterrupt reports whether err is or wraps a context cancel, deadline, or [ErrTimeout].
func IsContextInterrupt(err error) bool {
return isContextInterrupt(err)
}
// NewShutdownError reports registry shutdown.
func NewShutdownError() *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeShutdown,
Reason: ErrShutdown.Error(),
Retryable: false,
Err: ErrShutdown,
}
}
// NewMaxCallsExceededError reports session call admission exhaustion.
func NewMaxCallsExceededError() *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeMaxCallsExceeded,
Reason: ErrMaxCallsExceeded.Error(),
Retryable: false,
Err: ErrMaxCallsExceeded,
}
}
// NewRegistryStateError reports uninitialized registry runtime state.
func NewRegistryStateError() *ToolError {
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeRegistryNotReady,
Reason: ErrRegistryState.Error(),
Retryable: false,
Err: ErrRegistryState,
}
}
// NewToolsContractMissingError reports required tools missing from the registry contract.
func NewToolsContractMissingError(required, missing []string) *ToolError {
reason := fmt.Sprintf("missing required tools: %v (contract requires %v)", missing, required)
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeToolsContractMissing,
Reason: reason,
Retryable: false,
FixableArgs: append([]string(nil), missing...),
Err: errors.New(reason),
}
}
// NewStateCodecMissingError reports a session state key without a registered codec in strict mode.
func NewStateCodecMissingError(key string) *ToolError {
reason := fmt.Sprintf("no state codec registered for key %q", key)
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeStateCodecMissing,
Reason: reason,
Retryable: false,
FixableArgs: []string{key},
Err: errors.New(reason),
}
}
// NewSnapshotHydrationError reports a fatal snapshot import/export failure (version mismatch, corrupt payload).
func NewSnapshotHydrationError(reason string, err error) *ToolError {
reason = strings.TrimSpace(reason)
if reason == "" {
reason = "session snapshot hydration failed"
}
if err == nil {
err = errors.New(reason)
}
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeInternal,
Reason: reason,
Retryable: false,
Err: err,
}
}
// NewBudgetExceededError reports a token or execution budget denial.
func NewBudgetExceededError(reason string) *ToolError {
reason = strings.TrimSpace(reason)
if reason == "" {
reason = ErrBudgetExceeded.Error()
}
return &ToolError{ //nolint:exhaustruct_v5 // optional envelope fields omitted by design
Code: CodeBudgetExceeded,
Reason: reason,
Retryable: true,
Err: ErrBudgetExceeded,
}
}
// NewToolNotFoundInSubsetError reports an unknown tool name when building a registry subset.
func NewToolNotFoundInSubsetError(name string) *ToolError {
te := NewToolNotFoundError()
te.Reason = fmt.Sprintf("unknown tool in subset: %q", name)
return te
}
func (e *ToolError) Error() string {
if e == nil {
return ""
}
if e.Reason != "" {
return fmt.Sprintf("%s: %s", e.Code, e.Reason)
}
if e.SafeMessage != "" {
return fmt.Sprintf("%s: %s", e.Code, e.SafeMessage)
}
return string(e.Code)
}
func (e *ToolError) Unwrap() error { return e.Err }
// AsToolError returns a [*ToolError] when err is or wraps one.
func AsToolError(err error) (*ToolError, bool) {
if te, ok := errors.AsType[*ToolError](err); ok {
return te, true
}
return nil, false
}
// ClientCorrectable reports whether the error code is correctable by the caller (LLM/agent).
//
// Returns true for SCHEMA_INVALID, VALIDATION_FAILED, and TOOL_NOT_FOUND — the LLM can fix
// arguments or pick another tool. Returns false for orchestrator/host issues such as
// DEPENDENCY_MISSING, TOOLS_CONTRACT_MISSING, INTERNAL, TIMEOUT, SHUTDOWN,
// MAX_CALLS_EXCEEDED, and REGISTRY_NOT_READY; route those by comparing [ToolError.Code] explicitly.
//
// Example:
//
// te, ok := AsToolError(err)
// if !ok {
// return handleUnexpected(err)
// }
// switch {
// case ClientCorrectable(te.Code):
// return retryWithLLMFix(te)
// case te.Code == CodeTimeout && te.Retryable:
// return retryLater()
// case te.Code == CodeToolsContractMissing:
// return registerMissingTools(te.FixableArgs)
// default:
// return escalate(te)
// }
func ClientCorrectable(code ErrorCode) bool {
switch code {
case CodeValidationFailed, CodeSchemaInvalid, CodeToolNotFound:
return true
case CodeTimeout,
CodeDependencyMissing,
CodeInternal,
CodeShutdown,
CodeMaxCallsExceeded,
CodeRegistryNotReady,
CodeToolsContractMissing,
CodeBudgetExceeded,
CodeStateCodecMissing,
CodePolicyDenied,
CodeCapabilityDenied,
CodeRemoteExecution:
return false
default:
return false
}
}
func orchestratorSystemCode(code ErrorCode) bool {
switch code {
case CodeInternal, CodeTimeout, CodeShutdown, CodeMaxCallsExceeded, CodeRegistryNotReady, CodeStateCodecMissing:
return true
case CodeSchemaInvalid,
CodeValidationFailed,
CodeToolNotFound,
CodeDependencyMissing,
CodeToolsContractMissing,
CodeBudgetExceeded,
CodePolicyDenied,
CodeCapabilityDenied,
CodeRemoteExecution:
return false
default:
return false
}
}
func clientCorrectable(err error) bool {
te, ok := AsToolError(err)
if !ok {
return false
}
return ClientCorrectable(te.Code)
}
func wrapJSONParseError(err error) error {
return NewJSONParseError(err)
}
// wrapYieldError wraps an error returned by the yield callback so that callers can detect
// stream abortion via [errors.Is](err, ErrStreamAborted). The original cause is preserved for Unwrap.
func wrapYieldError(err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%w: %w", ErrStreamAborted, err)
}
// requiresOutcomeReconciliation guards known post-dispatch contract failures
// before generic timeout, retry and argument-repair classification.
func requiresOutcomeReconciliation(err error) bool {
var outcome *OperationOutcomeError
var result *ResultContractError
return errors.As(err, &outcome) || errors.As(err, &result)
}