-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdriver.go
More file actions
610 lines (563 loc) · 24.6 KB
/
Copy pathdriver.go
File metadata and controls
610 lines (563 loc) · 24.6 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
package codebuddy
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"github.com/agent-dance/agent-adaptor/driver"
"github.com/agent-dance/agent-adaptor/internal/clihelper"
"github.com/agent-dance/agent-adaptor/internal/driverutil"
"github.com/agent-dance/agent-adaptor/internal/engine"
"github.com/agent-dance/agent-adaptor/internal/mcpruntime"
"github.com/agent-dance/agent-adaptor/internal/profileagents"
"github.com/agent-dance/agent-adaptor/internal/profileconfig"
"github.com/agent-dance/agent-adaptor/internal/profilehooks"
"github.com/agent-dance/agent-adaptor/internal/profileinstructions"
"github.com/agent-dance/agent-adaptor/internal/profilesnapshot"
)
// DriverType is the stable descriptor type for the built-in CodeBuddy driver.
const DriverType = "codebuddy"
// defaultCommand is the CodeBuddy CLI executable.
const defaultCommand = "codebuddy"
type adapter struct {
persistent *persistentPool
}
func (a adapter) CloseProcesses(ctx context.Context) error {
if a.persistent == nil {
return nil
}
return a.persistent.close(ctx)
}
func (adapter) StreamCapability() driver.StreamCapability {
return driver.StreamCapability{
Native: true,
TokenLevel: true,
Reasoning: true,
ToolCallArgs: true,
HITL: true,
}
}
var (
validPermissionModes = map[PermissionMode]struct{}{
PermissionDefault: {},
PermissionAcceptEdits: {},
PermissionPlan: {},
PermissionAuto: {},
PermissionDontAsk: {},
PermissionBypass: {},
}
validEfforts = map[ThinkingEffort]struct{}{
"minimal": {}, "low": {}, "medium": {}, "high": {}, "xhigh": {}, "max": {},
}
)
func (adapter) Descriptor() driver.Descriptor {
fields := []driver.ConfigField{
{Name: "command", Label: "Command", Type: "text", Description: "Override the CodeBuddy CLI executable.", Hint: "Defaults to `codebuddy` when unset.", Default: defaultCommand, Group: "command"},
{Name: "cwd", Label: "Working Directory", Type: "text", Description: "Default working directory when the workspace manager does not override it.", Hint: "Leave empty to let the workspace manager resolve the cwd.", Group: "command"},
{Name: "model", Label: "Model", Type: "select", Description: "CodeBuddy model identifier.", Default: defaultModel, Options: modelOptions(models()), Group: "model"},
{Name: "effort", Label: "Reasoning Effort", Type: "select", Description: "Optional reasoning effort.", Options: []driver.ConfigOption{{Value: "minimal", Label: "Minimal"}, {Value: "low", Label: "Low"}, {Value: "medium", Label: "Medium"}, {Value: "high", Label: "High"}, {Value: "xhigh", Label: "X-High"}, {Value: "max", Label: "Max"}}, Group: "model"},
{Name: "permission_mode", Label: "Permission Mode", Type: "select", Description: "CodeBuddy headless permission mode. Leave empty to derive from run policy.", Options: []driver.ConfigOption{{Value: "default", Label: "Always Ask"}, {Value: "acceptEdits", Label: "Accept Edits"}, {Value: "plan", Label: "Plan"}, {Value: "auto", Label: "Auto"}, {Value: "dontAsk", Label: "Don't Ask"}, {Value: "bypassPermissions", Label: "Bypass Permissions"}}, Group: "execution"},
{Name: "max_turns_per_run", Label: "Max Turns", Type: "number", Description: "Optional max-turns guard for one run.", Group: "execution"},
{Name: "extra_args", Label: "Extra Args", Type: "textarea", Description: "Additional CLI args appended after SDK-managed flags.", Group: "command"},
}
fields = append(fields, profileconfig.CapabilityFields(DriverType)...)
return driver.Descriptor{
Type: DriverType,
DisplayName: "CodeBuddy Code",
Models: models(),
ConfigSchema: &driver.ConfigSchema{Fields: fields},
Sessions: driver.SessionCapability{SupportsResume: true},
Skills: driver.SkillCapability{Supported: true, Mode: driver.SkillSyncPersistent},
MCP: driver.MCPCapability{Supported: true, Stdio: true, HTTP: true, SSE: true},
Instructions: driver.InstructionsCapability{Supported: true},
Workspace: driver.WorkspaceCapability{Supported: true},
Process: driver.ProcessCapability{Persistent: true},
RunPolicyCaps: driver.RunPolicyCapabilities{
// CodeBuddy CLI has no controllable flag for web search or
// browser tooling (browser lives in the agent-browser plugin),
// so the SDK does not model those dimensions. Their availability
// is implicit in the user's local CodeBuddy configuration.
Isolation: false, WebSearch: false, Browser: false,
// SDK stream-json control requests provide all three blocking
// decision classes. Retry is not supported because CodeBuddy does
// not reissue the same control request.
Permission: driver.HumanDecisionSupport{Ask: true, AutoApprove: true, AutoReject: true, Retry: false},
PlanReview: driver.HumanDecisionSupport{Ask: true, AutoApprove: true, AutoReject: true, Retry: false},
Question: driver.QuestionSupport{Ask: true, AutoReject: true, Retry: false},
},
Runtime: driver.RuntimeCapability{ReportsServices: true},
StructuredOutput: driver.StructuredOutputCapability{
JSONSchemaNative: true,
JSONSchemaPromptValidate: true,
WorksWithRun: true,
WorksWithStreaming: false,
WorksWithHITL: false,
Notes: "Native JSON Schema output uses CodeBuddy print-mode --output-format json --json-schema; stream-json/HITL combinations are not advertised.",
},
}
}
func (adapter) ValidateConfig(cfg any) error {
config, ok := asConfig(cfg)
if !ok {
return errors.New("codebuddy driver requires codebuddy.Config")
}
if config.PermissionMode != PermissionUnset {
if _, ok := validPermissionModes[config.PermissionMode]; !ok {
return fmt.Errorf("codebuddy: unsupported permission_mode %q", config.PermissionMode)
}
}
if config.Effort != "" {
if _, ok := validEfforts[config.Effort]; !ok {
return fmt.Errorf("codebuddy: unsupported effort %q", config.Effort)
}
}
return nil
}
func (adapter) CheckEnvironment(_ context.Context, cfg any) (driver.EnvironmentReport, error) {
config := readConfig(cfg)
command := config.Command
if command == "" {
command = defaultCommand
}
checks := append(driverutil.CommandEnvironmentChecks(command), driverutil.CWDEnvironmentChecks(config.CommonConfig.CWD)...)
bindings, err := effectiveBindings(config.CommonConfig, nil)
if err != nil {
checks = append(checks, driver.EnvironmentCheck{Code: "codebuddy_profile_error", Level: "fail", Message: "CodeBuddy profile resolution failed.", Detail: err.Error()})
return driverutil.SummarizeEnvironment(DriverType, checks), nil
}
checks = append(checks, authChecks(bindings)...)
return driverutil.SummarizeEnvironment(DriverType, checks), nil
}
func (adapter) ListModels(_ context.Context, _ any) ([]driver.ModelInfo, error) {
return models(), nil
}
func (adapter) DetectModel(_ context.Context, cfg any, _ *driver.ProfileSelection) (*driver.DetectedModel, error) {
return detectEffectiveModel(readConfig(cfg)), nil
}
func (adapter) GetProfile(_ context.Context, cfg any, _ driver.AgentIdentity, profile *driver.ProfileSelection) (driver.AgentProfile, error) {
return resolveProfile(readConfig(cfg).CommonConfig, profile), nil
}
func (adapter) ConfigSchema(_ context.Context, _ any) (*driver.ConfigSchema, error) {
return adapter{}.Descriptor().ConfigSchema, nil
}
func (adapter) ListSkills(_ context.Context, cfg any, payload driver.ResolvedSkills, selected []string, resolved []driver.Skill, profile *driver.ProfileSelection) (driver.SkillSnapshot, error) {
bindings, err := effectiveBindings(readConfig(cfg).CommonConfig, profile)
if err != nil {
return driver.SkillSnapshot{}, err
}
return listSkills(payload, selected, resolved, bindings)
}
func (adapter) InjectSkills(_ context.Context, _ any, _ driver.ResolvedSkills, _ *driver.ProfileSelection) error {
return nil
}
func (adapter) SyncSkills(ctx context.Context, cfg any, payload driver.ResolvedSkills, selected []string, resolved []driver.Skill, profile *driver.ProfileSelection) (driver.SkillSnapshot, error) {
config := readConfig(cfg)
bindings, err := effectiveBindings(config.CommonConfig, profile)
if err != nil {
return driver.SkillSnapshot{}, err
}
_, kind := profileAndKind(config.CommonConfig, profile)
return syncSkills(ctx, payload, selected, resolved, bindings, kind)
}
func (adapter) SnapshotProfileResources(_ context.Context, cfg any, _ driver.AgentIdentity, profile *driver.ProfileSelection, payload driver.ProfilePayload, selected []string, resolved []driver.Skill) (engine.ProfileSnapshot, error) {
config := readConfig(cfg)
bindings, err := effectiveBindings(config.CommonConfig, profile)
if err != nil {
return engine.ProfileSnapshot{}, err
}
skills, err := listSkills(payload.Skills, selected, resolved, bindings)
if err != nil {
return engine.ProfileSnapshot{}, err
}
effectiveProfile, kind := profileAndKind(config.CommonConfig, profile)
snapshot := profilesnapshot.Build(DriverType, effectiveProfile, kind, payload, skills, false)
mcpSnapshot, err := mcpruntime.SnapshotResource(DriverType, effectiveProfile.Dir, payload.MCP, false)
if err != nil {
return engine.ProfileSnapshot{}, err
}
snapshot = profileconfig.WithSnapshotResource(snapshot, mcpSnapshot)
if payload.Declared.Config {
snapshot = profileconfig.WithSnapshotResource(snapshot, profileconfig.Snapshot(DriverType, effectiveProfile.Dir, payload.Config, false))
}
if payload.Declared.Instructions {
snapshot = profileconfig.WithSnapshotResource(snapshot, profileinstructions.Snapshot(DriverType, effectiveProfile.Dir, payload.Instructions, false))
}
if payload.Declared.Agents {
snapshot = profileconfig.WithSnapshotResource(snapshot, profileagents.Snapshot(DriverType, effectiveProfile.Dir, payload.Agents, false))
}
if payload.Declared.Hooks {
snapshot = profileconfig.WithSnapshotResource(snapshot, profilehooks.Snapshot(DriverType, effectiveProfile.Dir, payload.Hooks, false))
}
return snapshot, nil
}
func (adapter) SyncProfileResources(ctx context.Context, cfg any, _ driver.AgentIdentity, profile *driver.ProfileSelection, payload driver.ProfilePayload, selected []string, resolved []driver.Skill) (engine.ProfileSnapshot, error) {
config := readConfig(cfg)
bindings, err := effectiveBindings(config.CommonConfig, profile)
if err != nil {
return engine.ProfileSnapshot{}, err
}
effectiveProfile, kind := profileAndKind(config.CommonConfig, profile)
skills, err := syncSkills(ctx, payload.Skills, selected, resolved, bindings, kind)
if err != nil {
return engine.ProfileSnapshot{}, err
}
mcpSnapshot, err := mcpruntime.SyncResource(ctx, DriverType, effectiveProfile.Dir, kind, payload.MCP)
if err != nil {
return engine.ProfileSnapshot{}, err
}
snapshot := profilesnapshot.Build(DriverType, effectiveProfile, kind, payload, skills, true)
snapshot = profileconfig.WithSnapshotResource(snapshot, mcpSnapshot)
if payload.Declared.Config {
configSnapshot, err := profileconfig.SyncNativePatches(ctx, DriverType, effectiveProfile.Dir, payload.Config)
if err != nil {
return engine.ProfileSnapshot{}, err
}
snapshot = profileconfig.WithSnapshotResource(snapshot, configSnapshot)
}
if payload.Declared.Instructions {
instructionsSnapshot, _, err := profileinstructions.Sync(ctx, DriverType, effectiveProfile.Dir, payload.Instructions)
if err != nil {
return engine.ProfileSnapshot{}, err
}
snapshot = profileconfig.WithSnapshotResource(snapshot, instructionsSnapshot)
}
if payload.Declared.Agents {
agentsSnapshot, err := profileagents.Sync(ctx, DriverType, effectiveProfile.Dir, payload.Agents)
if err != nil {
return engine.ProfileSnapshot{}, err
}
snapshot = profileconfig.WithSnapshotResource(snapshot, agentsSnapshot)
}
if payload.Declared.Hooks {
hooksSnapshot, err := profilehooks.Sync(ctx, DriverType, effectiveProfile.Dir, payload.Hooks)
if err != nil {
return engine.ProfileSnapshot{}, err
}
snapshot = profileconfig.WithSnapshotResource(snapshot, hooksSnapshot)
}
return snapshot, nil
}
func (a adapter) Run(ctx context.Context, req driver.Request, sink driver.EventSink) (driver.Response, error) {
cfg := readConfig(req.Config)
if m := strings.TrimSpace(req.ModelOverride); m != "" {
cfg.Model = m
}
command := cfg.Command
if command == "" {
command = defaultCommand
}
prep, err := a.prepareRun(ctx, cfg, req)
if err != nil {
return driver.Response{}, err
}
controlRequested := wantsControlTransport(req.Policy.HumanDecision)
if controlRequested {
if req.OutputSchema != nil && req.StructuredOutputSource == driver.StructuredOutputSourceNative {
return driver.Response{}, &driver.StructuredOutputUnsupportedError{
Driver: DriverType,
Reason: "CodeBuddy native structured output is not supported with control HITL",
}
}
}
var writer *persistentWriter
resumeID := codeBuddyResumeID(req)
if a.persistent != nil && persistentSessionKey(req) != "" {
writer = a.persistent.lockWriter(persistentWriterKey(req))
defer writer.release()
}
spec := persistentSpec{
command: command, model: requestedModelFlag(cfg), effort: string(cfg.Effort),
extraArgs: append([]string(nil), cfg.ExtraArgs...),
cwd: prep.effectiveCWD, env: appendCodeBuddyEntrypoint(prep.env),
resumeID: resumeID, prompt: prep.prompt,
engineSessionID: persistentSessionKey(req),
previousEngineID: persistentPreviousSessionKey(req),
profileFingerprint: req.ProfilePayload.SessionFingerprint(),
settingsFingerprint: codeBuddySettingsFingerprint(prep.bindings, prep.effectiveCWD, prep.profileDir, cfg.ExtraArgs),
commandFingerprint: commandFileFingerprint(command),
gracePeriod: cfg.GracePeriod,
}
if writer != nil && !req.Spawn && persistentEligible(cfg, req) {
decisionSink, ok := sink.(driver.DecisionCapableSink)
if ok {
p := newParser(sink)
p.enablePersistentControl(ctx, decisionSink, req.RunID, req.Policy.HumanDecision, prep.prompt, resolveConfigDir(prep.bindings))
if req.Streaming {
p.enableStreaming(req.RunID)
} else {
p.enableOutputReconstruction(req.RunID)
}
raw, persistentErr := writer.run(ctx, spec, sink, p)
if persistentErr == nil {
raw.Terminal = p.terminal
return buildPersistentCodeBuddyResponse(req, p, raw, prep), nil
}
if !errors.Is(persistentErr, errPersistentFallback) {
return driver.Response{}, persistentErr
}
} else if controlRequested {
return driver.Response{}, errControlSinkRequired
} else if err := writer.suspendAndWait(resumeID, persistentSessionKey(req), persistentPreviousSessionKey(req)); err != nil {
return driver.Response{}, err
}
} else if writer != nil {
if err := writer.suspendAndWait(resumeID, persistentSessionKey(req), persistentPreviousSessionKey(req)); err != nil {
return driver.Response{}, err
}
}
var result driver.Response
if controlRequested {
result, err = a.runControl(ctx, cfg, command, req, sink, prep)
} else {
result, err = a.runHeadless(ctx, cfg, command, req, sink, prep)
}
if err != nil {
return driver.Response{}, err
}
if writer != nil && !req.Spawn && persistentPreWarmEligible(cfg, req) &&
result.ExitCode == 0 && result.Failure == nil &&
result.Checkpoint != nil && result.Checkpoint.Valid && result.Checkpoint.State != nil {
prewarm := spec
prewarm.prompt = ""
prewarm.resumeID = result.Checkpoint.State.ResumeID
_ = writer.preWarm(prewarm, sink)
}
return result, nil
}
// runPrep carries the resolved per-run inputs shared by both engines.
type runPrep struct {
bindings []driver.EnvBinding
env []driver.EnvBinding
effectiveCWD string
profileDir string
prompt string
reportedModel string
}
func (a adapter) prepareRun(ctx context.Context, cfg Config, req driver.Request) (runPrep, error) {
profileFingerprint := req.ProfilePayload.SessionFingerprint()
if err := validateCodeBuddySessionContext(req); err != nil {
return runPrep{}, err
}
if _, err := effectiveBindingsNoInitialize(cfg.CommonConfig, req.Profile); err != nil {
return runPrep{}, err
}
effectiveCWD := chooseCWD(cfg.CommonConfig, req.Workspace)
if err := validateSessionGuard(req, effectiveCWD, profileFingerprint); err != nil {
return runPrep{}, err
}
bindings, err := effectiveBindings(cfg.CommonConfig, req.Profile)
if err != nil {
return runPrep{}, err
}
effectiveProfile, kind := profileAndKind(cfg.CommonConfig, req.Profile)
if _, err := syncSkills(ctx, req.Skills, req.Skills.Keys(), nil, bindings, kind); err != nil {
return runPrep{}, err
}
if _, err := mcpruntime.SyncResource(ctx, DriverType, effectiveProfile.Dir, kind, req.MCP); err != nil {
return runPrep{}, err
}
if req.ProfilePayload.Declared.Config {
if _, err := profileconfig.SyncNativePatches(ctx, DriverType, effectiveProfile.Dir, req.ProfilePayload.Config); err != nil {
return runPrep{}, err
}
}
var preparedInstructions profileinstructions.Prepared
if req.ProfilePayload.Declared.Instructions {
preparedInstructions, err = profileinstructions.PrepareForRun(ctx, DriverType, effectiveProfile.Dir, effectiveCWD, req.Instructions)
if err != nil {
return runPrep{}, err
}
}
if req.ProfilePayload.Declared.Agents {
if _, err := profileagents.Sync(ctx, DriverType, effectiveProfile.Dir, req.ProfilePayload.Agents); err != nil {
return runPrep{}, err
}
}
if req.ProfilePayload.Declared.Hooks {
if _, err := profilehooks.Sync(ctx, DriverType, effectiveProfile.Dir, req.ProfilePayload.Hooks); err != nil {
return runPrep{}, err
}
}
env, err := driverutil.RuntimeEnvBindings(bindings, req.Runtime)
if err != nil {
return runPrep{}, err
}
prompt := req.Prompt
if runtimePrefix := driverutil.RuntimePromptPrefix(req.Runtime); runtimePrefix != "" {
prompt = runtimePrefix + "\n\n" + prompt
}
if prefix := profileinstructions.PromptPrefix(preparedInstructions, profileinstructions.Mode(req.Instructions)); prefix != "" {
prompt = prefix + "\n\n" + prompt
}
reportedModel := requestedModelFlag(cfg)
if reportedModel == "" {
if detected := detectEffectiveModel(cfg); detected != nil {
reportedModel = detected.Model
}
}
return runPrep{
bindings: bindings,
env: env,
effectiveCWD: effectiveCWD,
profileDir: effectiveProfile.Dir,
prompt: prompt,
reportedModel: reportedModel,
}, nil
}
func buildPersistentCodeBuddyResponse(req driver.Request, p *parser, raw driver.RawStreams, prep runPrep) driver.Response {
failure := p.failureForOutcome(0)
p.completeStream(failure, 0, "", false)
checkpoint := p.checkpointForOutcome(0, "", false, failure)
if checkpoint != nil && checkpoint.State != nil {
checkpoint.State.Data = map[string]string{
driver.SessionParamCWD: prep.effectiveCWD,
driver.SessionParamWorkspaceID: req.Workspace.ID,
driver.SessionParamProfileFingerprint: req.ProfilePayload.SessionFingerprint(),
}
}
return driver.Response{
Output: p.buildOutput(), RawStreams: &raw, Transcript: p.transcript,
ExitCode: 0, Usage: p.usage, Checkpoint: checkpoint,
Metadata: p.outputMetadata(), Provider: "codebuddy", Model: prep.reportedModel,
Summary: p.finalSummary(),
RuntimeServices: driverutil.RuntimeReportsFromRefs(req.Runtime.Ensured, req.Agent),
Failure: failure,
}
}
func (adapter) runHeadless(ctx context.Context, cfg Config, command string, req driver.Request, sink driver.EventSink, prep runPrep) (driver.Response, error) {
permMode := headlessPermissionMode(cfg, req.Policy)
args := buildExecArgs(cfg, req, permMode, false)
args = append(args, prep.prompt)
p := newParser(sink)
if req.Streaming {
p.enableStreaming(req.RunID)
}
runReq := clihelper.CommandRequest{
Command: command,
Args: args,
CWD: prep.effectiveCWD,
Env: prep.env,
Observe: p.onChunk,
}
result, err := clihelper.Run(ctx, runReq, sink)
if err != nil {
return driver.Response{}, err
}
p.finalize()
raw := driver.RawStreams{Stdout: result.RawStreams.Stdout, Stderr: result.RawStreams.Stderr, Terminal: p.terminal}
if resumedCodeBuddySession(req) && isCodeBuddyResumeRejected(result.ExitCode, p.errorMessage, raw.Stdout, raw.Stderr) {
reason := strings.TrimSpace(p.errorMessage)
if reason == "" {
reason = fmt.Sprintf("codebuddy resume session %q is unavailable", req.Session.State.ResumeID)
}
p.completeStream(&driver.RunFailure{Code: driver.FailureAgentError, Message: reason}, result.ExitCode, result.Signal, result.TimedOut)
return driver.Response{}, &engine.ResumeRejectedError{Reason: reason}
}
failure := p.failureForOutcome(result.ExitCode)
var structuredOutput *driver.StructuredOutput
if req.OutputSchema != nil && req.StructuredOutputSource == driver.StructuredOutputSourceNative {
candidate := p.nativeStructuredOutputForOutcome(result.ExitCode, result.Signal, result.TimedOut, failure)
structuredOutput, failure = engine.FinalizeStructuredOutput(
req.OutputSchema,
driver.StructuredOutputSourceNative,
p.buildOutput(),
candidate,
failure,
)
}
p.completeStream(failure, result.ExitCode, result.Signal, result.TimedOut)
checkpoint := p.checkpointForOutcome(result.ExitCode, result.Signal, result.TimedOut, failure)
if checkpoint != nil && checkpoint.State != nil {
checkpoint.State.Data = map[string]string{
driver.SessionParamCWD: prep.effectiveCWD,
driver.SessionParamWorkspaceID: req.Workspace.ID,
driver.SessionParamProfileFingerprint: req.ProfilePayload.SessionFingerprint(),
}
}
return driver.Response{
Output: p.buildOutput(),
RawStreams: &raw,
Transcript: p.transcript,
ExitCode: result.ExitCode,
Signal: result.Signal,
TimedOut: result.TimedOut,
Usage: p.usage,
Checkpoint: checkpoint,
Metadata: p.outputMetadata(),
Provider: "codebuddy",
Model: prep.reportedModel,
Summary: p.finalSummary(),
StructuredOutput: structuredOutput,
RuntimeServices: driverutil.RuntimeReportsFromRefs(req.Runtime.Ensured, req.Agent),
Failure: failure,
}, nil
}
func validateSessionGuard(req driver.Request, effectiveCWD, profileFingerprint string) error {
if req.Session == nil || req.Session.State == nil {
return nil
}
data := req.Session.State.Data
if data[driver.SessionParamCWD] != "" && data[driver.SessionParamCWD] != effectiveCWD {
return &engine.ResumeRejectedError{Reason: "session working directory changed"}
}
if data[driver.SessionParamWorkspaceID] != "" && data[driver.SessionParamWorkspaceID] != req.Workspace.ID {
return &engine.ResumeRejectedError{Reason: "session workspace changed"}
}
if data[driver.SessionParamProfileFingerprint] != "" && data[driver.SessionParamProfileFingerprint] != profileFingerprint {
return &engine.ResumeRejectedError{Reason: "profile resources changed"}
}
return nil
}
func validateCodeBuddySessionContext(req driver.Request) error {
if req.Session == nil || req.Session.Mode != driver.SessionFork {
return nil
}
// CodeBuddy's public headless/CLI reference documents resume but no fork
// flag. Some SDK wrappers expose an internal fork_session option, but the
// Driver cannot make an unpublished CLI detail part of the v1 contract.
// Reject before profile/resource materialization so a fork can never
// silently advance the parent via ordinary --resume.
return &engine.ResumeRejectedError{Reason: "CodeBuddy CLI does not expose a supported headless session fork"}
}
func resumedCodeBuddySession(req driver.Request) bool {
return req.Session != nil && req.Session.State != nil && strings.TrimSpace(req.Session.State.ResumeID) != ""
}
var codeBuddyResumeRejectedRE = regexp.MustCompile(`(?i)^(?:error:\s*)?(?:conversation\s+\S+\s+(?:not found|does not exist|expired|is invalid)|session\s+\S+\s+(?:not found|does not exist|expired|is invalid)|no conversation found (?:for session|with session id:?)\s*\S+|failed to resume (?:session|conversation)(?:\s+\S+)?|(?:unable|cannot) to (?:resume|find|load) (?:session|conversation)(?:\s+\S+)?)\.?$`)
func isCodeBuddyResumeRejected(exitCode int, providerMessage, stdout, stderr string) bool {
// On an official error ResultMessage, parser.errorMessage is authoritative
// even when the CLI exits zero. For a non-zero process, startup/session
// lookup diagnostics may exist only in raw stdout/stderr.
haystack := providerMessage + "\n" + stderr
if exitCode != 0 {
haystack += "\n" + stdout
}
for _, line := range strings.Split(haystack, "\n") {
if codeBuddyResumeRejectedRE.MatchString(strings.TrimSpace(line)) {
return true
}
}
return false
}
func chooseCWD(cfg CommonConfig, workspace driver.WorkspaceLease) string {
if workspace.CWD != "" {
return workspace.CWD
}
return cfg.CWD
}
// asConfig accepts only the package-owned provider configuration.
func asConfig(cfg any) (Config, bool) {
switch typed := cfg.(type) {
case Config:
return typed, true
case *Config:
if typed != nil {
return *typed, true
}
}
return Config{}, false
}
func readConfig(cfg any) Config {
config, _ := asConfig(cfg)
return config
}