appctl 0.15.0

CLI: sync OpenAPI, databases, and frameworks into LLM tool definitions; chat, run, and HTTP serve.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
    path::PathBuf,
    time::Duration,
};

use anyhow::{Context, Result, bail};
use async_trait::async_trait;

use crate::{
    config::{AppConfig, ConfigPaths, read_json, write_json},
    doctor::{DoctorRunArgs, run_doctor},
    schema::{Schema, SyncSource},
    term::{print_path_row, print_section_title, print_status_success, print_tip},
    tools::{ToolDef, schema_to_tools},
};

pub mod aspnet;
pub mod db;
pub mod django;
pub mod flask;
pub mod laravel;
pub mod mcp;
pub mod openapi;
pub mod rails;
pub mod strapi;
pub mod supabase;
pub mod url;

#[derive(Debug, Clone, Default)]
pub struct SyncRequest {
    pub openapi: Option<String>,
    pub django: Option<PathBuf>,
    pub flask: Option<PathBuf>,
    pub db: Option<String>,
    pub url: Option<String>,
    pub mcp: Option<String>,
    pub rails: Option<PathBuf>,
    pub laravel: Option<PathBuf>,
    pub aspnet: Option<PathBuf>,
    pub strapi: Option<PathBuf>,
    pub supabase: Option<String>,
    pub supabase_anon_ref: Option<String>,
    pub auth_header: Option<String>,
    pub base_url: Option<String>,
    pub force: bool,
    pub watch: bool,
    pub watch_interval_secs: u64,
    pub doctor_write: bool,
    pub login_url: Option<String>,
    pub login_user: Option<String>,
    pub login_password: Option<String>,
    pub login_form_selector: Option<String>,
    /// `sync --db` (Postgres): only these schemas (empty = all non-system). Merged with `[target].db_schemas`.
    pub db_schemas: Vec<String>,
    /// Exclude `table` or `schema.table`. Merged with `[target].db_exclude_tables`.
    pub db_exclude: Vec<String>,
    /// Skip common infra tables when true; merged with `[target].db_skip_infra`.
    pub db_skip_infra: bool,
}

#[async_trait]
pub trait SyncPlugin {
    async fn introspect(&self) -> Result<Schema>;
}

pub async fn run_sync(paths: ConfigPaths, request: SyncRequest) -> Result<()> {
    if request.watch {
        return run_sync_watch(paths, request).await;
    }
    run_sync_once(paths, &request).await
}

async fn run_sync_once(paths: ConfigPaths, request: &SyncRequest) -> Result<()> {
    paths.ensure()?;

    if !request.force && paths.schema.exists() {
        bail!(
            "Tools are already synced at: {}\n\
Run this next to replace them: appctl sync --force ...\n\
Working in the wrong project? Use this app dir explicitly: appctl --app-dir {} sync ...\n\
Tip: `appctl setup` can walk you through the safe path.",
            paths.schema.display(),
            paths.root.display()
        );
    }

    let mut schema = if let Some(source) = &request.openapi {
        openapi::OpenApiSync::new(source.clone(), request.auth_header.clone())
            .introspect()
            .await?
    } else if let Some(path) = &request.django {
        django::DjangoSync::new(path.clone(), request.base_url.clone())
            .introspect()
            .await?
    } else if let Some(path) = &request.flask {
        flask::FlaskSync::new(path.clone(), request.base_url.clone())
            .introspect()
            .await?
    } else if let Some(connection_string) = &request.db {
        let options = db_introspect_options_from_config_and_request(&paths, request);
        db::DbSync::with_options(connection_string.clone(), options)
            .introspect()
            .await?
    } else if let Some(source_url) = &request.url {
        url::UrlSync::new(source_url.clone(), &paths, request)?
            .introspect()
            .await?
    } else if let Some(server_url) = &request.mcp {
        mcp::McpSync::new(server_url.clone()).introspect().await?
    } else if let Some(path) = &request.rails {
        rails::RailsSync::new(path.clone(), request.base_url.clone())
            .introspect()
            .await?
    } else if let Some(path) = &request.laravel {
        laravel::LaravelSync::new(path.clone(), request.base_url.clone())
            .introspect()
            .await?
    } else if let Some(path) = &request.aspnet {
        aspnet::AspNetSync::new(path.clone(), request.base_url.clone())
            .introspect()
            .await?
    } else if let Some(path) = &request.strapi {
        strapi::StrapiSync::new(path.clone(), request.base_url.clone())
            .introspect()
            .await?
    } else if let Some(base) = &request.supabase {
        supabase::SupabaseSync::new(
            base.clone(),
            request
                .supabase_anon_ref
                .clone()
                .unwrap_or_else(|| "SUPABASE_ANON_KEY".to_string()),
        )
        .introspect()
        .await?
    } else {
        bail!(
            "choose one sync source: --openapi, --django, --flask, --db, --url, --mcp, --rails, --laravel, --aspnet, --strapi, --supabase"
        );
    };

    if request.base_url.is_some() {
        schema.base_url = request.base_url.clone();
    }
    if let Some(header) = &request.auth_header {
        schema.metadata.insert(
            "auth_header".to_string(),
            serde_json::Value::String(header.clone()),
        );
    }

    let tools = schema_to_tools(&schema);
    write_json(&paths.schema, &schema)?;
    write_json(&paths.tools, &tools)?;

    if let Some(conn) = &request.db {
        merge_target_database_url_from_sync(&paths, conn)?;
    }
    if let Some(header) = &request.auth_header {
        merge_target_auth_header_from_sync(&paths, header)?;
    }

    print_section_title("Sync complete");
    print_path_row("app directory", &paths.root);
    if matches!(schema.source, SyncSource::Db) {
        if let Some(scope) = schema
            .metadata
            .get("db_introspect_scope")
            .and_then(|v| v.as_str())
        {
            let n_schema = schema
                .metadata
                .get("db_introspect_schema_count")
                .and_then(|v| v.as_u64());
            let n_tables = schema
                .metadata
                .get("db_introspect_table_count")
                .and_then(|v| v.as_u64());
            if let (Some(n_schema), Some(n_tables)) = (n_schema, n_tables) {
                if scope == "all_non_system" {
                    print_status_success(&format!(
                        "Db: {} schemas, {} base tables (all non-system) → {} resources, {} tools",
                        n_schema,
                        n_tables,
                        schema.resources.len(),
                        tools.len()
                    ));
                } else {
                    print_status_success(&format!(
                        "Db: {} schemas, {} base tables (user filter) → {} resources, {} tools",
                        n_schema,
                        n_tables,
                        schema.resources.len(),
                        tools.len()
                    ));
                }
            } else {
                print_status_success(&format!(
                    "Db: {} resources, {} tools written under .appctl",
                    schema.resources.len(),
                    tools.len()
                ));
            }
        } else {
            print_status_success(&format!(
                "Db: {} resources, {} tools written under .appctl",
                schema.resources.len(),
                tools.len()
            ));
        }
        if let Some(n) = schema
            .metadata
            .get("db_introspect_table_count")
            .and_then(|v| v.as_u64())
        {
            if n > 200 {
                print_tip(
                    "Many database tables are exposed as tools. Narrow with `sync --db-schema` / [target] db_schemas, or `sync --db-exclude`.",
                );
            }
        }
    } else {
        print_status_success(&format!(
            "{:?}: {} resources, {} tools written under .appctl",
            schema.source,
            schema.resources.len(),
            tools.len()
        ));
    }
    if !paths.config.exists() {
        print_tip(&format!(
            "No provider config at {} yet — run `appctl init` (or `appctl --app-dir {} init`) before chat/run.",
            paths.config.display(),
            paths.root.display()
        ));
    }
    if request.doctor_write && paths.config.exists() {
        print_tip("Running `appctl doctor --write` after sync.");
        run_doctor(
            &paths,
            DoctorRunArgs {
                write: true,
                timeout_secs: 5,
            },
        )
        .await?;
    }

    Ok(())
}

async fn run_sync_watch(paths: ConfigPaths, request: SyncRequest) -> Result<()> {
    let Some(source) = request.openapi.as_deref() else {
        bail!("`appctl sync --watch` currently supports only `--openapi` sources");
    };

    let interval_secs = request.watch_interval_secs.max(1);
    print_tip(&format!(
        "watching OpenAPI source for changes every {interval_secs}s — press Ctrl+C to stop"
    ));

    let mut last_hash: Option<u64> = None;
    let mut watch_request = request.clone();
    watch_request.force = true;
    loop {
        let raw = openapi::load_openapi_source(source, request.auth_header.as_deref()).await?;
        let next_hash = stable_hash(&raw);
        if last_hash != Some(next_hash) {
            run_sync_once(paths.clone(), &watch_request).await?;
            last_hash = Some(next_hash);
        }
        tokio::time::sleep(Duration::from_secs(interval_secs)).await;
    }
}

fn stable_hash(value: &str) -> u64 {
    let mut hasher = DefaultHasher::new();
    value.hash(&mut hasher);
    hasher.finish()
}

/// Merge `sync` CLI database filters with `[target]` in config (CLI wins when it sets lists).
fn db_introspect_options_from_config_and_request(
    paths: &ConfigPaths,
    request: &SyncRequest,
) -> db::DbIntrospectOptions {
    let from_file = if paths.config.exists() {
        AppConfig::load(paths).ok()
    } else {
        None
    };
    let schema_allowlist = if !request.db_schemas.is_empty() {
        request.db_schemas.clone()
    } else {
        from_file
            .as_ref()
            .map(|c| c.target.db_schemas.clone())
            .unwrap_or_default()
    };
    let table_excludes = if !request.db_exclude.is_empty() {
        request.db_exclude.clone()
    } else {
        from_file
            .as_ref()
            .map(|c| c.target.db_exclude_tables.clone())
            .unwrap_or_default()
    };
    let skip_infra =
        request.db_skip_infra || from_file.as_ref().is_some_and(|c| c.target.db_skip_infra);
    db::DbIntrospectOptions {
        schema_allowlist,
        table_excludes,
        skip_infra,
    }
}

/// `appctl sync --db` uses a connection string for introspection, but `appctl chat` / run read
/// [`AppConfig::target::database_url`](crate::config::TargetConfig::database_url). If that is
/// unset, copy the sync string so DB tools work without a second manual copy.
fn merge_target_database_url_from_sync(paths: &ConfigPaths, connection_string: &str) -> Result<()> {
    let mut config = AppConfig::load_or_init(paths)?;
    let missing = config
        .target
        .database_url
        .as_deref()
        .map(str::trim)
        .is_none_or(|s| s.is_empty());
    if !missing {
        if config.target.database_url.as_deref() != Some(connection_string) {
            print_tip(
                "This sync used a different DB connection than [target] database_url; chat/run will use the configured target URL.",
            );
        }
        return Ok(());
    }
    config.target.database_url = Some(connection_string.to_string());
    config.save(paths)?;
    print_tip(
        "Set [target] database_url from this `sync --db` connection (required for DB tool calls in chat/run).",
    );
    Ok(())
}

/// Keep target API auth in one predictable place for runtime commands.
///
/// The schema metadata keeps the original sync header for backwards compatibility, but chat/run
/// users should be able to open `.appctl/config.toml` and see the target auth source there.
fn merge_target_auth_header_from_sync(paths: &ConfigPaths, auth_header: &str) -> Result<()> {
    let mut config = AppConfig::load_or_init(paths)?;
    let missing = config
        .target
        .auth_header
        .as_deref()
        .map(str::trim)
        .is_none_or(|s| s.is_empty());
    if !missing {
        if config.target.auth_header.as_deref() != Some(auth_header) {
            print_tip(
                "This sync used a different auth header than [target] auth_header; chat/run will use the configured target header.",
            );
        }
        return Ok(());
    }
    config.target.auth_header = Some(auth_header.to_string());
    config.save(paths)?;
    print_tip("Set [target] auth_header from this sync (used by doctor/chat/run HTTP tools).");
    Ok(())
}

pub fn load_schema(paths: &ConfigPaths) -> Result<Schema> {
    read_json(&paths.schema).with_context(|| {
        format!(
            "failed to load schema; run `appctl sync` first ({})",
            paths.schema.display()
        )
    })
}

pub fn load_tools(paths: &ConfigPaths) -> Result<Vec<ToolDef>> {
    read_json(&paths.tools).with_context(|| {
        format!(
            "failed to load tools; run `appctl sync` first ({})",
            paths.tools.display()
        )
    })
}

pub fn load_runtime_tools(paths: &ConfigPaths, config: &AppConfig) -> Result<Vec<ToolDef>> {
    let tools = load_tools(paths)?;
    let pinned = if config.tooling.pin.is_empty() {
        None
    } else {
        Some(
            config
                .tooling
                .pin
                .iter()
                .map(|name| config.resolve_tool_name(name).to_string())
                .collect::<std::collections::BTreeSet<_>>(),
        )
    };

    let mut runtime_tools = tools
        .into_iter()
        .filter(|tool| {
            pinned
                .as_ref()
                .is_none_or(|names| names.contains(&tool.name))
        })
        .collect::<Vec<_>>();

    for (alias, canonical) in &config.tooling.aliases {
        if let Some(tool) = runtime_tools
            .iter()
            .find(|tool| tool.name == *canonical)
            .cloned()
        {
            runtime_tools.push(ToolDef {
                name: alias.clone(),
                description: format!("Alias for {}", tool.name),
                input_schema: tool.input_schema,
            });
        }
    }
    Ok(runtime_tools)
}

pub fn source_name(source: &SyncSource) -> &'static str {
    match source {
        SyncSource::Openapi => "openapi",
        SyncSource::Django => "django",
        SyncSource::Flask => "flask",
        SyncSource::Db => "db",
        SyncSource::Url => "url",
        SyncSource::Mcp => "mcp",
        SyncSource::Rails => "rails",
        SyncSource::Laravel => "laravel",
        SyncSource::Aspnet => "aspnet",
        SyncSource::Strapi => "strapi",
        SyncSource::Supabase => "supabase",
        SyncSource::Plugin => "plugin",
    }
}