Repository navigation
Expand file tree
/
Copy pathcallback.go
More file actions
727 lines (651 loc) · 29.7 KB
/
Copy pathcallback.go
File metadata and controls
727 lines (651 loc) · 29.7 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// Package callback is the wire contract of the hive-side callback endpoint
// the Crux runtime calls for hive-provided capabilities (hivecommons/hive#14138
// stage 2; src/docs/design/crux.md "Credentials and hive-provided
// capabilities"). It imports only the standard library and crux/api (itself
// stdlib-only), so a hive that mounts it links nothing of the runtime and a
// runtime that calls it links nothing of hive.
//
// The direction is runtime → hive. The runtime never holds the GitHub App
// private key, the canary registry or any other hive-owned credential; it
// asks hive for a short-lived scoped token, a scan verdict, a created PR, and
// reports accounting and conditions back. Capabilities is the one interface
// set both ends implement: *Client over HTTP, hive's pkg/cruxhost directly.
// Every method fails closed: an unreachable or refusing hive is an error the
// caller treats as a refusal, never a less-safe default.
//
// Transport follows crux/api: HTTP+JSON under /v1, api.Error bodies with
// stable codes, a 0600 unix socket in a uid-owned 0700 directory, optional
// TCP only behind a bearer token, and a token-less server that answers only
// requests it saw arrive on its own socket.
//
// GET /v1/health server is up; which capabilities exist
// POST /v1/tokens mint a scoped GitHub token
// POST /v1/github/rest record one relayed GitHub REST response
// GET /v1/github/rate-limit shared core-bucket snapshot
// POST /v1/usage record inference token usage
// POST /v1/scan/canary scan a GitHub write body for canaries
// POST /v1/scan/text scan tool payload text
// POST /v1/conditions observe or clear a runtime condition
// GET /v1/linear/credential the Linear credential to inject
// POST /v1/pulls open a pull request as the hive's App
// GET /v1/policy the host policy snapshot (stage 4)
// POST /v1/policy/repo-auto-merge whether auto-merge is enabled for a repo
// PUT /v1/inference/routes/{agent} route an agent's inference traffic (stage 4)
// DELETE /v1/inference/routes/{agent} clear that route
// POST /v1/effects begin a journaled external mutation (stage 4)
// POST /v1/effects/{id}/end report how it ended
// POST /v1/tokens/mint issue an agent's short-lived mint credential (stage 4)
// GET /v1/bob/credential the Bob API key and where it came from (stage 4)
// POST /v1/knowledge/advise mid-task knowledge advice for a scope an agent entered (hivecommons/hive#17157)
package callback
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"time"
)
// Version is the API version every route is prefixed with.
const Version = "v1"
// Routes.
const (
PathHealth = "/" + Version + "/health"
PathTokens = "/" + Version + "/tokens"
PathGitHubREST = "/" + Version + "/github/rest"
PathGitHubRateLimit = "/" + Version + "/github/rate-limit"
PathUsage = "/" + Version + "/usage"
PathScanCanary = "/" + Version + "/scan/canary"
PathScanText = "/" + Version + "/scan/text"
PathConditions = "/" + Version + "/conditions"
PathLinearCredential = "/" + Version + "/linear/credential"
PathPulls = "/" + Version + "/pulls"
PathPolicy = "/" + Version + "/policy"
PathRepoAutoMerge = "/" + Version + "/policy/repo-auto-merge"
PathInferenceRoutes = "/" + Version + "/inference/routes"
PathEffects = "/" + Version + "/effects"
PathAgentMint = "/" + Version + "/tokens/mint"
PathBobCredential = "/" + Version + "/bob/credential"
// PathKnowledgeAdvise is the mid-task knowledge adviser route.
PathKnowledgeAdvise = "/" + Version + "/knowledge/advise"
)
// InferenceRoutePath is the route for one agent's inference route.
func InferenceRoutePath(agent string) string {
return PathInferenceRoutes + "/" + url.PathEscape(agent)
}
// EffectEndPath is the route that ends the effect begun as id.
func EffectEndPath(id string) string {
return PathEffects + "/" + url.PathEscape(id) + "/end"
}
// Environment variables.
const (
// SocketEnvVar overrides the default unix socket path hive serves the
// callback endpoint on and the runtime dials.
SocketEnvVar = "CRUX_HIVE_SOCKET"
// TokenEnvVar is the bearer token hive requires and the runtime presents.
// Optional on the socket (the file mode is the credential), required
// for TCP.
TokenEnvVar = "CRUX_HIVE_TOKEN"
// ListenEnvVar is an optional loopback TCP address hive also serves on
// (the k8s sidecar-container option, where the containers share the
// pod's network namespace). It always requires TokenEnvVar and is
// refused off loopback: the listener is plain http.
ListenEnvVar = "CRUX_HIVE_LISTEN"
// SocketName is the socket file name; it sits next to the runtime's
// crux.sock in the same private directory.
SocketName = "hive.sock"
// socketDirName mirrors crux/config.ServeSocketDirName.
socketDirName = "crux"
)
// File modes, the same as the runtime socket's.
const (
SocketMode os.FileMode = 0o600
SocketDirMode os.FileMode = 0o700
)
// Media type.
const ContentTypeJSON = "application/json"
// Error codes carried in api.Error bodies.
const (
CodeUnauthorized = "unauthorized"
CodeBadRequest = "bad_request"
// CodeNotConfigured is a route for a capability this hive does not have
// (no GitHub App, no canary registry, no Linear). The runtime treats it
// exactly as the nil seam it stands in for.
CodeNotConfigured = "not_configured"
// CodeUpstream is a configured capability whose own upstream (GitHub,
// Linear) refused; the message says why.
CodeUpstream = "upstream_error"
// CodeHive is an unexpected hive-side failure.
CodeHive = "hive_error"
// CodeEffectDenied is POST /v1/effects refused by hive's mutation
// boundary (the fence or the journal said no); the runtime maps it to
// effects.ErrDenied.
CodeEffectDenied = "effect_denied"
// CodeEffectUnknown is an end for an id hive is not holding: it was
// never begun, or already ended, or hive restarted in between.
CodeEffectUnknown = "effect_unknown"
// CodeForbidden is a request hive understood and refused on identity
// grounds: POST /v1/knowledge/advise for an agent this runtime does not
// own, or for a kick the agent is no longer in.
CodeForbidden = "forbidden"
// CodeRateLimited is a request hive refused because the runtime is
// asking more often than the contract allows (POST /v1/knowledge/advise:
// a second call in flight for one agent, or a third evaluation of one
// scope in one kick).
CodeRateLimited = "rate_limited"
)
// ConditionClassUnavailable is the runtime condition class reserved for
// "the hive callback endpoint is unreachable"; Client.Status carries it
// locally and stage 4 surfaces it on the runtime's health route.
const ConditionClassUnavailable = "hive_callback_unavailable"
// DefaultTimeout bounds one callback when the caller's context has no
// deadline of its own. Fail-closed answers are cheap, so a dead socket
// costs at most this per call.
const DefaultTimeout = 5 * time.Second
// Sentinel errors a caller can test with errors.Is. Both are refusals.
var (
// ErrUnavailable wraps a transport failure, timeout or 5xx: hive could
// not answer.
ErrUnavailable = errors.New("hive callback endpoint unavailable")
// ErrUnauthorized wraps a 401: hive rejected the runtime's credential.
// It is never retried with another credential.
ErrUnauthorized = errors.New("hive callback endpoint rejected the bearer token")
// ErrNotConfigured wraps a 404 CodeNotConfigured.
ErrNotConfigured = errors.New("capability not configured on this hive")
// ErrEffectDenied wraps a 403 CodeEffectDenied.
ErrEffectDenied = errors.New("hive mutation boundary denied the effect")
// ErrEffectUnknown wraps a 404 CodeEffectUnknown.
ErrEffectUnknown = errors.New("hive is not holding that effect")
// ErrForbidden wraps a 403 CodeForbidden. A capability returns it for an
// identity mismatch; the server answers 403 for it.
ErrForbidden = errors.New("hive refused the request for this agent or kick")
// ErrRateLimited wraps a 429 CodeRateLimited. A capability returns it to
// refuse an over-frequent call; the server answers 429 for it.
ErrRateLimited = errors.New("hive refused the request: too many calls")
// ErrInvalidRequest is returned by a capability for a request body that
// parsed but breaks the contract (an over-long pane tail, an unknown
// scope kind); the server answers 400 for it.
ErrInvalidRequest = errors.New("invalid request")
)
// DefaultSocket is the socket path hive and the runtime agree on when
// neither is told otherwise: $CRUX_HIVE_SOCKET if set, else
// $XDG_RUNTIME_DIR/crux/hive.sock, else <tmp>/crux-<uid>/hive.sock. The
// rule is crux/config.DefaultServeSocket's with a different file name so the
// two sockets share one private directory.
func DefaultSocket() string {
if p := os.Getenv(SocketEnvVar); p != "" {
return p
}
return filepath.Join(DefaultSocketDir(), SocketName)
}
// DefaultSocketDir is the directory DefaultSocket places the socket in.
func DefaultSocketDir() string {
if dir := os.Getenv("XDG_RUNTIME_DIR"); dir != "" {
return filepath.Join(dir, socketDirName)
}
return filepath.Join(os.TempDir(), fmt.Sprintf("%s-%d", socketDirName, os.Getuid()))
}
// Health is the body of GET /v1/health.
type Health struct {
Version string `json:"version"`
// Capabilities names the capabilities this hive has configured, as the
// Capability* constants.
Capabilities []string `json:"capabilities"`
}
// Capability names, as Health reports them.
const (
CapabilityTokens = "tokens"
CapabilityGitHubREST = "github_rest"
CapabilityUsage = "usage"
CapabilityCanary = "canary"
CapabilityText = "text"
CapabilityConditions = "conditions"
CapabilityLinear = "linear"
CapabilityPulls = "pulls"
// CapabilityPolicy covers both policy routes. It is served only by a
// Capabilities that also implements PolicySource.
CapabilityPolicy = "policy"
// CapabilityInferenceRoutes covers the inference route routes; served
// only by a Capabilities that also implements InferenceRouter.
CapabilityInferenceRoutes = "inference_routes"
// CapabilityEffects covers the effect routes; served only by a
// Capabilities that also implements EffectBoundary.
CapabilityEffects = "effects"
// CapabilityAgentMint covers POST /v1/tokens/mint; served only by a
// Capabilities that also implements AgentMinter (hive's opt-in mint).
CapabilityAgentMint = "agent_mint"
// CapabilityBob covers GET /v1/bob/credential; served only by a
// Capabilities that also implements BobCredentials.
CapabilityBob = "bob"
// CapabilityKnowledgeAdvise covers POST /v1/knowledge/advise; served only
// by a Capabilities that also implements KnowledgeAdvisers, and only
// while the hive's knowledge.sidecar_advise is on (default off).
CapabilityKnowledgeAdvise = "knowledge_advise"
)
// MintTokenRequest is the body of POST /v1/tokens. Tier is the permission
// tier (pushbroker.DefaultTier when empty). Repo is "owner/name" and Repos
// bare repository names; the server narrows the token to the union of the
// two (installation-wide when both are empty, the existing
// ScopedTokenForRepos contract). TTLSeconds is a request; the response says
// what was granted.
type MintTokenRequest struct {
Agent string `json:"agent,omitempty"`
Repo string `json:"repo,omitempty"`
Repos []string `json:"repos,omitempty"`
Tier string `json:"tier,omitempty"`
TTLSeconds int `json:"ttl_seconds,omitempty"`
}
// MintTokenResponse is the body of a successful POST /v1/tokens.
type MintTokenResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
// String prints the response with the token redacted so an accidental %v in
// a log line cannot leak it.
func (r MintTokenResponse) String() string {
return fmt.Sprintf("callback.MintTokenResponse{Token: <redacted>, ExpiresAt: %s}", r.ExpiresAt.Format(time.RFC3339))
}
// GoString is String, for %#v.
func (r MintTokenResponse) GoString() string { return r.String() }
// RESTRecord is the body of POST /v1/github/rest: one relayed GitHub REST
// response. Injected says the daemon's credential was used (its rate-limit
// headers describe the shared core bucket) rather than the agent's own.
// RateLimit carries only the X-RateLimit-* response headers.
type RESTRecord struct {
Caller string `json:"caller"`
Method string `json:"method"`
Path string `json:"path"`
Status int `json:"status"`
Injected bool `json:"injected"`
RateLimit map[string]string `json:"rate_limit,omitempty"`
}
// RateLimitHeaderPrefix selects the response headers RESTRecord carries.
const RateLimitHeaderPrefix = "X-Ratelimit-"
// RateLimitSnapshot is the body of GET /v1/github/rate-limit. OK is false
// when hive has no snapshot yet.
type RateLimitSnapshot struct {
Remaining int `json:"remaining"`
Reset time.Time `json:"reset"`
OK bool `json:"ok"`
}
// Usage kinds, the UsageSink record paths.
const (
UsageKindGateway = "gateway"
UsageKindCopilot = "copilot"
UsageKindCopilotCache = "copilot_cache"
// UsageKindGatewayCache is a gateway response whose prompt was partly
// served from cache: InputTokens excludes CacheRead.
UsageKindGatewayCache = "gateway_cache"
)
// UsageRecord is the body of POST /v1/usage.
type UsageRecord struct {
Agent string `json:"agent"`
Model string `json:"model"`
Kind string `json:"kind"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CacheRead int64 `json:"cache_read_tokens,omitempty"`
CacheCreation int64 `json:"cache_creation_tokens,omitempty"`
}
// CanaryScanRequest is the body of POST /v1/scan/canary.
type CanaryScanRequest struct {
Agent string `json:"agent"`
Text string `json:"text"`
Source string `json:"source"`
}
// CanaryScanResponse is the body of a successful canary scan. It never
// carries the matched canary token: hive knows which one it planted, and
// the runtime only needs to refuse.
type CanaryScanResponse struct {
Detected bool `json:"detected"`
Agent string `json:"agent,omitempty"`
Source string `json:"source,omitempty"`
}
// Scan directions.
const (
ScanInput = "input"
ScanOutput = "output"
)
// TextScanRequest is the body of POST /v1/scan/text.
type TextScanRequest struct {
Direction string `json:"direction"`
Text string `json:"text"`
}
// TextScanResponse is the body of a successful text scan; it is the wire
// form of toolapprove.TextVerdict.
type TextScanResponse struct {
Blocked bool `json:"blocked"`
CriticalInjection bool `json:"critical_injection,omitempty"`
Findings []TextFinding `json:"findings,omitempty"`
}
// TextFinding is one rule hit; Snippet is already masked by the scanner.
// High is the severity bit toolapprove turns into a violation.
type TextFinding struct {
Kind string `json:"kind"`
Snippet string `json:"snippet,omitempty"`
Rule string `json:"rule,omitempty"`
High bool `json:"high,omitempty"`
}
// Condition actions.
const (
ConditionObserve = "observe"
ConditionClear = "clear"
)
// ConditionReport is the body of POST /v1/conditions: one Observe or Clear
// of crux.ConditionReporter.
type ConditionReport struct {
Action string `json:"action"`
Class string `json:"class"`
Key string `json:"key"`
Message string `json:"message,omitempty"`
Diagnostics string `json:"diagnostics,omitempty"`
}
// LinearCredential is the body of GET /v1/linear/credential. Both fields
// empty means hive has none to inject.
type LinearCredential struct {
AccessToken string `json:"access_token,omitempty"`
APIKey string `json:"api_key,omitempty"`
}
// Empty reports whether no credential is available.
func (c LinearCredential) Empty() bool { return c.AccessToken == "" && c.APIKey == "" }
// String redacts both secrets.
func (c LinearCredential) String() string {
return fmt.Sprintf("callback.LinearCredential{AccessToken: %s, APIKey: %s}", redactedIf(c.AccessToken), redactedIf(c.APIKey))
}
// GoString is String, for %#v.
func (c LinearCredential) GoString() string { return c.String() }
func redactedIf(s string) string {
if s == "" {
return `""`
}
return "<redacted>"
}
// CreatePRRequest is the body of POST /v1/pulls.
type CreatePRRequest struct {
Repo string `json:"repo"`
Head string `json:"head"`
Base string `json:"base"`
Title string `json:"title"`
Body string `json:"body,omitempty"`
}
// CreatePRResponse is the body of a successful POST /v1/pulls: the fields
// of crux.PRResult.
type CreatePRResponse struct {
Number int `json:"number"`
URL string `json:"url"`
Author string `json:"author,omitempty"`
AlreadyExisted bool `json:"already_existed,omitempty"`
DuplicateTree bool `json:"duplicate_tree,omitempty"`
DuplicateReason string `json:"duplicate_reason,omitempty"`
}
// Capabilities is the full capability set, as both ends see it: *Client
// implements it over HTTP, hive's pkg/cruxhost directly, and the runtime's
// crux/hivecap adapters are written against it so either serves. A nil
// error means hive answered; the error cases are the sentinels above, an
// *api.StatusError for anything else the server said, or a plain error.
type Capabilities interface {
TokenMinter
GitHubAccounting
UsageRecorder
CanaryScanner
TextScanner
ConditionSink
LinearCredentials
PRCreator
}
// TokenMinter mints a scoped GitHub token.
type TokenMinter interface {
MintToken(ctx context.Context, req MintTokenRequest) (MintTokenResponse, error)
}
// GitHubAccounting records relayed REST traffic and reads the shared
// core-bucket snapshot.
type GitHubAccounting interface {
RecordREST(ctx context.Context, rec RESTRecord) error
RateLimit(ctx context.Context) (RateLimitSnapshot, error)
}
// UsageRecorder records inference token usage.
type UsageRecorder interface {
RecordUsage(ctx context.Context, rec UsageRecord) error
}
// CanaryScanner scans a GitHub write body for planted canaries.
type CanaryScanner interface {
ScanCanary(ctx context.Context, req CanaryScanRequest) (CanaryScanResponse, error)
}
// TextScanner scans tool payload text.
type TextScanner interface {
ScanText(ctx context.Context, req TextScanRequest) (TextScanResponse, error)
}
// ConditionSink receives runtime condition observations and clears.
type ConditionSink interface {
ReportCondition(ctx context.Context, rep ConditionReport) error
}
// LinearCredentials returns the Linear credential to inject.
type LinearCredentials interface {
LinearCredential(ctx context.Context) (LinearCredential, error)
}
// PRCreator opens a pull request as the hive's App.
type PRCreator interface {
CreatePR(ctx context.Context, req CreatePRRequest) (CreatePRResponse, error)
}
// Policy is the body of GET /v1/policy: the values hive hands an in-process
// runtime through the crux.Host policy setters (SetBuildInfo,
// SetExplainModeDefaultResolver, SetKickLogSourceResolver,
// SetGatewayBackendChecker, SetRepoAutoMergeEnabledResolver,
// SetDeadSessionRecoveryOwner, SetSandboxConfig), as one snapshot a sidecar
// runtime polls. An absent (nil / false) field is a setter hive has not
// called; the runtime leaves its own default in place for it.
type Policy struct {
Build *BuildInfo `json:"build,omitempty"`
// ExplainModeDefault is the hive-wide default explain mode, already
// resolved against hive's environment fallback.
ExplainModeDefault *string `json:"explain_mode_default,omitempty"`
// KickLogSource is the kick log source in force, already resolved
// against hive's environment override.
KickLogSource *string `json:"kick_log_source,omitempty"`
// GatewayBackends names the configured model gateways the runtime treats
// as inference-routable backends (matched case-insensitively).
GatewayBackends *[]string `json:"gateway_backends,omitempty"`
// RepoAutoMerge says hive answers POST /v1/policy/repo-auto-merge; the
// per-repository answer is a call, not part of the snapshot.
RepoAutoMerge bool `json:"repo_auto_merge,omitempty"`
// DeadSessionRecoveryOwnedElsewhere is SetDeadSessionRecoveryOwner's
// argument: true when hive's watchdog owns dead-session restarts.
DeadSessionRecoveryOwnedElsewhere *bool `json:"dead_session_recovery_owned_elsewhere,omitempty"`
// Sandbox is the agent_sandbox block (crux/config.AgentSandboxConfig)
// as JSON. It stays raw so this package keeps importing only the
// standard library and crux/api.
Sandbox json.RawMessage `json:"sandbox,omitempty"`
// KnowledgeAdvise says hive serves POST /v1/knowledge/advise
// (knowledge.sidecar_advise on, default off). Absent means the runtime
// installs no knowledge adviser and behaves as it did before the route
// existed (hivecommons/hive#17157).
KnowledgeAdvise bool `json:"knowledge_advise,omitempty"`
}
// BuildInfo is the hive version and commit recorded in kick log headers.
type BuildInfo struct {
Version string `json:"version"`
Commit string `json:"commit"`
}
// RepoAutoMergeRequest is the body of POST /v1/policy/repo-auto-merge.
type RepoAutoMergeRequest struct {
Repo string `json:"repo"`
}
// RepoAutoMergeResponse is its answer.
type RepoAutoMergeResponse struct {
Enabled bool `json:"enabled"`
}
// PolicySource is the policy half of the callback contract. It is separate
// from Capabilities so existing implementations stay valid: the server
// answers the policy routes only when its Caps also implement it (404
// CodeNotConfigured otherwise); *Client always does.
type PolicySource interface {
Policy(ctx context.Context) (Policy, error)
RepoAutoMergeEnabled(ctx context.Context, repo string) (bool, error)
}
// InferenceRoute is the body of PUT /v1/inference/routes/{agent}: the
// backend and model the manager resolved for the agent at launch, which
// hive's inference proxy turns into the upstream it forwards that agent's
// API traffic to (the in-process SetInferenceCallbacks setRoute arguments).
type InferenceRoute struct {
Backend string `json:"backend"`
Model string `json:"model"`
}
// InferenceRouter is the inference-route half of the callback contract,
// optional like PolicySource: the server answers the routes only when its
// Caps implements it; *Client always does. Set replaces the agent's route;
// Clear removes it (the clearRoute callback).
type InferenceRouter interface {
SetInferenceRoute(ctx context.Context, agent string, route InferenceRoute) error
ClearInferenceRoute(ctx context.Context, agent string) error
}
// EffectClaim is the body of POST /v1/effects: the fields of effects.Claim.
// The runtime is about to perform one external mutation (today: a sandbox
// branch push) and asks hive's mutation boundary to journal it, exactly as
// an in-process SetSandboxMutationBoundary would wrap it.
type EffectClaim struct {
Repo string `json:"repo"`
Kind string `json:"kind"`
Target string `json:"target"`
Actor string `json:"actor,omitempty"`
Inputs map[string]string `json:"inputs,omitempty"`
}
// BeginEffectResponse is the body of a successful POST /v1/effects: hive
// admitted the effect and is holding the claim until EffectEndPath(ID) is
// called. A denial is 403 CodeEffectDenied, not a body.
type BeginEffectResponse struct {
ID string `json:"id"`
}
// EndEffectRequest is the body of POST /v1/effects/{id}/end: the result of
// the runtime-side effect. Error is the effect's own error text, "" when it
// succeeded; hive journals it and releases the claim.
type EndEffectRequest struct {
Provenance string `json:"provenance,omitempty"`
Error string `json:"error,omitempty"`
}
// EndEffectResponse is the body of a successful end: what hive's boundary
// returned around the effect. Error is non-empty when the boundary itself
// failed after the effect ran (the journal could not record it); the
// runtime surfaces it like the in-process boundary's return.
type EndEffectResponse struct {
Provenance string `json:"provenance,omitempty"`
Error string `json:"error,omitempty"`
}
// EffectBoundary is the mutation-boundary half of the contract, optional
// like PolicySource. Begin blocks until hive's boundary has admitted or
// denied the claim; End delivers the effect's outcome and returns the
// boundary's. A runtime that begins and never ends (it died) leaves hive to
// time the claim out on its own TTL.
type EffectBoundary interface {
BeginEffect(ctx context.Context, claim EffectClaim) (BeginEffectResponse, error)
EndEffect(ctx context.Context, id string, req EndEffectRequest) (EndEffectResponse, error)
}
// AgentMintRequest is the body of POST /v1/tokens/mint: the arguments of
// crux.AgentMintIssuer.MintAgentToken. Tier is the agent's trust tier, the
// same one its App token is scoped to.
type AgentMintRequest struct {
Agent string `json:"agent"`
Tier string `json:"tier,omitempty"`
}
// AgentMintResponse is the body of a successful POST /v1/tokens/mint. An
// empty Token with a nil error is how a hive whose mint is configured but
// disabled answers (crux.AgentMintIssuer's "" contract); a hive without the
// mint at all answers 404 not_configured.
type AgentMintResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at,omitzero"`
}
// String prints the response with the token redacted.
func (r AgentMintResponse) String() string {
return fmt.Sprintf("callback.AgentMintResponse{Token: %s, ExpiresAt: %s}", redactedIf(r.Token), r.ExpiresAt.Format(time.RFC3339))
}
// GoString is String, for %#v.
func (r AgentMintResponse) GoString() string { return r.String() }
// AgentMinter is the mint half of the contract, optional like PolicySource:
// the server answers POST /v1/tokens/mint only when its Caps implements it;
// *Client always does. It is crux.AgentMintIssuer with a context.
type AgentMinter interface {
MintAgentToken(ctx context.Context, req AgentMintRequest) (AgentMintResponse, error)
}
// BobCredential is the body of GET /v1/bob/credential: the IBM Bob API key
// hive resolved from its config (SetBobAPIKeyResolver) and the loggable
// source it came from ("file:<path>", "env:<NAME>", "" when unconfigured;
// SetBobKeySourceResolver). APIKey is never logged.
type BobCredential struct {
APIKey string `json:"api_key,omitempty"`
Source string `json:"source,omitempty"`
}
// String prints the credential with the key redacted.
func (c BobCredential) String() string {
return fmt.Sprintf("callback.BobCredential{APIKey: %s, Source: %q}", redactedIf(c.APIKey), c.Source)
}
// GoString is String, for %#v.
func (c BobCredential) GoString() string { return c.String() }
// BobCredentials is the Bob half of the contract, optional like
// PolicySource.
type BobCredentials interface {
BobCredential(ctx context.Context) (BobCredential, error)
}
// KnowledgeScope is crux.KnowledgeScope on the wire: one unit of work
// context the runtime observed an agent enter. PaneTail is the last
// pane_lines lines of the agent's scrollback with tokens redacted, present
// only when the policy asked for it.
type KnowledgeScope struct {
Kind string `json:"kind"`
Key string `json:"key"`
Path string `json:"path,omitempty"`
Keywords []string `json:"keywords,omitempty"`
Action string `json:"action,omitempty"`
PaneTail string `json:"pane_tail,omitempty"`
}
// KnowledgeAdvice is crux.KnowledgeAdvice on the wire: one knowledge entry
// the adviser matched, rendered by the runtime as a single typed line. It is
// data: the runtime types these four fields and nothing else, never a
// ranking model's reason.
type KnowledgeAdvice struct {
Slug string `json:"slug"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Ref string `json:"ref,omitempty"`
}
// KnowledgeAdvisorPolicy is crux.KnowledgeAdvisorPolicy on the wire: how the
// hive wants advice for one agent delivered. Enabled false means the runtime
// neither parses the agent's pane nor types anything. CooldownMS is the
// minimum gap between two deliveries, in milliseconds; zero or negative means
// the runtime's default.
type KnowledgeAdvisorPolicy struct {
Enabled bool `json:"enabled"`
MaxPerKick int `json:"max_per_kick,omitempty"`
CooldownMS int `json:"cooldown_ms,omitempty"`
WantsPaneTail bool `json:"wants_pane_tail,omitempty"`
PaneLines int `json:"pane_lines,omitempty"`
}
// KnowledgeAdviseRequest is the body of POST /v1/knowledge/advise. Agent is
// the runtime's agent name and KickAt its current kick identity (the agent's
// LastKick); hive refuses with 403 an agent the runtime does not own or a
// KickAt that is not that agent's current kick. PolicyOnly asks for the
// agent's policy without an evaluation: Scope and KickAt are ignored and no
// candidates are searched, no model is called. Candidates always come from
// the hive's knowledge store under its knowledge.agent_scopes restriction;
// nothing in the request widens that or picks an entry.
type KnowledgeAdviseRequest struct {
Agent string `json:"agent"`
KickAt time.Time `json:"kick_at,omitzero"`
PolicyOnly bool `json:"policy_only,omitempty"`
Scope KnowledgeScope `json:"scope"`
}
// KnowledgeAdviseResponse is the body of a successful POST
// /v1/knowledge/advise: the advice, best first (empty when nothing applies),
// and the policy in force for the agent.
type KnowledgeAdviseResponse struct {
Advice []KnowledgeAdvice `json:"advice"`
Policy KnowledgeAdvisorPolicy `json:"policy"`
}
// KnowledgeAdvisers is the mid-task knowledge adviser half of the contract,
// optional like PolicySource: the server answers POST /v1/knowledge/advise
// only when its Caps implements it and reports the capability configured;
// *Client always does. It fails closed: an error means no advice.
type KnowledgeAdvisers interface {
AdviseKnowledge(ctx context.Context, req KnowledgeAdviseRequest) (KnowledgeAdviseResponse, error)
}