feat: context window report and viewer (#10462)
Co-authored-by: Douwe Osinga <douwe.osinga@gmail.com>
This commit is contained in:
@@ -122,6 +122,43 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// The tools and prompt contributions every operation adds to the next
|
||||
/// request. Derived from the session and conversation, so this is safe to
|
||||
/// call outside a turn to preview the request.
|
||||
pub async fn collect_prompt_contributions(
|
||||
&self,
|
||||
session: &S,
|
||||
conversation: &Conversation,
|
||||
) -> Result<InferenceInput> {
|
||||
let mut input = InferenceInput::default();
|
||||
let mut tool_names = HashSet::new();
|
||||
for operation in self.steps.iter().map(|step| step.operation()) {
|
||||
let tools = operation.inference_tools(session).await?;
|
||||
add_tools_to_inference_input(&mut input, &mut tool_names, tools)?;
|
||||
input
|
||||
.prompt_parts
|
||||
.extend(operation.prompt_parts(session, conversation).await?);
|
||||
}
|
||||
Ok(input)
|
||||
}
|
||||
|
||||
/// The prompt contributions plus the turn-context parts.
|
||||
pub async fn collect_inference_input(
|
||||
&self,
|
||||
session: &S,
|
||||
conversation: &Conversation,
|
||||
) -> Result<InferenceInput> {
|
||||
let mut input = self
|
||||
.collect_prompt_contributions(session, conversation)
|
||||
.await?;
|
||||
for operation in self.steps.iter().map(|step| step.operation()) {
|
||||
input
|
||||
.moim_parts
|
||||
.extend(operation.moim_parts(session, conversation).await?);
|
||||
}
|
||||
Ok(input)
|
||||
}
|
||||
|
||||
pub async fn step(&self, session: &S, emit: &Emitter) -> Result<StepResult<E>> {
|
||||
let conversation = session
|
||||
.conversation()
|
||||
@@ -144,18 +181,7 @@ where
|
||||
if !inference.applies(conversation) {
|
||||
return Ok(OperationResult::NotApplicable);
|
||||
}
|
||||
let mut input = InferenceInput::default();
|
||||
let mut tool_names = HashSet::new();
|
||||
for operation in self.steps.iter().map(|step| step.operation()) {
|
||||
let tools = operation.inference_tools(session).await?;
|
||||
add_tools_to_inference_input(&mut input, &mut tool_names, tools)?;
|
||||
input
|
||||
.prompt_parts
|
||||
.extend(operation.prompt_parts(session, conversation).await?);
|
||||
input
|
||||
.moim_parts
|
||||
.extend(operation.moim_parts(session, conversation).await?);
|
||||
}
|
||||
let input = self.collect_inference_input(session, conversation).await?;
|
||||
inference.infer(session, conversation, input, emit).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -844,6 +844,10 @@ pub struct MessageMetadata {
|
||||
/// Whether this message is a per-turn context event appended by the agent.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub turn_context: bool,
|
||||
/// Whether this message is the summary that compaction left in place of
|
||||
/// the messages it removed.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub compaction_summary: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage: Option<Box<MessageUsage>>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
@@ -864,6 +868,7 @@ impl Default for MessageMetadata {
|
||||
output_token_limit_reached: false,
|
||||
steer: false,
|
||||
turn_context: false,
|
||||
compaction_summary: false,
|
||||
usage: None,
|
||||
operation_logs: Vec::new(),
|
||||
operations: None,
|
||||
@@ -957,6 +962,11 @@ impl MessageMetadata {
|
||||
self.turn_context = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_compaction_summary(mut self) -> Self {
|
||||
self.compaction_summary = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)]
|
||||
@@ -1374,6 +1384,10 @@ impl Message {
|
||||
pub fn is_turn_context(&self) -> bool {
|
||||
self.metadata.turn_context
|
||||
}
|
||||
|
||||
pub fn is_compaction_summary(&self) -> bool {
|
||||
self.metadata.compaction_summary
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
|
||||
@@ -325,6 +325,89 @@ pub struct DiagnosticsGetResponse {
|
||||
pub report: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Break down what fills the model's context window if the session were
|
||||
/// prompted right now. Makes no model call.
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcRequest)]
|
||||
#[request(method = "_goose/unstable/context/report", response = ContextReportResponse)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextReportRequest {
|
||||
pub session_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, JsonRpcResponse)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextReportResponse {
|
||||
pub model: ContextReportModel,
|
||||
/// Measured with goose's local tokenizer; always the sum of the segments.
|
||||
pub total_tokens: u64,
|
||||
/// Non-overlapping. Prompt and tool segments come in request order; the
|
||||
/// conversation follows grouped by message kind, with each part labelled
|
||||
/// by its position in the request.
|
||||
pub segments: Vec<ContextSegment>,
|
||||
/// The provider keeps its own history and only receives the latest prompt
|
||||
/// (Claude Code, Gemini CLI), so goose assembles no request to break down;
|
||||
/// `segments` is empty and `total_tokens` is zero.
|
||||
pub provider_manages_context: bool,
|
||||
/// The session is past the auto-compaction threshold, so the loop compacts
|
||||
/// the conversation before it sends the next request.
|
||||
pub auto_compaction_pending: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextReportModel {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub provider: Option<String>,
|
||||
pub model_name: String,
|
||||
pub context_limit: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextSegment {
|
||||
pub category: ContextCategory,
|
||||
pub label: String,
|
||||
/// Display-only provenance, such as a file path or a tool count.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<String>,
|
||||
pub token_count: u64,
|
||||
/// Truncated with a trailing `… (+N more chars)` marker. Omitted when
|
||||
/// `parts` carries the previews.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub content_preview: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub parts: Vec<ContextPart>,
|
||||
}
|
||||
|
||||
/// Parts add up to their segment's `tokenCount`, except where a segment is
|
||||
/// split into prose sections; there the headings and framing are carried by
|
||||
/// the segment alone.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextPart {
|
||||
pub label: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<String>,
|
||||
pub token_count: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub content_preview: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ContextCategory {
|
||||
/// The base prompt, plus the residual row that reconciles the segments
|
||||
/// with the request total.
|
||||
SystemPrompt,
|
||||
ExtensionInstructions,
|
||||
/// Hint files, project instructions and other prompt extras.
|
||||
AdditionalInstructions,
|
||||
TurnContext,
|
||||
ToolDefinitions,
|
||||
CompactionSummary,
|
||||
Messages,
|
||||
}
|
||||
|
||||
/// Information about a prompt template, including its default content and customization status.
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -85,6 +85,11 @@
|
||||
"requestType": "DiagnosticsGetRequest_unstable",
|
||||
"responseType": "DiagnosticsGetResponse_unstable"
|
||||
},
|
||||
{
|
||||
"method": "_goose/unstable/context/report",
|
||||
"requestType": "ContextReportRequest_unstable",
|
||||
"responseType": "ContextReportResponse_unstable"
|
||||
},
|
||||
{
|
||||
"method": "_goose/unstable/config/prompts/list",
|
||||
"requestType": "ListPromptsRequest_unstable",
|
||||
|
||||
@@ -1438,6 +1438,172 @@
|
||||
"x-side": "agent",
|
||||
"x-method": "_goose/unstable/diagnostics/get"
|
||||
},
|
||||
"ContextReportRequest_unstable": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sessionId": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"sessionId"
|
||||
],
|
||||
"description": "Break down what fills the model's context window if the session were\nprompted right now. Makes no model call.",
|
||||
"x-side": "agent",
|
||||
"x-method": "_goose/unstable/context/report"
|
||||
},
|
||||
"ContextReportResponse_unstable": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model": {
|
||||
"$ref": "#/$defs/ContextReportModel"
|
||||
},
|
||||
"totalTokens": {
|
||||
"type": "integer",
|
||||
"description": "Measured with goose's local tokenizer; always the sum of the segments.",
|
||||
"minimum": 0
|
||||
},
|
||||
"segments": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/ContextSegment"
|
||||
},
|
||||
"description": "Non-overlapping. Prompt and tool segments come in request order; the\nconversation follows grouped by message kind, with each part labelled\nby its position in the request."
|
||||
},
|
||||
"providerManagesContext": {
|
||||
"type": "boolean",
|
||||
"description": "The provider keeps its own history and only receives the latest prompt\n(Claude Code, Gemini CLI), so goose assembles no request to break down;\n`segments` is empty and `total_tokens` is zero."
|
||||
},
|
||||
"autoCompactionPending": {
|
||||
"type": "boolean",
|
||||
"description": "The session is past the auto-compaction threshold, so the loop compacts\nthe conversation before it sends the next request."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"model",
|
||||
"totalTokens",
|
||||
"segments",
|
||||
"providerManagesContext",
|
||||
"autoCompactionPending"
|
||||
],
|
||||
"x-side": "agent",
|
||||
"x-method": "_goose/unstable/context/report"
|
||||
},
|
||||
"ContextReportModel": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"modelName": {
|
||||
"type": "string"
|
||||
},
|
||||
"contextLimit": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"modelName",
|
||||
"contextLimit"
|
||||
]
|
||||
},
|
||||
"ContextSegment": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"category": {
|
||||
"$ref": "#/$defs/ContextCategory"
|
||||
},
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"source": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Display-only provenance, such as a file path or a tool count."
|
||||
},
|
||||
"tokenCount": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"contentPreview": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"description": "Truncated with a trailing `… (+N more chars)` marker. Omitted when\n`parts` carries the previews."
|
||||
},
|
||||
"parts": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/ContextPart"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"category",
|
||||
"label",
|
||||
"tokenCount"
|
||||
]
|
||||
},
|
||||
"ContextCategory": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"extension_instructions",
|
||||
"turn_context",
|
||||
"tool_definitions",
|
||||
"compaction_summary",
|
||||
"messages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"const": "system_prompt",
|
||||
"description": "The base prompt, plus the residual row that reconciles the segments\nwith the request total."
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"const": "additional_instructions",
|
||||
"description": "Hint files, project instructions and other prompt extras."
|
||||
}
|
||||
]
|
||||
},
|
||||
"ContextPart": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"source": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"tokenCount": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"contentPreview": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"label",
|
||||
"tokenCount"
|
||||
],
|
||||
"description": "Parts add up to their segment's `tokenCount`, except where a segment is\nsplit into prose sections; there the headings and framing are carried by\nthe segment alone."
|
||||
},
|
||||
"ListPromptsRequest_unstable": {
|
||||
"type": "object",
|
||||
"description": "List all available goose prompt templates.",
|
||||
@@ -7212,6 +7378,15 @@
|
||||
"description": "Params for _goose/unstable/diagnostics/get",
|
||||
"title": "DiagnosticsGetRequest_unstable"
|
||||
},
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/$defs/ContextReportRequest_unstable"
|
||||
}
|
||||
],
|
||||
"description": "Params for _goose/unstable/context/report",
|
||||
"title": "ContextReportRequest_unstable"
|
||||
},
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
@@ -8183,6 +8358,14 @@
|
||||
],
|
||||
"title": "DiagnosticsGetResponse_unstable"
|
||||
},
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/$defs/ContextReportResponse_unstable"
|
||||
}
|
||||
],
|
||||
"title": "ContextReportResponse_unstable"
|
||||
},
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
|
||||
@@ -99,6 +99,7 @@ mod agent_mentions;
|
||||
use crate::agents::{ActiveRunRegistry, StartRunError};
|
||||
mod apps;
|
||||
mod config;
|
||||
mod context_report;
|
||||
mod custom_dispatch;
|
||||
mod diagnostics;
|
||||
mod dictation;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
use super::*;
|
||||
use crate::token_counter::create_token_counter;
|
||||
|
||||
impl AcpConnection {
|
||||
pub(super) async fn on_get_context_report(
|
||||
&self,
|
||||
req: ContextReportRequest,
|
||||
) -> Result<ContextReportResponse, agent_client_protocol::Error> {
|
||||
let token_counter = create_token_counter().await.internal_err()?;
|
||||
|
||||
self.services
|
||||
.build_context_report(&req.session_id, &token_counter)
|
||||
.await
|
||||
.internal_err()
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,14 @@ impl AcpConnection {
|
||||
self.on_get_diagnostics(req).await
|
||||
}
|
||||
|
||||
#[custom_method(ContextReportRequest)]
|
||||
async fn dispatch_get_context_report(
|
||||
&self,
|
||||
req: ContextReportRequest,
|
||||
) -> Result<ContextReportResponse, agent_client_protocol::Error> {
|
||||
self.on_get_context_report(req).await
|
||||
}
|
||||
|
||||
#[custom_method(ListPromptsRequest)]
|
||||
async fn dispatch_list_prompts(
|
||||
&self,
|
||||
|
||||
@@ -0,0 +1,829 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use rmcp::model::{Role, Tool};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub use goose_sdk_types::custom_requests::{
|
||||
ContextCategory, ContextPart, ContextReportModel, ContextReportResponse, ContextSegment,
|
||||
};
|
||||
|
||||
use crate::agents::extension_manager::get_tool_owner;
|
||||
use crate::agents::state_machine::enrich_unclaimed_tool_errors;
|
||||
use crate::agents::{PromptManager, SessionConfig, StateMachineServices};
|
||||
use crate::conversation::message::{Message, MessageContent};
|
||||
use crate::conversation::{
|
||||
effective_role, fix_conversation, merge_consecutive_messages_for_request, Conversation,
|
||||
};
|
||||
use crate::providers::toolshim::{
|
||||
convert_tool_messages_to_text, format_tool_info, modify_system_prompt_for_tool_json,
|
||||
toolshim_system_prompt_appendix,
|
||||
};
|
||||
use crate::token_counter::{TokenCounter, TOKENS_PER_MESSAGE};
|
||||
|
||||
const MAX_PREVIEW_CHARS: usize = 2_000;
|
||||
|
||||
fn preview(text: &str) -> String {
|
||||
let count = text.chars().count();
|
||||
if count <= MAX_PREVIEW_CHARS {
|
||||
return text.to_string();
|
||||
}
|
||||
let kept: String = text.chars().take(MAX_PREVIEW_CHARS).collect();
|
||||
format!("{kept}… (+{} more chars)", count - MAX_PREVIEW_CHARS)
|
||||
}
|
||||
|
||||
pub(super) const NEXT_PROMPT_STAND_IN: &str = "[next user prompt]";
|
||||
|
||||
/// A stand-in keeps the last assistant reply from looking like a dangling
|
||||
/// message while the next request is repaired, then disappears from the report.
|
||||
fn next_request_messages(persisted: &Conversation) -> Vec<Message> {
|
||||
let mut messages = persisted.agent_visible_messages();
|
||||
messages.push(Message::user().with_text(NEXT_PROMPT_STAND_IN));
|
||||
let (fixed, _) = fix_conversation(Conversation::new_unvalidated(messages));
|
||||
let mut messages: Vec<Message> = fixed.into_iter().collect();
|
||||
if let Some(last) = messages.last_mut() {
|
||||
if matches!(
|
||||
last.content.last(),
|
||||
Some(MessageContent::Text(text)) if text.text == NEXT_PROMPT_STAND_IN
|
||||
) {
|
||||
last.content.pop();
|
||||
}
|
||||
if last.content.is_empty() {
|
||||
messages.pop();
|
||||
}
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
fn text_segment(
|
||||
category: ContextCategory,
|
||||
label: impl Into<String>,
|
||||
source: Option<String>,
|
||||
text: &str,
|
||||
token_counter: &TokenCounter,
|
||||
) -> ContextSegment {
|
||||
ContextSegment {
|
||||
category,
|
||||
label: label.into(),
|
||||
source,
|
||||
token_count: token_counter.count_tokens(text) as u64,
|
||||
content_preview: Some(preview(text)),
|
||||
parts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
impl StateMachineServices {
|
||||
pub async fn build_context_report(
|
||||
self: &Arc<Self>,
|
||||
session_id: &str,
|
||||
token_counter: &TokenCounter,
|
||||
) -> Result<ContextReportResponse> {
|
||||
let session = self.session_manager.get_session(session_id, true).await?;
|
||||
let provider = self.provider(session_id).await?;
|
||||
let model_config = self.effective_model_config_for_session(session_id).await?;
|
||||
let context_limit =
|
||||
crate::context_limit::get_context_limit(provider.as_ref(), &model_config.model_name)
|
||||
.await
|
||||
.unwrap_or_else(|_| model_config.context_limit());
|
||||
let model = ContextReportModel {
|
||||
provider: session.provider_name.clone(),
|
||||
model_name: model_config.model_name.clone(),
|
||||
context_limit: context_limit as u64,
|
||||
};
|
||||
if provider.manages_own_context() {
|
||||
return Ok(ContextReportResponse {
|
||||
model,
|
||||
provider_manages_context: true,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
let persisted = session
|
||||
.conversation
|
||||
.clone()
|
||||
.unwrap_or_else(Conversation::empty);
|
||||
let auto_compaction_pending = crate::context_mgmt::check_if_compaction_needed(
|
||||
provider.as_ref(),
|
||||
&persisted,
|
||||
None,
|
||||
&session,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let (session, lease) = self
|
||||
.extension_manager
|
||||
.current_session_snapshot(&session)
|
||||
.await?;
|
||||
let code_execution_active = {
|
||||
#[cfg(feature = "code-mode")]
|
||||
{
|
||||
lease.is_enabled(crate::agents::platform_extensions::code_execution::EXTENSION_NAME)
|
||||
}
|
||||
#[cfg(not(feature = "code-mode"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
};
|
||||
let extension_lease = Arc::new(std::sync::Mutex::new(Some(Arc::new(lease))));
|
||||
|
||||
let mut next_messages = session
|
||||
.conversation
|
||||
.clone()
|
||||
.unwrap_or_else(Conversation::empty)
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
next_messages.push(Message::user().with_text(NEXT_PROMPT_STAND_IN));
|
||||
let next_conversation = Conversation::new_unvalidated(next_messages);
|
||||
let machine = self
|
||||
.create_state_machine_with_lease(
|
||||
provider.clone(),
|
||||
model_config.clone(),
|
||||
context_limit,
|
||||
SessionConfig {
|
||||
id: session.id.clone(),
|
||||
schedule_id: session.schedule_id.clone(),
|
||||
max_turns: None,
|
||||
},
|
||||
CancellationToken::new(),
|
||||
self.runtime.steer_queue(session_id),
|
||||
extension_lease,
|
||||
)
|
||||
.await;
|
||||
let input = machine
|
||||
.collect_inference_input(&session, &next_conversation)
|
||||
.await?;
|
||||
if session.goose_mode == crate::config::GooseMode::SmartApprove {
|
||||
self.tool_inspection_manager
|
||||
.apply_tool_annotations(&input.tools);
|
||||
}
|
||||
let tools =
|
||||
crate::agents::reply_parts::prepare_inference_tools(input.tools, code_execution_active);
|
||||
let prompt = PromptManager::new().build_system_prompt_parts(
|
||||
&session,
|
||||
input.prompt_parts,
|
||||
session.goose_mode,
|
||||
)?;
|
||||
let turn_context = crate::agents::moim::turn_context_event(
|
||||
&session.working_dir,
|
||||
Some(context_limit),
|
||||
input.moim_parts,
|
||||
chrono::Local::now(),
|
||||
);
|
||||
let toolshim = model_config.toolshim;
|
||||
|
||||
let mut system_prompt = prompt.join();
|
||||
if toolshim {
|
||||
system_prompt = modify_system_prompt_for_tool_json(&system_prompt, &tools);
|
||||
}
|
||||
|
||||
let mut messages = next_request_messages(&persisted);
|
||||
// The prompt that will follow is unknown, but the turn-context event
|
||||
// appended after it is not.
|
||||
messages.extend(turn_context);
|
||||
messages = enrich_unclaimed_tool_errors(&messages, &tools);
|
||||
let messages = Conversation::new_unvalidated(messages);
|
||||
let request_messages = merge_consecutive_messages_for_request(messages.messages().clone());
|
||||
let (request_tools, request_messages, counted_messages) = if toolshim {
|
||||
(
|
||||
Vec::new(),
|
||||
convert_tool_messages_to_text(&request_messages),
|
||||
convert_tool_messages_to_text(messages.messages()),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
tools.clone(),
|
||||
Conversation::new_unvalidated(request_messages),
|
||||
messages.clone(),
|
||||
)
|
||||
};
|
||||
let request_tokens = token_counter.count_chat_tokens(
|
||||
&system_prompt,
|
||||
request_messages.messages(),
|
||||
&request_tools,
|
||||
) as u64;
|
||||
|
||||
let mut segments = Vec::new();
|
||||
segments.push(text_segment(
|
||||
ContextCategory::SystemPrompt,
|
||||
"Base system prompt",
|
||||
Some(if prompt.base_is_override {
|
||||
"override".to_string()
|
||||
} else {
|
||||
"prompts/system.md".to_string()
|
||||
}),
|
||||
&prompt.base,
|
||||
token_counter,
|
||||
));
|
||||
for (key, value) in &prompt.extras {
|
||||
let (category, label, source) = extra_descriptor(key);
|
||||
segments.push(text_segment(category, label, source, value, token_counter));
|
||||
}
|
||||
if toolshim {
|
||||
segments.push(toolshim_tool_segment(&tools, token_counter));
|
||||
} else {
|
||||
segments.extend(tool_segments(&tools, token_counter));
|
||||
}
|
||||
segments.extend(message_segments(
|
||||
messages.messages(),
|
||||
counted_messages.messages(),
|
||||
token_counter,
|
||||
));
|
||||
|
||||
// Tokenizing the rows one by one is not additive with tokenizing the
|
||||
// joined request: a positive residual is the overhead row, a negative
|
||||
// one comes off the prompt rows, so the rows always sum to the request.
|
||||
let attributed: u64 = segments.iter().map(|segment| segment.token_count).sum();
|
||||
if request_tokens > attributed {
|
||||
segments.push(ContextSegment {
|
||||
category: ContextCategory::SystemPrompt,
|
||||
label: "Prompt overhead".to_string(),
|
||||
source: None,
|
||||
token_count: request_tokens - attributed,
|
||||
content_preview: None,
|
||||
parts: Vec::new(),
|
||||
});
|
||||
} else {
|
||||
let mut excess = attributed - request_tokens;
|
||||
for segment in &mut segments {
|
||||
if excess == 0 {
|
||||
break;
|
||||
}
|
||||
let taken = segment.token_count.min(excess);
|
||||
segment.token_count -= taken;
|
||||
excess -= taken;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ContextReportResponse {
|
||||
model,
|
||||
total_tokens: request_tokens,
|
||||
segments,
|
||||
provider_manages_context: false,
|
||||
auto_compaction_pending,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn extra_descriptor(key: &str) -> (ContextCategory, String, Option<String>) {
|
||||
if key == "hints" {
|
||||
(
|
||||
ContextCategory::AdditionalInstructions,
|
||||
"Hint files".to_string(),
|
||||
None,
|
||||
)
|
||||
} else if let Some(dir) = key.strip_prefix("subdir_hints:") {
|
||||
(
|
||||
ContextCategory::AdditionalInstructions,
|
||||
"Subdirectory hints".to_string(),
|
||||
Some(dir.to_string()),
|
||||
)
|
||||
} else if key == "extensions" {
|
||||
(
|
||||
ContextCategory::ExtensionInstructions,
|
||||
"Extensions".to_string(),
|
||||
None,
|
||||
)
|
||||
} else if let Some(name) = key.strip_prefix("extension:") {
|
||||
(
|
||||
ContextCategory::ExtensionInstructions,
|
||||
name.to_string(),
|
||||
None,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
ContextCategory::AdditionalInstructions,
|
||||
key.to_string(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_content(tool: &Tool) -> String {
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": tool.name,
|
||||
"description": tool.description,
|
||||
"inputSchema": tool.input_schema,
|
||||
}))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Tools are counted in request order as marginal additions to a growing
|
||||
/// prefix so the parts sum to exactly what `count_tokens_for_tools` charges
|
||||
/// the request; owners appear in the order their first tool does.
|
||||
fn tool_segments(tools: &[Tool], token_counter: &TokenCounter) -> Vec<ContextSegment> {
|
||||
let mut segments: Vec<ContextSegment> = Vec::new();
|
||||
let mut segment_by_owner: HashMap<String, usize> = HashMap::new();
|
||||
let mut cumulative: Vec<Tool> = Vec::with_capacity(tools.len());
|
||||
let mut cumulative_tokens = 0usize;
|
||||
for tool in tools {
|
||||
let before = cumulative_tokens;
|
||||
cumulative.push(tool.clone());
|
||||
cumulative_tokens = token_counter.count_tokens_for_tools(&cumulative);
|
||||
let part = ContextPart {
|
||||
label: tool.name.to_string(),
|
||||
source: None,
|
||||
token_count: (cumulative_tokens - before) as u64,
|
||||
content_preview: Some(preview(&tool_content(tool))),
|
||||
};
|
||||
let owner = get_tool_owner(tool).unwrap_or_else(|| "ungrouped".to_string());
|
||||
let index = *segment_by_owner.entry(owner.clone()).or_insert_with(|| {
|
||||
segments.push(ContextSegment {
|
||||
category: ContextCategory::ToolDefinitions,
|
||||
label: owner,
|
||||
source: None,
|
||||
token_count: 0,
|
||||
content_preview: None,
|
||||
parts: Vec::new(),
|
||||
});
|
||||
segments.len() - 1
|
||||
});
|
||||
segments[index].token_count += part.token_count;
|
||||
segments[index].parts.push(part);
|
||||
}
|
||||
for segment in &mut segments {
|
||||
segment.source = Some(format!("{} tools", segment.parts.len()));
|
||||
}
|
||||
segments
|
||||
}
|
||||
|
||||
fn toolshim_tool_segment(tools: &[Tool], token_counter: &TokenCounter) -> ContextSegment {
|
||||
let mut cumulative: Vec<Tool> = Vec::with_capacity(tools.len());
|
||||
let mut appendix = toolshim_system_prompt_appendix(&cumulative);
|
||||
let mut cumulative_tokens = token_counter.count_tokens(&appendix);
|
||||
|
||||
let mut parts = Vec::with_capacity(tools.len() + 1);
|
||||
parts.push(ContextPart {
|
||||
label: "Tool calling instructions".to_string(),
|
||||
source: None,
|
||||
token_count: cumulative_tokens as u64,
|
||||
content_preview: Some(preview(&appendix)),
|
||||
});
|
||||
for tool in tools {
|
||||
cumulative.push(tool.clone());
|
||||
appendix = toolshim_system_prompt_appendix(&cumulative);
|
||||
let before = cumulative_tokens;
|
||||
cumulative_tokens = token_counter.count_tokens(&appendix);
|
||||
parts.push(ContextPart {
|
||||
label: tool.name.to_string(),
|
||||
source: None,
|
||||
token_count: (cumulative_tokens - before) as u64,
|
||||
content_preview: Some(preview(&format_tool_info(std::slice::from_ref(tool)))),
|
||||
});
|
||||
}
|
||||
|
||||
ContextSegment {
|
||||
category: ContextCategory::ToolDefinitions,
|
||||
label: "Toolshim tool instructions".to_string(),
|
||||
source: Some(format!("{} tools", tools.len())),
|
||||
token_count: cumulative_tokens as u64,
|
||||
content_preview: None,
|
||||
parts,
|
||||
}
|
||||
}
|
||||
|
||||
fn message_text(message: &Message) -> String {
|
||||
message
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|content| {
|
||||
if let Some(text) = content.as_text() {
|
||||
Some(text.to_string())
|
||||
} else if let Some(request) = content.as_tool_request() {
|
||||
request.tool_call.as_ref().ok().map(|call| {
|
||||
format!(
|
||||
"{}({})",
|
||||
call.name,
|
||||
serde_json::to_string(&call.arguments).unwrap_or_default()
|
||||
)
|
||||
})
|
||||
} else {
|
||||
content.as_tool_response_text()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
enum MessageKind {
|
||||
TurnContext,
|
||||
CompactionSummary,
|
||||
User,
|
||||
Assistant,
|
||||
ToolCalls,
|
||||
ToolResults,
|
||||
}
|
||||
|
||||
impl MessageKind {
|
||||
fn classify(message: &Message) -> Self {
|
||||
if message.is_turn_context() {
|
||||
MessageKind::TurnContext
|
||||
} else if crate::context_mgmt::is_compaction_summary(message) {
|
||||
MessageKind::CompactionSummary
|
||||
} else if message
|
||||
.content
|
||||
.iter()
|
||||
.any(|c| c.as_tool_response().is_some())
|
||||
{
|
||||
MessageKind::ToolResults
|
||||
} else if message
|
||||
.content
|
||||
.iter()
|
||||
.any(|c| c.as_tool_request().is_some())
|
||||
{
|
||||
MessageKind::ToolCalls
|
||||
} else if message.role == Role::Assistant {
|
||||
MessageKind::Assistant
|
||||
} else {
|
||||
MessageKind::User
|
||||
}
|
||||
}
|
||||
|
||||
fn category(self) -> ContextCategory {
|
||||
match self {
|
||||
MessageKind::TurnContext => ContextCategory::TurnContext,
|
||||
MessageKind::CompactionSummary => ContextCategory::CompactionSummary,
|
||||
_ => ContextCategory::Messages,
|
||||
}
|
||||
}
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
MessageKind::TurnContext => "Turn context",
|
||||
MessageKind::CompactionSummary => "Conversation summary",
|
||||
MessageKind::User => "User messages",
|
||||
MessageKind::Assistant => "Assistant messages",
|
||||
MessageKind::ToolCalls => "Tool calls",
|
||||
MessageKind::ToolResults => "Tool results",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits on `##` headings outside fenced blocks, since code samples can
|
||||
/// contain heading lines.
|
||||
fn summary_sections(text: &str) -> Vec<(String, String)> {
|
||||
let mut sections: Vec<(String, String)> = Vec::new();
|
||||
let mut open_fence: Option<usize> = None;
|
||||
|
||||
for line in text.lines() {
|
||||
let backticks = line.trim_start().chars().take_while(|c| *c == '`').count();
|
||||
match open_fence {
|
||||
Some(len) if backticks >= len => open_fence = None,
|
||||
Some(_) => {}
|
||||
None if backticks >= 3 => open_fence = Some(backticks),
|
||||
None => {
|
||||
if let Some(heading) = line.strip_prefix("## ") {
|
||||
sections.push((heading.trim().to_string(), String::new()));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((_, body)) = sections.last_mut() {
|
||||
body.push_str(line);
|
||||
body.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
sections.retain_mut(|(_, body)| {
|
||||
*body = body.trim().to_string();
|
||||
!body.is_empty()
|
||||
});
|
||||
sections
|
||||
}
|
||||
|
||||
/// `counted_messages` is `messages` after any toolshim conversion, so previews
|
||||
/// come from the original while token counts come from what is sent.
|
||||
fn message_segments(
|
||||
messages: &[Message],
|
||||
counted_messages: &[Message],
|
||||
token_counter: &TokenCounter,
|
||||
) -> Vec<ContextSegment> {
|
||||
let mut grouped: BTreeMap<MessageKind, Vec<(ContextPart, String)>> = BTreeMap::new();
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
let counted = counted_messages.get(index).unwrap_or(message);
|
||||
let kind = MessageKind::classify(message);
|
||||
let text = message_text(message);
|
||||
// The request merges same-role neighbours into one message, which pays
|
||||
// the per-message framing once; charge the follow-on messages only for
|
||||
// their content so the rows sum to what the request pays.
|
||||
let merged_into_previous = index
|
||||
.checked_sub(1)
|
||||
.is_some_and(|previous| effective_role(&messages[previous]) == effective_role(message));
|
||||
let mut token_count = token_counter.count_message_tokens(counted);
|
||||
if merged_into_previous {
|
||||
token_count -= TOKENS_PER_MESSAGE;
|
||||
}
|
||||
let part = ContextPart {
|
||||
label: format!("#{}", index + 1),
|
||||
source: None,
|
||||
token_count: token_count as u64,
|
||||
content_preview: Some(preview(&text)),
|
||||
};
|
||||
grouped.entry(kind).or_default().push((part, text));
|
||||
}
|
||||
|
||||
grouped
|
||||
.into_iter()
|
||||
.map(|(kind, parts)| {
|
||||
let token_count = parts.iter().map(|(part, _)| part.token_count).sum();
|
||||
let parts = match (kind, parts.as_slice()) {
|
||||
(MessageKind::CompactionSummary, [(_, text)]) => {
|
||||
compaction_summary_parts(text, token_counter)
|
||||
.unwrap_or_else(|| parts.into_iter().map(|(part, _)| part).collect())
|
||||
}
|
||||
_ => parts.into_iter().map(|(part, _)| part).collect(),
|
||||
};
|
||||
ContextSegment {
|
||||
category: kind.category(),
|
||||
label: kind.label().to_string(),
|
||||
source: None,
|
||||
token_count,
|
||||
content_preview: None,
|
||||
parts,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Section counts are measured on the text alone, so they sum to just under
|
||||
/// the segment, which also carries the message framing.
|
||||
fn compaction_summary_parts(
|
||||
summary: &str,
|
||||
token_counter: &TokenCounter,
|
||||
) -> Option<Vec<ContextPart>> {
|
||||
let sections = summary_sections(summary);
|
||||
if sections.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
sections
|
||||
.into_iter()
|
||||
.map(|(heading, body)| ContextPart {
|
||||
label: heading,
|
||||
source: None,
|
||||
token_count: token_counter.count_tokens(&body) as u64,
|
||||
content_preview: Some(preview(&body)),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::conversation::message::MessageMetadata;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn test_tool(name: &str, owner: Option<&str>) -> Tool {
|
||||
let mut tool = Tool::new(
|
||||
name.to_string(),
|
||||
format!("{name} does a thing."),
|
||||
Arc::new(rmcp::object!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": { "type": "string", "description": "File path to operate on." },
|
||||
"mode": { "type": "string", "enum": ["read", "write"] }
|
||||
}
|
||||
})),
|
||||
);
|
||||
if let Some(owner) = owner {
|
||||
tool.meta = Some(rmcp::model::MetaObject(
|
||||
rmcp::object!({ "goose_extension": owner }),
|
||||
));
|
||||
}
|
||||
tool
|
||||
}
|
||||
|
||||
fn part_total(segment: &ContextSegment) -> u64 {
|
||||
segment.parts.iter().map(|part| part.token_count).sum()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_segments_account_for_every_tool_token_exactly() {
|
||||
let token_counter = TokenCounter::new().await.unwrap();
|
||||
let tools = vec![
|
||||
test_tool("orphan", None),
|
||||
test_tool("beta__search", Some("beta")),
|
||||
test_tool("alpha__read", Some("alpha")),
|
||||
test_tool("beta__write", Some("beta")),
|
||||
test_tool("alpha__write", Some("alpha")),
|
||||
];
|
||||
|
||||
let segments = tool_segments(&tools, &token_counter);
|
||||
|
||||
let owners: Vec<&str> = segments
|
||||
.iter()
|
||||
.map(|segment| segment.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(owners, ["ungrouped", "beta", "alpha"]);
|
||||
assert_eq!(segments[1].parts.len(), 2);
|
||||
for segment in &segments {
|
||||
assert_eq!(segment.category, ContextCategory::ToolDefinitions);
|
||||
assert_eq!(segment.token_count, part_total(segment));
|
||||
}
|
||||
let segment_total: u64 = segments.iter().map(|segment| segment.token_count).sum();
|
||||
assert_eq!(
|
||||
segment_total,
|
||||
token_counter.count_tokens_for_tools(&tools) as u64
|
||||
);
|
||||
}
|
||||
|
||||
const RENDERED_SUMMARY: &str = "# Conversation Summary
|
||||
|
||||
## User Intent
|
||||
- Fix the parser bug
|
||||
|
||||
## Files + Code
|
||||
### src/parser.rs
|
||||
Fixed off-by-one in scan loop
|
||||
````
|
||||
## heading inside a fence
|
||||
fn scan() {}
|
||||
````
|
||||
|
||||
## Next Step
|
||||
Finish the regression test
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn extension_extras_report_as_extension_instructions() {
|
||||
// Instructions can carry their own markdown headings, so the key is
|
||||
// what names the extension.
|
||||
assert_eq!(
|
||||
extra_descriptor("extension:autovisualiser"),
|
||||
(
|
||||
ContextCategory::ExtensionInstructions,
|
||||
"autovisualiser".to_string(),
|
||||
None
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
extra_descriptor("recipe"),
|
||||
(
|
||||
ContextCategory::AdditionalInstructions,
|
||||
"recipe".to_string(),
|
||||
None
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn message_segments_group_by_kind_and_sum_to_the_messages() {
|
||||
let token_counter = TokenCounter::new().await.unwrap();
|
||||
let messages = vec![
|
||||
Message::user()
|
||||
.with_text(RENDERED_SUMMARY)
|
||||
.with_metadata(MessageMetadata::agent_only().with_compaction_summary()),
|
||||
Message::assistant().with_text("continuing where we left off"),
|
||||
Message::user().with_text("now add the test"),
|
||||
Message::user()
|
||||
.with_text("<turn-context>\n<current-time>now</current-time>\n</turn-context>")
|
||||
.with_metadata(MessageMetadata::agent_only().with_turn_context()),
|
||||
Message::assistant().with_tool_request(
|
||||
"call_1",
|
||||
Ok(rmcp::model::CallToolRequestParams::new("read_file")
|
||||
.with_arguments(rmcp::object!({"path": "a.txt"}))),
|
||||
),
|
||||
Message::user().with_tool_response(
|
||||
"call_1",
|
||||
Ok(rmcp::model::CallToolResult::success(vec![
|
||||
rmcp::model::ContentBlock::text("file contents"),
|
||||
])),
|
||||
),
|
||||
];
|
||||
|
||||
let segments = message_segments(&messages, &messages, &token_counter);
|
||||
|
||||
let labels: Vec<&str> = segments
|
||||
.iter()
|
||||
.map(|segment| segment.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
labels,
|
||||
vec![
|
||||
"Turn context",
|
||||
"Conversation summary",
|
||||
"User messages",
|
||||
"Assistant messages",
|
||||
"Tool calls",
|
||||
"Tool results",
|
||||
]
|
||||
);
|
||||
let summary = &segments[1];
|
||||
assert_eq!(summary.category, ContextCategory::CompactionSummary);
|
||||
let headings: Vec<&str> = summary
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| part.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(headings, vec!["User Intent", "Files + Code", "Next Step"]);
|
||||
assert!(summary.parts[1]
|
||||
.content_preview
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.contains("## heading inside a fence"));
|
||||
assert!(part_total(summary) <= summary.token_count);
|
||||
assert_eq!(segments[0].category, ContextCategory::TurnContext);
|
||||
assert_eq!(segments[2].category, ContextCategory::Messages);
|
||||
assert!(segments[4].parts[0]
|
||||
.content_preview
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.contains("read_file"));
|
||||
|
||||
// The prompt and its turn-context event merge into one request message.
|
||||
let expected_total: u64 = merge_consecutive_messages_for_request(messages.clone())
|
||||
.iter()
|
||||
.map(|message| token_counter.count_message_tokens(message) as u64)
|
||||
.sum();
|
||||
let segment_total: u64 = segments.iter().map(|segment| segment.token_count).sum();
|
||||
assert_eq!(segment_total, expected_total);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unclaimed_tool_errors_count_the_tool_list_the_request_appends() {
|
||||
let token_counter = TokenCounter::new().await.unwrap();
|
||||
let mut response = Message::user();
|
||||
response.add_tool_response_with_metadata(
|
||||
"call_1",
|
||||
Ok(rmcp::model::CallToolResult::error(vec![
|
||||
rmcp::model::ContentBlock::text("Tool missing__tool is not available."),
|
||||
])),
|
||||
Some(&serde_json::Map::from_iter([(
|
||||
crate::agents::state_machine::UNCLAIMED_TOOL_ERROR.to_string(),
|
||||
true.into(),
|
||||
)])),
|
||||
);
|
||||
let messages = vec![response];
|
||||
let tools = vec![
|
||||
test_tool("alpha__read", Some("alpha")),
|
||||
test_tool("beta__write", Some("beta")),
|
||||
];
|
||||
|
||||
let persisted = message_segments(&messages, &messages, &token_counter);
|
||||
let enriched = enrich_unclaimed_tool_errors(&messages, &tools);
|
||||
let requested = message_segments(&enriched, &enriched, &token_counter);
|
||||
|
||||
assert!(requested[0].token_count > persisted[0].token_count);
|
||||
assert!(requested[0].parts[0]
|
||||
.content_preview
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.contains("Available tools: [alpha__read, beta__write]."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_request_keeps_the_last_reply_and_drops_unanswered_tool_requests() {
|
||||
let persisted = Conversation::new_unvalidated(vec![
|
||||
Message::user().with_text("read a.txt"),
|
||||
Message::assistant()
|
||||
.with_tool_request(
|
||||
"answered",
|
||||
Ok(rmcp::model::CallToolRequestParams::new("read_file")),
|
||||
)
|
||||
.with_tool_request(
|
||||
"unanswered",
|
||||
Ok(rmcp::model::CallToolRequestParams::new("read_file")),
|
||||
),
|
||||
Message::user().with_tool_response(
|
||||
"answered",
|
||||
Ok(rmcp::model::CallToolResult::success(vec![
|
||||
rmcp::model::ContentBlock::text("a"),
|
||||
])),
|
||||
),
|
||||
Message::assistant().with_text("done"),
|
||||
]);
|
||||
|
||||
let messages = next_request_messages(&persisted);
|
||||
|
||||
assert_eq!(messages.len(), 4);
|
||||
let requests: Vec<&str> = messages[1]
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|content| content.as_tool_request())
|
||||
.map(|request| request.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(requests, ["answered"]);
|
||||
assert!(matches!(
|
||||
messages[3].content.as_slice(),
|
||||
[MessageContent::Text(text)] if text.text == "done"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_request_stand_in_leaves_no_trace_in_a_trailing_prompt() {
|
||||
let persisted = Conversation::new_unvalidated(vec![
|
||||
Message::user().with_text("hello"),
|
||||
Message::assistant().with_text("hi"),
|
||||
Message::user().with_text("interrupted before a reply"),
|
||||
]);
|
||||
|
||||
let messages = next_request_messages(&persisted);
|
||||
|
||||
assert_eq!(messages.len(), 3);
|
||||
assert!(matches!(
|
||||
messages[2].content.as_slice(),
|
||||
[MessageContent::Text(text)] if text.text == "interrupted before a reply"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
mod active_run;
|
||||
pub mod container;
|
||||
pub mod context_report;
|
||||
pub mod execute_commands;
|
||||
pub mod extension;
|
||||
pub mod extension_malware_check;
|
||||
|
||||
@@ -105,6 +105,10 @@ impl<'a> SystemPromptBuilder<'a, PromptManager> {
|
||||
}
|
||||
|
||||
pub fn build(self) -> anyhow::Result<String> {
|
||||
Ok(self.build_parts()?.join())
|
||||
}
|
||||
|
||||
pub fn build_parts(self) -> anyhow::Result<SystemPromptParts> {
|
||||
let mut extensions_info = self.extensions_info;
|
||||
|
||||
// Stable tool ordering is important for multi session prompt caching.
|
||||
@@ -117,7 +121,6 @@ impl<'a> SystemPromptBuilder<'a, PromptManager> {
|
||||
ext_info
|
||||
})
|
||||
.collect();
|
||||
|
||||
let goose_mode = self
|
||||
.goose_mode
|
||||
.unwrap_or_else(|| Config::global().get_goose_mode().unwrap_or_default());
|
||||
@@ -132,7 +135,8 @@ impl<'a> SystemPromptBuilder<'a, PromptManager> {
|
||||
moim_system_prompt_block: moim::system_prompt_block(),
|
||||
};
|
||||
|
||||
let base_prompt = if let Some(override_prompt) = &self.system_prompt_override {
|
||||
let base_is_override = self.system_prompt_override.is_some();
|
||||
let rendered = if let Some(override_prompt) = &self.system_prompt_override {
|
||||
let sanitized_override_prompt = sanitize_unicode_tags(override_prompt);
|
||||
prompt_template::render_string(&sanitized_override_prompt, &context)
|
||||
} else {
|
||||
@@ -140,34 +144,55 @@ impl<'a> SystemPromptBuilder<'a, PromptManager> {
|
||||
}
|
||||
.map_err(|error| anyhow::anyhow!("Could not render system prompt: {error}"))?;
|
||||
|
||||
let mut system_prompt_extras = self.prompt_extras;
|
||||
let mut extras = self.prompt_extras;
|
||||
|
||||
if let Some(hints) = self.hints {
|
||||
system_prompt_extras.insert("hints".to_string(), hints);
|
||||
extras.insert("hints".to_string(), hints);
|
||||
}
|
||||
|
||||
if goose_mode == GooseMode::Chat {
|
||||
system_prompt_extras.insert(
|
||||
extras.insert(
|
||||
"chat_mode".to_string(),
|
||||
"Right now you are in the chat only mode, no access to any tool use and system."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
if system_prompt_extras.is_empty() {
|
||||
Ok(base_prompt)
|
||||
} else {
|
||||
let sanitized_system_prompt_extras: Vec<String> = system_prompt_extras
|
||||
.into_values()
|
||||
.map(|extra| sanitize_unicode_tags(&extra))
|
||||
.collect();
|
||||
let extras = extras
|
||||
.into_iter()
|
||||
.map(|(key, extra)| (key, sanitize_unicode_tags(&extra)))
|
||||
.collect();
|
||||
|
||||
Ok(format!(
|
||||
"{}\n\n# Additional Instructions:\n\n{}",
|
||||
base_prompt,
|
||||
sanitized_system_prompt_extras.join("\n\n")
|
||||
))
|
||||
Ok(SystemPromptParts {
|
||||
base: rendered.clone(),
|
||||
rendered,
|
||||
base_is_override,
|
||||
extras,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SystemPromptParts {
|
||||
rendered: String,
|
||||
pub base: String,
|
||||
pub base_is_override: bool,
|
||||
pub extras: IndexMap<String, String>,
|
||||
}
|
||||
|
||||
impl SystemPromptParts {
|
||||
pub fn join(&self) -> String {
|
||||
if self.extras.is_empty() {
|
||||
return self.rendered.clone();
|
||||
}
|
||||
format!(
|
||||
"{}\n\n# Additional Instructions:\n\n{}",
|
||||
self.rendered,
|
||||
self.extras
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,13 +218,24 @@ impl PromptManager {
|
||||
prompt_parts: Vec<(String, String)>,
|
||||
goose_mode: GooseMode,
|
||||
) -> anyhow::Result<String> {
|
||||
Ok(self
|
||||
.build_system_prompt_parts(session, prompt_parts, goose_mode)?
|
||||
.join())
|
||||
}
|
||||
|
||||
pub fn build_system_prompt_parts(
|
||||
&self,
|
||||
session: &Session,
|
||||
prompt_parts: Vec<(String, String)>,
|
||||
goose_mode: GooseMode,
|
||||
) -> anyhow::Result<SystemPromptParts> {
|
||||
self.builder()
|
||||
.with_session(session)
|
||||
.with_prompt_extras(prompt_parts)
|
||||
.with_hints(&session.working_dir)
|
||||
.with_goose_mode(goose_mode)
|
||||
.without_extensions()
|
||||
.build()
|
||||
.build_parts()
|
||||
}
|
||||
|
||||
pub fn builder<'a>(&'a self) -> SystemPromptBuilder<'a, Self> {
|
||||
@@ -272,6 +308,26 @@ mod tests {
|
||||
assert!(result.contains("hidden"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_parts_preserves_prompt_contribution_keys() {
|
||||
let manager = PromptManager::new();
|
||||
let parts = manager
|
||||
.builder()
|
||||
.with_prompt_extras([
|
||||
("recipe".to_string(), "Follow the recipe.".to_string()),
|
||||
("project".to_string(), "Project instructions.".to_string()),
|
||||
])
|
||||
.build_parts()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parts.extras.keys().map(String::as_str).collect::<Vec<_>>(),
|
||||
["recipe", "project"]
|
||||
);
|
||||
assert!(parts.join().contains("Follow the recipe."));
|
||||
assert!(parts.join().contains("Project instructions."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_contributions_are_not_retained() {
|
||||
let manager = PromptManager::new();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex as StdMutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
@@ -11,7 +11,7 @@ use tracing_futures::Instrument;
|
||||
use super::gen_ai_telemetry;
|
||||
use super::tool_confirmation_coordinator::{ActiveTurnGuard, ConfirmationAnswer};
|
||||
use crate::action_required_manager::ElicitationOutcome;
|
||||
use crate::agents::extension_manager::{ClientContext, ExtensionManager};
|
||||
use crate::agents::extension_manager::{ClientContext, ExtensionLease, ExtensionManager};
|
||||
use crate::agents::provider_manager::ProviderManager;
|
||||
use crate::agents::session_runtime::{Attachment, SessionRuntime};
|
||||
use crate::agents::state_machine::ops_recipe;
|
||||
@@ -725,16 +725,39 @@ impl StateMachineServices {
|
||||
cancel: CancellationToken,
|
||||
steer_queue: SteerQueue,
|
||||
) -> StateMachine<'_, Session, GooseEffect> {
|
||||
let settings = match &self.turn_settings {
|
||||
Some(settings) => settings.clone(),
|
||||
None => TurnSettings::from_config(provider.as_ref(), &model_config),
|
||||
};
|
||||
let max_turns = session_config.max_turns.unwrap_or(settings.max_turns);
|
||||
let extension_lease = self
|
||||
.runtime
|
||||
.confirmations
|
||||
.session(&session_config.id)
|
||||
.extension_lease();
|
||||
self.create_state_machine_with_lease(
|
||||
provider,
|
||||
model_config,
|
||||
context_limit,
|
||||
session_config,
|
||||
cancel,
|
||||
steer_queue,
|
||||
extension_lease,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn create_state_machine_with_lease(
|
||||
self: &Arc<Self>,
|
||||
provider: Arc<dyn Provider>,
|
||||
model_config: goose_providers::model::ModelConfig,
|
||||
context_limit: usize,
|
||||
session_config: SessionConfig,
|
||||
cancel: CancellationToken,
|
||||
steer_queue: SteerQueue,
|
||||
extension_lease: Arc<StdMutex<Option<Arc<ExtensionLease>>>>,
|
||||
) -> StateMachine<'_, Session, GooseEffect> {
|
||||
let settings = match &self.turn_settings {
|
||||
Some(settings) => settings.clone(),
|
||||
None => TurnSettings::from_config(provider.as_ref(), &model_config),
|
||||
};
|
||||
let max_turns = session_config.max_turns.unwrap_or(settings.max_turns);
|
||||
let compaction_threshold = crate::context_mgmt::capped_compaction_threshold(
|
||||
settings.compaction_threshold,
|
||||
settings.compaction_token_limit,
|
||||
|
||||
@@ -61,11 +61,13 @@ pub(super) use ops_doctor::DoctorOperation;
|
||||
pub(super) use ops_empty_response::EmptyResponseOperation;
|
||||
pub(crate) use ops_exit_on_error::turn_failure;
|
||||
pub(super) use ops_exit_on_error::ExitOnErrorOperation;
|
||||
pub(super) use ops_llm::{GooseInferenceProvider, InferenceRunner};
|
||||
pub(super) use ops_llm::{enrich_unclaimed_tool_errors, GooseInferenceProvider, InferenceRunner};
|
||||
pub(super) use ops_maxturns::{MaxTurnsOperation, MAX_TURNS_MESSAGE};
|
||||
pub(super) use ops_project::ProjectOperation;
|
||||
pub(super) use ops_recipe::RecipeOperation;
|
||||
pub(super) use ops_remaining_tool_calls::RemainingToolCallsOperation;
|
||||
#[cfg(test)]
|
||||
pub(super) use ops_remaining_tool_calls::UNCLAIMED_TOOL_ERROR;
|
||||
pub(super) use ops_retry::RetryOperation;
|
||||
pub(super) use ops_skills::SkillOperation;
|
||||
pub(super) use ops_slash_command::SlashCommandOperation;
|
||||
|
||||
@@ -36,7 +36,10 @@ impl InferenceEffect for GooseEffect {
|
||||
}
|
||||
}
|
||||
|
||||
fn enrich_unclaimed_tool_errors(messages: &[Message], tools: &[rmcp::model::Tool]) -> Vec<Message> {
|
||||
pub(crate) fn enrich_unclaimed_tool_errors(
|
||||
messages: &[Message],
|
||||
tools: &[rmcp::model::Tool],
|
||||
) -> Vec<Message> {
|
||||
let mut available_tools = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.as_ref())
|
||||
|
||||
@@ -24,7 +24,7 @@ use crate::conversation::Conversation;
|
||||
use crate::hooks::HookManager;
|
||||
use crate::session::Session;
|
||||
|
||||
pub(super) const UNCLAIMED_TOOL_ERROR: &str = "goose.unclaimed_tool";
|
||||
pub(crate) const UNCLAIMED_TOOL_ERROR: &str = "goose.unclaimed_tool";
|
||||
const NOT_HANDLED_RESPONSE: &str = "This tool call was not handled.";
|
||||
|
||||
fn unanswered_tool_requests<'a>(
|
||||
|
||||
@@ -7,6 +7,7 @@ use async_trait::async_trait;
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use rmcp::model::{CallToolRequestParams, CallToolResult, ContentBlock, ErrorData, Role, Tool};
|
||||
|
||||
use crate::agents::extension::ExtensionInfo;
|
||||
use crate::agents::extension_manager::{CallRequest, ExtensionLease, ExtensionManager};
|
||||
use crate::agents::state_machine::ops_llm::{ADVERTISED_TOOLS_NOTE, LLM_OPERATION_NAME};
|
||||
use crate::agents::state_machine::ops_tool_approval::request_executable;
|
||||
@@ -798,6 +799,31 @@ fn approval_denied(permission: Option<&crate::permission::Permission>) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The extension block, as a header part plus one part per extension. Prompt
|
||||
/// extras are joined with a blank line, so this renders the same text as one
|
||||
/// combined part while keeping each extension's tokens attributable.
|
||||
fn extension_prompt_parts(extensions: &[ExtensionInfo]) -> Vec<(String, String)> {
|
||||
let mut parts = vec![(
|
||||
"extensions".to_string(),
|
||||
"# Extensions\n\n\
|
||||
Extensions provide additional tools and context from different data sources and applications.\n\
|
||||
You can dynamically enable or disable extensions as needed to help complete tasks.\n\n\
|
||||
Because you dynamically load extensions, your conversation history may refer to interactions with extensions that are not currently active. The currently active extensions are below. Each of these extensions provides tools that are in your tool specification."
|
||||
.to_string(),
|
||||
)];
|
||||
for extension in extensions {
|
||||
let mut lines = vec![format!("## {}", extension.name)];
|
||||
if extension.has_resources {
|
||||
lines.push(format!("{} supports resources.", extension.name));
|
||||
}
|
||||
if !extension.instructions.is_empty() {
|
||||
lines.push(format!("### Instructions\n{}", extension.instructions));
|
||||
}
|
||||
parts.push((format!("extension:{}", extension.name), lines.join("\n\n")));
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Operation<Session, GooseEffect> for ToolExecutionOperation {
|
||||
fn name(&self) -> &'static str {
|
||||
@@ -886,24 +912,9 @@ impl Operation<Session, GooseEffect> for ToolExecutionOperation {
|
||||
if extensions.is_empty() {
|
||||
return Ok(prompt_parts);
|
||||
}
|
||||
|
||||
let mut lines = vec![
|
||||
"# Extensions".to_string(),
|
||||
"Extensions provide additional tools and context from different data sources and applications.\n\
|
||||
You can dynamically enable or disable extensions as needed to help complete tasks.\n\n\
|
||||
Because you dynamically load extensions, your conversation history may refer to interactions with extensions that are not currently active. The currently active extensions are below. Each of these extensions provides tools that are in your tool specification."
|
||||
.to_string(),
|
||||
];
|
||||
for extension in extensions {
|
||||
lines.push(format!("## {}", extension.name));
|
||||
if extension.has_resources {
|
||||
lines.push(format!("{} supports resources.", extension.name));
|
||||
}
|
||||
if !extension.instructions.is_empty() {
|
||||
lines.push(format!("### Instructions\n{}", extension.instructions));
|
||||
}
|
||||
}
|
||||
prompt_parts.push(("extensions".to_string(), lines.join("\n\n")));
|
||||
// HashMap order shuffles across restarts and would bust the prompt cache.
|
||||
extensions.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
prompt_parts.extend(extension_prompt_parts(&extensions));
|
||||
Ok(prompt_parts)
|
||||
}
|
||||
|
||||
@@ -1110,6 +1121,30 @@ impl Operation<Session, GooseEffect> for ToolExecutionOperation {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extension_prompt_parts_render_one_block_per_extension() {
|
||||
let extensions = vec![
|
||||
ExtensionInfo::new("developer", "Shell things.", false),
|
||||
ExtensionInfo::new("memory", "", true),
|
||||
];
|
||||
|
||||
let parts = extension_prompt_parts(&extensions);
|
||||
|
||||
let keys: Vec<&str> = parts.iter().map(|(key, _)| key.as_str()).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
["extensions", "extension:developer", "extension:memory"]
|
||||
);
|
||||
let rendered = parts
|
||||
.iter()
|
||||
.map(|(_, value)| value.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
assert!(rendered.ends_with(
|
||||
"## developer\n\n### Instructions\nShell things.\n\n## memory\n\nmemory supports resources."
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn externally_dispatched_observations_are_not_pending_execution() {
|
||||
use crate::conversation::message::TOOL_META_EXTERNAL_DISPATCH_KEY;
|
||||
|
||||
@@ -73,6 +73,25 @@ const MANUAL_COMPACT_CONTINUATION_TEXT: &str =
|
||||
Do not mention that you read a summary or that conversation summarization occurred.
|
||||
Just continue the conversation naturally based on the summarized context.";
|
||||
|
||||
/// Summaries persisted before the `compaction_summary` flag existed are known
|
||||
/// by the continuation text compaction merges into them. Conversation repair
|
||||
/// may have concatenated it onto the summary text, so match the tail.
|
||||
pub fn is_compaction_summary(message: &Message) -> bool {
|
||||
message.is_compaction_summary()
|
||||
|| (message.is_agent_visible()
|
||||
&& !message.metadata.user_visible
|
||||
&& message.content.iter().any(|content| match content {
|
||||
MessageContent::Text(text) => [
|
||||
CONVERSATION_CONTINUATION_TEXT,
|
||||
TOOL_LOOP_CONTINUATION_TEXT,
|
||||
MANUAL_COMPACT_CONTINUATION_TEXT,
|
||||
]
|
||||
.iter()
|
||||
.any(|continuation| text.text.ends_with(continuation)),
|
||||
_ => false,
|
||||
}))
|
||||
}
|
||||
|
||||
pub struct CompactionResult {
|
||||
pub conversation: Conversation,
|
||||
/// Billable usage of the summarization call, counting the raw model
|
||||
@@ -173,7 +192,8 @@ pub async fn compact_messages(
|
||||
final_messages.push(updated_msg);
|
||||
}
|
||||
|
||||
let summary_msg = summary_message.with_metadata(MessageMetadata::agent_only());
|
||||
let summary_msg =
|
||||
summary_message.with_metadata(MessageMetadata::agent_only().with_compaction_summary());
|
||||
|
||||
let mut continuation_messages = vec![summary_msg];
|
||||
|
||||
@@ -243,7 +263,7 @@ pub(crate) async fn count_context_tokens(messages: &[Message]) -> Result<i32> {
|
||||
let total: usize = messages
|
||||
.iter()
|
||||
.filter(|message| message.is_agent_visible())
|
||||
.map(|message| counter.count_chat_tokens("", std::slice::from_ref(message), &[]))
|
||||
.map(|message| counter.count_message_tokens(message))
|
||||
.sum();
|
||||
Ok(total.try_into()?)
|
||||
}
|
||||
@@ -281,13 +301,13 @@ pub async fn check_if_compaction_needed(
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create token counter: {}", e))?;
|
||||
|
||||
let token_counts: Vec<_> = messages
|
||||
let estimated: usize = messages
|
||||
.iter()
|
||||
.filter(|m| m.is_agent_visible())
|
||||
.map(|msg| token_counter.count_chat_tokens("", std::slice::from_ref(msg), &[]))
|
||||
.collect();
|
||||
.filter(|message| message.is_agent_visible())
|
||||
.map(|message| token_counter.count_message_tokens(message))
|
||||
.sum();
|
||||
|
||||
(token_counts.iter().sum(), "estimated")
|
||||
(estimated, "estimated")
|
||||
}
|
||||
};
|
||||
|
||||
@@ -524,6 +544,33 @@ mod tests {
|
||||
use goose_providers::conversation::token_usage::Usage;
|
||||
use rmcp::model::{CallToolRequestParams, Tool};
|
||||
|
||||
#[test]
|
||||
fn summaries_written_before_the_flag_are_still_recognized() {
|
||||
let legacy = Message::assistant()
|
||||
.with_text("# Conversation Summary\nWe were adding a test.")
|
||||
.with_text(CONVERSATION_CONTINUATION_TEXT)
|
||||
.with_metadata(MessageMetadata::agent_only());
|
||||
let ordinary = Message::assistant()
|
||||
.with_text("Continuing.")
|
||||
.with_metadata(MessageMetadata::agent_only());
|
||||
let quoted = Message::assistant().with_text(CONVERSATION_CONTINUATION_TEXT);
|
||||
|
||||
assert!(is_compaction_summary(&legacy));
|
||||
assert!(!is_compaction_summary(&ordinary));
|
||||
assert!(!is_compaction_summary("ed));
|
||||
|
||||
// The report repairs the conversation first, which concatenates the
|
||||
// summary's text blocks.
|
||||
let (repaired, _) =
|
||||
crate::conversation::fix_conversation(Conversation::new_unvalidated(vec![
|
||||
Message::user().with_text("hi"),
|
||||
legacy,
|
||||
Message::user().with_text("next"),
|
||||
]));
|
||||
assert_eq!(repaired.messages()[1].content.len(), 1);
|
||||
assert!(is_compaction_summary(&repaired.messages()[1]));
|
||||
}
|
||||
|
||||
fn create_tool_pair(
|
||||
call_id: &str,
|
||||
response_id: &str,
|
||||
|
||||
@@ -1280,11 +1280,19 @@ pub fn convert_tool_messages_to_text(messages: &[Message]) -> Conversation {
|
||||
|
||||
/// Modifies the system prompt to include tool usage instructions when tool interpretation is enabled
|
||||
pub fn modify_system_prompt_for_tool_json(system_prompt: &str, tools: &[Tool]) -> String {
|
||||
format!(
|
||||
"{}\n\n{}",
|
||||
system_prompt,
|
||||
toolshim_system_prompt_appendix(tools)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn toolshim_system_prompt_appendix(tools: &[Tool]) -> String {
|
||||
let tool_info = format_tool_info(tools);
|
||||
|
||||
format!(
|
||||
"{}\n\n{}\n\nBreak down your task into smaller steps and do one step and tool call at a time. Do not try to use multiple tools at once. If you want to use a tool, tell the user what tool to use by specifying the tool in this JSON format\n{{\n \"name\": \"tool_name\",\n \"arguments\": {{\n \"parameter1\": \"value1\",\n \"parameter2\": \"value2\"\n }}\n}}. After you get the tool result back, consider the result and then proceed to do the next step and tool call if required.",
|
||||
system_prompt, tool_info
|
||||
"{}\n\nBreak down your task into smaller steps and do one step and tool call at a time. Do not try to use multiple tools at once. If you want to use a tool, tell the user what tool to use by specifying the tool in this JSON format\n{{\n \"name\": \"tool_name\",\n \"arguments\": {{\n \"parameter1\": \"value1\",\n \"parameter2\": \"value2\"\n }}\n}}. After you get the tool result back, consider the result and then proceed to do the next step and tool call if required.",
|
||||
tool_info
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ static TOKENIZER: OnceCell<Arc<CoreBPE>> = OnceCell::const_new();
|
||||
|
||||
const MAX_TOKEN_CACHE_SIZE: usize = 1_024;
|
||||
|
||||
pub(crate) const TOKENS_PER_MESSAGE: usize = 4;
|
||||
const REPLY_PRIMER_TOKENS: usize = 3;
|
||||
|
||||
// token use for various bits of a tool calls:
|
||||
const FUNC_INIT: usize = 7;
|
||||
const PROP_INIT: usize = 3;
|
||||
@@ -126,46 +129,51 @@ impl TokenCounter {
|
||||
func_token_count
|
||||
}
|
||||
|
||||
/// Agent-invisible messages are never sent, so they count as zero.
|
||||
pub fn count_message_tokens(&self, message: &Message) -> usize {
|
||||
if !message.metadata.agent_visible {
|
||||
return 0;
|
||||
}
|
||||
let mut num_tokens = TOKENS_PER_MESSAGE;
|
||||
for content in &message.content {
|
||||
if let Some(content_text) = content.as_text() {
|
||||
num_tokens += self.count_tokens(content_text);
|
||||
} else if let Some(tool_request) = content.as_tool_request() {
|
||||
if let Ok(tool_call) = tool_request.tool_call.as_ref() {
|
||||
let text = format!(
|
||||
"{}:{}:{:?}",
|
||||
tool_request.id, tool_call.name, tool_call.arguments
|
||||
);
|
||||
num_tokens += self.count_tokens(&text);
|
||||
}
|
||||
} else if let Some(tool_response_text) = content.as_tool_response_text() {
|
||||
num_tokens += self.count_tokens(&tool_response_text);
|
||||
}
|
||||
}
|
||||
num_tokens
|
||||
}
|
||||
|
||||
pub fn count_chat_tokens(
|
||||
&self,
|
||||
system_prompt: &str,
|
||||
messages: &[Message],
|
||||
tools: &[Tool],
|
||||
) -> usize {
|
||||
let tokens_per_message = 4;
|
||||
let mut num_tokens = 0;
|
||||
|
||||
if !system_prompt.is_empty() {
|
||||
num_tokens += self.count_tokens(system_prompt) + tokens_per_message;
|
||||
num_tokens += self.count_tokens(system_prompt) + TOKENS_PER_MESSAGE;
|
||||
}
|
||||
|
||||
for message in messages {
|
||||
if !message.metadata.agent_visible {
|
||||
continue;
|
||||
}
|
||||
num_tokens += tokens_per_message;
|
||||
for content in &message.content {
|
||||
if let Some(content_text) = content.as_text() {
|
||||
num_tokens += self.count_tokens(content_text);
|
||||
} else if let Some(tool_request) = content.as_tool_request() {
|
||||
if let Ok(tool_call) = tool_request.tool_call.as_ref() {
|
||||
let text = format!(
|
||||
"{}:{}:{:?}",
|
||||
tool_request.id, tool_call.name, tool_call.arguments
|
||||
);
|
||||
num_tokens += self.count_tokens(&text);
|
||||
}
|
||||
} else if let Some(tool_response_text) = content.as_tool_response_text() {
|
||||
num_tokens += self.count_tokens(&tool_response_text);
|
||||
}
|
||||
}
|
||||
num_tokens += self.count_message_tokens(message);
|
||||
}
|
||||
|
||||
if !tools.is_empty() {
|
||||
num_tokens += self.count_tokens_for_tools(tools);
|
||||
}
|
||||
|
||||
num_tokens += 3; // Reply primer
|
||||
num_tokens += REPLY_PRIMER_TOKENS;
|
||||
|
||||
num_tokens
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use agent_client_protocol::schema::v1::{
|
||||
};
|
||||
use common_tests::fixtures::server::AcpServerConnection;
|
||||
use common_tests::fixtures::{
|
||||
run_test, send_custom, Connection, Session, SessionData, TestConnectionConfig,
|
||||
run_test, send_custom, Connection, PermissionDecision, Session, SessionData,
|
||||
TestConnectionConfig,
|
||||
};
|
||||
use goose::acp::server::AcpProviderFactory;
|
||||
use goose::providers::base::{MessageStream, Provider};
|
||||
@@ -1246,6 +1247,81 @@ fn test_app_tool_call_dispatched_in_auto_mode() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn test_custom_context_report() {
|
||||
write_acp_global_config(DEFAULT_ACP_TEST_CONFIG);
|
||||
run_test(async move {
|
||||
let openai = OpenAiFixture::new(
|
||||
vec![(
|
||||
"start work".to_string(),
|
||||
include_str!("acp_test_data/openai_steer_first.txt"),
|
||||
)],
|
||||
Arc::new(IgnoreSessionId),
|
||||
)
|
||||
.await;
|
||||
let mut conn = AcpServerConnection::new(TestConnectionConfig::default(), openai).await;
|
||||
|
||||
let SessionData { mut session, .. } = conn.new_session().await.unwrap();
|
||||
let session_id = session.session_id().0.to_string();
|
||||
|
||||
let empty = send_custom(
|
||||
conn.cx(),
|
||||
"_goose/unstable/context/report",
|
||||
serde_json::json!({ "sessionId": session_id }),
|
||||
)
|
||||
.await
|
||||
.expect("context report on an empty session should succeed");
|
||||
assert!(empty["totalTokens"].as_u64().unwrap() > 0);
|
||||
let turn_context = empty["segments"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|segment| segment["category"] == "turn_context")
|
||||
.expect("report should include turn context");
|
||||
assert!(turn_context["tokenCount"].as_u64().unwrap() > 0);
|
||||
|
||||
session
|
||||
.prompt("start work", PermissionDecision::Cancel)
|
||||
.await
|
||||
.expect("prompt should succeed");
|
||||
|
||||
let report = send_custom(
|
||||
conn.cx(),
|
||||
"_goose/unstable/context/report",
|
||||
serde_json::json!({ "sessionId": session_id }),
|
||||
)
|
||||
.await
|
||||
.expect("context report should succeed");
|
||||
|
||||
let segments = report["segments"].as_array().expect("segments array");
|
||||
let categories: Vec<&str> = segments
|
||||
.iter()
|
||||
.map(|segment| segment["category"].as_str().unwrap())
|
||||
.collect();
|
||||
for expected in ["system_prompt", "tool_definitions", "messages"] {
|
||||
assert!(
|
||||
categories.contains(&expected),
|
||||
"missing {expected} in {categories:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let assistant = segments
|
||||
.iter()
|
||||
.find(|segment| segment["label"] == "Assistant messages")
|
||||
.expect("assistant segment");
|
||||
let preview = assistant["parts"][0]["contentPreview"].as_str().unwrap();
|
||||
assert!(preview.contains("first response"), "preview: {preview}");
|
||||
|
||||
let attributed: u64 = segments
|
||||
.iter()
|
||||
.map(|segment| segment["tokenCount"].as_u64().unwrap())
|
||||
.sum();
|
||||
assert_eq!(report["totalTokens"].as_u64().unwrap(), attributed);
|
||||
assert!(report["model"]["contextLimit"].as_u64().unwrap() > 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn test_app_tool_call_applies_extension_mutation() {
|
||||
|
||||
Reference in New Issue
Block a user