aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,194 @@
//! Retrieves installation locations from the prepared catalog without reading skill contents.
use std::collections::HashSet;
use std::sync::Arc;
use akode_extension_api::ExtensionMetrics;
use akode_extension_api::FunctionCallError;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolExecutorFuture;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::aliases::SkillLocator;
use super::InstallationLocation;
use super::InstallationSource;
use super::MAX_HANDLE_BYTES;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::validate_handle;
use super::value_fingerprint;
const TOOL_NAME: &str = "installations";
const MAX_INSTALLATIONS_RESPONSE_BYTES: usize = 8 * 1024;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct InstallationsArgs {
#[schemars(with = "String")]
package: SkillLocator,
source: Option<InstallationSource>,
cursor: Option<String>,
}
#[derive(JsonSchema, Serialize)]
#[schemars(deny_unknown_fields)]
struct InstallationsResponse {
installations: Vec<InstallationLocation>,
next_cursor: Option<String>,
}
pub(super) struct InstallationsTool {
pub(super) context: SkillToolContext,
pub(super) metrics: Option<Arc<dyn ExtensionMetrics>>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for InstallationsTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
skill_function_tool::<InstallationsArgs, InstallationsResponse>(
TOOL_NAME,
"Find a skill's enabled executor locations, including those omitted by skills.read. Pass its provided package directly; root aliases are resolved automatically. Use source {kind: executor, environment_id: ...} for one environment. Omit source for all locations. Executor locations return environment_id and skill_root, the absolute directory containing instructions and supporting files such as scripts. Pass next_cursor back as cursor with the same package and source to continue listing locations. Omit cursor to start again. An empty list without next_cursor means no enabled location matches.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let mut outcome = "internal_error";
let mut source_filter = "unparsed";
let result = (|| {
let args: InstallationsArgs =
parse_args(&call).inspect_err(|_| outcome = "invalid_arguments")?;
source_filter = match &args.source {
None => "all",
Some(InstallationSource::Executor { .. }) => "executor",
};
validate_handle("package", args.package.as_str(), MAX_HANDLE_BYTES)
.inspect_err(|_| outcome = "invalid_package")?;
if let Some(source) = &args.source {
source
.validate()
.inspect_err(|_| outcome = "invalid_source")?;
}
let matches = self
.context
.matching_packages(&args.package)
.inspect_err(|_| outcome = "ambiguous_name")?;
let (entry, _) = matches.first().ok_or_else(|| {
outcome = if args.package.alias_source().is_some()
&& self
.context
.step_state
.catalog
.aliases
.resolve(&args.package)
.is_none()
{
"unresolved_alias"
} else {
"package_unavailable"
};
FunctionCallError::RespondToModel("skill package is not available".to_string())
})?;
let mut installations = Vec::new();
let mut seen = HashSet::new();
for installation in matches
.iter()
.flat_map(|(entry, matched_source)| {
std::iter::once(matched_source.clone()).chain(entry.source_locations())
})
.filter(|source| {
args.source
.as_ref()
.is_none_or(|filter| filter.matches(source))
})
.filter_map(|source| InstallationLocation::from_source(&source))
{
if seen.insert(installation.clone()) {
installations.push(installation);
}
}
let identity = (&entry.id.0, &args.source, &installations);
let start = parse_pagination_cursor(
args.cursor.as_deref(),
&identity,
"skills.installations",
)
.inspect_err(|_| outcome = "invalid_cursor")?;
if start > installations.len() {
outcome = "invalid_cursor";
return Err(FunctionCallError::RespondToModel(
"skills.installations cursor is invalid".to_string(),
));
}
let fingerprint = value_fingerprint(&identity);
let cursor_at = |offset| format!("{fingerprint:016x}:{offset}");
let budget = call.response_byte_budget(MAX_INSTALLATIONS_RESPONSE_BYTES);
let mut response = InstallationsResponse {
installations: Vec::new(),
next_cursor: None,
};
let installation_count = installations.len();
for (index, installation) in installations.into_iter().enumerate().skip(start) {
response.installations.push(installation);
response.next_cursor =
(index + 1 < installation_count).then(|| cursor_at(index + 1));
if serialized_len(&response)? > budget {
response.installations.pop();
response.next_cursor = Some(cursor_at(index));
break;
}
}
if (start < installation_count && response.installations.is_empty())
|| serialized_len(&response)? > budget
{
outcome = "response_budget";
return Err(FunctionCallError::RespondToModel(
"skills.installations response budget leaves no room for an installation"
.to_string(),
));
}
let output = skill_json_output(&response, SkillToolAuthoritySelector::Executor)?;
outcome = if response.installations.is_empty() {
"empty"
} else {
"success"
};
Ok(output)
})();
if let Some(metrics) = &self.metrics {
metrics.counter(
"codex.skills.installations.result",
/*inc*/ 1,
&[
("outcome", outcome),
("source_filter", source_filter),
("discovery_version", "v2"),
],
);
}
result
})
}
}

View File

@@ -0,0 +1,241 @@
use akode_extension_api::FunctionCallError;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolExecutorFuture;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_utils_string::take_bytes_at_char_boundary;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::catalog::SkillCatalogEntry;
use crate::render::MAX_SKILL_NAME_BYTES;
use crate::render::truncate_catalog_skill_description;
use crate::warnings::bounded_warnings;
use super::MAX_HANDLE_BYTES;
use super::MAX_SKILL_RESPONSE_BYTES;
use super::SkillToolAuthority;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::is_bounded_handle;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::value_fingerprint;
const TOOL_NAME: &str = "list";
const MAX_SKILLS_PER_PAGE: usize = 20;
const OVERSIZED_ENTRY_WARNING: &str =
"Some skills were omitted because their metadata is too large.";
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ListArgs {
authority: SkillToolAuthoritySelector,
cursor: Option<String>,
}
#[derive(Clone, Debug, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ListedSkill {
authority: SkillToolAuthority,
package: String,
name: String,
description: String,
main_resource: String,
}
#[derive(Debug, Eq, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ListResponse {
skills: Vec<ListedSkill>,
warnings: Vec<String>,
next_cursor: Option<String>,
}
#[derive(Clone)]
pub(super) struct ListTool {
pub(super) context: SkillToolContext,
}
impl<'call> ToolExecutor<ToolCall<'call>> for ListTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
skill_function_tool::<ListArgs, ListResponse>(
TOOL_NAME,
"List skills owned by the requested authority. Returns each skill's authority, package, and main_resource. Pass the package to skills.read, and pass next_cursor back as cursor to continue.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: ListArgs = parse_args(&call)?;
let response_byte_budget = call.response_byte_budget(MAX_SKILL_RESPONSE_BYTES);
let catalog = self
.context
.step_state
.catalog
.select_from_catalog(args.authority);
let mut omitted_oversized_entry = false;
let canonical_skills = catalog
.entries
.into_iter()
.filter(SkillCatalogEntry::is_model_visible)
.filter_map(|entry| {
let listed = listed_skill(entry);
omitted_oversized_entry |= listed.is_none();
listed
})
.collect::<Vec<_>>();
// Older cursors contain only the catalog fingerprint and offset. New cursors
// also record the budget whose omissions have already been reported.
let (cursor, previous_byte_budget) = match args.cursor.as_deref() {
Some(cursor) => match cursor.rsplit_once(':') {
Some((canonical_cursor, byte_budget)) => {
if canonical_cursor.contains(':') {
let byte_budget = byte_budget.parse::<usize>().map_err(|_| {
FunctionCallError::RespondToModel(
"skills.list cursor is invalid".to_string(),
)
})?;
(Some(canonical_cursor), Some(byte_budget))
} else {
(Some(cursor), None)
}
}
None => (Some(cursor), None),
},
None => (None, None),
};
let start = parse_pagination_cursor(cursor, &canonical_skills, "skills.list")?;
if start > canonical_skills.len() {
return Err(FunctionCallError::RespondToModel(
"skills.list cursor is invalid".to_string(),
));
}
let cursor_fingerprint = value_fingerprint(&canonical_skills);
let cursor_at =
|offset| format!("{cursor_fingerprint:016x}:{offset}:{response_byte_budget}");
let mut skills = Vec::with_capacity(canonical_skills.len().saturating_sub(start));
// The final retained skill needs no cursor, even if later entries are oversized.
for (index, skill) in canonical_skills.iter().enumerate().skip(start).rev() {
let next_cursor = (!skills.is_empty()).then(|| cursor_at(index.saturating_add(1)));
if single_entry_response_is_bounded(skill, response_byte_budget, next_cursor) {
skills.push((index, skill));
} else {
omitted_oversized_entry = true;
}
}
skills.reverse();
let mut provider_warnings = if args.cursor.is_none() {
bounded_warnings(&catalog.warnings)
} else {
Vec::new()
};
let omission_warning = (omitted_oversized_entry
&& previous_byte_budget != Some(response_byte_budget))
.then_some(OVERSIZED_ENTRY_WARNING);
let mut end = MAX_SKILLS_PER_PAGE.min(skills.len());
loop {
let mut response = ListResponse {
skills: skills[..end]
.iter()
.map(|(_, skill)| (*skill).clone())
.collect(),
warnings: provider_warnings
.iter()
.cloned()
.chain(omission_warning.map(str::to_string))
.collect(),
next_cursor: (end < skills.len())
.then(|| cursor_at(skills[end.saturating_sub(1)].0.saturating_add(1))),
};
if serialized_len(&response)? <= response_byte_budget {
return skill_json_output(&response, args.authority);
}
if end > 1 {
end = end.saturating_sub(1);
} else if provider_warnings.len() > 1 {
provider_warnings.pop();
} else if !response.warnings.is_empty() {
response.skills.clear();
// Recording this budget acknowledges the omission warning, even when
// the next call resumes at the same canonical skill offset.
response.next_cursor = Some(cursor_at(start));
if serialized_len(&response)? <= response_byte_budget {
return skill_json_output(&response, args.authority);
}
if omission_warning.is_some() && !provider_warnings.is_empty() {
response.warnings = provider_warnings;
// Report discovery first without acknowledging an unshown omission.
// Reusing this offset lets the next call report it before advancing.
response.next_cursor = Some(format!("{cursor_fingerprint:016x}:{start}"));
if serialized_len(&response)? <= response_byte_budget {
return skill_json_output(&response, args.authority);
}
}
// FunctionCallError cannot carry external-context metadata, so do not
// expose provider warnings through this path.
return Err(FunctionCallError::RespondToModel(
"skills.list response budget leaves no room for discovery warnings"
.to_string(),
));
} else {
return Err(FunctionCallError::RespondToModel(
"skill metadata is too large to list".to_string(),
));
}
}
})
}
}
fn single_entry_response_is_bounded(
skill: &ListedSkill,
response_byte_budget: usize,
next_cursor: Option<String>,
) -> bool {
serialized_len(&ListResponse {
skills: vec![skill.clone()],
warnings: Vec::new(),
next_cursor,
})
.is_ok_and(|size| size <= response_byte_budget)
}
pub(super) fn listed_name(name: &str) -> &str {
take_bytes_at_char_boundary(name, MAX_SKILL_NAME_BYTES)
}
fn listed_skill(entry: SkillCatalogEntry) -> Option<ListedSkill> {
let authority = SkillToolAuthority::from_authority(&entry.authority)?;
if !is_bounded_handle(&entry.authority.id, MAX_HANDLE_BYTES)
|| !is_bounded_handle(&entry.id.0, MAX_HANDLE_BYTES)
|| !is_bounded_handle(entry.main_prompt.as_str(), MAX_HANDLE_BYTES)
{
return None;
}
Some(ListedSkill {
authority,
package: entry.id.0,
name: listed_name(&entry.name).to_owned(),
description: truncate_catalog_skill_description(&entry.description).into_owned(),
main_resource: entry.main_prompt.as_str().to_string(),
})
}

View File

@@ -0,0 +1,420 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionMetrics;
use akode_extension_api::FunctionCallError;
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ResponsesApiTool;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolOutput;
use akode_extension_api::ToolSpec;
use akode_extension_api::parse_tool_input_schema;
use akode_otel::SessionTelemetry;
use akode_otel::SkillInvocationEvent;
use akode_otel::SkillInvocationType as InvocationType;
use akode_otel::sanitize_metric_tag_value;
use akode_tools::ResponsesApiNamespace;
use akode_tools::ResponsesApiNamespaceTool;
use akode_tools::default_namespace_description;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use crate::aliases::SkillLocator;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillSourceKind;
use crate::catalog::SkillSourceLocation;
use crate::sources::SkillProviders;
use crate::state::SkillsSessionState;
use crate::state::SkillsThreadState;
use crate::step_state::SkillToolAuthoritySelector;
use crate::step_state::SkillsStepState;
use crate::telemetry::ActiveSkillTurnMetrics;
use crate::telemetry::SkillTurnMetrics;
mod installations;
mod list;
mod read;
mod schema;
const SKILLS_NAMESPACE: &str = "skills";
const MAX_HANDLE_BYTES: usize = 2_048;
const MAX_SKILL_RESPONSE_BYTES: usize = 512 * 1024;
pub(crate) fn skill_tools(
providers: SkillProviders,
session_store: &ExtensionData,
thread_store: &ExtensionData,
step_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let Some(thread_state) = thread_store.get::<SkillsThreadState>() else {
return Vec::new();
};
let Some(step_state) = step_store.get::<SkillsStepState>() else {
return Vec::new();
};
if !step_state.tools_enabled {
return Vec::new();
}
let invocations = SkillInvocationRecorder::from_stores(session_store, thread_store);
let metrics = step_store
.get::<Arc<dyn ExtensionMetrics>>()
.map(|metrics| Arc::clone(metrics.as_ref()));
let context = SkillToolContext {
thread_id: thread_store.level_id().to_string(),
providers,
thread_state,
invocations,
step_state,
};
let mut tools: Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> = vec![
Arc::new(list::ListTool {
context: context.clone(),
}),
Arc::new(read::ReadTool {
context: context.clone(),
metrics: metrics.clone(),
}),
];
if context.step_state.discovery_v2 {
tools.push(Arc::new(installations::InstallationsTool {
context,
metrics,
}));
}
tools
}
/// Records skill invocations to local logs and local metrics only.
#[derive(Clone)]
pub(crate) struct SkillInvocationRecorder {
telemetry: Option<Arc<SessionTelemetry>>,
metrics: Option<Arc<dyn ExtensionMetrics>>,
turn_metrics: Option<Arc<SkillTurnMetrics>>,
}
impl SkillInvocationRecorder {
pub(crate) fn from_stores(
session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Option<Self> {
Some(Self {
telemetry: session_store.get::<SessionTelemetry>(),
metrics: session_store
.get::<SkillsSessionState>()
.and_then(|state| state.extension_metrics.clone()),
// Code-mode callbacks retain these tools after another turn becomes active.
turn_metrics: thread_store
.get_or_init(ActiveSkillTurnMetrics::default)
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.upgrade(),
})
}
pub(crate) fn record_skill_invocation(
&self,
skill: &SkillCatalogEntry,
source: &SkillSourceLocation,
model: String,
turn_id: String,
invocation_type: InvocationType,
) {
let invocation = skill.invocation(source, invocation_type);
if let Some(telemetry) = &self.telemetry {
telemetry
.as_ref()
.clone()
.with_model(&model, &model)
.skill_invocation(SkillInvocationEvent {
turn_id: &turn_id,
skill_name: &skill.name,
scope: skill.invocation_scope,
plugin_id: invocation.plugin_id.as_deref(),
invocation_type,
});
}
let turn_metrics = self
.turn_metrics
.as_ref()
.filter(|turn| turn.turn_id == turn_id);
if let Some(turn_metrics) = &turn_metrics {
turn_metrics.record_plugin(invocation.plugin_id.as_deref());
}
if let Some(metrics) = &self.metrics {
let skill_name_tag = sanitize_metric_tag_value(skill.name.as_str());
let plugin_id_tag = sanitize_metric_tag_value(
invocation.plugin_id.as_deref().unwrap_or("unattributed"),
);
let model_slug_tag = sanitize_metric_tag_value(model.as_str());
let reasoning_effort = turn_metrics
.as_ref()
.map(|turn| turn.reasoning_effort.as_str())
.unwrap_or("unknown");
let invoke_type = match invocation_type {
InvocationType::Explicit => "explicit",
InvocationType::Implicit => "implicit",
};
metrics.counter(
"codex.skill.injected",
/*inc*/ 1,
&[
("status", "ok"),
("skill", skill_name_tag.as_str()),
("invoke_type", invoke_type),
("plugin_id", plugin_id_tag.as_str()),
("model_slug", model_slug_tag.as_str()),
("reasoning_effort", reasoning_effort),
],
);
}
}
}
#[derive(Clone)]
struct SkillToolContext {
thread_id: String,
providers: SkillProviders,
thread_state: Arc<SkillsThreadState>,
invocations: Option<SkillInvocationRecorder>,
step_state: Arc<SkillsStepState>,
}
impl SkillToolContext {
fn matching_packages<'a>(
&'a self,
package: &SkillLocator,
) -> Result<Vec<(&'a SkillCatalogEntry, SkillSourceLocation)>, FunctionCallError> {
let catalog = &self.step_state.catalog.merged;
let matching_entries = |resolved_package: &str, alias_source: Option<&SkillSourceKind>| {
catalog
.entries
.iter()
.filter_map(|entry| {
entry.source_locations().find_map(|source| {
if source.package.0 != resolved_package
|| alias_source.is_some_and(|kind| *kind != source.authority.kind)
{
return None;
}
SkillToolAuthority::from_authority(&source.authority)?;
Some((entry, source))
})
})
.collect::<Vec<_>>()
};
let locator = package.as_str();
let exact = matching_entries(locator, /*alias_source*/ None);
if !exact.is_empty() || locator.starts_with("skill://") {
return Ok(exact);
}
if let Some(source) = package.alias_source() {
let resolved = self.step_state.catalog.aliases.resolve(package);
return Ok(resolved.map_or_else(Vec::new, |id| matching_entries(&id, Some(source))));
}
let named = catalog
.entries
.iter()
.filter(|entry| entry.is_model_visible())
.filter(|entry| entry.name == locator || list::listed_name(&entry.name) == locator)
.filter_map(|entry| {
entry.source_locations().find_map(|source| {
SkillToolAuthority::from_authority(&source.authority)?;
Some((entry, source))
})
})
.collect::<Vec<_>>();
// Separate environments can each have an installation of the same package.
if let Some(((_, first), rest)) = named.split_first()
&& rest.iter().any(|(_, source)| {
source.authority != first.authority || source.package != first.package
})
{
return Err(FunctionCallError::RespondToModel(
"skill name is ambiguous; use skills.list and pass the package for the intended skill"
.to_string(),
));
}
Ok(named)
}
}
#[derive(Deserialize, Hash, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
enum InstallationSource {
Executor { environment_id: String },
}
impl InstallationSource {
fn validate(&self) -> Result<(), FunctionCallError> {
let Self::Executor { environment_id } = self;
validate_handle("environment_id", environment_id, MAX_HANDLE_BYTES)
}
fn matches(&self, source: &SkillSourceLocation) -> bool {
source.enabled
&& match self {
Self::Executor { environment_id } => {
source.authority.kind == SkillSourceKind::Executor
&& source
.main_prompt
.environment_path()
.is_some_and(|(id, _)| id == environment_id)
}
}
}
}
#[derive(Clone, Debug, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(untagged)]
#[schemars(deny_unknown_fields)]
enum InstallationLocation {
Executor {
environment_id: String,
skill_root: String,
},
}
impl InstallationLocation {
fn from_source(source: &SkillSourceLocation) -> Option<Self> {
if !source.enabled {
return None;
}
match &source.authority.kind {
SkillSourceKind::Executor => {
let (environment_id, path) = source.main_prompt.environment_path()?;
Some(Self::Executor {
environment_id: environment_id.to_string(),
skill_root: path.parent()?.inferred_native_path_string(),
})
}
SkillSourceKind::Host | SkillSourceKind::Custom(_) => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum SkillToolAuthority {
Executor { id: String },
}
impl SkillToolAuthority {
fn selector(&self) -> SkillToolAuthoritySelector {
match self {
Self::Executor { .. } => SkillToolAuthoritySelector::Executor,
}
}
pub(crate) fn from_authority(authority: &SkillAuthority) -> Option<Self> {
match &authority.kind {
SkillSourceKind::Executor => Some(Self::Executor {
id: authority.id.clone(),
}),
SkillSourceKind::Host | SkillSourceKind::Custom(_) => None,
}
}
}
fn skill_tool_name(name: &str) -> ToolName {
ToolName::namespaced(SKILLS_NAMESPACE, name)
}
fn skill_function_tool<I: JsonSchema, O: JsonSchema>(name: &str, description: &str) -> ToolSpec {
let tool = ResponsesApiTool {
name: name.to_string(),
description: description.to_string(),
strict: false,
defer_loading: None,
parameters: parse_tool_input_schema(&schema::input_schema_for::<I>())
.unwrap_or_else(|err| panic!("generated input schema for {name} should parse: {err}")),
output_schema: Some(schema::output_schema_for::<O>().into()),
};
ToolSpec::Namespace(ResponsesApiNamespace {
name: SKILLS_NAMESPACE.to_string(),
description: default_namespace_description(SKILLS_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
})
}
fn parse_args<T: for<'de> Deserialize<'de>>(call: &ToolCall<'_>) -> Result<T, FunctionCallError> {
let arguments = call.function_arguments()?;
let value = if arguments.trim().is_empty() {
Value::Object(serde_json::Map::new())
} else {
serde_json::from_str(arguments)
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?
};
serde_json::from_value(value).map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
}
fn validate_handle(name: &str, value: &str, max_bytes: usize) -> Result<(), FunctionCallError> {
if is_bounded_handle(value, max_bytes) {
return Ok(());
}
Err(FunctionCallError::RespondToModel(format!(
"{name} must be non-empty, contain no control characters, and be at most {max_bytes} bytes"
)))
}
fn is_bounded_handle(value: &str, max_bytes: usize) -> bool {
!value.is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control)
}
fn pagination_cursor(value: &(impl Hash + ?Sized), offset: usize) -> String {
format!("{:016x}:{offset}", value_fingerprint(value))
}
fn parse_pagination_cursor(
cursor: Option<&str>,
value: &(impl Hash + ?Sized),
tool: &str,
) -> Result<usize, FunctionCallError> {
let Some(cursor) = cursor else {
return Ok(0);
};
let invalid = || FunctionCallError::RespondToModel(format!("{tool} cursor is invalid"));
let (fingerprint, offset) = cursor.split_once(':').ok_or_else(invalid)?;
if u64::from_str_radix(fingerprint, 16).ok() != Some(value_fingerprint(value)) {
return Err(FunctionCallError::RespondToModel(format!(
"{tool} cursor is stale; restart from the first page"
)));
}
offset.parse::<usize>().map_err(|_| invalid())
}
fn value_fingerprint(value: &(impl Hash + ?Sized)) -> u64 {
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
hasher.finish()
}
fn serialized_len(value: &impl Serialize) -> Result<usize, FunctionCallError> {
serde_json::to_vec(value)
.map(|value| value.len())
.map_err(|err| FunctionCallError::Fatal(err.to_string()))
}
fn skill_json_output<T: Serialize>(
value: &T,
authority: SkillToolAuthoritySelector,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let value = serde_json::to_value(value).map_err(|err| {
FunctionCallError::Fatal(format!("failed to serialize tool output: {err}"))
})?;
let output = JsonToolOutput::new(value);
Ok(match authority {
SkillToolAuthoritySelector::Executor => Box::new(output),
})
}

View File

@@ -0,0 +1,483 @@
use std::sync::Arc;
use akode_extension_api::ExtensionMetrics;
use akode_extension_api::FunctionCallError;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolExecutorFuture;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::SkillInvocationType as InvocationType;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::aliases::SkillLocator;
use crate::catalog::SkillResourceId;
use crate::provider::MAX_SKILL_RESOURCE_CONTENT_BYTES;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::state::ExecutorReadSnapshot;
use super::InstallationLocation;
use super::InstallationSource;
use super::MAX_HANDLE_BYTES;
use super::MAX_SKILL_RESPONSE_BYTES;
use super::SKILLS_NAMESPACE;
use super::SkillToolAuthority;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::pagination_cursor;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::validate_handle;
const TOOL_NAME: &str = "read";
const MAX_INSTALLATION_METADATA_BYTES: usize = 1024;
#[derive(Deserialize, JsonSchema)]
struct ReadArgs {
#[schemars(with = "String")]
package: SkillLocator,
resource: Option<String>,
cursor: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
struct ReadInstallationArgs {
#[serde(flatten)]
read: ReadArgs,
source: Option<InstallationSource>,
}
#[derive(Debug, Eq, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ReadResponse<M> {
resource: String,
contents: String,
#[serde(flatten)]
metadata: M,
next_cursor: Option<String>,
}
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
struct LegacyReadMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
skill_root: Option<String>,
}
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
struct InstallationReadMetadata {
installations: Vec<InstallationLocation>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
installations_truncated: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
enum ReadMetadata {
Legacy(LegacyReadMetadata),
Installations(InstallationReadMetadata),
}
#[derive(Clone)]
pub(super) struct ReadTool {
pub(super) context: SkillToolContext,
pub(super) metrics: Option<Arc<dyn ExtensionMetrics>>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
if !self.context.step_state.discovery_v2 {
return skill_function_tool::<ReadArgs, ReadResponse<LegacyReadMetadata>>(
TOOL_NAME,
"Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. For executor-backed skills, skill_root is the skill's absolute directory in the executor filesystem and can be used to locate bundled scripts. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor to continue the same snapshot while it is cached; omit cursor to read again.",
);
}
skill_function_tool::<ReadInstallationArgs, ReadResponse<InstallationReadMetadata>>(
TOOL_NAME,
"Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. Use source {kind: executor, environment_id: ...} for one environment. Omit source to read the first matching location. The installations list contains executor locations (environment_id and skill_root, the absolute directory containing instructions and supporting files such as scripts). If installations_truncated is true, use skills.installations with the same package to retrieve all locations. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor with the same package, source, and resource to continue the same snapshot while it is cached; omit cursor to read again.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let mut outcome = "internal_error";
let result = async {
let (args, source) = if self.context.step_state.discovery_v2 {
let args: ReadInstallationArgs =
parse_args(&call).inspect_err(|_| outcome = "invalid_arguments")?;
(args.read, args.source)
} else {
(
parse_args::<ReadArgs>(&call)
.inspect_err(|_| outcome = "invalid_arguments")?,
None,
)
};
if let Some(source) = &source {
source
.validate()
.inspect_err(|_| outcome = "invalid_arguments")?;
}
let response_byte_budget = call.response_byte_budget(MAX_SKILL_RESPONSE_BYTES);
validate_handle("package", args.package.as_str(), MAX_HANDLE_BYTES)
.inspect_err(|_| outcome = "invalid_arguments")?;
if let Some(resource) = args.resource.as_deref() {
validate_handle("resource", resource, MAX_HANDLE_BYTES)
.inspect_err(|_| outcome = "invalid_arguments")?;
}
let matches = self
.context
.matching_packages(&args.package)
.inspect_err(|_| outcome = "ambiguous_name")?;
let (skill_entry, selected_source, output_authority) = matches
.iter()
.find_map(|(entry, matched_source)| {
let selected_source = match &source {
None => matched_source.clone(),
Some(filter) => std::iter::once(matched_source.clone())
.chain(entry.source_locations())
.find(|candidate| filter.matches(candidate))?,
};
let authority =
SkillToolAuthority::from_authority(&selected_source.authority)?
.selector();
Some((*entry, selected_source, authority))
})
.ok_or_else(|| {
outcome = if !matches.is_empty() {
"source_unavailable"
} else if args.package.alias_source().is_some()
&& self
.context
.step_state
.catalog
.aliases
.resolve(&args.package)
.is_none()
{
"unresolved_alias"
} else {
"package_unavailable"
};
FunctionCallError::RespondToModel(if source.is_some() {
"skill package is not available from the requested source".to_string()
} else {
"skill package is not available".to_string()
})
})?;
let authority = selected_source.authority.clone();
let package = selected_source.package.clone();
let main_prompt = selected_source.main_prompt.clone();
let requested_resource = match args.resource {
None => main_prompt.clone(),
Some(resource) if resource == main_prompt.as_str() => main_prompt.clone(),
Some(resource) => main_prompt
.bind_environment_package_resource(&package, resource.clone())
.unwrap_or_else(|| SkillResourceId::new(resource)),
};
// Record the selected route before either cache or provider can serve the read.
// This is an attempted read, not a successful invocation or a backend RPC.
tracing::event!(
name: "codex.skill_read.source_selected",
target: "akode_otel.trace_safe",
tracing::Level::INFO,
event.name = "codex.skill_read.source_selected",
conversation.id = %self.context.thread_id,
turn_id = %call.turn_id,
call_id = %call.call_id,
tool_namespace = SKILLS_NAMESPACE,
tool_name = TOOL_NAME,
skill_source = match output_authority {
SkillToolAuthoritySelector::Executor => "executor",
},
skill_name = %skill_entry.name,
skill_plugin_id = selected_source.plugin_id.as_deref(),
skill_resource_kind = if requested_resource == main_prompt {
"main_prompt"
} else {
"supporting_resource"
},
is_continuation = args.cursor.is_some(),
"Selected skill read source"
);
let (context, access_key) = match output_authority {
SkillToolAuthoritySelector::Executor => {
let fs = requested_resource
.environment_path()
.and_then(|(id, _)| {
call.environments
.iter()
.find(|env| env.environment_id == id)
})
.map(akode_extension_api::ToolEnvironment::fs)
.ok_or_else(|| {
outcome = "environment_unavailable";
FunctionCallError::RespondToModel(
"skill environment is not available for this callback"
.to_string(),
)
})?;
(SkillReadContext::Executor { fs }, Some(fs.cache_key()))
}
};
let cursor_start = |contents: &str| {
if self.context.step_state.discovery_v2 {
parse_pagination_cursor(
args.cursor.as_deref(),
&(&source, &package, contents),
"skills.read",
)
} else {
parse_pagination_cursor(args.cursor.as_deref(), contents, "skills.read")
}
};
// Reuse the snapshot to avoid reading the whole file for each page. File edits
// are not detected on cache hits, so a continuation can return old contents.
// Snapshots have no expiry and are not cleared after the final page.
let cached = args.cursor.as_deref().and_then(|_| {
let access = access_key.as_ref()?;
let snapshot = self
.context
.thread_state
.executor_read_snapshot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let snapshot = snapshot.as_ref().filter(|snapshot| {
snapshot.authority == authority
&& snapshot.package == package
&& snapshot.result.resource == requested_resource
&& snapshot.access == *access
})?;
let start = cursor_start(&snapshot.result.contents).ok()?;
Some((Arc::clone(&snapshot.result), start))
});
let (result, start) = match cached {
Some(cached) => cached,
None => {
let result = self
.context
.thread_state
.read_skill(
&self.context.providers,
SkillReadRequest {
authority: authority.clone(),
package: package.clone(),
resource: requested_resource.clone(),
context,
},
)
.await
.map_err(|err| {
outcome = "read_failed";
tracing::warn!(
error = %err,
turn_id = %call.turn_id,
call_id = %call.call_id,
resource = requested_resource.as_str(),
"skills.read provider request failed"
);
FunctionCallError::RespondToModel(
"failed to read skill resource".to_string(),
)
})?;
if result.resource != requested_resource {
return Err(FunctionCallError::Fatal(
"skill provider returned a different resource".to_string(),
));
}
let start = cursor_start(&result.contents)
.inspect_err(|_| outcome = "invalid_cursor")?;
(Arc::new(result), start)
}
};
if start > result.contents.len() || !result.contents.is_char_boundary(start) {
outcome = "invalid_cursor";
return Err(FunctionCallError::RespondToModel(
"skills.read cursor is invalid".to_string(),
));
}
let metadata = if self.context.step_state.discovery_v2 {
let mut installations = Vec::new();
let mut installations_truncated = false;
let mut installation_bytes = 2; // JSON array brackets.
let installation_budget =
MAX_INSTALLATION_METADATA_BYTES.min(response_byte_budget / 4);
// Prefer the installation used by this read before other sources fill the budget.
for source in std::iter::once(selected_source.clone())
.chain(skill_entry.source_locations())
{
let Some(installation) = InstallationLocation::from_source(&source) else {
continue;
};
if installations.contains(&installation) {
continue;
}
let size =
serialized_len(&installation)? + usize::from(!installations.is_empty());
if installation_bytes + size > installation_budget {
installations_truncated = true;
continue;
}
installation_bytes += size;
installations.push(installation);
}
installations_truncated |= matches.iter().any(|(entry, _)| {
entry
.source_locations()
.filter_map(|source| InstallationLocation::from_source(&source))
.any(|location| !installations.contains(&location))
});
ReadMetadata::Installations(InstallationReadMetadata {
installations,
installations_truncated,
})
} else {
let skill_root = if output_authority == SkillToolAuthoritySelector::Executor {
main_prompt
.environment_path()
.and_then(|(_, path)| path.parent())
.map(|path| path.inferred_native_path_string())
} else {
None
};
ReadMetadata::Legacy(LegacyReadMetadata { skill_root })
};
let response = page_response(
result.resource.as_str(),
&result.contents,
&metadata,
start,
response_byte_budget,
|offset| {
if self.context.step_state.discovery_v2 {
pagination_cursor(
&(&source, &package, result.contents.as_str()),
offset,
)
} else {
pagination_cursor(result.contents.as_str(), offset)
}
},
)
.inspect_err(|error| {
outcome = match error {
FunctionCallError::RespondToModel(_) => "response_budget",
FunctionCallError::Fatal(_) => "internal_error",
};
})?;
let output = skill_json_output(&response, output_authority)?;
if output_authority == super::SkillToolAuthoritySelector::Executor
&& response.next_cursor.is_some()
&& result.contents.len() <= MAX_SKILL_RESOURCE_CONTENT_BYTES
&& let Some(access) = access_key
{
*self
.context
.thread_state
.executor_read_snapshot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
Some(ExecutorReadSnapshot {
authority,
package,
access,
result,
});
}
if requested_resource == main_prompt
&& args.cursor.is_none()
&& let Some(invocations) = self.context.invocations.as_ref()
{
invocations.record_skill_invocation(
skill_entry,
&selected_source,
call.model.clone(),
call.turn_id.clone(),
InvocationType::Implicit,
);
}
outcome = "success";
Ok(output)
}
.await;
if let Some(metrics) = &self.metrics {
metrics.counter(
"codex.skills.read.result",
/*inc*/ 1,
&[
("outcome", outcome),
(
"discovery_version",
if self.context.step_state.discovery_v2 {
"v2"
} else {
"v1"
},
),
],
);
}
result
})
}
}
fn page_response(
resource: &str,
contents: &str,
metadata: &ReadMetadata,
start: usize,
max_response_bytes: usize,
cursor_at: impl Fn(usize) -> String,
) -> Result<ReadResponse<ReadMetadata>, FunctionCallError> {
let response = |end, next_cursor| ReadResponse {
resource: resource.to_string(),
contents: contents[start..end].to_string(),
metadata: metadata.clone(),
next_cursor,
};
let complete = response(contents.len(), None);
if serialized_len(&complete)? <= max_response_bytes {
return Ok(complete);
}
let mut lower = start;
let mut upper = contents.len();
let mut best = None;
while lower < upper {
// Probe strictly above lower so a multibyte character cannot stall the search.
let end = contents.ceil_char_boundary(lower.midpoint(upper).saturating_add(1));
let candidate = response(end, Some(cursor_at(end)));
if serialized_len(&candidate)? <= max_response_bytes {
lower = end;
best = Some(candidate);
} else {
upper = contents.floor_char_boundary(end.saturating_sub(1));
}
}
best.ok_or_else(|| {
FunctionCallError::RespondToModel(
"skills.read response budget leaves no room for contents".to_string(),
)
})
}

View File

@@ -0,0 +1,42 @@
use schemars::JsonSchema;
use schemars::r#gen::SchemaSettings;
use serde_json::Map;
use serde_json::Value;
pub(super) fn input_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ false)
}
pub(super) fn output_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ true)
}
fn schema_for<T: JsonSchema>(option_add_null_type: bool) -> Value {
let schema = SchemaSettings::draft2019_09()
.with(|settings| {
settings.inline_subschemas = true;
settings.option_add_null_type = option_add_null_type;
})
.into_generator()
.into_root_schema_for::<T>();
let schema_value = serde_json::to_value(schema)
.unwrap_or_else(|err| panic!("generated skill tool schema should serialize: {err}"));
let Value::Object(mut schema_object) = schema_value else {
unreachable!("root tool schema must be an object");
};
let mut tool_schema = Map::new();
for key in [
"properties",
"required",
"type",
"additionalProperties",
"$defs",
"definitions",
] {
if let Some(value) = schema_object.remove(key) {
tool_schema.insert(key.to_string(), value);
}
}
Value::Object(tool_schema)
}