use std::collections::BTreeMap;
use std::path::PathBuf;
use offline_generator::package_json;
use offline_generator::project_detect;
use offline_generator::project_wiring::{self, McpRegistration};
use offline_registry::{
architecture_markdown, implementation_plan_markdown, normalize_platform, restate_platform,
unsupported_framework, Plan, Registry, RegistryError,
};
use offline_rn_shell::{finalize_react_native_mesh_app, rn_module_name};
use serde_json::{json, Value};
use crate::lookup::{self, Kind, Lookup, PlatformInput, PLATFORMS_DOCS};
use crate::mode::{DeploymentMode, HOSTED_BLOCKED_TOOLS};
const PLATFORM_ENUM: &[&str] = lookup::PLATFORM_ENUM;
pub const DEFAULT_PREVIEW_NAME: &str = "my-app";
pub fn tool_definitions() -> Vec<Value> {
tool_definitions_for(DeploymentMode::Local)
}
pub fn tool_definitions_for(mode: DeploymentMode) -> Vec<Value> {
let tools = [
(
"list_packages",
"List every Offline Protocol package in the registry with version, platforms, capabilities, and license.",
json!({"type": "object", "properties": {}, "additionalProperties": false}),
),
(
"get_package",
"Get the full manifest for one package: capabilities, peer dependencies, integration notes, and examples.",
json!({
"type": "object",
"properties": {"name": {"type": "string", "description": "Package name, e.g. @offline-protocol/mesh-sdk"}},
"required": ["name"],
"additionalProperties": false
}),
),
(
"search_packages",
"Search Offline Protocol packages by name, capability, or description keywords.",
query_schema(),
),
(
"search_capabilities",
"Search ecosystem capabilities (e.g. 'peer discovery', 'encrypted groups') and learn which packages and workflows provide them.",
query_schema(),
),
(
"search_workflows",
"Search product workflows (local handoff, retained event delivery to a backend, nearby service invocation, nearby chat, Offline ID sign-in, …) by keywords describing what you want to build.",
query_schema(),
),
(
"search_examples",
"Search reference example apps and integrations across the ecosystem.",
query_schema(),
),
(
"search_skills",
"Search skill documents (integration guides) by topic. Prefer get_skill once you know the skill name.",
query_schema(),
),
(
"list_workflows",
"List all product workflows with their capabilities and supported platforms.",
json!({"type": "object", "properties": {}, "additionalProperties": false}),
),
(
"get_workflow",
"Get one workflow in full: capabilities, per-platform packages, templates, and the reference architecture (screens, services, events, data models).",
json!({
"type": "object",
"properties": {"name": {"type": "string", "description": "Workflow name, e.g. local-handoff, backend-delivery or nearby-service"}},
"required": ["name"],
"additionalProperties": false
}),
),
(
"list_skills",
"List all skill documents (integration guides) with their use-when triggers.",
json!({"type": "object", "properties": {}, "additionalProperties": false}),
),
(
"get_skill",
"Read a skill document: accurate API usage, code samples, and best practices for one integration area. ALWAYS read the relevant skill before writing Offline Protocol SDK code.",
json!({
"type": "object",
"properties": {"name": {"type": "string", "description": "Skill name, e.g. mesh-networking, identity, groups"}},
"required": ["name"],
"additionalProperties": false
}),
),
(
"resolve_packages",
"Resolve a package set (or a workflow) for a platform into the full install list: versions, transitive requirements, peer dependencies, install commands, and license warnings.",
json!({
"type": "object",
"properties": {
"packages": {"type": "array", "items": {"type": "string"}, "description": "Explicit package names to resolve"},
"workflow": {"type": "string", "description": "Alternatively, a workflow name to resolve"},
"platform": {"type": "string", "enum": PLATFORM_ENUM, "description": "Target platform"}
},
"required": ["platform"],
"additionalProperties": false
}),
),
(
"get_template",
"Get a starter template's metadata: variables, post-generate steps, notes, and its file listing.",
json!({
"type": "object",
"properties": {"name": {"type": "string", "description": "Template name, e.g. react-native-mesh-app"}},
"required": ["name"],
"additionalProperties": false
}),
),
(
"generate_architecture",
"Turn a natural-language app idea into a concrete plan: chosen workflow, platform, resolved packages, starter template, architecture documents, and next_actions for scaffolding or integration. Deterministic and registry-driven. Start here for new apps. Returns an error, not a React Native plan, when the prompt asks for a framework the planner has no starter for (Flutter, native Kotlin or Swift, and similar) unless `platform` is passed explicitly.",
json!({
"type": "object",
"properties": {
"prompt": {"type": "string", "description": "What you want to build, e.g. 'Hand over equipment between field engineers and reconcile with our backend'"},
"platform": {"type": "string", "enum": PLATFORM_ENUM, "description": "Optional platform override; inferred from the prompt otherwise"}
},
"required": ["prompt"],
"additionalProperties": false
}),
),
(
"preview_scaffold",
"Dry-run a project scaffold: returns the planned workflow, template, packages, and target path without writing files. Use before scaffold_project.",
scaffold_schema(false),
),
(
"scaffold_project",
"Scaffold a new Offline Protocol project on disk from a natural-language prompt, workflow name, or template name. Writes template files, offline.config / agent guidance (from the template), and architecture docs when prompt-driven. Prefer this over inventing project structure.",
scaffold_schema(true),
),
(
"integrate_packages",
"Add Offline Protocol package(s) (plus transitive registry requirements) to an existing project's package.json. Only missing dependencies are added; key order and formatting are preserved. Does not invent APIs; pair with get_skill for wiring code.",
json!({
"type": "object",
"properties": {
"packages": {
"type": "array",
"items": {"type": "string"},
"description": "Package names, e.g. [@offline-protocol/mesh-sdk] or short names [mesh-sdk]"
},
"dir": {"type": "string", "description": "Project directory (default: current working directory)"},
"platform": {"type": "string", "enum": PLATFORM_ENUM, "description": "Optional override; inferred from package.json otherwise"},
"dryRun": {"type": "boolean", "description": "If true, report changes without writing"}
},
"required": ["packages"],
"additionalProperties": false
}),
),
(
"init_project",
"Wire Offline Protocol metadata into an existing project (JS/TS with package.json, Python, Swift, or Gradle Kotlin/Java): offline.config.json, a .mcp.json that starts this release's MCP server through npx (an existing .mcp.json is never modified), and an AGENTS.md section that states whether .mcp.json registers the server. Use after integrate_packages or when adopting Offline Protocol in a brownfield app.",
json!({
"type": "object",
"properties": {
"dir": {"type": "string", "description": "Project directory (default: current working directory)"},
"appId": {"type": "string", "description": "App ID (app_…) from your organization on the developer portal"},
"projectId": {"type": "string", "description": "Deprecated alias for appId"}
},
"additionalProperties": false
}),
),
];
tools
.into_iter()
.filter(|(name, _, _)| crate::mode::tool_allowed_in_mode(name, mode))
.map(|(name, description, schema)| {
json!({
"name": name,
"description": description,
"inputSchema": schema,
"annotations": tool_annotations(name),
})
})
.collect()
}
pub fn tool_annotations(name: &str) -> Value {
let (title, read_only, destructive, idempotent, open_world) = match name {
"list_packages" => ("List packages", true, false, true, false),
"get_package" => ("Get package", true, false, true, false),
"search_packages" => ("Search packages", true, false, true, false),
"search_capabilities" => ("Search capabilities", true, false, true, false),
"search_workflows" => ("Search workflows", true, false, true, false),
"search_examples" => ("Search examples", true, false, true, false),
"search_skills" => ("Search skills", true, false, true, false),
"list_workflows" => ("List workflows", true, false, true, false),
"get_workflow" => ("Get workflow", true, false, true, false),
"list_skills" => ("List skills", true, false, true, false),
"get_skill" => ("Get skill", true, false, true, false),
"resolve_packages" => ("Resolve packages", true, false, true, false),
"get_template" => ("Get template", true, false, true, false),
"generate_architecture" => ("Generate architecture", true, false, true, false),
"preview_scaffold" => ("Preview scaffold", true, false, true, false),
"scaffold_project" => ("Scaffold project", false, false, false, true),
"integrate_packages" => ("Integrate packages", false, false, true, false),
"init_project" => ("Initialize project", false, false, true, false),
_ => ("", false, true, false, true),
};
json!({
"title": title,
"readOnlyHint": read_only,
"destructiveHint": destructive,
"idempotentHint": idempotent,
"openWorldHint": open_world,
})
}
fn query_schema() -> Value {
json!({
"type": "object",
"properties": {"query": {"type": "string", "description": "Search keywords"}},
"required": ["query"],
"additionalProperties": false
})
}
fn scaffold_schema(include_write_flags: bool) -> Value {
let mut props = json!({
"prompt": {"type": "string", "description": "Natural-language app idea (uses the planner)"},
"workflow": {"type": "string", "description": "Workflow name, e.g. local-handoff, backend-delivery or nearby-service"},
"template": {"type": "string", "description": "Template name, e.g. react-native-social"},
"platform": {"type": "string", "enum": PLATFORM_ENUM, "description": "Required when a multi-platform workflow is named without a template"},
"name": {"type": "string", "description": "Project name / directory slug"},
"dir": {"type": "string", "description": "Output directory (defaults to ./<name>)"},
"appId": {"type": "string", "description": "App ID app_… (required for Offline ID templates; injected as template variable app_id)"},
"projectId": {"type": "string", "description": "Deprecated alias for appId"},
"enableMesh": {"type": "boolean", "description": "Enable mesh SDK for React Native templates (default: true for mesh workflows / mesh templates)"},
"enableOfflineId": {"type": "boolean", "description": "Enable Offline ID (id-react-native) for React Native templates. Default: true for offline-social-network / offline-id-mesh-chat workflows and react-native-social; auto-switches react-native-mesh-app to react-native-social when true."}
});
if include_write_flags {
props.as_object_mut().unwrap().insert(
"dryRun".into(),
json!({"type": "boolean", "description": "If true, plan only — same as preview_scaffold"}),
);
}
json!({
"type": "object",
"properties": props,
"required": ["name"],
"additionalProperties": false
})
}
pub fn call_tool(registry: &Registry, name: &str, args: &Value) -> Result<Value, String> {
call_tool_for(registry, name, args, DeploymentMode::Local)
}
pub fn call_tool_for(
registry: &Registry,
name: &str,
args: &Value,
mode: DeploymentMode,
) -> Result<Value, String> {
if !crate::mode::tool_allowed_in_mode(name, mode) {
return Err(format!(
"tool `{name}` is not available on hosted MCP (writes to disk). \
Use local `offline mcp serve` or the Offline CLI for: {}.",
HOSTED_BLOCKED_TOOLS.join(", ")
));
}
match run_tool(registry, name, args) {
Ok(value) | Err(Stop::Answer(value)) => Ok(value),
Err(Stop::Error(message)) => Err(message),
}
}
enum Stop {
Answer(Value),
Error(String),
}
impl From<String> for Stop {
fn from(message: String) -> Self {
Stop::Error(message)
}
}
fn run_tool(registry: &Registry, name: &str, args: &Value) -> Result<Value, Stop> {
let str_arg = |key: &str| -> Result<String, String> {
args.get(key)
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| format!("missing required argument `{key}`"))
};
let opt_str = |key: &str| -> Option<String> {
args.get(key)
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string)
};
let opt_bool = |key: &str| -> Option<bool> { args.get(key).and_then(Value::as_bool) };
match name {
"list_packages" => Ok(json!(registry.packages().collect::<Vec<_>>())),
"get_package" => {
let mut notes = Vec::new();
let name = find(registry, Kind::Package, &str_arg("name")?, &mut notes)?;
let package = registry
.package(&name)
.expect("lookup returns registry names");
Ok(with_notes(json!(package), notes))
}
"search_packages" => Ok(json!(registry.search_packages(&str_arg("query")?))),
"search_capabilities" => Ok(json!(registry.search_capabilities(&str_arg("query")?))),
"search_workflows" => Ok(json!(registry.search_workflows(&str_arg("query")?))),
"search_examples" => Ok(json!(registry.search_examples(&str_arg("query")?))),
"search_skills" => Ok(json!(registry.search_skills(&str_arg("query")?))),
"list_workflows" => Ok(json!(registry.workflows().collect::<Vec<_>>())),
"get_workflow" => {
let mut notes = Vec::new();
let name = find(registry, Kind::Workflow, &str_arg("name")?, &mut notes)?;
let workflow = registry
.workflow(&name)
.expect("lookup returns registry names");
Ok(with_notes(json!(workflow), notes))
}
"list_skills" => Ok(json!(registry
.skills()
.map(|s| json!({
"name": s.name,
"title": s.title,
"description": s.description,
"useWhen": s.use_when,
"packages": s.packages,
}))
.collect::<Vec<_>>())),
"get_skill" => {
let mut notes = Vec::new();
let name = find(registry, Kind::Skill, &str_arg("name")?, &mut notes)?;
let skill = registry
.skill(&name)
.expect("lookup returns registry names");
Ok(with_notes(json!(skill), notes))
}
"resolve_packages" => {
let mut notes = Vec::new();
let platform = platform_arg(&str_arg("platform")?, &mut notes, false)?;
if let Some(wf) = args.get("workflow").and_then(Value::as_str) {
let wf = find(registry, Kind::Workflow, wf, &mut notes)?;
return match registry.resolve_workflow(&wf, &platform.resolved) {
Ok(r) => Ok(with_notes(json!(r), notes)),
Err(e) => Err(incompatible(registry, e, &platform, &[], Some(&wf), notes)),
};
}
let requested: Vec<String> = args
.get("packages")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default();
if requested.is_empty() {
return Ok(with_notes(nothing_to_resolve(registry, &platform), notes));
}
let mut packages = Vec::new();
for p in &requested {
packages.push(find(registry, Kind::Package, p, &mut notes)?);
}
match registry.resolve_packages(&packages, &platform.resolved) {
Ok(r) => Ok(with_notes(json!(r), notes)),
Err(e) => Err(incompatible(registry, e, &platform, &packages, None, notes)),
}
}
"get_template" => {
let mut notes = Vec::new();
let name = find(registry, Kind::Template, &str_arg("name")?, &mut notes)?;
let meta = registry
.template(&name)
.expect("lookup returns registry names");
let files: Vec<String> = registry
.template_files(&name)
.map_err(|e| e.to_string())?
.into_iter()
.map(|(p, _)| p.to_string_lossy().replace('\\', "/"))
.collect();
Ok(with_notes(json!({"meta": meta, "files": files}), notes))
}
"generate_architecture" => {
let prompt = str_arg("prompt")?;
let mut notes = Vec::new();
let platform = match opt_str("platform") {
Some(p) => Some(platform_arg(&p, &mut notes, true)?),
None => None,
};
let plan = registry
.plan(&prompt, platform.as_ref().map(|p| p.value.as_str()))
.map_err(|e| plan_stop(registry, e, &prompt, platform.as_ref(), notes.clone()))?;
let architecture_md = architecture_markdown(&plan);
let implementation_plan_md = implementation_plan_markdown(&plan);
let next_actions = next_actions_for_plan(&plan);
Ok(with_notes(
json!({
"plan": plan,
"documents": {
"architecture.md": architecture_md,
"implementation-plan.md": implementation_plan_md,
},
"nextActions": next_actions,
}),
notes,
))
}
"preview_scaffold" => scaffold_project(registry, args, true),
"scaffold_project" => {
let dry = opt_bool("dryRun").unwrap_or(false);
scaffold_project(registry, args, dry)
}
"integrate_packages" => Ok(integrate_packages(registry, args)?),
"init_project" => Ok(init_project(registry, args)?),
other => Err(format!("unknown tool `{other}`").into()),
}
}
fn find(
registry: &Registry,
kind: Kind,
input: &str,
notes: &mut Vec<String>,
) -> Result<String, Stop> {
match lookup::lookup(registry, kind, input) {
Lookup::Found { name, note } => {
notes.extend(note);
Ok(name)
}
Lookup::Answer(answer) => Err(Stop::Answer(answer)),
}
}
fn with_notes(mut value: Value, notes: Vec<String>) -> Value {
if !notes.is_empty() {
if let Some(object) = value.as_object_mut() {
object.insert("note".to_string(), json!(notes.join("; ")));
}
}
value
}
struct PlatformArg {
requested: String,
value: String,
resolved: String,
}
fn platform_arg(input: &str, notes: &mut Vec<String>, plan: bool) -> Result<PlatformArg, Stop> {
let value = match lookup::classify_platform(input) {
PlatformInput::Exact => input.to_string(),
PlatformInput::Alias(value, note) => {
notes.push(note);
value.to_string()
}
PlatformInput::Unsupported(framework) => {
return Err(Stop::Answer(lookup::unsupported_platform_answer(
input, framework, plan,
)))
}
PlatformInput::Unknown => return Err(Stop::Error(lookup::unknown_platform_message(input))),
};
let resolved = normalize_platform(&value).expect("schema platform values normalize");
Ok(PlatformArg {
requested: input.to_string(),
value,
resolved,
})
}
fn workflows_on(registry: &Registry, platform: &str) -> Vec<String> {
registry
.workflows()
.filter(|w| w.packages.contains_key(platform))
.map(|w| w.name.clone())
.collect()
}
fn packages_on_alternative(registry: &Registry, platform: &PlatformArg) -> Option<Value> {
let packages: Vec<&str> = registry
.packages()
.filter(|p| p.platforms.contains(&platform.resolved))
.map(|p| p.name.as_str())
.collect();
(!packages.is_empty()).then(|| {
json!({
"description": format!(
"Packages on {}: {}. Resolve them for their install lines.",
offline_registry::platform_label(&platform.resolved),
packages.join(", ")
),
"arguments": {"packages": packages, "platform": platform.value},
})
})
}
fn push_alternative(alternatives: &mut Vec<Value>, alternative: Value) {
if !alternatives.contains(&alternative) {
alternatives.push(alternative);
}
}
fn nothing_to_resolve(registry: &Registry, platform: &PlatformArg) -> Value {
let packages: Vec<Value> = registry
.packages()
.filter(|p| p.platforms.contains(&platform.resolved))
.map(|p| json!({"name": p.name, "description": lookup::one_line(&p.description)}))
.collect();
let workflows: Vec<Value> = registry
.workflows()
.filter(|w| w.packages.contains_key(&platform.resolved))
.map(|w| json!({"name": w.name, "description": lookup::one_line(&w.description)}))
.collect();
json!({
"resolved": false,
"platform": platform.value,
"message": format!(
"Nothing to resolve: pass `packages` (package names) or `workflow` (a workflow name) with the platform. The packages and workflows available on `{}` are listed here.",
platform.value
),
"packages": packages,
"workflows": workflows,
})
}
fn incompatible(
registry: &Registry,
err: RegistryError,
platform: &PlatformArg,
packages: &[String],
workflow: Option<&str>,
notes: Vec<String>,
) -> Stop {
let reason = match restate_platform(err, &platform.requested, &platform.resolved) {
RegistryError::Incompatible(reason) => reason,
other => return Stop::Error(other.to_string()),
};
let mut alternatives = Vec::new();
if let Some(wf) = workflow.and_then(|w| registry.workflow(w)) {
for p in wf.packages.keys() {
push_alternative(
&mut alternatives,
json!({
"description": format!("`{}` is available on {p}", wf.name),
"arguments": {"workflow": wf.name, "platform": p},
}),
);
}
}
for name in packages {
let Some(pkg) = registry.package(name) else {
continue;
};
if pkg.platforms.contains(&platform.resolved) {
continue;
}
for other in registry.packages().filter(|o| {
o.name != pkg.name
&& o.platforms.contains(&platform.resolved)
&& o.capabilities
.iter()
.any(|c| c != "shared-types" && pkg.capabilities.contains(c))
}) {
push_alternative(
&mut alternatives,
json!({
"description": format!(
"`{}` provides capabilities of `{}` on {}",
other.name, pkg.name, platform.resolved
),
"arguments": {"packages": [other.name], "platform": platform.value},
}),
);
}
for p in &pkg.platforms {
push_alternative(
&mut alternatives,
json!({
"description": format!("`{}` is available on {p}", pkg.name),
"arguments": {"packages": [pkg.name], "platform": p},
}),
);
}
}
let on_platform = workflows_on(registry, &platform.resolved);
if !on_platform.is_empty() {
push_alternative(
&mut alternatives,
json!({
"description": format!(
"Workflows available on {}: {}",
platform.resolved,
on_platform.join(", ")
),
}),
);
} else if let Some(alternative) = packages_on_alternative(registry, platform) {
push_alternative(&mut alternatives, alternative);
}
Stop::Answer(with_notes(
json!({
"supported": false,
"reason": reason,
"requestedPlatform": platform.requested,
"supportedPlatforms": PLATFORM_ENUM,
"alternatives": alternatives,
"docs": PLATFORMS_DOCS,
}),
notes,
))
}
fn plan_stop(
registry: &Registry,
err: RegistryError,
prompt: &str,
platform: Option<&PlatformArg>,
notes: Vec<String>,
) -> Stop {
let message = match err {
RegistryError::Incompatible(message) => message,
other => return Stop::Error(other.to_string()),
};
let reason = if message.starts_with("no plan generated") {
message
} else {
format!("no plan generated: {message}")
};
let mut answer = json!({
"supported": false,
"planGenerated": false,
"reason": reason,
});
let mut alternatives = Vec::new();
match platform {
None => {
if let Some(framework) = unsupported_framework(prompt) {
answer["framework"] = json!(framework);
}
alternatives.push(json!({
"description": "React Native covers iOS and Android. If the user chooses React Native, call again with platform `react-native`.",
"arguments": {"platform": "react-native"},
}));
}
Some(platform) => {
answer["requestedPlatform"] = json!(platform.requested);
if let Ok(plan) = registry.plan(prompt, None) {
alternatives.push(json!({
"description": format!(
"The prompt matches the `{}` workflow, which runs on {}. Call again with that platform, or without `platform`.",
plan.workflow, plan.platform
),
"arguments": {"platform": plan.platform},
}));
}
let on_platform = workflows_on(registry, &platform.resolved);
if !on_platform.is_empty() {
alternatives.push(json!({
"description": format!(
"Workflows available on {}: {}",
platform.resolved,
on_platform.join(", ")
),
}));
}
if on_platform.is_empty() || matches!(platform.resolved.as_str(), "python" | "java") {
if let Some(alternative) = packages_on_alternative(registry, platform) {
alternatives.push(alternative);
}
}
if matches!(platform.resolved.as_str(), "nextjs" | "react-vite")
&& registry.package("offline-protocol-web").is_some()
{
alternatives.push(json!({
"description": offline_registry::BROWSER_NOTE,
"arguments": {"packages": ["offline-protocol-web"], "platform": platform.value},
}));
}
}
}
answer["supportedPlatforms"] = json!(PLATFORM_ENUM);
answer["alternatives"] = json!(alternatives);
answer["docs"] = json!(PLATFORMS_DOCS);
Stop::Answer(with_notes(answer, notes))
}
fn resolve_platform_arg(input: &str) -> Result<String, String> {
normalize_platform(input).ok_or_else(|| {
format!(
"unknown platform `{input}` (expected one of: {})",
PLATFORM_ENUM.join(", ")
)
})
}
fn next_actions_for_plan(plan: &Plan) -> Vec<Value> {
let mut actions = Vec::new();
if plan.existing_app {
actions.push(json!({
"tool": "integrate_packages",
"reason": "The prompt is about an existing app: add the resolved packages to its package.json",
"arguments": {
"packages": plan.resolution.packages.iter().map(|p| &p.name).collect::<Vec<_>>(),
"platform": plan.platform,
}
}));
actions.push(json!({
"tool": "init_project",
"reason": "Register offline.config.json, .mcp.json and AGENTS.md guidance in the existing app",
"arguments": {}
}));
if let Some(template) = &plan.template {
actions.push(json!({
"tool": "preview_scaffold",
"reason": "Reference implementation to copy modules from (see architecture.md, Existing application)",
"arguments": {
"template": template,
"name": "<reference-project-name>",
}
}));
}
} else if let Some(template) = &plan.template {
actions.push(json!({
"tool": "scaffold_project",
"reason": "Create a new project from the recommended starter",
"arguments": {
"prompt": plan.prompt,
"platform": plan.platform,
"name": "<choose-a-project-name>",
"workflow": plan.workflow,
"template": template,
}
}));
} else {
actions.push(json!({
"tool": "resolve_packages",
"reason": "No starter template for this workflow/platform — install packages into an existing app",
"arguments": {
"workflow": plan.workflow,
"platform": plan.platform,
}
}));
actions.push(json!({
"tool": "integrate_packages",
"reason": "Add resolved packages to an existing package.json",
"arguments": {
"packages": plan.resolution.packages.iter().map(|p| &p.name).collect::<Vec<_>>(),
"platform": plan.platform,
}
}));
}
for skill in plan.skills.iter().take(5) {
actions.push(json!({
"tool": "get_skill",
"reason": "Read accurate SDK usage before writing Offline Protocol code",
"arguments": {"name": skill}
}));
}
if plan.alternatives.iter().any(|a| a.score > 0.0) {
actions.push(json!({
"tool": "get_workflow",
"reason": "Review alternative workflows if the primary match is a weak fit",
"arguments": {"name": plan.alternatives.first().map(|a| a.workflow.clone()).unwrap_or_default()}
}));
}
actions
}
struct ScaffoldResolved {
template_name: String,
project_name: String,
target_dir: PathBuf,
plan: Option<Plan>,
vars: BTreeMap<String, String>,
mesh_enabled: bool,
offline_id_enabled: bool,
notes: Vec<String>,
}
fn prompt_implies_offline_id(prompt: &str) -> bool {
let lower = prompt.to_lowercase();
[
"offline id",
"offline identity",
"authentication",
"sign in",
"sign-in",
"sign up",
"sign-up",
"user account",
"user accounts",
"identity management",
"username-based",
"offline protocol identity",
]
.iter()
.any(|k| lower.contains(k))
}
fn workflow_implies_offline_id(workflow: &str) -> bool {
workflow == "offline-social-network"
|| workflow == "offline-id-mesh-chat"
|| workflow.contains("offline-id")
}
fn resolve_scaffold(
registry: &Registry,
args: &Value,
dry_run: bool,
) -> Result<ScaffoldResolved, Stop> {
let mut notes = Vec::new();
let name_raw = match args.get("name").and_then(Value::as_str) {
Some(name) => name.to_string(),
None if dry_run => {
notes.push(format!(
"no `name` given; previewed as `{DEFAULT_PREVIEW_NAME}`. Pass `name` to choose the project name and directory"
));
DEFAULT_PREVIEW_NAME.to_string()
}
None => return Err("missing required argument `name`".to_string().into()),
};
let project_name = slugify(&name_raw);
if project_name.is_empty() {
return Err("project `name` must contain letters or digits"
.to_string()
.into());
}
let prompt = args.get("prompt").and_then(Value::as_str);
let workflow_arg = args.get("workflow").and_then(Value::as_str);
let template_arg = args.get("template").and_then(Value::as_str);
let platform = args
.get("platform")
.and_then(Value::as_str)
.filter(|p| !p.is_empty())
.map(|p| platform_arg(p, &mut notes, prompt.is_some()))
.transpose()?;
let mut workflow_resolved: Option<String> = None;
let (mut template_name, plan) = if let Some(prompt) = prompt {
let plan = registry
.plan(prompt, platform.as_ref().map(|p| p.value.as_str()))
.map_err(|e| plan_stop(registry, e, prompt, platform.as_ref(), notes.clone()))?;
let Some(template) = plan.template.clone() else {
return Err(Stop::Answer(no_template_answer(
registry,
&plan.workflow,
&plan.platform,
notes,
)));
};
(template, Some(plan))
} else if let Some(template) = template_arg {
(find(registry, Kind::Template, template, &mut notes)?, None)
} else if let Some(wf_in) = workflow_arg {
let wf_name = find(registry, Kind::Workflow, wf_in, &mut notes)?;
let wf = registry
.workflow(&wf_name)
.expect("lookup returns registry names");
workflow_resolved = Some(wf_name.clone());
let platform = match platform {
Some(p) => p.resolved,
None if wf.templates.len() == 1 => wf.templates.keys().next().unwrap().clone(),
None => {
return Err(Stop::Answer(with_notes(
json!({
"found": false,
"query": wf_in,
"message": format!(
"Several matches: workflow `{wf_name}` has starter templates for several platforms ({}). Call again with `platform`.",
wf.templates.keys().cloned().collect::<Vec<_>>().join(", ")
),
"matches": wf.templates.iter().map(|(p, t)| json!({
"platform": p,
"template": t,
"description": registry.template(t).map(|m| lookup::one_line(&m.description)).unwrap_or_default(),
})).collect::<Vec<_>>(),
}),
notes,
)))
}
};
let Some(template) = wf.templates.get(&platform).cloned() else {
return Err(Stop::Answer(no_template_answer(
registry, &wf_name, &platform, notes,
)));
};
(template, None)
} else {
return Err(
"provide one of `prompt`, `workflow`, or `template` to choose a starter"
.to_string()
.into(),
);
};
let workflow = workflow_resolved.as_deref().or(workflow_arg);
let offline_id_default = template_name == "react-native-social"
|| template_name == "react-native-id-only"
|| plan
.as_ref()
.map(|p| workflow_implies_offline_id(&p.workflow))
.unwrap_or(false)
|| prompt.map(prompt_implies_offline_id).unwrap_or(false);
let offline_id_enabled = args
.get("enableOfflineId")
.and_then(Value::as_bool)
.unwrap_or(offline_id_default);
let from_mesh_app_with_offline_id =
offline_id_enabled && template_name == "react-native-mesh-app";
if from_mesh_app_with_offline_id {
template_name = "react-native-social".to_string();
}
let mut template_meta = registry
.template(&template_name)
.ok_or_else(|| format!("template `{template_name}` not found"))?
.clone();
let workflow_name = plan.as_ref().map(|p| p.workflow.as_str()).or(workflow);
let mesh_default = template_name.contains("mesh")
|| from_mesh_app_with_offline_id
|| workflow_name
.map(|w| {
w.contains("nearby")
|| w.contains("group")
|| w == "offline-id-mesh-chat"
|| w == "custom-p2p-app"
})
.unwrap_or(false);
let mut mesh_enabled = args
.get("enableMesh")
.and_then(Value::as_bool)
.unwrap_or(mesh_default && template_meta.platform == "react-native");
if offline_id_enabled && workflow_name == Some("offline-id-mesh-chat") {
mesh_enabled = true;
}
if template_meta.requires_mesh {
if args.get("enableMesh").and_then(Value::as_bool) == Some(false) {
return Err(format!(
"template `{template_name}` is built on the Mesh SDK; enableMesh=false does not apply"
)
.into());
}
mesh_enabled = true;
}
if !offline_id_enabled && mesh_enabled && template_name == "react-native-social" {
template_name = "react-native-mesh-app".to_string();
template_meta = registry
.template(&template_name)
.ok_or_else(|| format!("template `{template_name}` not found"))?
.clone();
}
if offline_id_enabled
&& !mesh_enabled
&& template_name == "react-native-social"
&& !from_mesh_app_with_offline_id
&& workflow_name != Some("offline-social-network")
{
template_name = "react-native-id-only".to_string();
template_meta = registry
.template(&template_name)
.ok_or_else(|| format!("template `{template_name}` not found"))?
.clone();
}
let template_meta = template_meta;
let target_dir = args
.get("dir")
.and_then(Value::as_str)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(&project_name));
let mut vars = BTreeMap::new();
vars.insert(
"enable_mesh".to_string(),
if mesh_enabled { "true" } else { "false" }.to_string(),
);
vars.insert(
"enable_offline_id".to_string(),
if offline_id_enabled { "true" } else { "false" }.to_string(),
);
if let Some(pid) = args
.get("appId")
.and_then(Value::as_str)
.or_else(|| args.get("projectId").and_then(Value::as_str))
{
vars.insert("app_id".to_string(), pid.to_string());
}
for v in &template_meta.variables {
if vars.contains_key(&v.name) {
continue;
}
if !mesh_enabled && matches!(v.name.as_str(), "mesh_app_id" | "relay_server_url") {
continue;
}
if let Some(default) = &v.default {
vars.insert(v.name.clone(), default.clone());
} else if v.name == "app_id" {
vars.insert(v.name.clone(), "YOUR_APP_ID".to_string());
} else if v.name == "mesh_app_id" {
vars.insert(v.name.clone(), project_name.clone());
} else if v.name == "relay_server_url" {
vars.insert(
v.name.clone(),
"wss://relay.offlineprotocol.com".to_string(),
);
} else if v.name == "service_name" {
vars.insert(
v.name.clone(),
format!("{}-service", project_name.replace('_', "-")),
);
} else if v.name == "transport_profile" {
vars.insert(
v.name.clone(),
plan.as_ref()
.and_then(|p| p.p2p_profile.as_ref())
.map(|p| p.transport_profile.clone())
.unwrap_or_else(|| "nearby-only".to_string()),
);
} else if v.name == "discovery_mode" {
vars.insert(
v.name.clone(),
plan.as_ref()
.and_then(|p| p.p2p_profile.as_ref())
.map(|p| p.discovery.clone())
.unwrap_or_else(|| "mesh-services".to_string()),
);
} else if v.name == "p2p_app_kind" {
vars.insert(
v.name.clone(),
plan.as_ref()
.and_then(|p| p.p2p_profile.as_ref())
.map(|p| p.app_kind.clone())
.unwrap_or_else(|| "generic".to_string()),
);
} else if v.required {
return Err(format!(
"template requires variable `{}` — pass appId or use offline create --var {}=...",
v.name, v.name
)
.into());
}
}
Ok(ScaffoldResolved {
template_name,
project_name,
target_dir,
plan,
vars,
mesh_enabled,
offline_id_enabled,
notes,
})
}
fn no_template_answer(
registry: &Registry,
workflow: &str,
platform: &str,
notes: Vec<String>,
) -> Value {
let mut alternatives: Vec<Value> = registry
.workflow(workflow)
.map(|wf| {
wf.templates
.iter()
.map(|(p, t)| {
json!({
"description": format!("`{workflow}` has the starter template `{t}` on {p}"),
"arguments": {"workflow": workflow, "platform": p},
})
})
.collect()
})
.unwrap_or_default();
alternatives.push(json!({
"description": "Add the workflow's packages to an existing app instead (resolve_packages lists them)",
"arguments": {"workflow": workflow, "platform": platform},
}));
with_notes(
json!({
"supported": false,
"reason": format!(
"workflow `{workflow}` has no starter template for platform `{platform}`, so there is no project to scaffold; use the packages in an existing app instead"
),
"alternatives": alternatives,
}),
notes,
)
}
fn prepend_offline_id_mesh_skill(skills: &mut Vec<String>) {
const SKILL: &str = "offline-id-mesh-integration";
if skills.iter().any(|s| s == SKILL) {
return;
}
skills.insert(0, SKILL.to_string());
}
fn prepend_mesh_chat_skills(skills: &mut Vec<String>, offline_id_enabled: bool) {
if offline_id_enabled {
prepend_offline_id_mesh_skill(skills);
}
for skill in ["groups", "messaging", "mesh-networking"] {
if skills.iter().any(|s| s == skill) {
continue;
}
skills.insert(if offline_id_enabled { 1 } else { 0 }, skill.to_string());
}
}
fn prepend_custom_p2p_skills(skills: &mut Vec<String>) {
for skill in [
"p2p-sync-patterns",
"p2p-discovery-patterns",
"p2p-app-architecture",
"mesh-networking",
"peer-discovery",
]
.iter()
.rev()
{
if skills.iter().any(|s| s == *skill) {
continue;
}
skills.insert(0, (*skill).to_string());
}
}
fn scaffold_project(registry: &Registry, args: &Value, dry_run: bool) -> Result<Value, Stop> {
let resolved = resolve_scaffold(registry, args, dry_run)?;
let template_meta = registry
.template(&resolved.template_name)
.expect("validated in resolve_scaffold");
let file_listing: Vec<String> = registry
.template_files(&resolved.template_name)
.map_err(|e| e.to_string())?
.into_iter()
.map(|(p, _)| p.to_string_lossy().replace('\\', "/"))
.collect();
let mut next_skills: Vec<String> = resolved
.plan
.as_ref()
.map(|p| p.skills.clone())
.unwrap_or_else(|| {
template_meta
.workflow
.as_ref()
.and_then(|wf| registry.resolve_workflow(wf, &template_meta.platform).ok())
.map(|res| {
let mut skills = Vec::new();
for rp in res.packages {
if let Some(pkg) = registry.package(&rp.name) {
for s in &pkg.skills {
if !skills.contains(s) {
skills.push(s.clone());
}
}
}
}
skills
})
.unwrap_or_default()
});
let workflow_skills = resolved
.plan
.as_ref()
.map(|p| p.workflow.as_str())
.or(template_meta.workflow.as_deref())
.and_then(|w| registry.workflow(w))
.map(|w| w.skills.clone())
.unwrap_or_default();
if !workflow_skills.is_empty() {
next_skills = workflow_skills;
} else if resolved.mesh_enabled {
let workflow = resolved
.plan
.as_ref()
.map(|p| p.workflow.as_str())
.or(template_meta.workflow.as_deref());
if workflow == Some("custom-p2p-app") {
prepend_custom_p2p_skills(&mut next_skills);
} else {
prepend_mesh_chat_skills(&mut next_skills, resolved.offline_id_enabled);
}
}
if dry_run {
let next = next_skills
.iter()
.take(5)
.map(|s| {
json!({
"tool": "get_skill",
"arguments": {"name": s}
})
})
.collect::<Vec<_>>();
let mut dry_notes = vec![
"No files written (dry run). Call scaffold_project without dryRun to create the project."
.to_string(),
];
if template_meta.platform == "react-native" {
dry_notes.push(
"React Native android/ and ios/ native shells are added automatically when scaffold_project runs (not in dry run).".into(),
);
}
dry_notes.extend(resolved.notes.iter().cloned());
let workflow = resolved
.plan
.as_ref()
.map(|p| p.workflow.clone())
.or_else(|| template_meta.workflow.clone());
return Ok(json!({
"dryRun": true,
"project": resolved.project_name,
"dir": resolved.target_dir,
"template": resolved.template_name,
"platform": template_meta.platform,
"workflow": workflow,
"meshEnabled": resolved.mesh_enabled,
"offlineIdEnabled": resolved.offline_id_enabled,
"files": file_listing,
"skills": next_skills,
"nextActions": next,
"notes": dry_notes,
}));
}
let generated = offline_generator::generate(
registry,
&resolved.template_name,
&resolved.target_dir,
&resolved.project_name,
&resolved.vars,
)
.map_err(|e| e.to_string())?;
let mut extra_files = Vec::new();
if let Some(plan) = &resolved.plan {
let arch = architecture_markdown(plan);
let impl_plan = implementation_plan_markdown(plan);
std::fs::write(resolved.target_dir.join("architecture.md"), &arch)
.map_err(|e| format!("failed to write architecture.md: {e}"))?;
std::fs::write(
resolved.target_dir.join("implementation-plan.md"),
&impl_plan,
)
.map_err(|e| format!("failed to write implementation-plan.md: {e}"))?;
extra_files.push("architecture.md".to_string());
extra_files.push("implementation-plan.md".to_string());
}
let mut native_shells_added = false;
let mut scaffold_warnings: Vec<String> = Vec::new();
if template_meta.platform == "react-native" {
let module = rn_module_name(&resolved.project_name);
let rn_result =
finalize_react_native_mesh_app(&generated.target_dir, &module, resolved.mesh_enabled);
extra_files.extend(rn_result.extra_files);
native_shells_added = rn_result.native_shells_added;
scaffold_warnings = rn_result.warnings;
}
let mut notes = generated.notes.clone();
if template_meta.platform == "react-native" {
notes.push(
"Native android/ and ios/ shells are added automatically by scaffold_project.".into(),
);
notes.push(
"Patterns follow offline-protocol-sdk/examples/demo-app — use physical devices for BLE.".into(),
);
notes.extend(scaffold_warnings);
}
notes.extend(resolved.notes.iter().cloned());
let mut files_written = generated.files_written.clone();
files_written.extend(extra_files);
let next = next_skills
.iter()
.take(5)
.map(|s| {
json!({
"tool": "get_skill",
"reason": "Read before writing Offline Protocol SDK code",
"arguments": {"name": s}
})
})
.collect::<Vec<_>>();
let workflow = resolved
.plan
.as_ref()
.map(|p| p.workflow.clone())
.or_else(|| template_meta.workflow.clone());
Ok(json!({
"dryRun": false,
"project": resolved.project_name,
"dir": generated.target_dir,
"template": generated.template,
"platform": template_meta.platform,
"workflow": workflow,
"meshEnabled": resolved.mesh_enabled,
"offlineIdEnabled": resolved.offline_id_enabled,
"nativeShellsAdded": native_shells_added,
"filesWritten": files_written,
"postGenerate": generated.post_generate,
"notes": notes,
"skills": next_skills,
"nextActions": next,
}))
}
fn expand_package_name(registry: &Registry, name: &str) -> Result<String, String> {
if registry.package(name).is_some() {
return Ok(name.to_string());
}
let scoped = format!("@offline-protocol/{name}");
if registry.package(&scoped).is_some() {
return Ok(scoped);
}
let hits = registry.search_packages(name);
let hint = hits
.first()
.map(|h| format!(". Did you mean `{}`?", h.name))
.unwrap_or_default();
Err(format!("unknown package `{name}`{hint}"))
}
fn detect_platform_from_pkg(pkg: &Value) -> String {
let deps = pkg
.get("dependencies")
.and_then(|d| d.as_object())
.cloned()
.unwrap_or_default();
let dev = pkg
.get("devDependencies")
.and_then(|d| d.as_object())
.cloned()
.unwrap_or_default();
if deps.contains_key("react-native") || dev.contains_key("react-native") {
"react-native".into()
} else if deps.contains_key("next") || dev.contains_key("next") {
"nextjs".into()
} else if deps.contains_key("vite") || dev.contains_key("vite") {
"react-vite".into()
} else {
"web".into()
}
}
fn integrate_packages(registry: &Registry, args: &Value) -> Result<Value, String> {
let packages_raw: Vec<String> = args
.get("packages")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default();
if packages_raw.is_empty() {
return Err("packages must be a non-empty array".into());
}
let dir = args
.get("dir")
.and_then(Value::as_str)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
let pkg_path = dir.join("package.json");
let raw = std::fs::read_to_string(&pkg_path).map_err(|_| {
format!(
"no package.json at {} — use scaffold_project for new apps",
pkg_path.display()
)
})?;
let mut pkg: Value = serde_json::from_str(&raw).map_err(|e| e.to_string())?;
let requested_platform = args
.get("platform")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| detect_platform_from_pkg(&pkg));
let platform = match args.get("platform").and_then(Value::as_str) {
Some(p) => resolve_platform_arg(p)?,
None => normalize_platform(&requested_platform).unwrap_or(requested_platform.clone()),
};
let dry_run = args.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
let mut all_added = Vec::new();
let mut all_peers = BTreeMap::new();
let mut all_warnings = Vec::new();
let mut skills = Vec::new();
let mut notes = Vec::new();
for raw_name in &packages_raw {
let full = expand_package_name(registry, raw_name)?;
let resolution = registry
.resolve_packages(std::slice::from_ref(&full), &platform)
.map_err(|e| restate_platform(e, &requested_platform, &platform).to_string())?;
all_peers.extend(resolution.peer_dependencies.clone());
all_warnings.extend(resolution.warnings.clone());
let entries: Vec<(String, String)> = resolution
.packages
.iter()
.filter(|rp| rp.registry == "npm")
.map(|rp| (rp.name.clone(), format!("^{}", rp.version)))
.collect();
if resolution.packages.iter().any(|rp| rp.registry != "npm") {
all_warnings.push(format!(
"Not added to package.json (not an npm package): {}. Install with: {}",
resolution
.packages
.iter()
.filter(|rp| rp.registry != "npm")
.map(|rp| rp.name.as_str())
.collect::<Vec<_>>()
.join(", "),
resolution.install_commands.join("; ")
));
}
let added = package_json::add_dependencies(&mut pkg, "dependencies", &entries)?;
for name in added {
if let Some((_, range)) = entries.iter().find(|(n, _)| *n == name) {
all_added.push(format!("{name}@{range}"));
}
}
if let Some(manifest) = registry.package(&full) {
for s in &manifest.skills {
if !skills.contains(s) {
skills.push(s.clone());
}
}
for n in &manifest.notes {
if !notes.contains(n) {
notes.push(n.clone());
}
}
}
}
if !dry_run && !all_added.is_empty() {
let text = package_json::to_string_like(&raw, &pkg)?;
std::fs::write(&pkg_path, text).map_err(|e| e.to_string())?;
}
let mut next = skills
.iter()
.map(|s| {
json!({
"tool": "get_skill",
"reason": "Wire providers and SDK calls from the skill — do not invent APIs",
"arguments": {"name": s}
})
})
.collect::<Vec<_>>();
next.push(json!({
"tool": "init_project",
"reason": "Add offline.config.json, .mcp.json, and AGENTS.md if missing",
"arguments": {"dir": dir}
}));
Ok(json!({
"dir": dir,
"platform": platform,
"added": all_added,
"dryRun": dry_run,
"peerDependencies": all_peers,
"warnings": all_warnings,
"notes": notes,
"skills": skills,
"nextActions": next,
}))
}
fn init_project(registry: &Registry, args: &Value) -> Result<Value, String> {
let dir = args
.get("dir")
.and_then(Value::as_str)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
let app_id = args
.get("appId")
.and_then(Value::as_str)
.or_else(|| args.get("projectId").and_then(Value::as_str))
.unwrap_or("")
.to_string();
let pkg_path = dir.join("package.json");
let (project_name, platform, installed, native) = if pkg_path.exists() {
let pkg: Value =
serde_json::from_str(&std::fs::read_to_string(&pkg_path).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())?;
let mut deps = Vec::new();
for key in ["dependencies", "devDependencies", "peerDependencies"] {
if let Some(map) = pkg.get(key).and_then(|d| d.as_object()) {
deps.extend(map.keys().cloned());
}
}
let platform = detect_platform_from_pkg(&pkg);
let project_name = pkg
.get("name")
.and_then(|n| n.as_str())
.unwrap_or("offline-app")
.to_string();
let installed: Vec<String> = registry
.packages()
.filter(|p| deps.iter().any(|d| d == &p.name))
.map(|p| p.name.clone())
.collect();
(project_name, platform, installed, None)
} else if let Some(project) = project_detect::detect_native(&dir) {
let installed = project.installed_packages(registry);
(
project.name.clone(),
project.platform.to_string(),
installed,
Some(project),
)
} else {
return Err(project_detect::unsupported_message(&dir)
.replace("use `offline create`", "use scaffold_project"));
};
let mut written = Vec::new();
let mut skipped = Vec::new();
let config_path = dir.join("offline.config.json");
if config_path.exists() {
skipped.push("offline.config.json (already exists)");
} else {
let config = json!({
"$schema": "https://dev.offlineprotocol.com/schemas/offline.config.json",
"projectName": project_name,
"appId": app_id,
"platform": platform,
"packages": installed,
});
std::fs::write(
&config_path,
serde_json::to_string_pretty(&config).map_err(|e| e.to_string())?,
)
.map_err(|e| e.to_string())?;
written.push("offline.config.json");
}
let mcp_path = dir.join(".mcp.json");
let registration = if mcp_path.exists() {
let existing = std::fs::read_to_string(&mcp_path).map_err(|e| e.to_string())?;
if project_wiring::registers_offline_mcp(&existing) {
skipped
.push(".mcp.json (already exists and registers the Offline Protocol MCP server)");
McpRegistration::AlreadyRegistered
} else {
skipped.push(
".mcp.json (already exists; left unchanged and does not register the Offline Protocol MCP server)",
);
McpRegistration::NotRegistered
}
} else {
std::fs::write(
&mcp_path,
serde_json::to_string_pretty(&project_wiring::mcp_json()).map_err(|e| e.to_string())?
+ "\n",
)
.map_err(|e| e.to_string())?;
written.push(".mcp.json");
McpRegistration::Written
};
let sdk = native
.as_ref()
.filter(|_| installed.is_empty())
.and_then(|p| p.sdk_package(registry));
let skills: Vec<String> = registry
.packages()
.filter(|p| installed.contains(&p.name))
.flat_map(|p| p.skills.clone())
.chain(sdk.map(|p| p.skills.clone()).unwrap_or_default())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
let section = project_wiring::agents_section(&installed, &skills, registration);
let agents_path = dir.join("AGENTS.md");
if agents_path.exists() {
let existing = std::fs::read_to_string(&agents_path).map_err(|e| e.to_string())?;
if project_wiring::agents_has_section(&existing) {
skipped.push("AGENTS.md (already has an Offline Protocol section)");
} else {
std::fs::write(&agents_path, format!("{existing}\n{section}"))
.map_err(|e| e.to_string())?;
written.push("AGENTS.md (appended)");
}
} else {
std::fs::write(&agents_path, format!("# Agent guide\n{section}"))
.map_err(|e| e.to_string())?;
written.push("AGENTS.md");
}
let mcp_server = match registration {
McpRegistration::NotRegistered => json!({
"registered": false,
"note": "Existing .mcp.json was not modified. To use the MCP tools in this project, add this server entry yourself or use the Offline Protocol plugin.",
"suggestedEntry": project_wiring::mcp_json()["mcpServers"],
}),
_ => json!({"registered": true}),
};
Ok(json!({
"dir": dir,
"platform": platform,
"detectedPackages": installed,
"filesWritten": written,
"skipped": skipped,
"mcpServer": mcp_server,
"skills": skills,
"nextActions": skills.iter().map(|s| json!({
"tool": "get_skill",
"arguments": {"name": s}
})).collect::<Vec<_>>(),
"nextSteps": native.as_ref().map(|p| json!({
"language": p.language,
"install": sdk.map(|pkg| p.install_hint(pkg)),
"docs": p.docs_url(),
})),
}))
}
fn slugify(s: &str) -> String {
let mut out = String::new();
let mut prev_dash = false;
for c in s.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
prev_dash = false;
} else if !prev_dash && !out.is_empty() {
out.push('-');
prev_dash = true;
}
}
while out.ends_with('-') {
out.pop();
}
out
}