♻️ Quality: internal/acp without smells (9 → 0)
- Prompt as an acpTurn: beginTurn (cancel + sink, one closing func), run, expand, generate, respond; endTurn/cancelled answers shared with askAgent and a2aAgent, which now take the turn instead of 7 arguments - slashCommand as a table (bare commands answered only without argument) - acp.Run takes the same agent.Setup as agent.Run - elicitByPermission as askByPermission, permissionOptions, chosenAnswer - parseClientTool checks in checkClientToolSpec; toolKind as a map - the client tool's definition and call in clienttools_call.go Checked old vs new binary over ACP (JSON-RPC on stdio) against a scripted fake OpenAI server: 14 prompts (answer, tool call, /unload, /redirect, /compact, /new...) and a session/cancel: identical messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dcb1fec parent: 7817163 modified
internal/acp/a2a.go +16 -15 | @@ -16,25 +16,26 @@ import ( | ||
| 16 | 16 | // a2aAgent is the editor's /a2a-<name> (ticket 263): the remote A2A agent |
| 17 | 17 | // answers in the agent's message, and the exchange joins the session's |
| 18 | 18 | // history, like /ask-<name>. |
| 19 | -func (f *front) a2aAgent(ctx, turnCtx context.Context, sid sdk.SessionId, s *session, k *sink, req command.A2ARequest, parseErr error) (sdk.PromptResponse, error) { | |
| 19 | +func (t *acpTurn) a2aAgent(req command.A2ARequest, parseErr error) (sdk.PromptResponse, error) { | |
| 20 | + f, s := t.f, t.s | |
| 20 | 21 | if parseErr != nil { |
| 21 | - k.Text("⚠️ " + parseErr.Error()) | |
| 22 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | |
| 22 | + t.k.Text("⚠️ " + parseErr.Error()) | |
| 23 | + return t.endTurn(), nil | |
| 23 | 24 | } |
| 24 | - k.Text("🤝 " + req.Agent + " (A2A)\n\n") | |
| 25 | - answer, err := tools.A2ASend(turnCtx, req.Agent, req.Message, false) | |
| 25 | + t.k.Text("🤝 " + req.Agent + " (A2A)\n\n") | |
| 26 | + answer, err := tools.A2ASend(t.turnCtx, req.Agent, req.Message, false) | |
| 26 | 27 | switch { |
| 27 | - case turnCtx.Err() != nil: | |
| 28 | - return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: s.usage.totals()}, nil | |
| 28 | + case t.turnCtx.Err() != nil: | |
| 29 | + return t.cancelled(), nil | |
| 29 | 30 | case err != nil: |
| 30 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s failed: %v\n", sid, req.Agent, err) | |
| 31 | - k.Text(fmt.Sprintf("⚠️ %s did not answer: %v", req.Agent, err)) | |
| 32 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | |
| 31 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s failed: %v\n", t.sid, req.Agent, err) | |
| 32 | + t.k.Text(fmt.Sprintf("⚠️ %s did not answer: %v", req.Agent, err)) | |
| 33 | + return t.endTurn(), nil | |
| 33 | 34 | } |
| 34 | - k.Text(answer) | |
| 35 | + t.k.Text(answer) | |
| 35 | 36 | s.messages = append(s.messages, ask.Exchange(req.Agent, "A2A", false, req.Message, answer, config.Cfg.MaxOutput)...) |
| 36 | - f.persist(sid, s) | |
| 37 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s answered\n", sid, req.Agent) | |
| 38 | - f.sendUsage(context.WithoutCancel(ctx), sid, contextUsed(s)) | |
| 39 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | |
| 37 | + f.persist(t.sid, s) | |
| 38 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s answered\n", t.sid, req.Agent) | |
| 39 | + f.sendUsage(context.WithoutCancel(t.ctx), t.sid, contextUsed(s)) | |
| 40 | + return t.endTurn(), nil | |
| 40 | 41 | } |
| @@ -16,25 +16,26 @@ import ( | |||
| 16 | // a2aAgent is the editor's /a2a-<name> (ticket 263): the remote A2A agent | 16 | // a2aAgent is the editor's /a2a-<name> (ticket 263): the remote A2A agent |
| 17 | // answers in the agent's message, and the exchange joins the session's | 17 | // answers in the agent's message, and the exchange joins the session's |
| 18 | // history, like /ask-<name>. | 18 | // history, like /ask-<name>. |
| 19 | -func (f *front) a2aAgent(ctx, turnCtx context.Context, sid sdk.SessionId, s *session, k *sink, req command.A2ARequest, parseErr error) (sdk.PromptResponse, error) { | 19 | +func (t *acpTurn) a2aAgent(req command.A2ARequest, parseErr error) (sdk.PromptResponse, error) { |
| 20 | + f, s := t.f, t.s | ||
| 20 | if parseErr != nil { | 21 | if parseErr != nil { |
| 21 | - k.Text("⚠️ " + parseErr.Error()) | 22 | + t.k.Text("⚠️ " + parseErr.Error()) |
| 22 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | 23 | + return t.endTurn(), nil |
| 23 | } | 24 | } |
| 24 | - k.Text("🤝 " + req.Agent + " (A2A)\n\n") | 25 | + t.k.Text("🤝 " + req.Agent + " (A2A)\n\n") |
| 25 | - answer, err := tools.A2ASend(turnCtx, req.Agent, req.Message, false) | 26 | + answer, err := tools.A2ASend(t.turnCtx, req.Agent, req.Message, false) |
| 26 | switch { | 27 | switch { |
| 27 | - case turnCtx.Err() != nil: | 28 | + case t.turnCtx.Err() != nil: |
| 28 | - return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: s.usage.totals()}, nil | 29 | + return t.cancelled(), nil |
| 29 | case err != nil: | 30 | case err != nil: |
| 30 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s failed: %v\n", sid, req.Agent, err) | 31 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s failed: %v\n", t.sid, req.Agent, err) |
| 31 | - k.Text(fmt.Sprintf("⚠️ %s did not answer: %v", req.Agent, err)) | 32 | + t.k.Text(fmt.Sprintf("⚠️ %s did not answer: %v", req.Agent, err)) |
| 32 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | 33 | + return t.endTurn(), nil |
| 33 | } | 34 | } |
| 34 | - k.Text(answer) | 35 | + t.k.Text(answer) |
| 35 | s.messages = append(s.messages, ask.Exchange(req.Agent, "A2A", false, req.Message, answer, config.Cfg.MaxOutput)...) | 36 | s.messages = append(s.messages, ask.Exchange(req.Agent, "A2A", false, req.Message, answer, config.Cfg.MaxOutput)...) |
| 36 | - f.persist(sid, s) | 37 | + f.persist(t.sid, s) |
| 37 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s answered\n", sid, req.Agent) | 38 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /a2a-%s answered\n", t.sid, req.Agent) |
| 38 | - f.sendUsage(context.WithoutCancel(ctx), sid, contextUsed(s)) | 39 | + f.sendUsage(context.WithoutCancel(t.ctx), t.sid, contextUsed(s)) |
| 39 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | 40 | + return t.endTurn(), nil |
| 40 | } | 41 | } |
modified
internal/acp/acp.go +126 -72 | @@ -29,6 +29,7 @@ import ( | ||
| 29 | 29 | "sync" |
| 30 | 30 | |
| 31 | 31 | "mm/internal/acpwire" |
| 32 | + "mm/internal/agent" | |
| 32 | 33 | "mm/internal/agentsmd" |
| 33 | 34 | "mm/internal/ask" |
| 34 | 35 | "mm/internal/command" |
| @@ -120,13 +121,13 @@ var _ sdk.Agent = (*front)(nil) | ||
| 120 | 121 | // client closes it. Same arguments as agent.Run: main.go's wiring — engine, |
| 121 | 122 | // system prompt, tool list — is identical for the two front ends. |
| 122 | 123 | // |
| 123 | -// d is the loop detector the built-in tools report to; the client tools | |
| 124 | -// (clienttools.go) report to it too. asker runs the /ask-<agent> commands; | |
| 124 | +// s.Detector is the loop detector the built-in tools report to; the client | |
| 125 | +// tools (clienttools.go) report to it too. asker runs the /ask-<agent> commands; | |
| 125 | 126 | // nil when no agent is configured. |
| 126 | -func Run(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, d *detector.LoopDetector, asker ask.Runner) { | |
| 127 | - f := newFront(e, system, tools, os.Stdout, os.Stdin) | |
| 127 | +func Run(ctx context.Context, s agent.Setup, asker ask.Runner) { | |
| 128 | + f := newFront(s.Engine, s.System, s.Tools, os.Stdout, os.Stdin) | |
| 128 | 129 | f.asker = asker |
| 129 | - f.detector = d | |
| 130 | + f.detector = s.Detector | |
| 130 | 131 | select { |
| 131 | 132 | case <-f.conn.Done(): // the editor closed our stdin: we are done |
| 132 | 133 | case <-ctx.Done(): |
| @@ -360,60 +361,90 @@ func (f *front) Prompt(ctx context.Context, p sdk.PromptRequest) (sdk.PromptResp | ||
| 360 | 361 | // A command the editor offered for a SKILL: "/greetings Bob" becomes the |
| 361 | 362 | // `$greetings Bob` notation and the turn runs normally from here. Done |
| 362 | 363 | // after slashCommand, so a real command always wins whatever a skill is |
| 363 | - // called. | |
| 364 | - input = skillCommand(input) | |
| 365 | - // /redirect <message> (ticket 267): a turn like any other, its question | |
| 366 | - // framed as a correction of the task the history holds. | |
| 367 | - input = redirectCommand(input) | |
| 368 | - | |
| 369 | - // One cancellable context per turn: session/cancel fires s.cancel, the | |
| 370 | - // generation and any pending permission request fall with it, and the spec's | |
| 371 | - // contract — still answer the prompt, with stopReason "cancelled" — is met | |
| 372 | - // at the bottom of this function. | |
| 364 | + // called. /redirect <message> (ticket 267): a turn like any other, its | |
| 365 | + // question framed as a correction of the task the history holds. | |
| 366 | + input = redirectCommand(skillCommand(input)) | |
| 367 | + | |
| 368 | + t, end := f.beginTurn(ctx, p.SessionId, s) | |
| 369 | + defer end() | |
| 370 | + return t.run(input) | |
| 371 | +} | |
| 372 | + | |
| 373 | +// acpTurn is one session/prompt being answered: the request's context, the | |
| 374 | +// turn's own (session/cancel cancels it), the session and the sink its | |
| 375 | +// events go through. | |
| 376 | +type acpTurn struct { | |
| 377 | + f *front | |
| 378 | + ctx context.Context | |
| 379 | + turnCtx context.Context | |
| 380 | + sid sdk.SessionId | |
| 381 | + s *session | |
| 382 | + k *sink | |
| 383 | +} | |
| 384 | + | |
| 385 | +// beginTurn opens a turn on session s, and returns it with the function | |
| 386 | +// that closes it. | |
| 387 | +// | |
| 388 | +// One cancellable context per turn: session/cancel fires s.cancel, the | |
| 389 | +// generation and any pending permission request fall with it, and the | |
| 390 | +// spec's contract — still answer the prompt, with stopReason "cancelled" — | |
| 391 | +// is met in respond. The sink is what turns the tools' events into | |
| 392 | +// session/update messages; installing it is what switches engine+tools to | |
| 393 | +// "ACP mode" for this turn. | |
| 394 | +func (f *front) beginTurn(ctx context.Context, sid sdk.SessionId, s *session) (*acpTurn, func()) { | |
| 373 | 395 | turnCtx, cancel := context.WithCancel(ctx) |
| 374 | 396 | f.mu.Lock() |
| 375 | 397 | s.cancel = cancel |
| 376 | 398 | f.mu.Unlock() |
| 377 | - defer func() { | |
| 399 | + t := &acpTurn{f: f, ctx: ctx, turnCtx: turnCtx, sid: sid, s: s, k: &sink{f: f, ctx: turnCtx, sid: sid, s: s}} | |
| 400 | + ui.SetActive(t.k) | |
| 401 | + return t, func() { | |
| 402 | + ui.SetActive(nil) | |
| 378 | 403 | f.mu.Lock() |
| 379 | 404 | s.cancel = nil |
| 380 | 405 | f.mu.Unlock() |
| 381 | 406 | cancel() |
| 382 | - }() | |
| 383 | - | |
| 384 | - // The sink is what turns the tools' events into session/update messages; | |
| 385 | - // installing it is what switches engine+tools to "ACP mode" for this turn. | |
| 386 | - k := &sink{f: f, ctx: turnCtx, sid: p.SessionId, s: s} | |
| 387 | - ui.SetActive(k) | |
| 388 | - defer ui.SetActive(nil) | |
| 407 | + } | |
| 408 | +} | |
| 389 | 409 | |
| 390 | - // /ask-bob: another agent answers instead of our model (ask.go). | |
| 410 | +// run answers the turn: another agent for /ask-bob (ask.go) and /a2a-alice | |
| 411 | +// (a2a.go, ticket 263), else our model. | |
| 412 | +func (t *acpTurn) run(input string) (sdk.PromptResponse, error) { | |
| 391 | 413 | if req, isAsk, err := command.ParseAsk(input); isAsk { |
| 392 | - return f.askAgent(ctx, turnCtx, p.SessionId, s, k, req, err) | |
| 414 | + return t.askAgent(req, err) | |
| 393 | 415 | } |
| 394 | - // /a2a-alice: a remote A2A agent answers (a2a.go, ticket 263). | |
| 395 | 416 | if req, isA2A, err := command.ParseA2A(input); isA2A { |
| 396 | - return f.a2aAgent(ctx, turnCtx, p.SessionId, s, k, req, err) | |
| 417 | + return t.a2aAgent(req, err) | |
| 397 | 418 | } |
| 419 | + return t.generate(t.expand(input)) | |
| 420 | +} | |
| 398 | 421 | |
| 399 | - // A typed "@path" — the editor's picker bypassed, or an editor without | |
| 400 | - // one — is understood like the resource_link the picker would have sent, | |
| 401 | - // against the session's cwd, which is the project the editor opened. | |
| 422 | +// expand is the question as the model reads it. A typed "@path" — the | |
| 423 | +// editor's picker bypassed, or an editor without one — is understood like | |
| 424 | +// the resource_link the picker would have sent, against the session's cwd, | |
| 425 | +// which is the project the editor opened. Same for "$skill": the editor has | |
| 426 | +// no picker for it, but the notation travels in the text and must mean what | |
| 427 | +// it means in the terminal. | |
| 428 | +func (t *acpTurn) expand(input string) string { | |
| 402 | 429 | typed := input |
| 403 | - input, attached := mention.Expand(input, s.cwd) | |
| 430 | + input, attached := mention.Expand(input, t.s.cwd) | |
| 404 | 431 | for _, a := range attached { |
| 405 | - fmt.Fprintf(os.Stderr, "[acp] session %s: attached %s\n", p.SessionId, a.Path) | |
| 432 | + fmt.Fprintf(os.Stderr, "[acp] session %s: attached %s\n", t.sid, a.Path) | |
| 406 | 433 | } |
| 407 | - // Same for "$skill": the editor has no picker for it, but the notation | |
| 408 | - // travels in the text and must mean what it means in the terminal. | |
| 409 | 434 | input, refs := skills.ExpandRefs(input, skills.Declared()) |
| 410 | 435 | for _, ref := range refs { |
| 411 | - fmt.Fprintf(os.Stderr, "[acp] session %s: skill %s\n", p.SessionId, ref.Name) | |
| 436 | + fmt.Fprintf(os.Stderr, "[acp] session %s: skill %s\n", t.sid, ref.Name) | |
| 412 | 437 | } |
| 413 | - input, routed := decide.RouteSkill(turnCtx, typed, input, len(refs), skills.Declared()) | |
| 438 | + input, routed := decide.RouteSkill(t.turnCtx, typed, input, len(refs), skills.Declared()) | |
| 414 | 439 | if routed != "" { |
| 415 | - fmt.Fprintf(os.Stderr, "[acp] session %s: %s\n", p.SessionId, routed) | |
| 440 | + fmt.Fprintf(os.Stderr, "[acp] session %s: %s\n", t.sid, routed) | |
| 416 | 441 | } |
| 442 | + return input | |
| 443 | +} | |
| 444 | + | |
| 445 | +// generate runs the model's turn on the question and keeps its history. | |
| 446 | +func (t *acpTurn) generate(input string) (sdk.PromptResponse, error) { | |
| 447 | + f, s := t.f, t.s | |
| 417 | 448 | s.messages = append(s.messages, ai.NewUserTextMessage(input)) |
| 418 | 449 | before := len(s.messages) |
| 419 | 450 | |
| @@ -421,12 +452,12 @@ func (f *front) Prompt(ctx context.Context, p sdk.PromptRequest) (sdk.PromptResp | ||
| 421 | 452 | // after the agent left it unknown for good; asking again while it is |
| 422 | 453 | // unknown is the REPL's rule (agent.go), and costs nothing once known. |
| 423 | 454 | if f.e.ContextWindow == 0 { |
| 424 | - if w, src := f.e.EnsureContextWindow(turnCtx); w > 0 { | |
| 455 | + if w, src := f.e.EnsureContextWindow(t.turnCtx); w > 0 { | |
| 425 | 456 | fmt.Fprintf(os.Stderr, "[acp] ctx: %d (%s)\n", w, src) |
| 426 | 457 | } |
| 427 | 458 | } |
| 428 | 459 | |
| 429 | - resp, full, err := f.e.Generate(turnCtx, s.messages, f.turnTools(s)) | |
| 460 | + resp, full, err := f.e.Generate(t.turnCtx, s.messages, f.turnTools(s)) | |
| 430 | 461 | |
| 431 | 462 | // Same rule as the REPL, for the same reason: keep the FULL history even |
| 432 | 463 | // when the turn failed or was cancelled — the commands that already ran are |
| @@ -441,55 +472,78 @@ func (f *front) Prompt(ctx context.Context, p sdk.PromptRequest) (sdk.PromptResp | ||
| 441 | 472 | turn := s.messages[min(before, len(s.messages)):] |
| 442 | 473 | fmt.Fprintf(os.Stderr, "[acp] turn done: %d command(s) · %d file op(s) · %d skill(s) · %d lsp call(s)\n", |
| 443 | 474 | len(engine.CommandList(turn)), len(engine.FileOps(turn)), engine.Skills(turn), engine.LSPCalls(turn)) |
| 444 | - f.persist(p.SessionId, s) | |
| 475 | + f.persist(t.sid, s) | |
| 445 | 476 | // The meter once more, on the history as the turn left it: the last model |
| 446 | 477 | // call's measure predates the answer, and a server that reports nothing |
| 447 | 478 | // sent no update at all. The request's context, not the turn's: a |
| 448 | 479 | // cancelled turn still changed the history. |
| 449 | - f.sendUsage(context.WithoutCancel(ctx), p.SessionId, contextUsed(s)) | |
| 480 | + f.sendUsage(context.WithoutCancel(t.ctx), t.sid, contextUsed(s)) | |
| 481 | + return t.respond(err, asked) | |
| 482 | +} | |
| 450 | 483 | |
| 484 | +// respond answers session/prompt once the turn is over. | |
| 485 | +// | |
| 486 | +// A cancelled turn — and both roads lead here: our Cancel method fires | |
| 487 | +// s.cancel (the child), AND the SDK cancels the request's own context when | |
| 488 | +// session/cancel arrives (the parent — measured: with the | |
| 489 | +// parent-must-be-intact test the REPL uses, a cancelled turn answered | |
| 490 | +// "Internal error: stream error: context canceled" instead of honouring the | |
| 491 | +// spec's contract) — is answered anyway, with stopReason "cancelled". A | |
| 492 | +// failure is one line, in the provider's words — the same text the REPL | |
| 493 | +// prints between brackets, delivered as a JSON-RPC error — and recorded in | |
| 494 | +// the session's file, where the editor's red banner is not. | |
| 495 | +func (t *acpTurn) respond(err error, asked []*ai.Message) (sdk.PromptResponse, error) { | |
| 451 | 496 | switch { |
| 452 | - case turnCtx.Err() != nil: | |
| 453 | - // The turn was cancelled — and both roads lead here: our Cancel method | |
| 454 | - // fires s.cancel (the child), AND the SDK cancels the request's own | |
| 455 | - // context when session/cancel arrives (the parent — measured: with the | |
| 456 | - // parent-must-be-intact test the REPL uses, a cancelled turn answered | |
| 457 | - // "Internal error: stream error: context canceled" instead of honouring | |
| 458 | - // the spec's contract). Either way the answer is the same: respond to | |
| 459 | - // session/prompt anyway, with stopReason "cancelled". | |
| 460 | - return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: s.usage.totals()}, nil | |
| 497 | + case t.turnCtx.Err() != nil: | |
| 498 | + return t.cancelled(), nil | |
| 461 | 499 | case err != nil: |
| 462 | - // One line, in the provider's words — the same text the REPL prints | |
| 463 | - // between brackets, delivered as a JSON-RPC error — and recorded in | |
| 464 | - // the session's file, where the editor's red banner is not. | |
| 465 | - explained := f.e.Explain(err) | |
| 466 | - f.fail(p.SessionId, s, store.NewFailure(asked, store.FailGeneration, explained, err)) | |
| 500 | + explained := t.f.e.Explain(err) | |
| 501 | + t.f.fail(t.sid, t.s, store.NewFailure(asked, store.FailGeneration, explained, err)) | |
| 467 | 502 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": explained}) |
| 468 | 503 | } |
| 469 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | |
| 504 | + return t.endTurn(), nil | |
| 505 | +} | |
| 506 | + | |
| 507 | +// endTurn is the answer of a turn that ended normally. | |
| 508 | +func (t *acpTurn) endTurn() sdk.PromptResponse { | |
| 509 | + return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: t.s.usage.totals()} | |
| 510 | +} | |
| 511 | + | |
| 512 | +// cancelled is the answer of a cancelled turn. | |
| 513 | +func (t *acpTurn) cancelled() sdk.PromptResponse { | |
| 514 | + return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: t.s.usage.totals()} | |
| 470 | 515 | } |
| 471 | 516 | |
| 472 | 517 | // slashCommand runs input when it is one of the commands this front end |
| 473 | 518 | // handles itself, and says whether it was. Called under turnMu. |
| 474 | 519 | func (f *front) slashCommand(ctx context.Context, sid sdk.SessionId, s *session, input string) (sdk.PromptResponse, bool) { |
| 475 | - switch { | |
| 476 | - case command.Is(input, command.New): | |
| 477 | - return f.startNewSession(ctx, sid, s), true | |
| 478 | - case command.Is(input, command.Compact): | |
| 479 | - return f.compactSession(ctx, sid, s), true | |
| 480 | - } | |
| 481 | 520 | cmd, arg, ok := command.Parse(input) |
| 482 | - switch { | |
| 483 | - case ok && cmd.Name == command.Unload: | |
| 484 | - return f.unloadModel(ctx, sid, s, arg), true | |
| 485 | - case ok && cmd.Name == command.Memory: | |
| 486 | - return f.searchMemory(ctx, sid, s, arg), true | |
| 487 | - case ok && cmd.Name == command.Docs: | |
| 488 | - return f.searchDocs(ctx, sid, s, arg), true | |
| 489 | - case ok && cmd.Name == command.Redirect && arg == "": | |
| 490 | - return f.say(ctx, sid, s, redirectNeedsMessage), true | |
| 521 | + c, known := slashCommands[cmd.Name] | |
| 522 | + if !ok || !known || (c.bare && arg != "") { | |
| 523 | + return sdk.PromptResponse{}, false | |
| 491 | 524 | } |
| 492 | - return sdk.PromptResponse{}, false | |
| 525 | + return c.run(f, ctx, sid, s, arg), true | |
| 526 | +} | |
| 527 | + | |
| 528 | +// slashCommands are the commands answered without a turn. A bare one is | |
| 529 | +// answered here only without an argument: /redirect with a message is a | |
| 530 | +// turn (redirectCommand), without one it is a reminder of its usage. | |
| 531 | +var slashCommands = map[string]struct { | |
| 532 | + run func(f *front, ctx context.Context, sid sdk.SessionId, s *session, arg string) sdk.PromptResponse | |
| 533 | + bare bool | |
| 534 | +}{ | |
| 535 | + command.New: {bare: true, run: func(f *front, ctx context.Context, sid sdk.SessionId, s *session, _ string) sdk.PromptResponse { | |
| 536 | + return f.startNewSession(ctx, sid, s) | |
| 537 | + }}, | |
| 538 | + command.Compact: {bare: true, run: func(f *front, ctx context.Context, sid sdk.SessionId, s *session, _ string) sdk.PromptResponse { | |
| 539 | + return f.compactSession(ctx, sid, s) | |
| 540 | + }}, | |
| 541 | + command.Redirect: {bare: true, run: func(f *front, ctx context.Context, sid sdk.SessionId, s *session, _ string) sdk.PromptResponse { | |
| 542 | + return f.say(ctx, sid, s, redirectNeedsMessage) | |
| 543 | + }}, | |
| 544 | + command.Unload: {run: (*front).unloadModel}, | |
| 545 | + command.Memory: {run: (*front).searchMemory}, | |
| 546 | + command.Docs: {run: (*front).searchDocs}, | |
| 493 | 547 | } |
| 494 | 548 | |
| 495 | 549 | // searchDocs is /docs <words> over ACP: the passages found in the session's |
| @@ -29,6 +29,7 @@ import ( | |||
| 29 | "sync" | 29 | "sync" |
| 30 | 30 | ||
| 31 | "mm/internal/acpwire" | 31 | "mm/internal/acpwire" |
| 32 | + "mm/internal/agent" | ||
| 32 | "mm/internal/agentsmd" | 33 | "mm/internal/agentsmd" |
| 33 | "mm/internal/ask" | 34 | "mm/internal/ask" |
| 34 | "mm/internal/command" | 35 | "mm/internal/command" |
| @@ -120,13 +121,13 @@ var _ sdk.Agent = (*front)(nil) | |||
| 120 | // client closes it. Same arguments as agent.Run: main.go's wiring — engine, | 121 | // client closes it. Same arguments as agent.Run: main.go's wiring — engine, |
| 121 | // system prompt, tool list — is identical for the two front ends. | 122 | // system prompt, tool list — is identical for the two front ends. |
| 122 | // | 123 | // |
| 123 | -// d is the loop detector the built-in tools report to; the client tools | 124 | +// s.Detector is the loop detector the built-in tools report to; the client |
| 124 | -// (clienttools.go) report to it too. asker runs the /ask-<agent> commands; | 125 | +// tools (clienttools.go) report to it too. asker runs the /ask-<agent> commands; |
| 125 | // nil when no agent is configured. | 126 | // nil when no agent is configured. |
| 126 | -func Run(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, d *detector.LoopDetector, asker ask.Runner) { | 127 | +func Run(ctx context.Context, s agent.Setup, asker ask.Runner) { |
| 127 | - f := newFront(e, system, tools, os.Stdout, os.Stdin) | 128 | + f := newFront(s.Engine, s.System, s.Tools, os.Stdout, os.Stdin) |
| 128 | f.asker = asker | 129 | f.asker = asker |
| 129 | - f.detector = d | 130 | + f.detector = s.Detector |
| 130 | select { | 131 | select { |
| 131 | case <-f.conn.Done(): // the editor closed our stdin: we are done | 132 | case <-f.conn.Done(): // the editor closed our stdin: we are done |
| 132 | case <-ctx.Done(): | 133 | case <-ctx.Done(): |
| @@ -360,60 +361,90 @@ func (f *front) Prompt(ctx context.Context, p sdk.PromptRequest) (sdk.PromptResp | |||
| 360 | // A command the editor offered for a SKILL: "/greetings Bob" becomes the | 361 | // A command the editor offered for a SKILL: "/greetings Bob" becomes the |
| 361 | // `$greetings Bob` notation and the turn runs normally from here. Done | 362 | // `$greetings Bob` notation and the turn runs normally from here. Done |
| 362 | // after slashCommand, so a real command always wins whatever a skill is | 363 | // after slashCommand, so a real command always wins whatever a skill is |
| 363 | - // called. | 364 | + // called. /redirect <message> (ticket 267): a turn like any other, its |
| 364 | - input = skillCommand(input) | 365 | + // question framed as a correction of the task the history holds. |
| 365 | - // /redirect <message> (ticket 267): a turn like any other, its question | 366 | + input = redirectCommand(skillCommand(input)) |
| 366 | - // framed as a correction of the task the history holds. | 367 | + |
| 367 | - input = redirectCommand(input) | 368 | + t, end := f.beginTurn(ctx, p.SessionId, s) |
| 368 | - | 369 | + defer end() |
| 369 | - // One cancellable context per turn: session/cancel fires s.cancel, the | 370 | + return t.run(input) |
| 370 | - // generation and any pending permission request fall with it, and the spec's | 371 | +} |
| 371 | - // contract — still answer the prompt, with stopReason "cancelled" — is met | 372 | + |
| 372 | - // at the bottom of this function. | 373 | +// acpTurn is one session/prompt being answered: the request's context, the |
| 374 | +// turn's own (session/cancel cancels it), the session and the sink its | ||
| 375 | +// events go through. | ||
| 376 | +type acpTurn struct { | ||
| 377 | + f *front | ||
| 378 | + ctx context.Context | ||
| 379 | + turnCtx context.Context | ||
| 380 | + sid sdk.SessionId | ||
| 381 | + s *session | ||
| 382 | + k *sink | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +// beginTurn opens a turn on session s, and returns it with the function | ||
| 386 | +// that closes it. | ||
| 387 | +// | ||
| 388 | +// One cancellable context per turn: session/cancel fires s.cancel, the | ||
| 389 | +// generation and any pending permission request fall with it, and the | ||
| 390 | +// spec's contract — still answer the prompt, with stopReason "cancelled" — | ||
| 391 | +// is met in respond. The sink is what turns the tools' events into | ||
| 392 | +// session/update messages; installing it is what switches engine+tools to | ||
| 393 | +// "ACP mode" for this turn. | ||
| 394 | +func (f *front) beginTurn(ctx context.Context, sid sdk.SessionId, s *session) (*acpTurn, func()) { | ||
| 373 | turnCtx, cancel := context.WithCancel(ctx) | 395 | turnCtx, cancel := context.WithCancel(ctx) |
| 374 | f.mu.Lock() | 396 | f.mu.Lock() |
| 375 | s.cancel = cancel | 397 | s.cancel = cancel |
| 376 | f.mu.Unlock() | 398 | f.mu.Unlock() |
| 377 | - defer func() { | 399 | + t := &acpTurn{f: f, ctx: ctx, turnCtx: turnCtx, sid: sid, s: s, k: &sink{f: f, ctx: turnCtx, sid: sid, s: s}} |
| 400 | + ui.SetActive(t.k) | ||
| 401 | + return t, func() { | ||
| 402 | + ui.SetActive(nil) | ||
| 378 | f.mu.Lock() | 403 | f.mu.Lock() |
| 379 | s.cancel = nil | 404 | s.cancel = nil |
| 380 | f.mu.Unlock() | 405 | f.mu.Unlock() |
| 381 | cancel() | 406 | cancel() |
| 382 | - }() | 407 | + } |
| 383 | - | 408 | +} |
| 384 | - // The sink is what turns the tools' events into session/update messages; | ||
| 385 | - // installing it is what switches engine+tools to "ACP mode" for this turn. | ||
| 386 | - k := &sink{f: f, ctx: turnCtx, sid: p.SessionId, s: s} | ||
| 387 | - ui.SetActive(k) | ||
| 388 | - defer ui.SetActive(nil) | ||
| 389 | 409 | ||
| 390 | - // /ask-bob: another agent answers instead of our model (ask.go). | 410 | +// run answers the turn: another agent for /ask-bob (ask.go) and /a2a-alice |
| 411 | +// (a2a.go, ticket 263), else our model. | ||
| 412 | +func (t *acpTurn) run(input string) (sdk.PromptResponse, error) { | ||
| 391 | if req, isAsk, err := command.ParseAsk(input); isAsk { | 413 | if req, isAsk, err := command.ParseAsk(input); isAsk { |
| 392 | - return f.askAgent(ctx, turnCtx, p.SessionId, s, k, req, err) | 414 | + return t.askAgent(req, err) |
| 393 | } | 415 | } |
| 394 | - // /a2a-alice: a remote A2A agent answers (a2a.go, ticket 263). | ||
| 395 | if req, isA2A, err := command.ParseA2A(input); isA2A { | 416 | if req, isA2A, err := command.ParseA2A(input); isA2A { |
| 396 | - return f.a2aAgent(ctx, turnCtx, p.SessionId, s, k, req, err) | 417 | + return t.a2aAgent(req, err) |
| 397 | } | 418 | } |
| 419 | + return t.generate(t.expand(input)) | ||
| 420 | +} | ||
| 398 | 421 | ||
| 399 | - // A typed "@path" — the editor's picker bypassed, or an editor without | 422 | +// expand is the question as the model reads it. A typed "@path" — the |
| 400 | - // one — is understood like the resource_link the picker would have sent, | 423 | +// editor's picker bypassed, or an editor without one — is understood like |
| 401 | - // against the session's cwd, which is the project the editor opened. | 424 | +// the resource_link the picker would have sent, against the session's cwd, |
| 425 | +// which is the project the editor opened. Same for "$skill": the editor has | ||
| 426 | +// no picker for it, but the notation travels in the text and must mean what | ||
| 427 | +// it means in the terminal. | ||
| 428 | +func (t *acpTurn) expand(input string) string { | ||
| 402 | typed := input | 429 | typed := input |
| 403 | - input, attached := mention.Expand(input, s.cwd) | 430 | + input, attached := mention.Expand(input, t.s.cwd) |
| 404 | for _, a := range attached { | 431 | for _, a := range attached { |
| 405 | - fmt.Fprintf(os.Stderr, "[acp] session %s: attached %s\n", p.SessionId, a.Path) | 432 | + fmt.Fprintf(os.Stderr, "[acp] session %s: attached %s\n", t.sid, a.Path) |
| 406 | } | 433 | } |
| 407 | - // Same for "$skill": the editor has no picker for it, but the notation | ||
| 408 | - // travels in the text and must mean what it means in the terminal. | ||
| 409 | input, refs := skills.ExpandRefs(input, skills.Declared()) | 434 | input, refs := skills.ExpandRefs(input, skills.Declared()) |
| 410 | for _, ref := range refs { | 435 | for _, ref := range refs { |
| 411 | - fmt.Fprintf(os.Stderr, "[acp] session %s: skill %s\n", p.SessionId, ref.Name) | 436 | + fmt.Fprintf(os.Stderr, "[acp] session %s: skill %s\n", t.sid, ref.Name) |
| 412 | } | 437 | } |
| 413 | - input, routed := decide.RouteSkill(turnCtx, typed, input, len(refs), skills.Declared()) | 438 | + input, routed := decide.RouteSkill(t.turnCtx, typed, input, len(refs), skills.Declared()) |
| 414 | if routed != "" { | 439 | if routed != "" { |
| 415 | - fmt.Fprintf(os.Stderr, "[acp] session %s: %s\n", p.SessionId, routed) | 440 | + fmt.Fprintf(os.Stderr, "[acp] session %s: %s\n", t.sid, routed) |
| 416 | } | 441 | } |
| 442 | + return input | ||
| 443 | +} | ||
| 444 | + | ||
| 445 | +// generate runs the model's turn on the question and keeps its history. | ||
| 446 | +func (t *acpTurn) generate(input string) (sdk.PromptResponse, error) { | ||
| 447 | + f, s := t.f, t.s | ||
| 417 | s.messages = append(s.messages, ai.NewUserTextMessage(input)) | 448 | s.messages = append(s.messages, ai.NewUserTextMessage(input)) |
| 418 | before := len(s.messages) | 449 | before := len(s.messages) |
| 419 | 450 | ||
| @@ -421,12 +452,12 @@ func (f *front) Prompt(ctx context.Context, p sdk.PromptRequest) (sdk.PromptResp | |||
| 421 | // after the agent left it unknown for good; asking again while it is | 452 | // after the agent left it unknown for good; asking again while it is |
| 422 | // unknown is the REPL's rule (agent.go), and costs nothing once known. | 453 | // unknown is the REPL's rule (agent.go), and costs nothing once known. |
| 423 | if f.e.ContextWindow == 0 { | 454 | if f.e.ContextWindow == 0 { |
| 424 | - if w, src := f.e.EnsureContextWindow(turnCtx); w > 0 { | 455 | + if w, src := f.e.EnsureContextWindow(t.turnCtx); w > 0 { |
| 425 | fmt.Fprintf(os.Stderr, "[acp] ctx: %d (%s)\n", w, src) | 456 | fmt.Fprintf(os.Stderr, "[acp] ctx: %d (%s)\n", w, src) |
| 426 | } | 457 | } |
| 427 | } | 458 | } |
| 428 | 459 | ||
| 429 | - resp, full, err := f.e.Generate(turnCtx, s.messages, f.turnTools(s)) | 460 | + resp, full, err := f.e.Generate(t.turnCtx, s.messages, f.turnTools(s)) |
| 430 | 461 | ||
| 431 | // Same rule as the REPL, for the same reason: keep the FULL history even | 462 | // Same rule as the REPL, for the same reason: keep the FULL history even |
| 432 | // when the turn failed or was cancelled — the commands that already ran are | 463 | // when the turn failed or was cancelled — the commands that already ran are |
| @@ -441,55 +472,78 @@ func (f *front) Prompt(ctx context.Context, p sdk.PromptRequest) (sdk.PromptResp | |||
| 441 | turn := s.messages[min(before, len(s.messages)):] | 472 | turn := s.messages[min(before, len(s.messages)):] |
| 442 | fmt.Fprintf(os.Stderr, "[acp] turn done: %d command(s) · %d file op(s) · %d skill(s) · %d lsp call(s)\n", | 473 | fmt.Fprintf(os.Stderr, "[acp] turn done: %d command(s) · %d file op(s) · %d skill(s) · %d lsp call(s)\n", |
| 443 | len(engine.CommandList(turn)), len(engine.FileOps(turn)), engine.Skills(turn), engine.LSPCalls(turn)) | 474 | len(engine.CommandList(turn)), len(engine.FileOps(turn)), engine.Skills(turn), engine.LSPCalls(turn)) |
| 444 | - f.persist(p.SessionId, s) | 475 | + f.persist(t.sid, s) |
| 445 | // The meter once more, on the history as the turn left it: the last model | 476 | // The meter once more, on the history as the turn left it: the last model |
| 446 | // call's measure predates the answer, and a server that reports nothing | 477 | // call's measure predates the answer, and a server that reports nothing |
| 447 | // sent no update at all. The request's context, not the turn's: a | 478 | // sent no update at all. The request's context, not the turn's: a |
| 448 | // cancelled turn still changed the history. | 479 | // cancelled turn still changed the history. |
| 449 | - f.sendUsage(context.WithoutCancel(ctx), p.SessionId, contextUsed(s)) | 480 | + f.sendUsage(context.WithoutCancel(t.ctx), t.sid, contextUsed(s)) |
| 481 | + return t.respond(err, asked) | ||
| 482 | +} | ||
| 450 | 483 | ||
| 484 | +// respond answers session/prompt once the turn is over. | ||
| 485 | +// | ||
| 486 | +// A cancelled turn — and both roads lead here: our Cancel method fires | ||
| 487 | +// s.cancel (the child), AND the SDK cancels the request's own context when | ||
| 488 | +// session/cancel arrives (the parent — measured: with the | ||
| 489 | +// parent-must-be-intact test the REPL uses, a cancelled turn answered | ||
| 490 | +// "Internal error: stream error: context canceled" instead of honouring the | ||
| 491 | +// spec's contract) — is answered anyway, with stopReason "cancelled". A | ||
| 492 | +// failure is one line, in the provider's words — the same text the REPL | ||
| 493 | +// prints between brackets, delivered as a JSON-RPC error — and recorded in | ||
| 494 | +// the session's file, where the editor's red banner is not. | ||
| 495 | +func (t *acpTurn) respond(err error, asked []*ai.Message) (sdk.PromptResponse, error) { | ||
| 451 | switch { | 496 | switch { |
| 452 | - case turnCtx.Err() != nil: | 497 | + case t.turnCtx.Err() != nil: |
| 453 | - // The turn was cancelled — and both roads lead here: our Cancel method | 498 | + return t.cancelled(), nil |
| 454 | - // fires s.cancel (the child), AND the SDK cancels the request's own | ||
| 455 | - // context when session/cancel arrives (the parent — measured: with the | ||
| 456 | - // parent-must-be-intact test the REPL uses, a cancelled turn answered | ||
| 457 | - // "Internal error: stream error: context canceled" instead of honouring | ||
| 458 | - // the spec's contract). Either way the answer is the same: respond to | ||
| 459 | - // session/prompt anyway, with stopReason "cancelled". | ||
| 460 | - return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: s.usage.totals()}, nil | ||
| 461 | case err != nil: | 499 | case err != nil: |
| 462 | - // One line, in the provider's words — the same text the REPL prints | 500 | + explained := t.f.e.Explain(err) |
| 463 | - // between brackets, delivered as a JSON-RPC error — and recorded in | 501 | + t.f.fail(t.sid, t.s, store.NewFailure(asked, store.FailGeneration, explained, err)) |
| 464 | - // the session's file, where the editor's red banner is not. | ||
| 465 | - explained := f.e.Explain(err) | ||
| 466 | - f.fail(p.SessionId, s, store.NewFailure(asked, store.FailGeneration, explained, err)) | ||
| 467 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": explained}) | 502 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": explained}) |
| 468 | } | 503 | } |
| 469 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | 504 | + return t.endTurn(), nil |
| 505 | +} | ||
| 506 | + | ||
| 507 | +// endTurn is the answer of a turn that ended normally. | ||
| 508 | +func (t *acpTurn) endTurn() sdk.PromptResponse { | ||
| 509 | + return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: t.s.usage.totals()} | ||
| 510 | +} | ||
| 511 | + | ||
| 512 | +// cancelled is the answer of a cancelled turn. | ||
| 513 | +func (t *acpTurn) cancelled() sdk.PromptResponse { | ||
| 514 | + return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: t.s.usage.totals()} | ||
| 470 | } | 515 | } |
| 471 | 516 | ||
| 472 | // slashCommand runs input when it is one of the commands this front end | 517 | // slashCommand runs input when it is one of the commands this front end |
| 473 | // handles itself, and says whether it was. Called under turnMu. | 518 | // handles itself, and says whether it was. Called under turnMu. |
| 474 | func (f *front) slashCommand(ctx context.Context, sid sdk.SessionId, s *session, input string) (sdk.PromptResponse, bool) { | 519 | func (f *front) slashCommand(ctx context.Context, sid sdk.SessionId, s *session, input string) (sdk.PromptResponse, bool) { |
| 475 | - switch { | ||
| 476 | - case command.Is(input, command.New): | ||
| 477 | - return f.startNewSession(ctx, sid, s), true | ||
| 478 | - case command.Is(input, command.Compact): | ||
| 479 | - return f.compactSession(ctx, sid, s), true | ||
| 480 | - } | ||
| 481 | cmd, arg, ok := command.Parse(input) | 520 | cmd, arg, ok := command.Parse(input) |
| 482 | - switch { | 521 | + c, known := slashCommands[cmd.Name] |
| 483 | - case ok && cmd.Name == command.Unload: | 522 | + if !ok || !known || (c.bare && arg != "") { |
| 484 | - return f.unloadModel(ctx, sid, s, arg), true | 523 | + return sdk.PromptResponse{}, false |
| 485 | - case ok && cmd.Name == command.Memory: | ||
| 486 | - return f.searchMemory(ctx, sid, s, arg), true | ||
| 487 | - case ok && cmd.Name == command.Docs: | ||
| 488 | - return f.searchDocs(ctx, sid, s, arg), true | ||
| 489 | - case ok && cmd.Name == command.Redirect && arg == "": | ||
| 490 | - return f.say(ctx, sid, s, redirectNeedsMessage), true | ||
| 491 | } | 524 | } |
| 492 | - return sdk.PromptResponse{}, false | 525 | + return c.run(f, ctx, sid, s, arg), true |
| 526 | +} | ||
| 527 | + | ||
| 528 | +// slashCommands are the commands answered without a turn. A bare one is | ||
| 529 | +// answered here only without an argument: /redirect with a message is a | ||
| 530 | +// turn (redirectCommand), without one it is a reminder of its usage. | ||
| 531 | +var slashCommands = map[string]struct { | ||
| 532 | + run func(f *front, ctx context.Context, sid sdk.SessionId, s *session, arg string) sdk.PromptResponse | ||
| 533 | + bare bool | ||
| 534 | +}{ | ||
| 535 | + command.New: {bare: true, run: func(f *front, ctx context.Context, sid sdk.SessionId, s *session, _ string) sdk.PromptResponse { | ||
| 536 | + return f.startNewSession(ctx, sid, s) | ||
| 537 | + }}, | ||
| 538 | + command.Compact: {bare: true, run: func(f *front, ctx context.Context, sid sdk.SessionId, s *session, _ string) sdk.PromptResponse { | ||
| 539 | + return f.compactSession(ctx, sid, s) | ||
| 540 | + }}, | ||
| 541 | + command.Redirect: {bare: true, run: func(f *front, ctx context.Context, sid sdk.SessionId, s *session, _ string) sdk.PromptResponse { | ||
| 542 | + return f.say(ctx, sid, s, redirectNeedsMessage) | ||
| 543 | + }}, | ||
| 544 | + command.Unload: {run: (*front).unloadModel}, | ||
| 545 | + command.Memory: {run: (*front).searchMemory}, | ||
| 546 | + command.Docs: {run: (*front).searchDocs}, | ||
| 493 | } | 547 | } |
| 494 | 548 | ||
| 495 | // searchDocs is /docs <words> over ACP: the passages found in the session's | 549 | // searchDocs is /docs <words> over ACP: the passages found in the session's |
modified
internal/acp/ask.go +14 -13 | @@ -19,24 +19,25 @@ import ( | ||
| 19 | 19 | // cancelled (stopReason "cancelled"), and a failure is a JSON-RPC error in the |
| 20 | 20 | // agent's words and a record in the session file; either way the history is |
| 21 | 21 | // left as it was. |
| 22 | -func (f *front) askAgent(ctx, turnCtx context.Context, sid sdk.SessionId, s *session, k *sink, req command.AskRequest, parseErr error) (sdk.PromptResponse, error) { | |
| 22 | +func (t *acpTurn) askAgent(req command.AskRequest, parseErr error) (sdk.PromptResponse, error) { | |
| 23 | + f, s := t.f, t.s | |
| 23 | 24 | if parseErr != nil { |
| 24 | - k.Text("⚠️ " + parseErr.Error()) | |
| 25 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | |
| 25 | + t.k.Text("⚠️ " + parseErr.Error()) | |
| 26 | + return t.endTurn(), nil | |
| 26 | 27 | } |
| 27 | - k.Text(ask.Label(req) + "\n\n") | |
| 28 | - exchange, err := f.asker.Run(turnCtx, req, s.messages, s.cwd, k) | |
| 28 | + t.k.Text(ask.Label(req) + "\n\n") | |
| 29 | + exchange, err := f.asker.Run(t.turnCtx, req, s.messages, s.cwd, t.k) | |
| 29 | 30 | switch { |
| 30 | - case turnCtx.Err() != nil: | |
| 31 | - return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: s.usage.totals()}, nil | |
| 31 | + case t.turnCtx.Err() != nil: | |
| 32 | + return t.cancelled(), nil | |
| 32 | 33 | case err != nil: |
| 33 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s failed: %v\n", sid, req.Agent, err) | |
| 34 | - f.fail(sid, s, store.NewFailure(s.messages, store.FailAsk, err.Error(), err)) | |
| 34 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s failed: %v\n", t.sid, req.Agent, err) | |
| 35 | + f.fail(t.sid, s, store.NewFailure(s.messages, store.FailAsk, err.Error(), err)) | |
| 35 | 36 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": err.Error()}) |
| 36 | 37 | } |
| 37 | 38 | s.messages = append(s.messages, exchange...) |
| 38 | - f.persist(sid, s) | |
| 39 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s answered\n", sid, req.Agent) | |
| 40 | - f.sendUsage(context.WithoutCancel(ctx), sid, contextUsed(s)) | |
| 41 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | |
| 39 | + f.persist(t.sid, s) | |
| 40 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s answered\n", t.sid, req.Agent) | |
| 41 | + f.sendUsage(context.WithoutCancel(t.ctx), t.sid, contextUsed(s)) | |
| 42 | + return t.endTurn(), nil | |
| 42 | 43 | } |
| @@ -19,24 +19,25 @@ import ( | |||
| 19 | // cancelled (stopReason "cancelled"), and a failure is a JSON-RPC error in the | 19 | // cancelled (stopReason "cancelled"), and a failure is a JSON-RPC error in the |
| 20 | // agent's words and a record in the session file; either way the history is | 20 | // agent's words and a record in the session file; either way the history is |
| 21 | // left as it was. | 21 | // left as it was. |
| 22 | -func (f *front) askAgent(ctx, turnCtx context.Context, sid sdk.SessionId, s *session, k *sink, req command.AskRequest, parseErr error) (sdk.PromptResponse, error) { | 22 | +func (t *acpTurn) askAgent(req command.AskRequest, parseErr error) (sdk.PromptResponse, error) { |
| 23 | + f, s := t.f, t.s | ||
| 23 | if parseErr != nil { | 24 | if parseErr != nil { |
| 24 | - k.Text("⚠️ " + parseErr.Error()) | 25 | + t.k.Text("⚠️ " + parseErr.Error()) |
| 25 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | 26 | + return t.endTurn(), nil |
| 26 | } | 27 | } |
| 27 | - k.Text(ask.Label(req) + "\n\n") | 28 | + t.k.Text(ask.Label(req) + "\n\n") |
| 28 | - exchange, err := f.asker.Run(turnCtx, req, s.messages, s.cwd, k) | 29 | + exchange, err := f.asker.Run(t.turnCtx, req, s.messages, s.cwd, t.k) |
| 29 | switch { | 30 | switch { |
| 30 | - case turnCtx.Err() != nil: | 31 | + case t.turnCtx.Err() != nil: |
| 31 | - return sdk.PromptResponse{StopReason: sdk.StopReasonCancelled, Usage: s.usage.totals()}, nil | 32 | + return t.cancelled(), nil |
| 32 | case err != nil: | 33 | case err != nil: |
| 33 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s failed: %v\n", sid, req.Agent, err) | 34 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s failed: %v\n", t.sid, req.Agent, err) |
| 34 | - f.fail(sid, s, store.NewFailure(s.messages, store.FailAsk, err.Error(), err)) | 35 | + f.fail(t.sid, s, store.NewFailure(s.messages, store.FailAsk, err.Error(), err)) |
| 35 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": err.Error()}) | 36 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": err.Error()}) |
| 36 | } | 37 | } |
| 37 | s.messages = append(s.messages, exchange...) | 38 | s.messages = append(s.messages, exchange...) |
| 38 | - f.persist(sid, s) | 39 | + f.persist(t.sid, s) |
| 39 | - fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s answered\n", sid, req.Agent) | 40 | + fmt.Fprintf(os.Stderr, "[acp] session %s: /ask %s answered\n", t.sid, req.Agent) |
| 40 | - f.sendUsage(context.WithoutCancel(ctx), sid, contextUsed(s)) | 41 | + f.sendUsage(context.WithoutCancel(t.ctx), t.sid, contextUsed(s)) |
| 41 | - return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn, Usage: s.usage.totals()}, nil | 42 | + return t.endTurn(), nil |
| 42 | } | 43 | } |
modified
internal/acp/clienttools.go +18 -186 | @@ -30,10 +30,7 @@ import ( | ||
| 30 | 30 | "strings" |
| 31 | 31 | |
| 32 | 32 | "mm/internal/config" |
| 33 | - "mm/internal/consent" | |
| 34 | - "mm/internal/detector" | |
| 35 | 33 | "mm/internal/mcp" |
| 36 | - "mm/internal/ui" | |
| 37 | 34 | |
| 38 | 35 | sdk "github.com/coder/acp-go-sdk" |
| 39 | 36 | "github.com/firebase/genkit/go/ai" |
| @@ -115,14 +112,8 @@ func parseClientTool(entry json.RawMessage) (clientTool, error) { | ||
| 115 | 112 | if err := json.Unmarshal(entry, &spec); err != nil { |
| 116 | 113 | return clientTool{}, fmt.Errorf("not a tool description: %v", err) |
| 117 | 114 | } |
| 118 | - if strings.TrimSpace(spec.Name) == "" { | |
| 119 | - return clientTool{}, errors.New("no name") | |
| 120 | - } | |
| 121 | - if !strings.HasPrefix(spec.Method, "_") { | |
| 122 | - return clientTool{}, fmt.Errorf("tool %q: method %q must start with \"_\" (an ACP extension method)", spec.Name, spec.Method) | |
| 123 | - } | |
| 124 | - if t, ok := spec.InputSchema["type"]; ok && t != "object" { | |
| 125 | - return clientTool{}, fmt.Errorf("tool %q: inputSchema.type must be \"object\", got %v", spec.Name, t) | |
| 115 | + if err := checkClientToolSpec(spec); err != nil { | |
| 116 | + return clientTool{}, err | |
| 126 | 117 | } |
| 127 | 118 | modelName, err := mcp.SanitizeToolName(clientToolPrefix, spec.Name) |
| 128 | 119 | if err != nil { |
| @@ -131,6 +122,22 @@ func parseClientTool(entry json.RawMessage) (clientTool, error) { | ||
| 131 | 122 | return clientTool{spec: spec, modelName: modelName}, nil |
| 132 | 123 | } |
| 133 | 124 | |
| 125 | +// checkClientToolSpec says what is wrong with a tool description: no name, | |
| 126 | +// a method that is not an ACP extension, or arguments that are not an | |
| 127 | +// object. | |
| 128 | +func checkClientToolSpec(spec clientToolSpec) error { | |
| 129 | + switch { | |
| 130 | + case strings.TrimSpace(spec.Name) == "": | |
| 131 | + return errors.New("no name") | |
| 132 | + case !strings.HasPrefix(spec.Method, "_"): | |
| 133 | + return fmt.Errorf("tool %q: method %q must start with \"_\" (an ACP extension method)", spec.Name, spec.Method) | |
| 134 | + } | |
| 135 | + if t, ok := spec.InputSchema["type"]; ok && t != "object" { | |
| 136 | + return fmt.Errorf("tool %q: inputSchema.type must be \"object\", got %v", spec.Name, t) | |
| 137 | + } | |
| 138 | + return nil | |
| 139 | +} | |
| 140 | + | |
| 134 | 141 | // --- discovery ----------------------------------------------------------------- |
| 135 | 142 | |
| 136 | 143 | // readClientToolsCapability reads what the client advertised at initialize, |
| @@ -221,181 +228,6 @@ func clientToolNames(tools []clientTool) string { | ||
| 221 | 228 | return strings.Join(names, ", ") |
| 222 | 229 | } |
| 223 | 230 | |
| 224 | -// --- the tool ------------------------------------------------------------------ | |
| 225 | - | |
| 226 | -// defineClientTool builds the Genkit tool of one client tool, bound to the | |
| 227 | -// session it belongs to. The tool is not registered: Genkit registers a | |
| 228 | -// dynamic tool for the duration of the call it is passed to, so two sessions | |
| 229 | -// may hold tools of the same name with different lists. | |
| 230 | -func (f *front) defineClientTool(sid sdk.SessionId, t clientTool) ai.ToolRef { | |
| 231 | - return ai.NewTool(t.modelName, clientToolDescription(t.spec), | |
| 232 | - func(tctx *ai.ToolContext, raw any) (string, error) { | |
| 233 | - in, _ := raw.(map[string]any) | |
| 234 | - if in == nil { | |
| 235 | - in = map[string]any{} | |
| 236 | - } | |
| 237 | - return f.runClientTool(tctx, sid, t, in) | |
| 238 | - }, | |
| 239 | - ai.WithInputSchema(mcp.ModelSchema(t.spec.InputSchema))) | |
| 240 | -} | |
| 241 | - | |
| 242 | -// clientToolDescription is the description the model reads: the client's, | |
| 243 | -// plus the required parameters, which mcp.ModelSchema takes out of the | |
| 244 | -// schema (a call missing one is answered by runClientTool instead). | |
| 245 | -func clientToolDescription(spec clientToolSpec) string { | |
| 246 | - description := spec.Description | |
| 247 | - if description == "" { | |
| 248 | - description = "Tool provided by the editor (" + spec.Method + ")." | |
| 249 | - } | |
| 250 | - if required := requiredParams(spec.InputSchema); len(required) > 0 { | |
| 251 | - description += "\nRequired parameters: " + strings.Join(required, ", ") | |
| 252 | - } | |
| 253 | - return description | |
| 254 | -} | |
| 255 | - | |
| 256 | -// requiredParams reads the `required` list of a JSON schema. | |
| 257 | -func requiredParams(schema map[string]any) []string { | |
| 258 | - list, _ := schema["required"].([]any) | |
| 259 | - var names []string | |
| 260 | - for _, v := range list { | |
| 261 | - if name, ok := v.(string); ok { | |
| 262 | - names = append(names, name) | |
| 263 | - } | |
| 264 | - } | |
| 265 | - return names | |
| 266 | -} | |
| 267 | - | |
| 268 | -// runClientTool is one call of a client tool, on the event path every ACP | |
| 269 | -// tool takes: the editor sees the call start, may be asked for permission, | |
| 270 | -// and sees the result. Whatever happens, the model gets an answer it can | |
| 271 | -// read; only a loop the detector stops ends the turn. | |
| 272 | -func (f *front) runClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | |
| 273 | - ev := ui.ToolEvent{ID: ui.NextCallID(), Tool: t.modelName, Title: "client: " + t.spec.Name, Kind: "other", Input: in} | |
| 274 | - sink := ui.ActiveSink() | |
| 275 | - if sink != nil { | |
| 276 | - sink.ToolStart(ev) | |
| 277 | - } | |
| 278 | - if mustAskClientTool() && (sink == nil || !sink.Allow(ctx, ev)) { | |
| 279 | - out := fmt.Sprintf("[%s rejected by user]", t.modelName) | |
| 280 | - if sink != nil { | |
| 281 | - sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true}) | |
| 282 | - } | |
| 283 | - return f.recordClientTool(t.modelName, in, out, true) | |
| 284 | - } | |
| 285 | - if sink != nil { | |
| 286 | - sink.ToolRunning(ev.ID) | |
| 287 | - } | |
| 288 | - out, err := f.callClientTool(ctx, sid, t, in) | |
| 289 | - failed := err != nil | |
| 290 | - if failed { | |
| 291 | - out = fmt.Sprintf("[client tool error: %v]", err) | |
| 292 | - } | |
| 293 | - out = mcp.Truncate(out) | |
| 294 | - if sink != nil { | |
| 295 | - sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed}) | |
| 296 | - } | |
| 297 | - return f.recordClientTool(t.modelName, in, out, failed) | |
| 298 | -} | |
| 299 | - | |
| 300 | -// mustAskClientTool says whether a call waits for the user: always with | |
| 301 | -// permissions "ask", and with "auto" when yolo is off — the MCP rule. | |
| 302 | -func mustAskClientTool() bool { | |
| 303 | - return config.Cfg.ACP.ClientTools.Permissions == config.PermissionsAsk || consent.Required() | |
| 304 | -} | |
| 305 | - | |
| 306 | -// callClientTool sends the extension request and reads the answer. | |
| 307 | -func (f *front) callClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | |
| 308 | - if missing := missingParams(requiredParams(t.spec.InputSchema), in); len(missing) > 0 { | |
| 309 | - return "", fmt.Errorf("missing required parameters: %s", strings.Join(missing, ", ")) | |
| 310 | - } | |
| 311 | - ctx, cancel := context.WithTimeout(ctx, config.Cfg.ACP.ClientTools.Timeout) | |
| 312 | - defer cancel() | |
| 313 | - raw, err := f.conn.CallExtension(ctx, t.spec.Method, callParams(sid, in)) | |
| 314 | - if err != nil { | |
| 315 | - return "", err | |
| 316 | - } | |
| 317 | - return clientToolOutput(raw) | |
| 318 | -} | |
| 319 | - | |
| 320 | -// missingParams lists the required parameters the model left out. | |
| 321 | -func missingParams(required []string, in map[string]any) []string { | |
| 322 | - var missing []string | |
| 323 | - for _, name := range required { | |
| 324 | - if _, ok := in[name]; !ok { | |
| 325 | - missing = append(missing, name) | |
| 326 | - } | |
| 327 | - } | |
| 328 | - return missing | |
| 329 | -} | |
| 330 | - | |
| 331 | -// callParams are the params of a call: the model's arguments, plus the | |
| 332 | -// session id in `_meta` — ACP's slot for data that is not an argument. The | |
| 333 | -// model's own `_meta`, if it invented one, is replaced. | |
| 334 | -// | |
| 335 | -// callParams("s1", map[string]any{"q": "x"}) | |
| 336 | -// // {"q": "x", "_meta": {"org.mini-me/sessionId": "s1"}} | |
| 337 | -func callParams(sid sdk.SessionId, in map[string]any) map[string]any { | |
| 338 | - params := make(map[string]any, len(in)+1) | |
| 339 | - for k, v := range in { | |
| 340 | - params[k] = v | |
| 341 | - } | |
| 342 | - params["_meta"] = map[string]any{sessionIDMetaKey: string(sid)} | |
| 343 | - return params | |
| 344 | -} | |
| 345 | - | |
| 346 | -// clientToolResult is the answer shape mm reads first: MCP's content list. | |
| 347 | -type clientToolResult struct { | |
| 348 | - Content []struct { | |
| 349 | - Type string `json:"type"` | |
| 350 | - Text string `json:"text"` | |
| 351 | - } `json:"content"` | |
| 352 | - IsError bool `json:"isError"` | |
| 353 | -} | |
| 354 | - | |
| 355 | -// clientToolOutput turns the client's answer into the text the model reads. | |
| 356 | -// Two shapes are accepted: MCP's `{"content":[{"type":"text","text":…}], | |
| 357 | -// "isError":…}` — the text blocks joined, an error when isError — and any | |
| 358 | -// other JSON value, given to the model as is (a JSON string unquoted). | |
| 359 | -func clientToolOutput(raw json.RawMessage) (string, error) { | |
| 360 | - var result clientToolResult | |
| 361 | - if err := json.Unmarshal(raw, &result); err == nil && result.Content != nil { | |
| 362 | - var text strings.Builder | |
| 363 | - for _, block := range result.Content { | |
| 364 | - if block.Type == "text" { | |
| 365 | - text.WriteString(block.Text) | |
| 366 | - } else { | |
| 367 | - fmt.Fprintf(&text, "[client tool: non-text content of type %s skipped]", block.Type) | |
| 368 | - } | |
| 369 | - } | |
| 370 | - if result.IsError { | |
| 371 | - return "", errors.New(text.String()) | |
| 372 | - } | |
| 373 | - return text.String(), nil | |
| 374 | - } | |
| 375 | - var text string | |
| 376 | - if json.Unmarshal(raw, &text) == nil { | |
| 377 | - return text, nil | |
| 378 | - } | |
| 379 | - return string(raw), nil | |
| 380 | -} | |
| 381 | - | |
| 382 | -// recordClientTool tells the loop detector about the call, like every other | |
| 383 | -// tool does: the same call repeated is flagged, then stops the turn. | |
| 384 | -func (f *front) recordClientTool(name string, in map[string]any, out string, failed bool) (string, error) { | |
| 385 | - d := f.detector | |
| 386 | - if d == nil { | |
| 387 | - return out, nil | |
| 388 | - } | |
| 389 | - input, _ := json.Marshal(in) | |
| 390 | - if !d.Record(detector.Action{ToolName: name, Input: string(input), Output: out, Failed: failed}) { | |
| 391 | - return out, nil | |
| 392 | - } | |
| 393 | - if d.Stuck() { | |
| 394 | - return "", d.StuckError(name) | |
| 395 | - } | |
| 396 | - return out + "\n\n" + d.LoopError(), nil | |
| 397 | -} | |
| 398 | - | |
| 399 | 231 | // turnTools are the tools of one turn: the agent's own, then the session's |
| 400 | 232 | // client tools. A new slice, so f.tools is never appended to in place. |
| 401 | 233 | // |
| @@ -30,10 +30,7 @@ import ( | |||
| 30 | "strings" | 30 | "strings" |
| 31 | 31 | ||
| 32 | "mm/internal/config" | 32 | "mm/internal/config" |
| 33 | - "mm/internal/consent" | ||
| 34 | - "mm/internal/detector" | ||
| 35 | "mm/internal/mcp" | 33 | "mm/internal/mcp" |
| 36 | - "mm/internal/ui" | ||
| 37 | 34 | ||
| 38 | sdk "github.com/coder/acp-go-sdk" | 35 | sdk "github.com/coder/acp-go-sdk" |
| 39 | "github.com/firebase/genkit/go/ai" | 36 | "github.com/firebase/genkit/go/ai" |
| @@ -115,14 +112,8 @@ func parseClientTool(entry json.RawMessage) (clientTool, error) { | |||
| 115 | if err := json.Unmarshal(entry, &spec); err != nil { | 112 | if err := json.Unmarshal(entry, &spec); err != nil { |
| 116 | return clientTool{}, fmt.Errorf("not a tool description: %v", err) | 113 | return clientTool{}, fmt.Errorf("not a tool description: %v", err) |
| 117 | } | 114 | } |
| 118 | - if strings.TrimSpace(spec.Name) == "" { | 115 | + if err := checkClientToolSpec(spec); err != nil { |
| 119 | - return clientTool{}, errors.New("no name") | 116 | + return clientTool{}, err |
| 120 | - } | ||
| 121 | - if !strings.HasPrefix(spec.Method, "_") { | ||
| 122 | - return clientTool{}, fmt.Errorf("tool %q: method %q must start with \"_\" (an ACP extension method)", spec.Name, spec.Method) | ||
| 123 | - } | ||
| 124 | - if t, ok := spec.InputSchema["type"]; ok && t != "object" { | ||
| 125 | - return clientTool{}, fmt.Errorf("tool %q: inputSchema.type must be \"object\", got %v", spec.Name, t) | ||
| 126 | } | 117 | } |
| 127 | modelName, err := mcp.SanitizeToolName(clientToolPrefix, spec.Name) | 118 | modelName, err := mcp.SanitizeToolName(clientToolPrefix, spec.Name) |
| 128 | if err != nil { | 119 | if err != nil { |
| @@ -131,6 +122,22 @@ func parseClientTool(entry json.RawMessage) (clientTool, error) { | |||
| 131 | return clientTool{spec: spec, modelName: modelName}, nil | 122 | return clientTool{spec: spec, modelName: modelName}, nil |
| 132 | } | 123 | } |
| 133 | 124 | ||
| 125 | +// checkClientToolSpec says what is wrong with a tool description: no name, | ||
| 126 | +// a method that is not an ACP extension, or arguments that are not an | ||
| 127 | +// object. | ||
| 128 | +func checkClientToolSpec(spec clientToolSpec) error { | ||
| 129 | + switch { | ||
| 130 | + case strings.TrimSpace(spec.Name) == "": | ||
| 131 | + return errors.New("no name") | ||
| 132 | + case !strings.HasPrefix(spec.Method, "_"): | ||
| 133 | + return fmt.Errorf("tool %q: method %q must start with \"_\" (an ACP extension method)", spec.Name, spec.Method) | ||
| 134 | + } | ||
| 135 | + if t, ok := spec.InputSchema["type"]; ok && t != "object" { | ||
| 136 | + return fmt.Errorf("tool %q: inputSchema.type must be \"object\", got %v", spec.Name, t) | ||
| 137 | + } | ||
| 138 | + return nil | ||
| 139 | +} | ||
| 140 | + | ||
| 134 | // --- discovery ----------------------------------------------------------------- | 141 | // --- discovery ----------------------------------------------------------------- |
| 135 | 142 | ||
| 136 | // readClientToolsCapability reads what the client advertised at initialize, | 143 | // readClientToolsCapability reads what the client advertised at initialize, |
| @@ -221,181 +228,6 @@ func clientToolNames(tools []clientTool) string { | |||
| 221 | return strings.Join(names, ", ") | 228 | return strings.Join(names, ", ") |
| 222 | } | 229 | } |
| 223 | 230 | ||
| 224 | -// --- the tool ------------------------------------------------------------------ | ||
| 225 | - | ||
| 226 | -// defineClientTool builds the Genkit tool of one client tool, bound to the | ||
| 227 | -// session it belongs to. The tool is not registered: Genkit registers a | ||
| 228 | -// dynamic tool for the duration of the call it is passed to, so two sessions | ||
| 229 | -// may hold tools of the same name with different lists. | ||
| 230 | -func (f *front) defineClientTool(sid sdk.SessionId, t clientTool) ai.ToolRef { | ||
| 231 | - return ai.NewTool(t.modelName, clientToolDescription(t.spec), | ||
| 232 | - func(tctx *ai.ToolContext, raw any) (string, error) { | ||
| 233 | - in, _ := raw.(map[string]any) | ||
| 234 | - if in == nil { | ||
| 235 | - in = map[string]any{} | ||
| 236 | - } | ||
| 237 | - return f.runClientTool(tctx, sid, t, in) | ||
| 238 | - }, | ||
| 239 | - ai.WithInputSchema(mcp.ModelSchema(t.spec.InputSchema))) | ||
| 240 | -} | ||
| 241 | - | ||
| 242 | -// clientToolDescription is the description the model reads: the client's, | ||
| 243 | -// plus the required parameters, which mcp.ModelSchema takes out of the | ||
| 244 | -// schema (a call missing one is answered by runClientTool instead). | ||
| 245 | -func clientToolDescription(spec clientToolSpec) string { | ||
| 246 | - description := spec.Description | ||
| 247 | - if description == "" { | ||
| 248 | - description = "Tool provided by the editor (" + spec.Method + ")." | ||
| 249 | - } | ||
| 250 | - if required := requiredParams(spec.InputSchema); len(required) > 0 { | ||
| 251 | - description += "\nRequired parameters: " + strings.Join(required, ", ") | ||
| 252 | - } | ||
| 253 | - return description | ||
| 254 | -} | ||
| 255 | - | ||
| 256 | -// requiredParams reads the `required` list of a JSON schema. | ||
| 257 | -func requiredParams(schema map[string]any) []string { | ||
| 258 | - list, _ := schema["required"].([]any) | ||
| 259 | - var names []string | ||
| 260 | - for _, v := range list { | ||
| 261 | - if name, ok := v.(string); ok { | ||
| 262 | - names = append(names, name) | ||
| 263 | - } | ||
| 264 | - } | ||
| 265 | - return names | ||
| 266 | -} | ||
| 267 | - | ||
| 268 | -// runClientTool is one call of a client tool, on the event path every ACP | ||
| 269 | -// tool takes: the editor sees the call start, may be asked for permission, | ||
| 270 | -// and sees the result. Whatever happens, the model gets an answer it can | ||
| 271 | -// read; only a loop the detector stops ends the turn. | ||
| 272 | -func (f *front) runClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | ||
| 273 | - ev := ui.ToolEvent{ID: ui.NextCallID(), Tool: t.modelName, Title: "client: " + t.spec.Name, Kind: "other", Input: in} | ||
| 274 | - sink := ui.ActiveSink() | ||
| 275 | - if sink != nil { | ||
| 276 | - sink.ToolStart(ev) | ||
| 277 | - } | ||
| 278 | - if mustAskClientTool() && (sink == nil || !sink.Allow(ctx, ev)) { | ||
| 279 | - out := fmt.Sprintf("[%s rejected by user]", t.modelName) | ||
| 280 | - if sink != nil { | ||
| 281 | - sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true}) | ||
| 282 | - } | ||
| 283 | - return f.recordClientTool(t.modelName, in, out, true) | ||
| 284 | - } | ||
| 285 | - if sink != nil { | ||
| 286 | - sink.ToolRunning(ev.ID) | ||
| 287 | - } | ||
| 288 | - out, err := f.callClientTool(ctx, sid, t, in) | ||
| 289 | - failed := err != nil | ||
| 290 | - if failed { | ||
| 291 | - out = fmt.Sprintf("[client tool error: %v]", err) | ||
| 292 | - } | ||
| 293 | - out = mcp.Truncate(out) | ||
| 294 | - if sink != nil { | ||
| 295 | - sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed}) | ||
| 296 | - } | ||
| 297 | - return f.recordClientTool(t.modelName, in, out, failed) | ||
| 298 | -} | ||
| 299 | - | ||
| 300 | -// mustAskClientTool says whether a call waits for the user: always with | ||
| 301 | -// permissions "ask", and with "auto" when yolo is off — the MCP rule. | ||
| 302 | -func mustAskClientTool() bool { | ||
| 303 | - return config.Cfg.ACP.ClientTools.Permissions == config.PermissionsAsk || consent.Required() | ||
| 304 | -} | ||
| 305 | - | ||
| 306 | -// callClientTool sends the extension request and reads the answer. | ||
| 307 | -func (f *front) callClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | ||
| 308 | - if missing := missingParams(requiredParams(t.spec.InputSchema), in); len(missing) > 0 { | ||
| 309 | - return "", fmt.Errorf("missing required parameters: %s", strings.Join(missing, ", ")) | ||
| 310 | - } | ||
| 311 | - ctx, cancel := context.WithTimeout(ctx, config.Cfg.ACP.ClientTools.Timeout) | ||
| 312 | - defer cancel() | ||
| 313 | - raw, err := f.conn.CallExtension(ctx, t.spec.Method, callParams(sid, in)) | ||
| 314 | - if err != nil { | ||
| 315 | - return "", err | ||
| 316 | - } | ||
| 317 | - return clientToolOutput(raw) | ||
| 318 | -} | ||
| 319 | - | ||
| 320 | -// missingParams lists the required parameters the model left out. | ||
| 321 | -func missingParams(required []string, in map[string]any) []string { | ||
| 322 | - var missing []string | ||
| 323 | - for _, name := range required { | ||
| 324 | - if _, ok := in[name]; !ok { | ||
| 325 | - missing = append(missing, name) | ||
| 326 | - } | ||
| 327 | - } | ||
| 328 | - return missing | ||
| 329 | -} | ||
| 330 | - | ||
| 331 | -// callParams are the params of a call: the model's arguments, plus the | ||
| 332 | -// session id in `_meta` — ACP's slot for data that is not an argument. The | ||
| 333 | -// model's own `_meta`, if it invented one, is replaced. | ||
| 334 | -// | ||
| 335 | -// callParams("s1", map[string]any{"q": "x"}) | ||
| 336 | -// // {"q": "x", "_meta": {"org.mini-me/sessionId": "s1"}} | ||
| 337 | -func callParams(sid sdk.SessionId, in map[string]any) map[string]any { | ||
| 338 | - params := make(map[string]any, len(in)+1) | ||
| 339 | - for k, v := range in { | ||
| 340 | - params[k] = v | ||
| 341 | - } | ||
| 342 | - params["_meta"] = map[string]any{sessionIDMetaKey: string(sid)} | ||
| 343 | - return params | ||
| 344 | -} | ||
| 345 | - | ||
| 346 | -// clientToolResult is the answer shape mm reads first: MCP's content list. | ||
| 347 | -type clientToolResult struct { | ||
| 348 | - Content []struct { | ||
| 349 | - Type string `json:"type"` | ||
| 350 | - Text string `json:"text"` | ||
| 351 | - } `json:"content"` | ||
| 352 | - IsError bool `json:"isError"` | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -// clientToolOutput turns the client's answer into the text the model reads. | ||
| 356 | -// Two shapes are accepted: MCP's `{"content":[{"type":"text","text":…}], | ||
| 357 | -// "isError":…}` — the text blocks joined, an error when isError — and any | ||
| 358 | -// other JSON value, given to the model as is (a JSON string unquoted). | ||
| 359 | -func clientToolOutput(raw json.RawMessage) (string, error) { | ||
| 360 | - var result clientToolResult | ||
| 361 | - if err := json.Unmarshal(raw, &result); err == nil && result.Content != nil { | ||
| 362 | - var text strings.Builder | ||
| 363 | - for _, block := range result.Content { | ||
| 364 | - if block.Type == "text" { | ||
| 365 | - text.WriteString(block.Text) | ||
| 366 | - } else { | ||
| 367 | - fmt.Fprintf(&text, "[client tool: non-text content of type %s skipped]", block.Type) | ||
| 368 | - } | ||
| 369 | - } | ||
| 370 | - if result.IsError { | ||
| 371 | - return "", errors.New(text.String()) | ||
| 372 | - } | ||
| 373 | - return text.String(), nil | ||
| 374 | - } | ||
| 375 | - var text string | ||
| 376 | - if json.Unmarshal(raw, &text) == nil { | ||
| 377 | - return text, nil | ||
| 378 | - } | ||
| 379 | - return string(raw), nil | ||
| 380 | -} | ||
| 381 | - | ||
| 382 | -// recordClientTool tells the loop detector about the call, like every other | ||
| 383 | -// tool does: the same call repeated is flagged, then stops the turn. | ||
| 384 | -func (f *front) recordClientTool(name string, in map[string]any, out string, failed bool) (string, error) { | ||
| 385 | - d := f.detector | ||
| 386 | - if d == nil { | ||
| 387 | - return out, nil | ||
| 388 | - } | ||
| 389 | - input, _ := json.Marshal(in) | ||
| 390 | - if !d.Record(detector.Action{ToolName: name, Input: string(input), Output: out, Failed: failed}) { | ||
| 391 | - return out, nil | ||
| 392 | - } | ||
| 393 | - if d.Stuck() { | ||
| 394 | - return "", d.StuckError(name) | ||
| 395 | - } | ||
| 396 | - return out + "\n\n" + d.LoopError(), nil | ||
| 397 | -} | ||
| 398 | - | ||
| 399 | // turnTools are the tools of one turn: the agent's own, then the session's | 231 | // turnTools are the tools of one turn: the agent's own, then the session's |
| 400 | // client tools. A new slice, so f.tools is never appended to in place. | 232 | // client tools. A new slice, so f.tools is never appended to in place. |
| 401 | // | 233 | // |
added
internal/acp/clienttools_call.go +193 -0 | new file mode 100644 | ||
| @@ -0,0 +1,193 @@ | ||
| 1 | +package acp | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "encoding/json" | |
| 6 | + "errors" | |
| 7 | + "fmt" | |
| 8 | + "mm/internal/config" | |
| 9 | + "mm/internal/consent" | |
| 10 | + "mm/internal/detector" | |
| 11 | + "mm/internal/mcp" | |
| 12 | + "mm/internal/ui" | |
| 13 | + "strings" | |
| 14 | + | |
| 15 | + sdk "github.com/coder/acp-go-sdk" | |
| 16 | + "github.com/firebase/genkit/go/ai" | |
| 17 | +) | |
| 18 | + | |
| 19 | +// A client tool as the model sees it, and one call of it: the Genkit tool | |
| 20 | +// (defineClientTool), then the request to the editor and its answer. | |
| 21 | + | |
| 22 | +// runClientTool is one call of a client tool, on the event path every ACP | |
| 23 | +// tool takes: the editor sees the call start, may be asked for permission, | |
| 24 | +// and sees the result. Whatever happens, the model gets an answer it can | |
| 25 | +// read; only a loop the detector stops ends the turn. | |
| 26 | +func (f *front) runClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | |
| 27 | + ev := ui.ToolEvent{ID: ui.NextCallID(), Tool: t.modelName, Title: "client: " + t.spec.Name, Kind: "other", Input: in} | |
| 28 | + sink := ui.ActiveSink() | |
| 29 | + if sink != nil { | |
| 30 | + sink.ToolStart(ev) | |
| 31 | + } | |
| 32 | + if mustAskClientTool() && (sink == nil || !sink.Allow(ctx, ev)) { | |
| 33 | + out := fmt.Sprintf("[%s rejected by user]", t.modelName) | |
| 34 | + if sink != nil { | |
| 35 | + sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true}) | |
| 36 | + } | |
| 37 | + return f.recordClientTool(t.modelName, in, out, true) | |
| 38 | + } | |
| 39 | + if sink != nil { | |
| 40 | + sink.ToolRunning(ev.ID) | |
| 41 | + } | |
| 42 | + out, err := f.callClientTool(ctx, sid, t, in) | |
| 43 | + failed := err != nil | |
| 44 | + if failed { | |
| 45 | + out = fmt.Sprintf("[client tool error: %v]", err) | |
| 46 | + } | |
| 47 | + out = mcp.Truncate(out) | |
| 48 | + if sink != nil { | |
| 49 | + sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed}) | |
| 50 | + } | |
| 51 | + return f.recordClientTool(t.modelName, in, out, failed) | |
| 52 | +} | |
| 53 | + | |
| 54 | +// mustAskClientTool says whether a call waits for the user: always with | |
| 55 | +// permissions "ask", and with "auto" when yolo is off — the MCP rule. | |
| 56 | +func mustAskClientTool() bool { | |
| 57 | + return config.Cfg.ACP.ClientTools.Permissions == config.PermissionsAsk || consent.Required() | |
| 58 | +} | |
| 59 | + | |
| 60 | +// callClientTool sends the extension request and reads the answer. | |
| 61 | +func (f *front) callClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | |
| 62 | + if missing := missingParams(requiredParams(t.spec.InputSchema), in); len(missing) > 0 { | |
| 63 | + return "", fmt.Errorf("missing required parameters: %s", strings.Join(missing, ", ")) | |
| 64 | + } | |
| 65 | + ctx, cancel := context.WithTimeout(ctx, config.Cfg.ACP.ClientTools.Timeout) | |
| 66 | + defer cancel() | |
| 67 | + raw, err := f.conn.CallExtension(ctx, t.spec.Method, callParams(sid, in)) | |
| 68 | + if err != nil { | |
| 69 | + return "", err | |
| 70 | + } | |
| 71 | + return clientToolOutput(raw) | |
| 72 | +} | |
| 73 | + | |
| 74 | +// missingParams lists the required parameters the model left out. | |
| 75 | +func missingParams(required []string, in map[string]any) []string { | |
| 76 | + var missing []string | |
| 77 | + for _, name := range required { | |
| 78 | + if _, ok := in[name]; !ok { | |
| 79 | + missing = append(missing, name) | |
| 80 | + } | |
| 81 | + } | |
| 82 | + return missing | |
| 83 | +} | |
| 84 | + | |
| 85 | +// callParams are the params of a call: the model's arguments, plus the | |
| 86 | +// session id in `_meta` — ACP's slot for data that is not an argument. The | |
| 87 | +// model's own `_meta`, if it invented one, is replaced. | |
| 88 | +// | |
| 89 | +// callParams("s1", map[string]any{"q": "x"}) | |
| 90 | +// // {"q": "x", "_meta": {"org.mini-me/sessionId": "s1"}} | |
| 91 | +func callParams(sid sdk.SessionId, in map[string]any) map[string]any { | |
| 92 | + params := make(map[string]any, len(in)+1) | |
| 93 | + for k, v := range in { | |
| 94 | + params[k] = v | |
| 95 | + } | |
| 96 | + params["_meta"] = map[string]any{sessionIDMetaKey: string(sid)} | |
| 97 | + return params | |
| 98 | +} | |
| 99 | + | |
| 100 | +// clientToolResult is the answer shape mm reads first: MCP's content list. | |
| 101 | +type clientToolResult struct { | |
| 102 | + Content []struct { | |
| 103 | + Type string `json:"type"` | |
| 104 | + Text string `json:"text"` | |
| 105 | + } `json:"content"` | |
| 106 | + IsError bool `json:"isError"` | |
| 107 | +} | |
| 108 | + | |
| 109 | +// clientToolOutput turns the client's answer into the text the model reads. | |
| 110 | +// Two shapes are accepted: MCP's `{"content":[{"type":"text","text":…}], | |
| 111 | +// "isError":…}` — the text blocks joined, an error when isError — and any | |
| 112 | +// other JSON value, given to the model as is (a JSON string unquoted). | |
| 113 | +func clientToolOutput(raw json.RawMessage) (string, error) { | |
| 114 | + var result clientToolResult | |
| 115 | + if err := json.Unmarshal(raw, &result); err == nil && result.Content != nil { | |
| 116 | + var text strings.Builder | |
| 117 | + for _, block := range result.Content { | |
| 118 | + if block.Type == "text" { | |
| 119 | + text.WriteString(block.Text) | |
| 120 | + } else { | |
| 121 | + fmt.Fprintf(&text, "[client tool: non-text content of type %s skipped]", block.Type) | |
| 122 | + } | |
| 123 | + } | |
| 124 | + if result.IsError { | |
| 125 | + return "", errors.New(text.String()) | |
| 126 | + } | |
| 127 | + return text.String(), nil | |
| 128 | + } | |
| 129 | + var text string | |
| 130 | + if json.Unmarshal(raw, &text) == nil { | |
| 131 | + return text, nil | |
| 132 | + } | |
| 133 | + return string(raw), nil | |
| 134 | +} | |
| 135 | + | |
| 136 | +// recordClientTool tells the loop detector about the call, like every other | |
| 137 | +// tool does: the same call repeated is flagged, then stops the turn. | |
| 138 | +func (f *front) recordClientTool(name string, in map[string]any, out string, failed bool) (string, error) { | |
| 139 | + d := f.detector | |
| 140 | + if d == nil { | |
| 141 | + return out, nil | |
| 142 | + } | |
| 143 | + input, _ := json.Marshal(in) | |
| 144 | + if !d.Record(detector.Action{ToolName: name, Input: string(input), Output: out, Failed: failed}) { | |
| 145 | + return out, nil | |
| 146 | + } | |
| 147 | + if d.Stuck() { | |
| 148 | + return "", d.StuckError(name) | |
| 149 | + } | |
| 150 | + return out + "\n\n" + d.LoopError(), nil | |
| 151 | +} | |
| 152 | + | |
| 153 | +// defineClientTool builds the Genkit tool of one client tool, bound to the | |
| 154 | +// session it belongs to. The tool is not registered: Genkit registers a | |
| 155 | +// dynamic tool for the duration of the call it is passed to, so two sessions | |
| 156 | +// may hold tools of the same name with different lists. | |
| 157 | +func (f *front) defineClientTool(sid sdk.SessionId, t clientTool) ai.ToolRef { | |
| 158 | + return ai.NewTool(t.modelName, clientToolDescription(t.spec), | |
| 159 | + func(tctx *ai.ToolContext, raw any) (string, error) { | |
| 160 | + in, _ := raw.(map[string]any) | |
| 161 | + if in == nil { | |
| 162 | + in = map[string]any{} | |
| 163 | + } | |
| 164 | + return f.runClientTool(tctx, sid, t, in) | |
| 165 | + }, | |
| 166 | + ai.WithInputSchema(mcp.ModelSchema(t.spec.InputSchema))) | |
| 167 | +} | |
| 168 | + | |
| 169 | +// clientToolDescription is the description the model reads: the client's, | |
| 170 | +// plus the required parameters, which mcp.ModelSchema takes out of the | |
| 171 | +// schema (a call missing one is answered by runClientTool instead). | |
| 172 | +func clientToolDescription(spec clientToolSpec) string { | |
| 173 | + description := spec.Description | |
| 174 | + if description == "" { | |
| 175 | + description = "Tool provided by the editor (" + spec.Method + ")." | |
| 176 | + } | |
| 177 | + if required := requiredParams(spec.InputSchema); len(required) > 0 { | |
| 178 | + description += "\nRequired parameters: " + strings.Join(required, ", ") | |
| 179 | + } | |
| 180 | + return description | |
| 181 | +} | |
| 182 | + | |
| 183 | +// requiredParams reads the `required` list of a JSON schema. | |
| 184 | +func requiredParams(schema map[string]any) []string { | |
| 185 | + list, _ := schema["required"].([]any) | |
| 186 | + var names []string | |
| 187 | + for _, v := range list { | |
| 188 | + if name, ok := v.(string); ok { | |
| 189 | + names = append(names, name) | |
| 190 | + } | |
| 191 | + } | |
| 192 | + return names | |
| 193 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,193 @@ | |||
| 1 | +package acp | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "encoding/json" | ||
| 6 | + "errors" | ||
| 7 | + "fmt" | ||
| 8 | + "mm/internal/config" | ||
| 9 | + "mm/internal/consent" | ||
| 10 | + "mm/internal/detector" | ||
| 11 | + "mm/internal/mcp" | ||
| 12 | + "mm/internal/ui" | ||
| 13 | + "strings" | ||
| 14 | + | ||
| 15 | + sdk "github.com/coder/acp-go-sdk" | ||
| 16 | + "github.com/firebase/genkit/go/ai" | ||
| 17 | +) | ||
| 18 | + | ||
| 19 | +// A client tool as the model sees it, and one call of it: the Genkit tool | ||
| 20 | +// (defineClientTool), then the request to the editor and its answer. | ||
| 21 | + | ||
| 22 | +// runClientTool is one call of a client tool, on the event path every ACP | ||
| 23 | +// tool takes: the editor sees the call start, may be asked for permission, | ||
| 24 | +// and sees the result. Whatever happens, the model gets an answer it can | ||
| 25 | +// read; only a loop the detector stops ends the turn. | ||
| 26 | +func (f *front) runClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | ||
| 27 | + ev := ui.ToolEvent{ID: ui.NextCallID(), Tool: t.modelName, Title: "client: " + t.spec.Name, Kind: "other", Input: in} | ||
| 28 | + sink := ui.ActiveSink() | ||
| 29 | + if sink != nil { | ||
| 30 | + sink.ToolStart(ev) | ||
| 31 | + } | ||
| 32 | + if mustAskClientTool() && (sink == nil || !sink.Allow(ctx, ev)) { | ||
| 33 | + out := fmt.Sprintf("[%s rejected by user]", t.modelName) | ||
| 34 | + if sink != nil { | ||
| 35 | + sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true}) | ||
| 36 | + } | ||
| 37 | + return f.recordClientTool(t.modelName, in, out, true) | ||
| 38 | + } | ||
| 39 | + if sink != nil { | ||
| 40 | + sink.ToolRunning(ev.ID) | ||
| 41 | + } | ||
| 42 | + out, err := f.callClientTool(ctx, sid, t, in) | ||
| 43 | + failed := err != nil | ||
| 44 | + if failed { | ||
| 45 | + out = fmt.Sprintf("[client tool error: %v]", err) | ||
| 46 | + } | ||
| 47 | + out = mcp.Truncate(out) | ||
| 48 | + if sink != nil { | ||
| 49 | + sink.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed}) | ||
| 50 | + } | ||
| 51 | + return f.recordClientTool(t.modelName, in, out, failed) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// mustAskClientTool says whether a call waits for the user: always with | ||
| 55 | +// permissions "ask", and with "auto" when yolo is off — the MCP rule. | ||
| 56 | +func mustAskClientTool() bool { | ||
| 57 | + return config.Cfg.ACP.ClientTools.Permissions == config.PermissionsAsk || consent.Required() | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +// callClientTool sends the extension request and reads the answer. | ||
| 61 | +func (f *front) callClientTool(ctx context.Context, sid sdk.SessionId, t clientTool, in map[string]any) (string, error) { | ||
| 62 | + if missing := missingParams(requiredParams(t.spec.InputSchema), in); len(missing) > 0 { | ||
| 63 | + return "", fmt.Errorf("missing required parameters: %s", strings.Join(missing, ", ")) | ||
| 64 | + } | ||
| 65 | + ctx, cancel := context.WithTimeout(ctx, config.Cfg.ACP.ClientTools.Timeout) | ||
| 66 | + defer cancel() | ||
| 67 | + raw, err := f.conn.CallExtension(ctx, t.spec.Method, callParams(sid, in)) | ||
| 68 | + if err != nil { | ||
| 69 | + return "", err | ||
| 70 | + } | ||
| 71 | + return clientToolOutput(raw) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +// missingParams lists the required parameters the model left out. | ||
| 75 | +func missingParams(required []string, in map[string]any) []string { | ||
| 76 | + var missing []string | ||
| 77 | + for _, name := range required { | ||
| 78 | + if _, ok := in[name]; !ok { | ||
| 79 | + missing = append(missing, name) | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + return missing | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +// callParams are the params of a call: the model's arguments, plus the | ||
| 86 | +// session id in `_meta` — ACP's slot for data that is not an argument. The | ||
| 87 | +// model's own `_meta`, if it invented one, is replaced. | ||
| 88 | +// | ||
| 89 | +// callParams("s1", map[string]any{"q": "x"}) | ||
| 90 | +// // {"q": "x", "_meta": {"org.mini-me/sessionId": "s1"}} | ||
| 91 | +func callParams(sid sdk.SessionId, in map[string]any) map[string]any { | ||
| 92 | + params := make(map[string]any, len(in)+1) | ||
| 93 | + for k, v := range in { | ||
| 94 | + params[k] = v | ||
| 95 | + } | ||
| 96 | + params["_meta"] = map[string]any{sessionIDMetaKey: string(sid)} | ||
| 97 | + return params | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +// clientToolResult is the answer shape mm reads first: MCP's content list. | ||
| 101 | +type clientToolResult struct { | ||
| 102 | + Content []struct { | ||
| 103 | + Type string `json:"type"` | ||
| 104 | + Text string `json:"text"` | ||
| 105 | + } `json:"content"` | ||
| 106 | + IsError bool `json:"isError"` | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +// clientToolOutput turns the client's answer into the text the model reads. | ||
| 110 | +// Two shapes are accepted: MCP's `{"content":[{"type":"text","text":…}], | ||
| 111 | +// "isError":…}` — the text blocks joined, an error when isError — and any | ||
| 112 | +// other JSON value, given to the model as is (a JSON string unquoted). | ||
| 113 | +func clientToolOutput(raw json.RawMessage) (string, error) { | ||
| 114 | + var result clientToolResult | ||
| 115 | + if err := json.Unmarshal(raw, &result); err == nil && result.Content != nil { | ||
| 116 | + var text strings.Builder | ||
| 117 | + for _, block := range result.Content { | ||
| 118 | + if block.Type == "text" { | ||
| 119 | + text.WriteString(block.Text) | ||
| 120 | + } else { | ||
| 121 | + fmt.Fprintf(&text, "[client tool: non-text content of type %s skipped]", block.Type) | ||
| 122 | + } | ||
| 123 | + } | ||
| 124 | + if result.IsError { | ||
| 125 | + return "", errors.New(text.String()) | ||
| 126 | + } | ||
| 127 | + return text.String(), nil | ||
| 128 | + } | ||
| 129 | + var text string | ||
| 130 | + if json.Unmarshal(raw, &text) == nil { | ||
| 131 | + return text, nil | ||
| 132 | + } | ||
| 133 | + return string(raw), nil | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +// recordClientTool tells the loop detector about the call, like every other | ||
| 137 | +// tool does: the same call repeated is flagged, then stops the turn. | ||
| 138 | +func (f *front) recordClientTool(name string, in map[string]any, out string, failed bool) (string, error) { | ||
| 139 | + d := f.detector | ||
| 140 | + if d == nil { | ||
| 141 | + return out, nil | ||
| 142 | + } | ||
| 143 | + input, _ := json.Marshal(in) | ||
| 144 | + if !d.Record(detector.Action{ToolName: name, Input: string(input), Output: out, Failed: failed}) { | ||
| 145 | + return out, nil | ||
| 146 | + } | ||
| 147 | + if d.Stuck() { | ||
| 148 | + return "", d.StuckError(name) | ||
| 149 | + } | ||
| 150 | + return out + "\n\n" + d.LoopError(), nil | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +// defineClientTool builds the Genkit tool of one client tool, bound to the | ||
| 154 | +// session it belongs to. The tool is not registered: Genkit registers a | ||
| 155 | +// dynamic tool for the duration of the call it is passed to, so two sessions | ||
| 156 | +// may hold tools of the same name with different lists. | ||
| 157 | +func (f *front) defineClientTool(sid sdk.SessionId, t clientTool) ai.ToolRef { | ||
| 158 | + return ai.NewTool(t.modelName, clientToolDescription(t.spec), | ||
| 159 | + func(tctx *ai.ToolContext, raw any) (string, error) { | ||
| 160 | + in, _ := raw.(map[string]any) | ||
| 161 | + if in == nil { | ||
| 162 | + in = map[string]any{} | ||
| 163 | + } | ||
| 164 | + return f.runClientTool(tctx, sid, t, in) | ||
| 165 | + }, | ||
| 166 | + ai.WithInputSchema(mcp.ModelSchema(t.spec.InputSchema))) | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +// clientToolDescription is the description the model reads: the client's, | ||
| 170 | +// plus the required parameters, which mcp.ModelSchema takes out of the | ||
| 171 | +// schema (a call missing one is answered by runClientTool instead). | ||
| 172 | +func clientToolDescription(spec clientToolSpec) string { | ||
| 173 | + description := spec.Description | ||
| 174 | + if description == "" { | ||
| 175 | + description = "Tool provided by the editor (" + spec.Method + ")." | ||
| 176 | + } | ||
| 177 | + if required := requiredParams(spec.InputSchema); len(required) > 0 { | ||
| 178 | + description += "\nRequired parameters: " + strings.Join(required, ", ") | ||
| 179 | + } | ||
| 180 | + return description | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +// requiredParams reads the `required` list of a JSON schema. | ||
| 184 | +func requiredParams(schema map[string]any) []string { | ||
| 185 | + list, _ := schema["required"].([]any) | ||
| 186 | + var names []string | ||
| 187 | + for _, v := range list { | ||
| 188 | + if name, ok := v.(string); ok { | ||
| 189 | + names = append(names, name) | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | + return names | ||
| 193 | +} | ||
modified
internal/acp/elicit.go +65 -42 | @@ -93,52 +93,75 @@ const ( | ||
| 93 | 93 | func (k *sink) elicitByPermission(ctx context.Context, ev ui.ToolEvent, f elicit.Form) elicit.Result { |
| 94 | 94 | res := elicit.Result{Status: elicit.Answered} |
| 95 | 95 | for _, q := range f.Questions { |
| 96 | - labels := q.Options | |
| 97 | - if q.Kind == elicit.Confirm { | |
| 98 | - labels = []string{"Yes", "No"} | |
| 96 | + a, status := k.askByPermission(ctx, ev, q) | |
| 97 | + if status != elicit.Answered { | |
| 98 | + return elicit.Result{Status: status} | |
| 99 | 99 | } |
| 100 | - options := make([]sdk.PermissionOption, 0, len(labels)+1) | |
| 101 | - for i, label := range labels { | |
| 102 | - options = append(options, sdk.PermissionOption{OptionId: sdk.PermissionOptionId(fmt.Sprint(i)), Name: label, Kind: sdk.PermissionOptionKindAllowOnce}) | |
| 103 | - } | |
| 104 | - if q.Kind == elicit.Choice && q.AllowOther { | |
| 105 | - options = append(options, sdk.PermissionOption{OptionId: otherOption, Name: elicit.OtherLabel, Kind: sdk.PermissionOptionKindAllowOnce}) | |
| 106 | - } | |
| 107 | - options = append(options, sdk.PermissionOption{OptionId: declineOption, Name: "Decline", Kind: sdk.PermissionOptionKindRejectOnce}) | |
| 108 | - resp, err := k.f.conn.RequestPermission(ctx, sdk.RequestPermissionRequest{ | |
| 109 | - SessionId: k.sid, | |
| 110 | - ToolCall: sdk.ToolCallUpdate{ | |
| 111 | - ToolCallId: sdk.ToolCallId(ev.ID), | |
| 112 | - Title: sdk.Ptr("? " + q.Prompt), | |
| 113 | - Kind: sdk.Ptr(sdk.ToolKindOther), | |
| 114 | - Status: sdk.Ptr(sdk.ToolCallStatusPending), | |
| 115 | - RawInput: ev.Input, | |
| 116 | - }, | |
| 117 | - Options: options, | |
| 118 | - }) | |
| 119 | - if err != nil || resp.Outcome.Cancelled != nil || resp.Outcome.Selected == nil { | |
| 120 | - return elicit.Result{Status: elicit.Cancelled} | |
| 121 | - } | |
| 122 | - chosen := string(resp.Outcome.Selected.OptionId) | |
| 123 | - if chosen == declineOption { | |
| 124 | - return elicit.Result{Status: elicit.Declined} | |
| 125 | - } | |
| 126 | - if chosen == otherOption { | |
| 127 | - res.Answers = append(res.Answers, elicit.Answer{OtherAsked: true}) | |
| 128 | - continue | |
| 129 | - } | |
| 130 | - var i int | |
| 131 | - if _, err := fmt.Sscan(chosen, &i); err != nil || i < 0 || i >= len(labels) { | |
| 132 | - return elicit.Result{Status: elicit.Cancelled} | |
| 133 | - } | |
| 134 | - value := labels[i] | |
| 135 | - if q.Kind == elicit.Confirm { | |
| 136 | - value = map[bool]string{true: "yes", false: "no"}[i == 0] | |
| 137 | - } | |
| 138 | - res.Answers = append(res.Answers, elicit.Answer{Values: []string{value}}) | |
| 100 | + res.Answers = append(res.Answers, a) | |
| 139 | 101 | } |
| 140 | 102 | return res |
| 141 | 103 | } |
| 142 | 104 | |
| 105 | +// askByPermission asks one question as a permission dialog and reads the | |
| 106 | +// button chosen; a dialog cancelled or closed cancels the form. | |
| 107 | +func (k *sink) askByPermission(ctx context.Context, ev ui.ToolEvent, q elicit.Question) (elicit.Answer, elicit.Status) { | |
| 108 | + labels, options := permissionOptions(q) | |
| 109 | + resp, err := k.f.conn.RequestPermission(ctx, sdk.RequestPermissionRequest{ | |
| 110 | + SessionId: k.sid, | |
| 111 | + ToolCall: sdk.ToolCallUpdate{ | |
| 112 | + ToolCallId: sdk.ToolCallId(ev.ID), | |
| 113 | + Title: sdk.Ptr("? " + q.Prompt), | |
| 114 | + Kind: sdk.Ptr(sdk.ToolKindOther), | |
| 115 | + Status: sdk.Ptr(sdk.ToolCallStatusPending), | |
| 116 | + RawInput: ev.Input, | |
| 117 | + }, | |
| 118 | + Options: options, | |
| 119 | + }) | |
| 120 | + if err != nil || resp.Outcome.Cancelled != nil || resp.Outcome.Selected == nil { | |
| 121 | + return elicit.Answer{}, elicit.Cancelled | |
| 122 | + } | |
| 123 | + return chosenAnswer(q, labels, string(resp.Outcome.Selected.OptionId)) | |
| 124 | +} | |
| 125 | + | |
| 126 | +// permissionOptions are a question's buttons: one per option (Yes and No | |
| 127 | +// for a confirmation), "other" when the question allows it, then Decline. | |
| 128 | +// labels are the options' names, indexed by their button's id. | |
| 129 | +func permissionOptions(q elicit.Question) (labels []string, options []sdk.PermissionOption) { | |
| 130 | + labels = q.Options | |
| 131 | + if q.Kind == elicit.Confirm { | |
| 132 | + labels = []string{"Yes", "No"} | |
| 133 | + } | |
| 134 | + options = make([]sdk.PermissionOption, 0, len(labels)+1) | |
| 135 | + for i, label := range labels { | |
| 136 | + options = append(options, sdk.PermissionOption{OptionId: sdk.PermissionOptionId(fmt.Sprint(i)), Name: label, Kind: sdk.PermissionOptionKindAllowOnce}) | |
| 137 | + } | |
| 138 | + if q.Kind == elicit.Choice && q.AllowOther { | |
| 139 | + options = append(options, sdk.PermissionOption{OptionId: otherOption, Name: elicit.OtherLabel, Kind: sdk.PermissionOptionKindAllowOnce}) | |
| 140 | + } | |
| 141 | + options = append(options, sdk.PermissionOption{OptionId: declineOption, Name: "Decline", Kind: sdk.PermissionOptionKindRejectOnce}) | |
| 142 | + return labels, options | |
| 143 | +} | |
| 144 | + | |
| 145 | +// chosenAnswer is the answer the button chosen gives: decline, "other" (the | |
| 146 | +// model asks again for the user's own words), or the option — "yes" or | |
| 147 | +// "no" for a confirmation. An unknown button cancels the form. | |
| 148 | +func chosenAnswer(q elicit.Question, labels []string, chosen string) (elicit.Answer, elicit.Status) { | |
| 149 | + switch chosen { | |
| 150 | + case declineOption: | |
| 151 | + return elicit.Answer{}, elicit.Declined | |
| 152 | + case otherOption: | |
| 153 | + return elicit.Answer{OtherAsked: true}, elicit.Answered | |
| 154 | + } | |
| 155 | + var i int | |
| 156 | + if _, err := fmt.Sscan(chosen, &i); err != nil || i < 0 || i >= len(labels) { | |
| 157 | + return elicit.Answer{}, elicit.Cancelled | |
| 158 | + } | |
| 159 | + value := labels[i] | |
| 160 | + if q.Kind == elicit.Confirm { | |
| 161 | + value = map[bool]string{true: "yes", false: "no"}[i == 0] | |
| 162 | + } | |
| 163 | + return elicit.Answer{Values: []string{value}}, elicit.Answered | |
| 164 | +} | |
| 165 | + | |
| 143 | 166 | // liftElicitationScope is acpwire.LiftElicitationScope (see there). |
| 144 | 167 | var liftElicitationScope = acpwire.LiftElicitationScope |
| @@ -93,52 +93,75 @@ const ( | |||
| 93 | func (k *sink) elicitByPermission(ctx context.Context, ev ui.ToolEvent, f elicit.Form) elicit.Result { | 93 | func (k *sink) elicitByPermission(ctx context.Context, ev ui.ToolEvent, f elicit.Form) elicit.Result { |
| 94 | res := elicit.Result{Status: elicit.Answered} | 94 | res := elicit.Result{Status: elicit.Answered} |
| 95 | for _, q := range f.Questions { | 95 | for _, q := range f.Questions { |
| 96 | - labels := q.Options | 96 | + a, status := k.askByPermission(ctx, ev, q) |
| 97 | - if q.Kind == elicit.Confirm { | 97 | + if status != elicit.Answered { |
| 98 | - labels = []string{"Yes", "No"} | 98 | + return elicit.Result{Status: status} |
| 99 | } | 99 | } |
| 100 | - options := make([]sdk.PermissionOption, 0, len(labels)+1) | 100 | + res.Answers = append(res.Answers, a) |
| 101 | - for i, label := range labels { | ||
| 102 | - options = append(options, sdk.PermissionOption{OptionId: sdk.PermissionOptionId(fmt.Sprint(i)), Name: label, Kind: sdk.PermissionOptionKindAllowOnce}) | ||
| 103 | - } | ||
| 104 | - if q.Kind == elicit.Choice && q.AllowOther { | ||
| 105 | - options = append(options, sdk.PermissionOption{OptionId: otherOption, Name: elicit.OtherLabel, Kind: sdk.PermissionOptionKindAllowOnce}) | ||
| 106 | - } | ||
| 107 | - options = append(options, sdk.PermissionOption{OptionId: declineOption, Name: "Decline", Kind: sdk.PermissionOptionKindRejectOnce}) | ||
| 108 | - resp, err := k.f.conn.RequestPermission(ctx, sdk.RequestPermissionRequest{ | ||
| 109 | - SessionId: k.sid, | ||
| 110 | - ToolCall: sdk.ToolCallUpdate{ | ||
| 111 | - ToolCallId: sdk.ToolCallId(ev.ID), | ||
| 112 | - Title: sdk.Ptr("? " + q.Prompt), | ||
| 113 | - Kind: sdk.Ptr(sdk.ToolKindOther), | ||
| 114 | - Status: sdk.Ptr(sdk.ToolCallStatusPending), | ||
| 115 | - RawInput: ev.Input, | ||
| 116 | - }, | ||
| 117 | - Options: options, | ||
| 118 | - }) | ||
| 119 | - if err != nil || resp.Outcome.Cancelled != nil || resp.Outcome.Selected == nil { | ||
| 120 | - return elicit.Result{Status: elicit.Cancelled} | ||
| 121 | - } | ||
| 122 | - chosen := string(resp.Outcome.Selected.OptionId) | ||
| 123 | - if chosen == declineOption { | ||
| 124 | - return elicit.Result{Status: elicit.Declined} | ||
| 125 | - } | ||
| 126 | - if chosen == otherOption { | ||
| 127 | - res.Answers = append(res.Answers, elicit.Answer{OtherAsked: true}) | ||
| 128 | - continue | ||
| 129 | - } | ||
| 130 | - var i int | ||
| 131 | - if _, err := fmt.Sscan(chosen, &i); err != nil || i < 0 || i >= len(labels) { | ||
| 132 | - return elicit.Result{Status: elicit.Cancelled} | ||
| 133 | - } | ||
| 134 | - value := labels[i] | ||
| 135 | - if q.Kind == elicit.Confirm { | ||
| 136 | - value = map[bool]string{true: "yes", false: "no"}[i == 0] | ||
| 137 | - } | ||
| 138 | - res.Answers = append(res.Answers, elicit.Answer{Values: []string{value}}) | ||
| 139 | } | 101 | } |
| 140 | return res | 102 | return res |
| 141 | } | 103 | } |
| 142 | 104 | ||
| 105 | +// askByPermission asks one question as a permission dialog and reads the | ||
| 106 | +// button chosen; a dialog cancelled or closed cancels the form. | ||
| 107 | +func (k *sink) askByPermission(ctx context.Context, ev ui.ToolEvent, q elicit.Question) (elicit.Answer, elicit.Status) { | ||
| 108 | + labels, options := permissionOptions(q) | ||
| 109 | + resp, err := k.f.conn.RequestPermission(ctx, sdk.RequestPermissionRequest{ | ||
| 110 | + SessionId: k.sid, | ||
| 111 | + ToolCall: sdk.ToolCallUpdate{ | ||
| 112 | + ToolCallId: sdk.ToolCallId(ev.ID), | ||
| 113 | + Title: sdk.Ptr("? " + q.Prompt), | ||
| 114 | + Kind: sdk.Ptr(sdk.ToolKindOther), | ||
| 115 | + Status: sdk.Ptr(sdk.ToolCallStatusPending), | ||
| 116 | + RawInput: ev.Input, | ||
| 117 | + }, | ||
| 118 | + Options: options, | ||
| 119 | + }) | ||
| 120 | + if err != nil || resp.Outcome.Cancelled != nil || resp.Outcome.Selected == nil { | ||
| 121 | + return elicit.Answer{}, elicit.Cancelled | ||
| 122 | + } | ||
| 123 | + return chosenAnswer(q, labels, string(resp.Outcome.Selected.OptionId)) | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +// permissionOptions are a question's buttons: one per option (Yes and No | ||
| 127 | +// for a confirmation), "other" when the question allows it, then Decline. | ||
| 128 | +// labels are the options' names, indexed by their button's id. | ||
| 129 | +func permissionOptions(q elicit.Question) (labels []string, options []sdk.PermissionOption) { | ||
| 130 | + labels = q.Options | ||
| 131 | + if q.Kind == elicit.Confirm { | ||
| 132 | + labels = []string{"Yes", "No"} | ||
| 133 | + } | ||
| 134 | + options = make([]sdk.PermissionOption, 0, len(labels)+1) | ||
| 135 | + for i, label := range labels { | ||
| 136 | + options = append(options, sdk.PermissionOption{OptionId: sdk.PermissionOptionId(fmt.Sprint(i)), Name: label, Kind: sdk.PermissionOptionKindAllowOnce}) | ||
| 137 | + } | ||
| 138 | + if q.Kind == elicit.Choice && q.AllowOther { | ||
| 139 | + options = append(options, sdk.PermissionOption{OptionId: otherOption, Name: elicit.OtherLabel, Kind: sdk.PermissionOptionKindAllowOnce}) | ||
| 140 | + } | ||
| 141 | + options = append(options, sdk.PermissionOption{OptionId: declineOption, Name: "Decline", Kind: sdk.PermissionOptionKindRejectOnce}) | ||
| 142 | + return labels, options | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// chosenAnswer is the answer the button chosen gives: decline, "other" (the | ||
| 146 | +// model asks again for the user's own words), or the option — "yes" or | ||
| 147 | +// "no" for a confirmation. An unknown button cancels the form. | ||
| 148 | +func chosenAnswer(q elicit.Question, labels []string, chosen string) (elicit.Answer, elicit.Status) { | ||
| 149 | + switch chosen { | ||
| 150 | + case declineOption: | ||
| 151 | + return elicit.Answer{}, elicit.Declined | ||
| 152 | + case otherOption: | ||
| 153 | + return elicit.Answer{OtherAsked: true}, elicit.Answered | ||
| 154 | + } | ||
| 155 | + var i int | ||
| 156 | + if _, err := fmt.Sscan(chosen, &i); err != nil || i < 0 || i >= len(labels) { | ||
| 157 | + return elicit.Answer{}, elicit.Cancelled | ||
| 158 | + } | ||
| 159 | + value := labels[i] | ||
| 160 | + if q.Kind == elicit.Confirm { | ||
| 161 | + value = map[bool]string{true: "yes", false: "no"}[i == 0] | ||
| 162 | + } | ||
| 163 | + return elicit.Answer{Values: []string{value}}, elicit.Answered | ||
| 164 | +} | ||
| 165 | + | ||
| 143 | // liftElicitationScope is acpwire.LiftElicitationScope (see there). | 166 | // liftElicitationScope is acpwire.LiftElicitationScope (see there). |
| 144 | var liftElicitationScope = acpwire.LiftElicitationScope | 167 | var liftElicitationScope = acpwire.LiftElicitationScope |
modified
internal/acp/sink.go +12 -13 | @@ -200,18 +200,17 @@ func (k *sink) ToolEnd(id string, res ui.ToolResult) { | ||
| 200 | 200 | // drives how a client displays the call (icon, colour), so unknown values |
| 201 | 201 | // default to execute rather than failing. |
| 202 | 202 | func toolKind(kind string) sdk.ToolKind { |
| 203 | - switch kind { | |
| 204 | - case "read": | |
| 205 | - return sdk.ToolKindRead | |
| 206 | - case "edit": | |
| 207 | - return sdk.ToolKindEdit | |
| 208 | - case "fetch": | |
| 209 | - return sdk.ToolKindFetch | |
| 210 | - case "search": // search_memory | |
| 211 | - return sdk.ToolKindSearch | |
| 212 | - case "other": // ask_agent, ask_user: a hand-off, a question — not a command | |
| 213 | - return sdk.ToolKindOther | |
| 214 | - default: | |
| 215 | - return sdk.ToolKindExecute | |
| 203 | + if k, ok := toolKinds[kind]; ok { | |
| 204 | + return k | |
| 216 | 205 | } |
| 206 | + return sdk.ToolKindExecute | |
| 207 | +} | |
| 208 | + | |
| 209 | +// toolKinds are the event kinds ACP has a kind for; any other is execute. | |
| 210 | +var toolKinds = map[string]sdk.ToolKind{ | |
| 211 | + "read": sdk.ToolKindRead, | |
| 212 | + "edit": sdk.ToolKindEdit, | |
| 213 | + "fetch": sdk.ToolKindFetch, | |
| 214 | + "search": sdk.ToolKindSearch, // search_memory | |
| 215 | + "other": sdk.ToolKindOther, // ask_agent, ask_user: a hand-off, a question — not a command | |
| 217 | 216 | } |
| @@ -200,18 +200,17 @@ func (k *sink) ToolEnd(id string, res ui.ToolResult) { | |||
| 200 | // drives how a client displays the call (icon, colour), so unknown values | 200 | // drives how a client displays the call (icon, colour), so unknown values |
| 201 | // default to execute rather than failing. | 201 | // default to execute rather than failing. |
| 202 | func toolKind(kind string) sdk.ToolKind { | 202 | func toolKind(kind string) sdk.ToolKind { |
| 203 | - switch kind { | 203 | + if k, ok := toolKinds[kind]; ok { |
| 204 | - case "read": | 204 | + return k |
| 205 | - return sdk.ToolKindRead | ||
| 206 | - case "edit": | ||
| 207 | - return sdk.ToolKindEdit | ||
| 208 | - case "fetch": | ||
| 209 | - return sdk.ToolKindFetch | ||
| 210 | - case "search": // search_memory | ||
| 211 | - return sdk.ToolKindSearch | ||
| 212 | - case "other": // ask_agent, ask_user: a hand-off, a question — not a command | ||
| 213 | - return sdk.ToolKindOther | ||
| 214 | - default: | ||
| 215 | - return sdk.ToolKindExecute | ||
| 216 | } | 205 | } |
| 206 | + return sdk.ToolKindExecute | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +// toolKinds are the event kinds ACP has a kind for; any other is execute. | ||
| 210 | +var toolKinds = map[string]sdk.ToolKind{ | ||
| 211 | + "read": sdk.ToolKindRead, | ||
| 212 | + "edit": sdk.ToolKindEdit, | ||
| 213 | + "fetch": sdk.ToolKindFetch, | ||
| 214 | + "search": sdk.ToolKindSearch, // search_memory | ||
| 215 | + "other": sdk.ToolKindOther, // ask_agent, ask_user: a hand-off, a question — not a command | ||
| 217 | } | 216 | } |
modified
main.go +1 -1 | @@ -227,7 +227,7 @@ func (s agentSession) runPrompt(ctx context.Context, prompt string, set toolSet) | ||
| 227 | 227 | func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bool, banner *bytes.Buffer) { |
| 228 | 228 | switch { |
| 229 | 229 | case cli.acp: |
| 230 | - acp.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker) | |
| 230 | + acp.Run(ctx, s.setup(), s.asker) | |
| 231 | 231 | case cli.a2a: |
| 232 | 232 | if err := runA2A(ctx, s.e, config.Cfg.System, s.tools, cli.a2aPort); err != nil { |
| 233 | 233 | fail("[a2a: %v ]", err) |
| @@ -227,7 +227,7 @@ func (s agentSession) runPrompt(ctx context.Context, prompt string, set toolSet) | |||
| 227 | func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bool, banner *bytes.Buffer) { | 227 | func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bool, banner *bytes.Buffer) { |
| 228 | switch { | 228 | switch { |
| 229 | case cli.acp: | 229 | case cli.acp: |
| 230 | - acp.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker) | 230 | + acp.Run(ctx, s.setup(), s.asker) |
| 231 | case cli.a2a: | 231 | case cli.a2a: |
| 232 | if err := runA2A(ctx, s.e, config.Cfg.System, s.tools, cli.a2aPort); err != nil { | 232 | if err := runA2A(ctx, s.e, config.Cfg.System, s.tools, cli.a2aPort); err != nil { |
| 233 | fail("[a2a: %v ]", err) | 233 | fail("[a2a: %v ]", err) |