Merge branch 'feature/sdk-plugin-tooling-build-debug-surface' into develop

This commit is contained in:
2026-08-02 13:37:02 +02:00
57 changed files with 7884 additions and 115 deletions

View File

@ -0,0 +1,39 @@
---
issueRef: "#123"
version: 4
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785670261241
---
## Contexte
Le besoin initial vient dun futur plugin orienté développement Android, mais le périmètre validé pour ce chantier est strictement **SDK générique**. Lobjectif nest pas dajouter des API Android-first, mais de combler les trous du SDK public qui empêchent aujourdhui tout plugin de développement un peu sérieux.
## Ce qui existe déjà
- Manifest public `idea-plugin.json`
- Runtime `activate(ctx)`
- `commands`, `storage`, `logger`
- `services.workspace`, `services.tasks`, `services.terminal`
- Contributions `menus`, `menuItems`, `layouts`, `mcpServers`
## Problème
Le SDK public actuel est volontairement minimal. Il permet des plugins simples, mais pas un plugin doutillage qui doit agir sur un workspace, lancer des outils externes, réagir aux événements du host, afficher une UI riche, ou analyser la structure dun projet.
## Décision de cadrage
Découper le besoin en tickets transverses, indépendants autant que possible.
Ordre de priorité retenu :
1. `#124` API fichiers/workspace
2. `#125` API lancement de commandes et tâches
3. `#126` API découverte/validation doutillage externe
4. `#127` API dévénements et de watch
5. `#128` runtime UI/layout publique
6. `#129` API danalyse/requête de structure projet
7. `#130` API de documents de configuration structurés
## Garde-fous
- Pas dAPI spécifique Android dans ce lot.
- Préserver une frontière SDK public vs runtime interne.
- Favoriser des primitives génériques réutilisables pour Android, iOS, Node, Python, Docker, etc.
- Éviter de forcer les plugins à dépendre de casts ad hoc ou dobjets runtime internes.
## Définition de done du parapluie
Le parapluie est clôturable quand les tickets enfants retenus pour le MVP sont livrés ou explicitement re-scopeés avec arbitrage.

View File

@ -0,0 +1,17 @@
---
id: "0013caf7-bbc9-439f-82b2-9d23ed9e901a"
number: 123
title: "SDK plugins: combler les capacités globales manquantes pour les plugins de développement outillés"
status: "qa"
priority: "high"
sprint: null
links: []
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662012603
updatedAt: 1785670261241
version: 4
---
Ticket parapluie pour structurer lextension du SDK public des plugins IdeA afin de supporter des plugins de développement avancés sans introduire dAPI métier spécifiques à une stack donnée. Le besoin initial vient du cas Android, mais le périmètre doit rester strictement transversal.

View File

@ -0,0 +1,39 @@
---
issueRef: "#124"
version: 4
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785666067073
---
## Problème
`WorkspaceService` public expose aujourdhui seulement le projet courant, son root, et la lecture/écriture du contexte Markdown IdeA. Cela ne suffit pas pour un plugin de développement qui doit lire, écrire, lister ou surveiller les fichiers dun projet.
## Pourquoi cest global
Ce besoin na rien de spécifique à Android. Tout plugin de dev outillé doit pouvoir manipuler le workspace : configs, manifests, scripts, sources, fichiers générés, assets, etc.
## Ce que ce ticket doit produire
Une API publique de workspace/fichiers permettant au minimum :
- lecture de fichier texte/binaire
- écriture atomique ou contrôlée
- listing de répertoires
- existence/stat basiques
- résolution sûre de chemins dans le project root
- capacité de watch ou point dextension compatible avec `#127`
## Contraintes darchitecture
- API strictement publique côté SDK TypeScript.
- Aucun accès direct aux objets runtime internes.
- Respect du sandboxing et du project root.
- Contrat clair sur les erreurs, encodages, chemins hors-root et fichiers absents.
## Non-objectifs
- Pas de parser Gradle/XML/JSON dans ce ticket.
- Pas danalyse sémantique du projet.
- Pas de conventions Android codées en dur.
## Dépendances
- Bloque `#126`, `#129`, `#130`.
## Critères dacceptation
- Un plugin peut lire/écrire/lister dans le workspace sans cast interne.
- Le contrat gère explicitement les chemins invalides/hors-root.
- La documentation SDK montre un exemple simple de manipulation de fichiers.

View File

@ -0,0 +1,17 @@
---
id: "639787e1-83b5-49b7-a89f-3a6985129163"
number: 124
title: "SDK plugins: exposer une API publique daccès fichiers/workspace"
status: "qa"
priority: "critical"
sprint: null
links: [{"target":"#123","kind":"blocks"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026640
updatedAt: 1785666067073
version: 4
---
Ajouter au SDK plugin une API publique de lecture/écriture/listing/watch dans le workspace projet, distincte du simple accès au contexte Markdown IdeA.

View File

@ -0,0 +1,40 @@
---
issueRef: "#125"
version: 4
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785667057177
---
## Problème
Le SDK public permet seulement :
- dobserver/contrôler des background tasks existantes
- douvrir un PTY interactif
Il manque une API publique pour **démarrer** une commande/outillage externe de façon intégrée à IdeA.
## Pourquoi cest global
Le besoin est transversal à tous les plugins de développement : build, test, lint, génération, outils CLI, pipelines locaux, simulateurs, wrappers maison.
## Ce que ce ticket doit produire
Une API publique de lancement de commandes/tâches permettant au minimum :
- exécuter une commande avec `cwd`, args, env
- choisir un mode tracked/background task plutôt quun PTY brut
- suivre statut, exit code, stdout/stderr
- annuler / éventuellement relancer
- corréler le run avec le modèle Work dIdeA
## Contraintes darchitecture
- Ne pas confondre terminal interactif et task runner.
- Contrat stable sur environnement, cwd, timeouts éventuels, sortie et erreurs.
- Le plugin ne doit pas avoir à bricoler une session PTY pour lancer un build.
## Non-objectifs
- Pas de sémantique Android/Gradle/adb.
- Pas dorchestration multi-étapes spécifique à une stack.
## Dépendances
- Bloque `#126`.
## Critères dacceptation
- Un plugin peut lancer une commande externe sans passer par un cast interne ni un PTY interactif.
- Lexécution remonte un état observable et un résultat terminal clair.
- Le contrat est documenté côté SDK avec exemple de commande simple.

View File

@ -0,0 +1,17 @@
---
id: "78bb45fb-6320-4d75-8db2-1e2a9591219f"
number: 125
title: "SDK plugins: exposer une API publique de lancement de commandes et tâches"
status: "qa"
priority: "critical"
sprint: null
links: [{"target":"#123","kind":"blocks"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026655
updatedAt: 1785667057177
version: 4
---
Ajouter au SDK plugin une API publique pour lancer des commandes/outils externes et suivre leur exécution comme tâches IdeA, au-delà de lobservation des tâches existantes et du simple PTY interactif.

View File

@ -0,0 +1,36 @@
---
issueRef: "#126"
version: 7
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785668062783
---
## Problème
Un plugin de dev a souvent besoin de savoir si un outillage externe existe, où il se trouve, quelle version est installée, et si lenvironnement est valide. Le SDK public nexpose pas aujourdhui cette capacité comme primitive générique.
## Pourquoi cest global
Ce besoin vaut pour Android SDK, Java, Node, Python, Docker, Go, Rust toolchain, etc. Le ticket doit fournir une abstraction générique de découverte/validation doutillage, pas une API dédiée Android.
## Ce que ce ticket doit produire
Une API publique permettant idéalement :
- résolution dun exécutable ou dune toolchain par nom/id
- lecture de version
- inspection de variables denvironnement pertinentes
- validation de prérequis déclaratifs
- restitution dun diagnostic structuré exploitable par une UI plugin
## Contraintes darchitecture
- La source de vérité peut sappuyer sur fichiers, env et exécution doutils, mais lAPI exposée doit rester stable et agnostique.
- Ne pas figer de modèle métier Android.
## Dépendances
- Dépend de `#124` pour laccès workspace/config.
- Dépend de `#125` pour lexécution contrôlée des commandes de détection.
## Non-objectifs
- Pas de gestion démulateur/device manager.
- Pas dinstallation automatique dune toolchain dans ce ticket.
## Critères dacceptation
- Un plugin peut diagnostiquer la présence/absence dun outillage externe de façon structurée.
- Le diagnostic est assez générique pour servir plusieurs stacks.
- La doc SDK montre un cas simple de détection dexécutable/version.

View File

@ -0,0 +1,17 @@
---
id: "51d4f4b0-4482-4400-a0d5-9f88471581f0"
number: 126
title: "SDK plugins: exposer une API publique de découverte/validation doutillage externe"
status: "qa"
priority: "high"
sprint: null
links: [{"target":"#123","kind":"blocks"},{"target":"#124","kind":"dependsOn"},{"target":"#125","kind":"dependsOn"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026684
updatedAt: 1785668062783
version: 7
---
Ajouter au SDK plugin une API publique pour détecter, valider et décrire des toolchains externes (exécutables, versions, variables denvironnement, prérequis) sans spécialiser le SDK pour une stack donnée.

View File

@ -0,0 +1,35 @@
---
issueRef: "#127"
version: 4
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785669121141
---
## Problème
Sans bus dévénements ou API de watch publique, un plugin doit poller létat du host ou du workspace pour se tenir à jour. Cest coûteux, fragile et peu réactif.
## Pourquoi cest global
Tout plugin de dev outillé peut avoir besoin de réagir à :
- changement de fichier
- fin/échec dune tâche
- changement de projet courant
- autres événements système ou host pertinents
## Ce que ce ticket doit produire
Une API publique dabonnement permettant au minimum :
- souscription/désinscription propre
- typage minimal des événements publics
- événements documentés et versionnables
- stratégie claire sur rétention/perte dévénements
## Contraintes darchitecture
- Exposer uniquement des événements publics stables.
- Ne pas refléter brut de décoffrage les événements internes du host.
- Bien définir les garanties: best effort vs livraison fiable.
## Non-objectifs
- Pas de protocole temps réel cross-process complexe si non nécessaire.
- Pas dévénements spécifiques Android.
## Critères dacceptation
- Un plugin peut se mettre à jour sur changements du workspace/host sans polling permanent.
- LAPI de subscription est proprement disposable et documentée.

View File

@ -0,0 +1,17 @@
---
id: "9b238559-9982-4a69-8795-99da8a46be1e"
number: 127
title: "SDK plugins: exposer une API publique dévénements et de watch"
status: "qa"
priority: "high"
sprint: null
links: [{"target":"#123","kind":"blocks"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026701
updatedAt: 1785669121141
version: 4
---
Ajouter au SDK plugin une API publique dabonnement aux événements utiles du host et du projet: changements de fichiers, évolution des tâches, focus projet et autres signaux nécessaires pour éviter le polling côté plugin.

View File

@ -0,0 +1,31 @@
---
issueRef: "#128"
version: 4
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785670260985
---
## Problème
Le manifeste expose déjà des contributions `layouts`, mais la runtime publique ne formalise pas proprement lenregistrement et le cycle de vie de ces layouts. Lexemple SDK actuel contourne la surface avec des casts ad hoc.
## Pourquoi cest global
Ce nest pas spécifique à Android: tout plugin de dev peut vouloir afficher un panneau détat, un tableau, un viewer de logs, une vue de diagnostic, etc.
## Ce que ce ticket doit produire
Une runtime UI/layout publique stable permettant au minimum :
- enregistrement typé dun layout
- props publiques documentées
- cycle de vie clair
- persistance/lecture de state si le host la supporte
- retrait propre via disposable
## Contraintes darchitecture
- Pas de dépendance à des détails runtime privés.
- Contrat explicite sur le rendu et la sérialisation du state plugin.
## Non-objectifs
- Pas dimposer un design system plugin complet.
- Pas dAPI spécifique aux vues Android.
## Critères dacceptation
- Lexemple SDK na plus besoin de cast ad hoc pour enregistrer un layout.
- La surface publique suffit pour un panneau plugin de dev non trivial.

View File

@ -0,0 +1,17 @@
---
id: "053f079d-1dfd-48bb-85a2-2dfa8d237999"
number: 128
title: "SDK plugins: typer et stabiliser la runtime UI/layout publique"
status: "qa"
priority: "medium"
sprint: null
links: [{"target":"#123","kind":"blocks"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026717
updatedAt: 1785670260985
version: 4
---
Formaliser la surface runtime publique pour les contributions UI/layout des plugins afin déviter les casts ad hoc et de permettre des panneaux/plugins de dev riches sur base stable.

View File

@ -0,0 +1,30 @@
---
issueRef: "#129"
version: 5
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785666067171
---
## Problème
Chaque plugin de développement devrait aujourdhui rescanner lui-même le workspace pour reconstruire une vision de la structure projet. Cela duplique les heuristiques et rend lécosystème fragile.
## Pourquoi cest global
Android nest quun cas parmi dautres. Les plugins pour monorepos JS, workspaces Rust, Python multi-env, etc. ont tous besoin dune lecture structurée minimale du projet.
## Ce que ce ticket doit produire
Une API publique danalyse/requête permettant idéalement :
- liste de fichiers ou sous-ensembles pertinents
- conventions détectées
- modules/units logiques quand connus
- graphes simples ou métadonnées projet de base
- résultats structurés et bornés, pas un AST universel magique
## Dépendances
- Dépend de `#124` car lanalyse repose au minimum sur laccès contrôlé au workspace.
## Non-objectifs
- Pas dindexation sémantique profonde de tous les langages.
- Pas de modèle Android-only (Gradle modules, variants, etc.) dans lAPI publique de base.
## Critères dacceptation
- Un plugin peut interroger la structure du projet sans rescanner tout le disque lui-même.
- Le contrat reste utile à plusieurs stacks et ne fuit pas des abstractions internes.

View File

@ -0,0 +1,17 @@
---
id: "550fe7ca-8a25-4529-be2e-2fd79c7ddde4"
number: 129
title: "SDK plugins: exposer une API publique danalyse/requête de structure projet"
status: "qa"
priority: "medium"
sprint: null
links: [{"target":"#123","kind":"blocks"},{"target":"#124","kind":"dependsOn"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026738
updatedAt: 1785666067171
version: 5
---
Ajouter au SDK plugin une API publique pour interroger la structure dun projet (fichiers, modules, graphes simples, conventions détectées) sans obliger chaque plugin à rescanner le workspace depuis zéro.

View File

@ -0,0 +1,31 @@
---
issueRef: "#130"
version: 5
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedAt: 1785669830933
---
## Problème
Un plugin de développement doit souvent lire ou modifier des documents structurés. Sans primitive publique, chaque plugin doit réimplémenter parsing, validation et patching, avec un risque élevé de corruption ou dincohérence.
## Pourquoi cest global
Le besoin concerne JSON, YAML, TOML, XML, propriétés, DSL de config, et potentiellement dautres formats. Android nest quun consommateur parmi dautres.
## Ce que ce ticket doit produire
Une API publique de documents/config structurés permettant idéalement :
- lecture dun document typé ou semi-structuré
- édition contrôlée/patch ciblé
- sérialisation stable
- erreurs structurées
- capacité dévolution format par format
## Dépendances
- Dépend de `#124` car il faut dabord un accès fichier/workspace public.
## Garde-fous
- Commencer petit si nécessaire; ne pas promettre tous les formats dun coup.
- Préférer une abstraction extensible plutôt quun parser universel monolithique.
- Ne pas embarquer des helpers Android-only.
## Critères dacceptation
- Le SDK expose une primitive réutilisable pour lire et mettre à jour un document de config sans bricolage spécifique par plugin.
- Le contrat précise clairement quels formats sont supportés dans le premier lot.

View File

@ -0,0 +1,17 @@
---
id: "07a76880-f176-4fc8-b1d3-732a88a8c837"
number: 130
title: "SDK plugins: exposer une API publique de documents de configuration structurés"
status: "qa"
priority: "medium"
sprint: null
links: [{"target":"#123","kind":"blocks"},{"target":"#124","kind":"dependsOn"}]
agentRefs: []
attachments: []
createdBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
updatedBy: {"kind":"agent","agent_id":"a6ced819-b893-4213-b003-9e9dc79b9641"}
createdAt: 1785662026750
updatedAt: 1785669830933
version: 5
---
Ajouter au SDK plugin une API publique pour lire/mettre à jour des documents de configuration structurés via un modèle générique plutôt que forcer chaque plugin à réimplémenter son parsing/patching.

View File

@ -1,3 +1,3 @@
{
"nextNumber": 123
"nextNumber": 131
}

View File

@ -1594,6 +1594,118 @@
"kind": "user"
},
"updatedAt": 1785592528432
},
{
"issueRef": "#123",
"path": "123",
"title": "SDK plugins: combler les capacités globales manquantes pour les plugins de développement outillés",
"status": "qa",
"priority": "high",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785670261241
},
{
"issueRef": "#124",
"path": "124",
"title": "SDK plugins: exposer une API publique daccès fichiers/workspace",
"status": "qa",
"priority": "critical",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785666067073
},
{
"issueRef": "#125",
"path": "125",
"title": "SDK plugins: exposer une API publique de lancement de commandes et tâches",
"status": "qa",
"priority": "critical",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785667057177
},
{
"issueRef": "#126",
"path": "126",
"title": "SDK plugins: exposer une API publique de découverte/validation doutillage externe",
"status": "qa",
"priority": "high",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785668062783
},
{
"issueRef": "#127",
"path": "127",
"title": "SDK plugins: exposer une API publique dévénements et de watch",
"status": "qa",
"priority": "high",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785669121141
},
{
"issueRef": "#128",
"path": "128",
"title": "SDK plugins: typer et stabiliser la runtime UI/layout publique",
"status": "qa",
"priority": "medium",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785670260985
},
{
"issueRef": "#129",
"path": "129",
"title": "SDK plugins: exposer une API publique danalyse/requête de structure projet",
"status": "qa",
"priority": "medium",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785666067171
},
{
"issueRef": "#130",
"path": "130",
"title": "SDK plugins: exposer une API publique de documents de configuration structurés",
"status": "qa",
"priority": "medium",
"sprint": null,
"assignedAgentIds": [],
"createdBy": {
"kind": "agent",
"agent_id": "a6ced819-b893-4213-b003-9e9dc79b9641"
},
"updatedAt": 1785669830933
}
]
}

View File

@ -56,3 +56,4 @@ vector-onnx = ["infrastructure/vector-onnx", "backend/vector-onnx"]
[dev-dependencies]
uuid = { workspace = true }
async-trait = { workspace = true }
tauri = { workspace = true, features = ["test"] }

View File

@ -397,6 +397,21 @@ pub fn run() {
plugins::plugin_set_enabled,
plugins::plugin_uninstall,
plugins::plugin_list_runtime_contributions,
plugins::plugin_workspace_read_text,
plugins::plugin_workspace_read_binary,
plugins::plugin_workspace_write_text,
plugins::plugin_workspace_write_binary,
plugins::plugin_workspace_list_dir,
plugins::plugin_workspace_stat,
plugins::plugin_query_project_structure,
plugins::plugin_config_read_document,
plugins::plugin_config_update_document,
plugins::plugin_task_run_command,
plugins::plugin_task_get_status,
plugins::plugin_toolchain_diagnose,
plugins::plugin_events_subscribe,
plugins::plugin_events_poll,
plugins::plugin_events_unsubscribe,
plugins::plugin_open_plugins_folder,
commands::get_server_exposure_settings,
commands::save_server_exposure_settings,
@ -415,6 +430,28 @@ pub fn run() {
.expect("error while running IdeA Tauri application");
}
#[cfg(test)]
fn plugin_workspace_invoke_handler<R: tauri::Runtime>(
) -> impl Fn(tauri::ipc::Invoke<R>) -> bool + Send + Sync + 'static {
tauri::generate_handler![
plugins::plugin_workspace_read_text,
plugins::plugin_workspace_read_binary,
plugins::plugin_workspace_write_text,
plugins::plugin_workspace_write_binary,
plugins::plugin_workspace_list_dir,
plugins::plugin_workspace_stat,
plugins::plugin_query_project_structure,
plugins::plugin_config_read_document,
plugins::plugin_config_update_document,
plugins::plugin_task_run_command,
plugins::plugin_task_get_status,
plugins::plugin_toolchain_diagnose,
plugins::plugin_events_subscribe,
plugins::plugin_events_poll,
plugins::plugin_events_unsubscribe,
]
}
async fn app_exit_work_guard_state(
handle: &tauri::AppHandle,
) -> Result<application::AppExitWorkGuardState, AppError> {
@ -713,6 +750,7 @@ fn persisted_monitor_is_available(
#[cfg(test)]
mod tests {
use super::plugin_workspace_invoke_handler;
use super::{
apply_main_close_decision, confirm_next_main_window_close, consume_exit_guard_confirmation,
decide_main_close_action, persisted_view_identity_from_label, persisted_window_identity,
@ -720,7 +758,10 @@ mod tests {
};
use super::{should_close_with_main_window, PersistedWindowKind};
use application::AppExitWorkGuardState;
use serde_json::json;
use std::cell::Cell;
use std::time::{SystemTime, UNIX_EPOCH};
use tauri::test::{get_ipc_response, mock_builder, mock_context, noop_assets, INVOKE_KEY};
#[test]
fn main_close_without_work_allows_shutdown_without_preventing_close() {
@ -880,4 +921,289 @@ mod tests {
);
assert!(persisted_window_identity("view-tickets-not-a-project").is_none());
}
#[test]
fn dto_plugins_workspace_commands_are_registered_in_tauri_invoke_handler() {
let app_data = test_app_data_dir("plugin-workspace-commands");
let app = mock_builder()
.manage(crate::state::AppState::build(app_data.clone()))
.invoke_handler(plugin_workspace_invoke_handler())
.build(mock_context(noop_assets()))
.expect("mock app builds");
let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.expect("mock webview builds");
let missing_project = uuid::Uuid::from_u128(124).to_string();
for command in [
"plugin_workspace_read_text",
"plugin_workspace_read_binary",
"plugin_workspace_list_dir",
"plugin_workspace_stat",
"plugin_query_project_structure",
] {
let err = invoke_plugin_command(
&webview,
command,
json!({
"input": {
"projectId": missing_project.clone(),
"path": "src/main.rs",
"maxDepth": 2,
"maxEntries": 10
}
}),
)
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND", "{command}");
}
for (command, input) in [
(
"plugin_workspace_write_text",
json!({
"projectId": missing_project.clone(),
"path": "generated.txt",
"content": "hello\n"
}),
),
(
"plugin_workspace_write_binary",
json!({
"projectId": missing_project.clone(),
"path": "generated.bin",
"bytes": [1, 2, 3]
}),
),
] {
let err = invoke_plugin_command(&webview, command, json!({ "input": input }))
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND", "{command}");
}
std::fs::remove_dir_all(app_data).ok();
}
#[test]
fn dto_plugins_config_document_commands_are_registered_in_tauri_invoke_handler() {
let app_data = test_app_data_dir("plugin-config-document-commands");
let app = mock_builder()
.manage(crate::state::AppState::build(app_data.clone()))
.invoke_handler(plugin_workspace_invoke_handler())
.build(mock_context(noop_assets()))
.expect("mock app builds");
let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.expect("mock webview builds");
let missing_project = uuid::Uuid::from_u128(130).to_string();
let err = invoke_plugin_command(
&webview,
"plugin_config_read_document",
json!({
"input": {
"projectId": missing_project.clone(),
"path": "config/settings.json",
"format": "json"
}
}),
)
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND");
let err = invoke_plugin_command(
&webview,
"plugin_config_update_document",
json!({
"input": {
"projectId": missing_project,
"path": "config/settings.json",
"format": "json",
"mode": "mergePatch",
"value": {"enabled": true}
}
}),
)
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND");
std::fs::remove_dir_all(app_data).ok();
}
#[test]
fn dto_plugins_command_task_commands_are_registered_in_tauri_invoke_handler() {
let app_data = test_app_data_dir("plugin-task-commands");
let app = mock_builder()
.manage(crate::state::AppState::build(app_data.clone()))
.invoke_handler(plugin_workspace_invoke_handler())
.build(mock_context(noop_assets()))
.expect("mock app builds");
let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.expect("mock webview builds");
let missing_project = uuid::Uuid::from_u128(125).to_string();
let owner = uuid::Uuid::from_u128(126).to_string();
let err = invoke_plugin_command(
&webview,
"plugin_task_run_command",
json!({
"input": {
"projectId": missing_project,
"ownerAgentId": owner,
"label": "cargo test",
"command": "cargo",
"args": ["test"],
"cwd": ".",
"env": [["RUST_LOG", "debug"]],
"recordOnly": true
}
}),
)
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND");
let task_id = uuid::Uuid::from_u128(127).to_string();
let value = invoke_plugin_command(
&webview,
"plugin_task_get_status",
json!({
"input": {
"taskId": task_id
}
}),
)
.expect("unknown task is a successful empty status");
assert_eq!(value, serde_json::Value::Null);
std::fs::remove_dir_all(app_data).ok();
}
#[test]
fn dto_plugins_toolchain_diagnostic_command_is_registered_in_tauri_invoke_handler() {
let app_data = test_app_data_dir("plugin-toolchain-diagnostic-command");
let app = mock_builder()
.manage(crate::state::AppState::build(app_data.clone()))
.invoke_handler(plugin_workspace_invoke_handler())
.build(mock_context(noop_assets()))
.expect("mock app builds");
let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.expect("mock webview builds");
let missing_project = uuid::Uuid::from_u128(126).to_string();
let err = invoke_plugin_command(
&webview,
"plugin_toolchain_diagnose",
json!({
"input": {
"projectId": missing_project,
"cwd": ".",
"tools": [{
"id": "rust",
"executable": "cargo",
"versionArgs": ["--version"],
"required": true
}],
"env": [{
"name": "RUSTUP_HOME",
"required": false
}],
"files": [{
"path": "Cargo.toml",
"required": true,
"kind": "file"
}]
}
}),
)
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND");
std::fs::remove_dir_all(app_data).ok();
}
#[test]
fn dto_plugins_event_commands_are_registered_in_tauri_invoke_handler() {
let app_data = test_app_data_dir("plugin-event-commands");
let app = mock_builder()
.manage(crate::state::AppState::build(app_data.clone()))
.invoke_handler(plugin_workspace_invoke_handler())
.build(mock_context(noop_assets()))
.expect("mock app builds");
let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.expect("mock webview builds");
let missing_project = uuid::Uuid::from_u128(127).to_string();
let err = invoke_plugin_command(
&webview,
"plugin_events_subscribe",
json!({
"input": {
"projectId": missing_project,
"eventTypes": ["workspaceFileChanged", "backgroundTaskChanged"],
"capacity": 10
}
}),
)
.expect_err("missing project must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND");
let subscription_id = uuid::Uuid::from_u128(128).to_string();
let err = invoke_plugin_command(
&webview,
"plugin_events_poll",
json!({
"input": {
"subscriptionId": subscription_id.clone(),
"maxEvents": 10
}
}),
)
.expect_err("unknown subscription must surface through the registered command");
assert_eq!(err["code"], "NOT_FOUND");
let disposed = invoke_plugin_command(
&webview,
"plugin_events_unsubscribe",
json!({
"input": {
"subscriptionId": subscription_id
}
}),
)
.expect("unsubscribe is idempotent");
assert_eq!(disposed["retention"], "disposed");
std::fs::remove_dir_all(app_data).ok();
}
fn invoke_plugin_command<W: AsRef<tauri::Webview<tauri::test::MockRuntime>>>(
webview: &W,
command: &str,
body: serde_json::Value,
) -> Result<serde_json::Value, serde_json::Value> {
get_ipc_response(
webview,
tauri::webview::InvokeRequest {
cmd: command.to_owned(),
callback: tauri::ipc::CallbackFn(0),
error: tauri::ipc::CallbackFn(1),
url: "tauri://localhost".parse().unwrap(),
body: tauri::ipc::InvokeBody::Json(body),
headers: Default::default(),
invoke_key: INVOKE_KEY.to_owned(),
},
)
.map(|body| body.deserialize::<serde_json::Value>().unwrap())
}
fn test_app_data_dir(label: &str) -> std::path::PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
std::env::temp_dir().join(format!("idea-{label}-{}-{nanos}", std::process::id()))
}
}

View File

@ -5,8 +5,16 @@ use std::path::{Path, PathBuf};
use application::{ReviewPluginPackageInput, SetPluginEnabledInput, UninstallPluginInput};
use backend::dto::{
ErrorDto, PluginAdminDto, PluginInstallResultDto, PluginReviewDto,
PluginRuntimeContributionCatalogDto, PluginUninstallResultDto, ReviewPluginPackageDto,
ErrorDto, PluginAdminDto, PluginConfigDocumentDto, PluginConfigDocumentReadDto,
PluginConfigDocumentUpdateDto, PluginConfigDocumentWriteResultDto, PluginEventBatchDto,
PluginEventPollDto, PluginEventSubscribeDto, PluginEventSubscriptionDto,
PluginEventUnsubscribeDto, PluginInstallResultDto, PluginProjectStructureDto,
PluginProjectStructureQueryDto, PluginReviewDto, PluginRunCommandDto,
PluginRuntimeContributionCatalogDto, PluginTaskDto, PluginTaskStatusDto,
PluginToolchainDiagnosticDto, PluginToolchainDiagnosticRequestDto, PluginUninstallResultDto,
PluginWorkspaceBinaryFileDto, PluginWorkspaceDirectoryListingDto, PluginWorkspacePathDto,
PluginWorkspaceStatDto, PluginWorkspaceTextFileDto, PluginWorkspaceWriteBinaryDto,
PluginWorkspaceWriteTextDto, ReviewPluginPackageDto,
};
use domain::ports::{PluginManifestValidator, PluginPackageStore, PluginRegistryStore};
use domain::{PluginId, RelativePath};
@ -156,6 +164,198 @@ pub async fn plugin_list_runtime_contributions(
.map_err(ErrorDto::from)
}
/// Reads a UTF-8 workspace file for the public plugin API.
#[tauri::command]
pub async fn plugin_workspace_read_text(
input: PluginWorkspacePathDto,
state: State<'_, AppState>,
) -> Result<PluginWorkspaceTextFileDto, ErrorDto> {
state
.plugin_workspace_access
.read_text(input.into())
.await
.map_err(ErrorDto::from)
}
/// Reads a binary workspace file for the public plugin API.
#[tauri::command]
pub async fn plugin_workspace_read_binary(
input: PluginWorkspacePathDto,
state: State<'_, AppState>,
) -> Result<PluginWorkspaceBinaryFileDto, ErrorDto> {
state
.plugin_workspace_access
.read_binary(input.into())
.await
.map_err(ErrorDto::from)
}
/// Writes a UTF-8 workspace file for the public plugin API.
#[tauri::command]
pub async fn plugin_workspace_write_text(
input: PluginWorkspaceWriteTextDto,
state: State<'_, AppState>,
) -> Result<(), ErrorDto> {
state
.plugin_workspace_access
.write_text(input.into())
.await
.map_err(ErrorDto::from)
}
/// Writes a binary workspace file for the public plugin API.
#[tauri::command]
pub async fn plugin_workspace_write_binary(
input: PluginWorkspaceWriteBinaryDto,
state: State<'_, AppState>,
) -> Result<(), ErrorDto> {
state
.plugin_workspace_access
.write_binary(input.into())
.await
.map_err(ErrorDto::from)
}
/// Lists a workspace directory for the public plugin API.
#[tauri::command]
pub async fn plugin_workspace_list_dir(
input: PluginWorkspacePathDto,
state: State<'_, AppState>,
) -> Result<PluginWorkspaceDirectoryListingDto, ErrorDto> {
state
.plugin_workspace_access
.list_dir(input.into())
.await
.map_err(ErrorDto::from)
}
/// Stats a workspace path for the public plugin API.
#[tauri::command]
pub async fn plugin_workspace_stat(
input: PluginWorkspacePathDto,
state: State<'_, AppState>,
) -> Result<PluginWorkspaceStatDto, ErrorDto> {
state
.plugin_workspace_access
.stat(input.into())
.await
.map_err(ErrorDto::from)
}
/// Queries a bounded generic project structure for the public plugin API.
#[tauri::command]
pub async fn plugin_query_project_structure(
input: PluginProjectStructureQueryDto,
state: State<'_, AppState>,
) -> Result<PluginProjectStructureDto, ErrorDto> {
state
.query_project_structure
.execute(input.into())
.await
.map_err(ErrorDto::from)
}
/// Reads a structured configuration document for the public plugin API.
#[tauri::command]
pub async fn plugin_config_read_document(
input: PluginConfigDocumentReadDto,
state: State<'_, AppState>,
) -> Result<PluginConfigDocumentDto, ErrorDto> {
state
.plugin_config_documents
.read(input.into())
.await
.map_err(ErrorDto::from)
}
/// Updates a structured configuration document for the public plugin API.
#[tauri::command]
pub async fn plugin_config_update_document(
input: PluginConfigDocumentUpdateDto,
state: State<'_, AppState>,
) -> Result<PluginConfigDocumentWriteResultDto, ErrorDto> {
state
.plugin_config_documents
.update(input.into())
.await
.map_err(ErrorDto::from)
}
/// Launches a command-backed background task for the public plugin API.
#[tauri::command]
pub async fn plugin_task_run_command(
input: PluginRunCommandDto,
state: State<'_, AppState>,
) -> Result<PluginTaskDto, ErrorDto> {
state
.plugin_command_tasks
.run_command(input.into())
.await
.map(PluginTaskDto::from)
.map_err(ErrorDto::from)
}
/// Reads one command task status for the public plugin API.
#[tauri::command]
pub async fn plugin_task_get_status(
input: PluginTaskStatusDto,
state: State<'_, AppState>,
) -> Result<Option<PluginTaskDto>, ErrorDto> {
state
.plugin_command_tasks
.get_status(input.into())
.await
.map(|task| task.map(PluginTaskDto::from))
.map_err(ErrorDto::from)
}
/// Diagnoses generic external toolchain prerequisites for the public plugin API.
#[tauri::command]
pub async fn plugin_toolchain_diagnose(
input: PluginToolchainDiagnosticRequestDto,
state: State<'_, AppState>,
) -> Result<PluginToolchainDiagnosticDto, ErrorDto> {
state
.plugin_toolchain_diagnostics
.diagnose(input.into())
.await
.map_err(ErrorDto::from)
}
/// Subscribes to stable public plugin events.
#[tauri::command]
pub async fn plugin_events_subscribe(
input: PluginEventSubscribeDto,
state: State<'_, AppState>,
) -> Result<PluginEventSubscriptionDto, ErrorDto> {
state
.plugin_event_subscriptions
.subscribe(input.into())
.await
.map_err(ErrorDto::from)
}
/// Drains retained public plugin events for one subscription.
#[tauri::command]
pub fn plugin_events_poll(
input: PluginEventPollDto,
state: State<'_, AppState>,
) -> Result<PluginEventBatchDto, ErrorDto> {
state
.plugin_event_subscriptions
.poll(input.into())
.map_err(ErrorDto::from)
}
/// Disposes a public plugin event subscription.
#[tauri::command]
pub fn plugin_events_unsubscribe(
input: PluginEventUnsubscribeDto,
state: State<'_, AppState>,
) -> PluginEventSubscriptionDto {
state.plugin_event_subscriptions.unsubscribe(input.into())
}
/// Opens the plugin store folder, or one plugin folder when an id is provided.
#[tauri::command]
pub fn plugin_open_plugins_folder(

View File

@ -17,11 +17,12 @@ use std::sync::Arc;
use domain::ports::{
BackgroundTaskPortError, BackgroundTaskRunner, BackgroundTaskSpec, BackgroundTaskStore, Clock,
IdGenerator, SpawnSpec,
EventBus, IdGenerator, SpawnSpec,
};
use domain::{
AgentId, BackgroundTask, BackgroundTaskKind, BackgroundTaskRendezvousLink,
BackgroundTaskResult, BackgroundTaskState, BackgroundTaskWakePolicy, ProjectId, TaskId,
BackgroundTaskResult, BackgroundTaskState, BackgroundTaskWakePolicy, DomainEvent, ProjectId,
TaskId,
};
use crate::error::AppError;
@ -71,6 +72,7 @@ pub struct SpawnBackgroundCommand {
runner: Arc<dyn BackgroundTaskRunner>,
clock: Arc<dyn Clock>,
ids: Arc<dyn IdGenerator>,
events: Option<Arc<dyn EventBus>>,
}
impl SpawnBackgroundCommand {
@ -87,9 +89,17 @@ impl SpawnBackgroundCommand {
runner,
clock,
ids,
events: None,
}
}
/// Attaches the public event stream publisher.
#[must_use]
pub fn with_events(mut self, events: Arc<dyn EventBus>) -> Self {
self.events = Some(events);
self
}
/// Allocates a task id, persists it (`Queued`→`Running`) and spawns it.
///
/// # Errors
@ -145,6 +155,19 @@ impl SpawnBackgroundCommand {
.transition(BackgroundTaskState::Running, now)
.map_err(|e| AppError::Invalid(e.to_string()))?;
self.store.save(&running).await.map_err(map_port_err)?;
if let Some(events) = &self.events {
events.publish(DomainEvent::BackgroundTaskStarted {
project_id,
task_id,
owner_agent_id,
});
events.publish(DomainEvent::BackgroundTaskStateChanged {
project_id,
task_id,
owner_agent_id,
state: BackgroundTaskState::Running,
});
}
let spec = BackgroundTaskSpec {
task_id,
@ -168,6 +191,14 @@ impl SpawnBackgroundCommand {
}) {
let _ = self.store.save(&failed).await;
}
if let Some(events) = &self.events {
events.publish(DomainEvent::BackgroundTaskFailed {
project_id,
task_id,
owner_agent_id,
rendezvous: None,
});
}
return Err(map_port_err(err));
}

View File

@ -155,10 +155,23 @@ pub use permission::{
};
pub use plugin::{
InstallPluginFromArchive, InstallPluginFromDirectory, JsonPluginManifestValidator,
ListPluginRuntimeContributions, ListPlugins, PluginAdmin, PluginContributionSummary,
PluginInstallResult, PluginReview, PluginRuntimeCatalog, PluginRuntimePlugin,
ReconcilePluginMcpServers, ReviewPluginPackage, ReviewPluginPackageInput, SetPluginEnabled,
SetPluginEnabledInput, UninstallPlugin, UninstallPluginInput, UninstallPluginResult,
ListPluginRuntimeContributions, ListPlugins, PluginAdmin, PluginCommandTasks,
PluginConfigDocument, PluginConfigDocumentReadInput, PluginConfigDocumentUpdateInput,
PluginConfigDocumentWriteResult, PluginConfigDocuments, PluginContributionSummary,
PluginDiagnosticMessage, PluginEnvDiagnostic, PluginEnvRequirement, PluginEventBatch,
PluginEventPollInput, PluginEventSubscribeInput, PluginEventSubscription,
PluginEventSubscriptions, PluginEventUnsubscribeInput, PluginFileDiagnostic,
PluginFileRequirement, PluginInstallResult, PluginPublicEvent, PluginReview,
PluginRunCommandInput, PluginRuntimeCatalog, PluginRuntimePlugin, PluginTaskStatusInput,
PluginToolDiagnostic, PluginToolRequirement, PluginToolchainDiagnostic,
PluginToolchainDiagnosticInput, PluginToolchainDiagnostics, PluginWorkspaceAccess,
PluginWorkspaceBinaryFile, PluginWorkspaceDirEntry, PluginWorkspaceDirectoryListing,
PluginWorkspacePathInput, PluginWorkspaceStat, PluginWorkspaceTextFile,
PluginWorkspaceWriteBinaryInput, PluginWorkspaceWriteTextInput, ProjectConvention,
ProjectModule, ProjectStructureEntry, ProjectStructureQuery, QueryProjectStructure,
QueryProjectStructureInput, ReconcilePluginMcpServers, ReviewPluginPackage,
ReviewPluginPackageInput, SetPluginEnabled, SetPluginEnabledInput, UninstallPlugin,
UninstallPluginInput, UninstallPluginResult,
};
pub use project::{
CloseProject, CloseProjectInput, CloseProjectOutput, CloseTab, CloseTabInput, CreateProject,

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,7 @@
//! JSON convention already used in the domain (`agents.json` etc.).
use serde::{Deserialize, Serialize};
use serde_json::Value;
use application::{
AgentBackgroundTaskState, AgentTicketState, AppError, AppExitWorkGuardDetail,
@ -273,6 +274,408 @@ impl From<application::PluginRuntimePlugin> for PluginRuntimePluginDto {
}
}
/// Plugin workspace path request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginWorkspacePathDto {
/// Project id.
pub project_id: String,
/// Relative path under the project root.
pub path: String,
}
impl From<PluginWorkspacePathDto> for application::PluginWorkspacePathInput {
fn from(value: PluginWorkspacePathDto) -> Self {
Self {
project_id: value.project_id,
path: value.path,
}
}
}
/// Plugin workspace text write request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginWorkspaceWriteTextDto {
/// Project id.
pub project_id: String,
/// Relative path under the project root.
pub path: String,
/// UTF-8 content.
pub content: String,
}
impl From<PluginWorkspaceWriteTextDto> for application::PluginWorkspaceWriteTextInput {
fn from(value: PluginWorkspaceWriteTextDto) -> Self {
Self {
project_id: value.project_id,
path: value.path,
content: value.content,
}
}
}
/// Plugin workspace binary write request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginWorkspaceWriteBinaryDto {
/// Project id.
pub project_id: String,
/// Relative path under the project root.
pub path: String,
/// Raw bytes.
pub bytes: Vec<u8>,
}
impl From<PluginWorkspaceWriteBinaryDto> for application::PluginWorkspaceWriteBinaryInput {
fn from(value: PluginWorkspaceWriteBinaryDto) -> Self {
Self {
project_id: value.project_id,
path: value.path,
bytes: value.bytes,
}
}
}
/// Plugin structured config document read request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginConfigDocumentReadDto {
/// Project id.
pub project_id: String,
/// Relative path under the project root.
pub path: String,
/// Optional explicit format. Omitted means inferred from extension.
#[serde(default)]
pub format: Option<String>,
}
impl From<PluginConfigDocumentReadDto> for application::PluginConfigDocumentReadInput {
fn from(value: PluginConfigDocumentReadDto) -> Self {
Self {
project_id: value.project_id,
path: value.path,
format: value.format,
}
}
}
/// Plugin structured config document update request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginConfigDocumentUpdateDto {
/// Project id.
pub project_id: String,
/// Relative path under the project root.
pub path: String,
/// Optional explicit format. Omitted means inferred from extension.
#[serde(default)]
pub format: Option<String>,
/// Update mode: `mergePatch` (default) or `replace`.
#[serde(default)]
pub mode: Option<String>,
/// JSON replacement or merge patch.
pub value: Value,
}
impl From<PluginConfigDocumentUpdateDto> for application::PluginConfigDocumentUpdateInput {
fn from(value: PluginConfigDocumentUpdateDto) -> Self {
Self {
project_id: value.project_id,
path: value.path,
format: value.format,
mode: value.mode,
value: value.value,
}
}
}
/// Plugin project structure query request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginProjectStructureQueryDto {
/// Project id.
pub project_id: String,
/// Optional relative root path.
#[serde(default)]
pub path: Option<String>,
/// Optional traversal depth.
#[serde(default)]
pub max_depth: Option<u8>,
/// Optional entry cap.
#[serde(default)]
pub max_entries: Option<usize>,
}
impl From<PluginProjectStructureQueryDto> for application::QueryProjectStructureInput {
fn from(value: PluginProjectStructureQueryDto) -> Self {
Self {
project_id: value.project_id,
path: value.path,
max_depth: value.max_depth,
max_entries: value.max_entries,
}
}
}
/// Public plugin command-task launch request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginRunCommandDto {
/// Owning project id.
pub project_id: String,
/// Agent id used for Work correlation and completion wake delivery.
pub owner_agent_id: String,
/// Human-facing task label.
pub label: String,
/// Executable to run.
pub command: String,
/// Arguments passed without shell parsing.
#[serde(default)]
pub args: Vec<String>,
/// Relative working directory under project root. Empty/omitted means root.
#[serde(default)]
pub cwd: Option<String>,
/// Extra environment variables.
#[serde(default)]
pub env: Vec<(String, String)>,
/// When true, completion is only recorded; otherwise the owner is woken.
#[serde(default)]
pub record_only: bool,
/// Optional absolute deadline, epoch milliseconds.
#[serde(default)]
pub deadline_ms: Option<u64>,
}
impl From<PluginRunCommandDto> for application::PluginRunCommandInput {
fn from(value: PluginRunCommandDto) -> Self {
Self {
project_id: value.project_id,
owner_agent_id: value.owner_agent_id,
label: value.label,
command: value.command,
args: value.args,
cwd: value.cwd,
env: value.env,
record_only: value.record_only,
deadline_ms: value.deadline_ms,
}
}
}
/// Public plugin task status request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginTaskStatusDto {
/// Task id to read.
pub task_id: String,
}
impl From<PluginTaskStatusDto> for application::PluginTaskStatusInput {
fn from(value: PluginTaskStatusDto) -> Self {
Self {
task_id: value.task_id,
}
}
}
/// Public plugin command-task status/output DTO.
pub type PluginTaskDto = BackgroundTaskDto;
/// Public plugin external-toolchain diagnostic request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginToolchainDiagnosticRequestDto {
/// Owning project id.
pub project_id: String,
/// Relative working directory under project root.
#[serde(default)]
pub cwd: Option<String>,
/// Executable probes to run.
#[serde(default)]
pub tools: Vec<PluginToolRequirementDto>,
/// Environment variable prerequisites.
#[serde(default)]
pub env: Vec<PluginEnvRequirementDto>,
/// Workspace file prerequisites.
#[serde(default)]
pub files: Vec<PluginFileRequirementDto>,
}
impl From<PluginToolchainDiagnosticRequestDto> for application::PluginToolchainDiagnosticInput {
fn from(value: PluginToolchainDiagnosticRequestDto) -> Self {
Self {
project_id: value.project_id,
cwd: value.cwd,
tools: value.tools.into_iter().map(Into::into).collect(),
env: value.env.into_iter().map(Into::into).collect(),
files: value.files.into_iter().map(Into::into).collect(),
}
}
}
/// Public plugin executable probe DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginToolRequirementDto {
/// Stable requirement id.
pub id: String,
/// Executable name or path.
pub executable: String,
/// Version/diagnostic arguments.
#[serde(default)]
pub version_args: Vec<String>,
/// Whether this probe is required.
#[serde(default)]
pub required: bool,
/// Extra environment variables for the probe.
#[serde(default)]
pub env: Vec<(String, String)>,
}
impl From<PluginToolRequirementDto> for application::PluginToolRequirement {
fn from(value: PluginToolRequirementDto) -> Self {
Self {
id: value.id,
executable: value.executable,
version_args: value.version_args,
required: value.required,
env: value.env,
}
}
}
/// Public plugin environment prerequisite DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginEnvRequirementDto {
/// Environment variable name.
pub name: String,
/// Whether this variable is required.
#[serde(default)]
pub required: bool,
/// Optional exact expected value.
#[serde(default)]
pub equals: Option<String>,
}
impl From<PluginEnvRequirementDto> for application::PluginEnvRequirement {
fn from(value: PluginEnvRequirementDto) -> Self {
Self {
name: value.name,
required: value.required,
equals: value.equals,
}
}
}
/// Public plugin workspace file prerequisite DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginFileRequirementDto {
/// Relative path under project root.
pub path: String,
/// Whether this path is required.
#[serde(default)]
pub required: bool,
/// Expected kind: `file`, `directory`, or `any`.
#[serde(default)]
pub kind: Option<String>,
}
impl From<PluginFileRequirementDto> for application::PluginFileRequirement {
fn from(value: PluginFileRequirementDto) -> Self {
Self {
path: value.path,
required: value.required,
kind: value.kind,
}
}
}
/// Public plugin external-toolchain diagnostic output DTO.
pub type PluginToolchainDiagnosticDto = application::PluginToolchainDiagnostic;
/// Public plugin event subscription request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginEventSubscribeDto {
/// Project id to observe.
pub project_id: String,
/// Public event types to retain. Empty means all supported types.
#[serde(default)]
pub event_types: Vec<String>,
/// Per-subscription retained event capacity.
#[serde(default)]
pub capacity: Option<usize>,
}
impl From<PluginEventSubscribeDto> for application::PluginEventSubscribeInput {
fn from(value: PluginEventSubscribeDto) -> Self {
Self {
project_id: value.project_id,
event_types: value.event_types,
capacity: value.capacity,
}
}
}
/// Public plugin event poll request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginEventPollDto {
/// Subscription id returned by subscribe.
pub subscription_id: String,
/// Maximum number of events to drain.
#[serde(default)]
pub max_events: Option<usize>,
}
impl From<PluginEventPollDto> for application::PluginEventPollInput {
fn from(value: PluginEventPollDto) -> Self {
Self {
subscription_id: value.subscription_id,
max_events: value.max_events,
}
}
}
/// Public plugin event unsubscribe request DTO.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginEventUnsubscribeDto {
/// Subscription id returned by subscribe.
pub subscription_id: String,
}
impl From<PluginEventUnsubscribeDto> for application::PluginEventUnsubscribeInput {
fn from(value: PluginEventUnsubscribeDto) -> Self {
Self {
subscription_id: value.subscription_id,
}
}
}
/// Public plugin event subscription output DTO.
pub type PluginEventSubscriptionDto = application::PluginEventSubscription;
/// Public plugin event poll output DTO.
pub type PluginEventBatchDto = application::PluginEventBatch;
/// Plugin workspace text file DTO.
pub type PluginWorkspaceTextFileDto = application::PluginWorkspaceTextFile;
/// Plugin workspace binary file DTO.
pub type PluginWorkspaceBinaryFileDto = application::PluginWorkspaceBinaryFile;
/// Plugin workspace directory listing DTO.
pub type PluginWorkspaceDirectoryListingDto = application::PluginWorkspaceDirectoryListing;
/// Plugin workspace stat DTO.
pub type PluginWorkspaceStatDto = application::PluginWorkspaceStat;
/// Plugin structured config document DTO.
pub type PluginConfigDocumentDto = application::PluginConfigDocument;
/// Plugin structured config document write result DTO.
pub type PluginConfigDocumentWriteResultDto = application::PluginConfigDocumentWriteResult;
/// Plugin project structure result DTO.
pub type PluginProjectStructureDto = application::ProjectStructureQuery;
/// Request DTO for the `health` command.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
@ -4352,6 +4755,356 @@ mod tests {
);
}
#[test]
fn dto_plugins_workspace_requests_use_stable_camel_case_contract() {
let path = PluginWorkspacePathDto {
project_id: Uuid::from_u128(124).to_string(),
path: "src/main.rs".to_owned(),
};
let text = PluginWorkspaceWriteTextDto {
project_id: path.project_id.clone(),
path: path.path.clone(),
content: "fn main() {}\n".to_owned(),
};
let binary = PluginWorkspaceWriteBinaryDto {
project_id: path.project_id.clone(),
path: "assets/icon.bin".to_owned(),
bytes: vec![1, 2, 3],
};
assert_eq!(
serde_json::to_value(&path).unwrap(),
json!({
"projectId": path.project_id,
"path": "src/main.rs"
})
);
assert_eq!(
serde_json::to_value(&text).unwrap(),
json!({
"projectId": text.project_id,
"path": "src/main.rs",
"content": "fn main() {}\n"
})
);
assert_eq!(
serde_json::to_value(&binary).unwrap(),
json!({
"projectId": binary.project_id,
"path": "assets/icon.bin",
"bytes": [1, 2, 3]
})
);
}
#[test]
fn dto_plugins_project_structure_query_maps_to_application_input() {
let dto = PluginProjectStructureQueryDto {
project_id: Uuid::from_u128(129).to_string(),
path: Some("crates".to_owned()),
max_depth: Some(4),
max_entries: Some(250),
};
let json = serde_json::to_value(&dto).unwrap();
assert_eq!(
json,
json!({
"projectId": dto.project_id,
"path": "crates",
"maxDepth": 4,
"maxEntries": 250
})
);
let input: application::QueryProjectStructureInput = dto.into();
assert_eq!(input.path.as_deref(), Some("crates"));
assert_eq!(input.max_depth, Some(4));
assert_eq!(input.max_entries, Some(250));
}
#[test]
fn dto_plugins_config_document_requests_use_stable_camel_case_contract() {
let project_id = Uuid::from_u128(130).to_string();
let read = PluginConfigDocumentReadDto {
project_id: project_id.clone(),
path: "config/settings.json".to_owned(),
format: Some("json".to_owned()),
};
assert_eq!(
serde_json::to_value(&read).unwrap(),
json!({
"projectId": project_id,
"path": "config/settings.json",
"format": "json"
})
);
let input: application::PluginConfigDocumentReadInput = read.into();
assert_eq!(input.path, "config/settings.json");
assert_eq!(input.format.as_deref(), Some("json"));
let update = PluginConfigDocumentUpdateDto {
project_id: Uuid::from_u128(130).to_string(),
path: "config/settings.json".to_owned(),
format: Some("json".to_owned()),
mode: Some("mergePatch".to_owned()),
value: json!({"enabled": true, "removeMe": null}),
};
assert_eq!(
serde_json::to_value(&update).unwrap(),
json!({
"projectId": Uuid::from_u128(130).to_string(),
"path": "config/settings.json",
"format": "json",
"mode": "mergePatch",
"value": {
"enabled": true,
"removeMe": null
}
})
);
let input: application::PluginConfigDocumentUpdateInput = update.into();
assert_eq!(input.mode.as_deref(), Some("mergePatch"));
assert_eq!(input.value["enabled"], true);
}
#[test]
fn dto_plugins_workspace_outputs_use_stable_camel_case_contract() {
let listing = PluginWorkspaceDirectoryListingDto {
path: "src".to_owned(),
entries: vec![application::PluginWorkspaceDirEntry {
name: "main.rs".to_owned(),
path: "src/main.rs".to_owned(),
is_dir: false,
}],
};
let stat = PluginWorkspaceStatDto {
path: "src/main.rs".to_owned(),
exists: true,
is_file: true,
is_dir: false,
len: Some(13),
};
let structure = PluginProjectStructureDto {
project_id: Uuid::from_u128(129).to_string(),
root_path: String::new(),
entries: vec![application::ProjectStructureEntry {
path: "Cargo.toml".to_owned(),
name: "Cargo.toml".to_owned(),
kind: "file".to_owned(),
}],
conventions: vec![application::ProjectConvention {
id: "rust-cargo".to_owned(),
marker_path: "Cargo.toml".to_owned(),
}],
modules: vec![application::ProjectModule {
path: String::new(),
marker_path: "Cargo.toml".to_owned(),
convention_id: "rust-cargo".to_owned(),
}],
truncated: false,
};
assert_eq!(
serde_json::to_value(&listing).unwrap(),
json!({
"path": "src",
"entries": [{
"name": "main.rs",
"path": "src/main.rs",
"isDir": false
}]
})
);
assert_eq!(
serde_json::to_value(&stat).unwrap(),
json!({
"path": "src/main.rs",
"exists": true,
"isFile": true,
"isDir": false,
"len": 13
})
);
assert_eq!(
serde_json::to_value(&structure).unwrap(),
json!({
"projectId": structure.project_id,
"rootPath": "",
"entries": [{
"path": "Cargo.toml",
"name": "Cargo.toml",
"kind": "file"
}],
"conventions": [{
"id": "rust-cargo",
"markerPath": "Cargo.toml"
}],
"modules": [{
"path": "",
"markerPath": "Cargo.toml",
"conventionId": "rust-cargo"
}],
"truncated": false
})
);
}
#[test]
fn dto_plugins_command_task_requests_use_stable_camel_case_contract() {
let project_id = Uuid::from_u128(125).to_string();
let owner_agent_id = Uuid::from_u128(126).to_string();
let run = PluginRunCommandDto {
project_id: project_id.clone(),
owner_agent_id: owner_agent_id.clone(),
label: "cargo test".to_owned(),
command: "cargo".to_owned(),
args: vec!["test".to_owned(), "-p".to_owned(), "application".to_owned()],
cwd: Some("crates/application".to_owned()),
env: vec![("RUST_LOG".to_owned(), "debug".to_owned())],
record_only: true,
deadline_ms: Some(1_800_000_000_000),
};
assert_eq!(
serde_json::to_value(&run).unwrap(),
json!({
"projectId": project_id,
"ownerAgentId": owner_agent_id,
"label": "cargo test",
"command": "cargo",
"args": ["test", "-p", "application"],
"cwd": "crates/application",
"env": [["RUST_LOG", "debug"]],
"recordOnly": true,
"deadlineMs": 1_800_000_000_000u64
})
);
let input: application::PluginRunCommandInput = run.into();
assert_eq!(input.cwd.as_deref(), Some("crates/application"));
assert_eq!(input.env, vec![("RUST_LOG".to_owned(), "debug".to_owned())]);
assert!(input.record_only);
let status = PluginTaskStatusDto {
task_id: Uuid::from_u128(127).to_string(),
};
assert_eq!(
serde_json::to_value(&status).unwrap(),
json!({ "taskId": status.task_id })
);
}
#[test]
fn dto_plugins_toolchain_diagnostic_request_maps_to_application_input() {
let project_id = Uuid::from_u128(126).to_string();
let request = PluginToolchainDiagnosticRequestDto {
project_id: project_id.clone(),
cwd: Some("crates/backend".to_owned()),
tools: vec![PluginToolRequirementDto {
id: "rust".to_owned(),
executable: "cargo".to_owned(),
version_args: vec!["--version".to_owned()],
required: true,
env: vec![("CARGO_TERM_COLOR".to_owned(), "never".to_owned())],
}],
env: vec![PluginEnvRequirementDto {
name: "RUSTUP_HOME".to_owned(),
required: false,
equals: None,
}],
files: vec![PluginFileRequirementDto {
path: "Cargo.toml".to_owned(),
required: true,
kind: Some("file".to_owned()),
}],
};
assert_eq!(
serde_json::to_value(&request).unwrap(),
json!({
"projectId": project_id,
"cwd": "crates/backend",
"tools": [{
"id": "rust",
"executable": "cargo",
"versionArgs": ["--version"],
"required": true,
"env": [["CARGO_TERM_COLOR", "never"]]
}],
"env": [{
"name": "RUSTUP_HOME",
"required": false,
"equals": null
}],
"files": [{
"path": "Cargo.toml",
"required": true,
"kind": "file"
}]
})
);
let input: application::PluginToolchainDiagnosticInput = request.into();
assert_eq!(input.cwd.as_deref(), Some("crates/backend"));
assert_eq!(input.tools[0].id, "rust");
assert_eq!(input.tools[0].env[0].0, "CARGO_TERM_COLOR");
assert_eq!(input.env[0].name, "RUSTUP_HOME");
assert_eq!(input.files[0].kind.as_deref(), Some("file"));
}
#[test]
fn dto_plugins_event_subscription_requests_use_stable_camel_case_contract() {
let project_id = Uuid::from_u128(127).to_string();
let subscribe = PluginEventSubscribeDto {
project_id: project_id.clone(),
event_types: vec![
"workspaceFileChanged".to_owned(),
"backgroundTaskChanged".to_owned(),
],
capacity: Some(250),
};
assert_eq!(
serde_json::to_value(&subscribe).unwrap(),
json!({
"projectId": project_id,
"eventTypes": ["workspaceFileChanged", "backgroundTaskChanged"],
"capacity": 250
})
);
let input: application::PluginEventSubscribeInput = subscribe.into();
assert_eq!(
input.event_types,
vec![
"workspaceFileChanged".to_owned(),
"backgroundTaskChanged".to_owned()
]
);
assert_eq!(input.capacity, Some(250));
let poll = PluginEventPollDto {
subscription_id: Uuid::from_u128(128).to_string(),
max_events: Some(50),
};
assert_eq!(
serde_json::to_value(&poll).unwrap(),
json!({
"subscriptionId": poll.subscription_id,
"maxEvents": 50
})
);
let input: application::PluginEventPollInput = poll.into();
assert_eq!(input.max_events, Some(50));
let unsubscribe = PluginEventUnsubscribeDto {
subscription_id: Uuid::from_u128(129).to_string(),
};
assert_eq!(
serde_json::to_value(&unsubscribe).unwrap(),
json!({ "subscriptionId": unsubscribe.subscription_id })
);
}
#[test]
fn background_task_dto_exposes_rendezvous_context_only_for_headless_rendezvous() {
let project_id = ProjectId::from_uuid(Uuid::from_u128(1));

View File

@ -401,6 +401,16 @@ pub enum DomainEventDto {
/// Project id.
project_id: String,
},
/// A workspace file changed through the public plugin workspace API.
#[serde(rename_all = "camelCase")]
PluginWorkspaceFileChanged {
/// Project id.
project_id: String,
/// Relative workspace path.
path: String,
/// Public operation label.
operation: String,
},
/// An issue-backed public ticket was created.
#[serde(rename_all = "camelCase")]
IssueCreated {
@ -1058,6 +1068,15 @@ impl From<&DomainEvent> for DomainEventDto {
DomainEvent::GitStateChanged { project_id } => Self::GitStateChanged {
project_id: project_id.to_string(),
},
DomainEvent::PluginWorkspaceFileChanged {
project_id,
path,
operation,
} => Self::PluginWorkspaceFileChanged {
project_id: project_id.to_string(),
path: path.clone(),
operation: operation.clone(),
},
DomainEvent::IssueCreated {
issue_id,
issue_ref,

View File

@ -35,37 +35,39 @@ use application::{
MarkIssueAttachmentSummarized, McpRuntime, McpToolPermissionCatalogue, MoveTabToNewWindow,
MutateLayout, OnnxModelView, OpenProject, OpenTerminal, OpenTicketAssistant,
OrchestratorService, PairAttemptLimiter, PairDevice, PermissionProjectorRegistry,
ProposeContext, ReadAgentContext, ReadContext, ReadConversationPage, ReadIssue,
ReadIssueAttachment, ReadIssueCarnet, ReadMcpToolPermissions, ReadMemory, ReadMemoryIndex,
ReadProjectContext, ReadSkill, ReadTemplate, RecallMemory, ReconcileLayouts,
ReconcileLiveState, ReconcileLiveStateInput, ReconcilePluginMcpServers, RecordTurn,
RecordTurnProvider, ReferenceProfiles, RenameDevice, RenameLayout, RenameSprint,
ReorderSprints, ResizeTerminal, ResolveAgentCapabilities, ResolveAgentPermissions,
ResolveAgentSystemPermissions, ResolveMemoryLinks, RestoreOpenWindows, RetryBackgroundTask,
ReviewPluginPackage, RevokeAllDevices, RevokeDevice, RotateConversationLog,
SaveEmbedderProfile, SaveModelServer, SaveOpenCodeProviderProfile, SaveProfile,
SessionLimitService, SetActiveLayout, SetPluginEnabled, SnapshotOpenWindows,
SnapshotRunningAgents, SpawnBackgroundCommand, StopLiveAgent, StructuredRoutingMode,
StructuredSessions, SuggestedThisSession, SyncAgentWithTemplate, TerminalSessions, TouchDevice,
UnassignSkillFromAgent, UnassignTicketFromSprint, UninstallPlugin, UnlinkIssues,
UpdateAgentContext, UpdateAgentMcpToolPermissions, UpdateAgentPermissions,
UpdateAgentSystemPermissions, UpdateIssue, UpdateIssueCarnet, UpdateLiveState, UpdateMemory,
UpdateProjectContext, UpdateProjectMcpToolPermissions, UpdateProjectPermissions,
UpdateProjectSystemPermissions, UpdateSkill, UpdateTemplate, WakeSessionProvider, WriteMemory,
WriteToTerminal, AGENT_MEMORY_RECALL_BUDGET,
PluginCommandTasks, PluginConfigDocuments, PluginEventSubscriptions,
PluginToolchainDiagnostics, PluginWorkspaceAccess, ProposeContext, QueryProjectStructure,
ReadAgentContext, ReadContext, ReadConversationPage, ReadIssue, ReadIssueAttachment,
ReadIssueCarnet, ReadMcpToolPermissions, ReadMemory, ReadMemoryIndex, ReadProjectContext,
ReadSkill, ReadTemplate, RecallMemory, ReconcileLayouts, ReconcileLiveState,
ReconcileLiveStateInput, ReconcilePluginMcpServers, RecordTurn, RecordTurnProvider,
ReferenceProfiles, RenameDevice, RenameLayout, RenameSprint, ReorderSprints, ResizeTerminal,
ResolveAgentCapabilities, ResolveAgentPermissions, ResolveAgentSystemPermissions,
ResolveMemoryLinks, RestoreOpenWindows, RetryBackgroundTask, ReviewPluginPackage,
RevokeAllDevices, RevokeDevice, RotateConversationLog, SaveEmbedderProfile, SaveModelServer,
SaveOpenCodeProviderProfile, SaveProfile, SessionLimitService, SetActiveLayout,
SetPluginEnabled, SnapshotOpenWindows, SnapshotRunningAgents, SpawnBackgroundCommand,
StopLiveAgent, StructuredRoutingMode, StructuredSessions, SuggestedThisSession,
SyncAgentWithTemplate, TerminalSessions, TouchDevice, UnassignSkillFromAgent,
UnassignTicketFromSprint, UninstallPlugin, UnlinkIssues, UpdateAgentContext,
UpdateAgentMcpToolPermissions, UpdateAgentPermissions, UpdateAgentSystemPermissions,
UpdateIssue, UpdateIssueCarnet, UpdateLiveState, UpdateMemory, UpdateProjectContext,
UpdateProjectMcpToolPermissions, UpdateProjectPermissions, UpdateProjectSystemPermissions,
UpdateSkill, UpdateTemplate, WakeSessionProvider, WriteMemory, WriteToTerminal,
AGENT_MEMORY_RECALL_BUDGET,
};
use async_trait::async_trait;
use domain::ports::{
AgentContextStore, AgentRuntime, AgentSession, AgentSessionFactory, AgentToolPolicyStore,
AgentWakePort, AssistantContextProvider, BackgroundTaskPortError, BackgroundTaskRunner,
BackgroundTaskStore, Clock, DeviceSessionStore, Embedder, EmbedderEnvInspector,
EmbedderProfileStore, EmbedderPromptStore, EventBus, FileSystem, GitPort, IdGenerator,
IssueNumberAllocator, IssueStore, McpToolPermissionStore, MemoryRecall, MemoryStore,
ModelArtifactDownloader, PermissionStore, PluginManifestValidator, PluginMcpSupervisor,
PluginPackageStore, PluginRegistryStore, ProcessSpawner, ProfileStore, ProjectStore, PtyHandle,
PtyPort, RuntimePermissionProbe, ScheduledTask, Scheduler, SecretStore, SkillStore,
SprintStore, StructuredSessionEnvironmentPreparer, SystemPermissionStore, TemplateStore,
ToolInvoker, WakeError, WakeReason, WindowStateStore,
EmbedderProfileStore, EmbedderPromptStore, EnvironmentReader, EventBus, FileSystem, GitPort,
IdGenerator, IssueNumberAllocator, IssueStore, McpToolPermissionStore, MemoryRecall,
MemoryStore, ModelArtifactDownloader, PermissionStore, PluginManifestValidator,
PluginMcpSupervisor, PluginPackageStore, PluginRegistryStore, ProcessSpawner, ProfileStore,
ProjectStore, PtyHandle, PtyPort, RuntimePermissionProbe, ScheduledTask, Scheduler,
SecretStore, SkillStore, SprintStore, StructuredSessionEnvironmentPreparer,
SystemPermissionStore, TemplateStore, ToolInvoker, WakeError, WakeReason, WindowStateStore,
};
use domain::profile::{
AgentProfile, ContextInjection, McpConfigStrategy, McpTransport, StructuredAdapter,
@ -93,13 +95,14 @@ use infrastructure::{
FsSprintStore, FsSystemPermissionStore, FsTemplateStore, FsWindowStateStore, Git2Repository,
HeuristicHandoffSummarizer, HfModelArtifactDownloader, HttpOpenAiCompatibleProbe,
HttpProviderModelCatalogue, IdeaiContextStore, InMemoryConversationRegistry, InMemoryMailbox,
InMemoryPairAttemptLimiter, LlamaCppRuntime, LocalFileSystem, LocalManagedProcess,
LocalProcessSpawner, McpServer, MediatedInbox, NaiveMemoryRecall, OrchestratorWatchHandle,
PortablePtyAdapter, ProcessCliVersionReader, ReadOnlyRuntimePermissionProbe, RwFileGuard,
StructuredSessionFactory, SystemClock, SystemMillisClock, TemplateToolProvider,
TicketAssistantEnvironmentPreparer, TicketToolProvider, TokioBroadcastEventBus, TokioScheduler,
ToolPolicyRegistry, UuidGenerator, VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL,
ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS, VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
InMemoryPairAttemptLimiter, LlamaCppRuntime, LocalEnvironmentReader, LocalFileSystem,
LocalManagedProcess, LocalProcessSpawner, McpServer, MediatedInbox, NaiveMemoryRecall,
OrchestratorWatchHandle, PortablePtyAdapter, ProcessCliVersionReader,
ReadOnlyRuntimePermissionProbe, RwFileGuard, StructuredSessionFactory, SystemClock,
SystemMillisClock, TemplateToolProvider, TicketAssistantEnvironmentPreparer,
TicketToolProvider, TokioBroadcastEventBus, TokioScheduler, ToolPolicyRegistry, UuidGenerator,
VectorMemoryRecall, DEFAULT_OLLAMA_BASE_URL, ONNX_CACHE_SUBDIR, RECOMMENDED_ONNX_MODELS,
VECTOR_HTTP_ENABLED, VECTOR_ONNX_ENABLED,
};
pub mod dto;
@ -1135,6 +1138,18 @@ pub struct BackendCore {
pub list_plugin_runtime_contributions: Arc<ListPluginRuntimeContributions>,
/// Reconcile external MCP plugin servers.
pub reconcile_plugin_mcp_servers: Arc<ReconcilePluginMcpServers>,
/// Public plugin workspace/file access facade.
pub plugin_workspace_access: Arc<PluginWorkspaceAccess>,
/// Public plugin structured config document facade.
pub plugin_config_documents: Arc<PluginConfigDocuments>,
/// Public plugin project-structure query use case.
pub query_project_structure: Arc<QueryProjectStructure>,
/// Public plugin command/task facade.
pub plugin_command_tasks: Arc<PluginCommandTasks>,
/// Public plugin external-toolchain diagnostic facade.
pub plugin_toolchain_diagnostics: Arc<PluginToolchainDiagnostics>,
/// Public plugin event subscription facade.
pub plugin_event_subscriptions: Arc<PluginEventSubscriptions>,
/// Package store exposed for the Tauri asset protocol adapter.
pub plugin_package_store: Arc<FsPluginPackageStore>,
/// Registry store exposed for the Tauri asset protocol adapter.
@ -1553,6 +1568,8 @@ impl BackendCore {
// registry.
let spawner = Arc::new(LocalProcessSpawner::new());
let spawner_port = Arc::clone(&spawner) as Arc<dyn ProcessSpawner>;
let environment_reader = Arc::new(LocalEnvironmentReader::new());
let environment_reader_port = Arc::clone(&environment_reader) as Arc<dyn EnvironmentReader>;
let runtime = Arc::new(CliAgentRuntime::new(Arc::clone(&spawner_port)));
let runtime_port = Arc::clone(&runtime) as Arc<dyn AgentRuntime>;
@ -2358,12 +2375,15 @@ impl BackendCore {
let _ = drain.await;
});
}
let spawn_background_command = Arc::new(SpawnBackgroundCommand::new(
Arc::clone(&background_tasks_port),
Arc::clone(&background_runner_port),
Arc::clone(&clock) as Arc<dyn Clock>,
Arc::clone(&ids) as Arc<dyn IdGenerator>,
));
let spawn_background_command = Arc::new(
SpawnBackgroundCommand::new(
Arc::clone(&background_tasks_port),
Arc::clone(&background_runner_port),
Arc::clone(&clock) as Arc<dyn Clock>,
Arc::clone(&ids) as Arc<dyn IdGenerator>,
)
.with_events(Arc::clone(&events_port)),
);
let cancel_background_task = Arc::new(CancelBackgroundTask::new(
Arc::clone(&background_tasks_port),
Arc::clone(&background_runner_port),
@ -2420,6 +2440,47 @@ impl BackendCore {
Arc::clone(&plugin_manifest_validator),
Arc::clone(&plugin_mcp_supervisor_port),
));
let plugin_workspace_access = Arc::new(
PluginWorkspaceAccess::new(Arc::clone(&store_port), Arc::clone(&fs_port))
.with_events(Arc::clone(&events_port)),
);
let plugin_config_documents = Arc::new(
PluginConfigDocuments::new(Arc::clone(&store_port), Arc::clone(&fs_port))
.with_events(Arc::clone(&events_port)),
);
let query_project_structure = Arc::new(QueryProjectStructure::new(
Arc::clone(&store_port),
Arc::clone(&fs_port),
));
let plugin_command_tasks = Arc::new(PluginCommandTasks::new(
Arc::clone(&store_port),
Arc::clone(&background_tasks_port),
Arc::clone(&spawn_background_command),
));
let plugin_toolchain_diagnostics = Arc::new(PluginToolchainDiagnostics::new(
Arc::clone(&store_port),
Arc::clone(&fs_port),
Arc::clone(&spawner_port),
Arc::clone(&environment_reader_port),
));
let plugin_event_subscriptions = Arc::new(PluginEventSubscriptions::new(
Arc::clone(&store_port),
Arc::clone(&ids) as Arc<dyn IdGenerator>,
Arc::clone(&clock) as Arc<dyn Clock>,
));
{
let mut rx = event_bus.raw_receiver();
let subscriptions = Arc::clone(&plugin_event_subscriptions);
spawn_detached(async move {
loop {
match rx.recv().await {
Ok(event) => subscriptions.record_domain_event(&event),
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
});
}
let background_wake = Arc::new(AgentWakeService::new(
Arc::clone(&mediated_inbox) as Arc<dyn AgentInbox>,
Arc::clone(&input_mediator),
@ -2982,6 +3043,12 @@ impl BackendCore {
uninstall_plugin,
list_plugin_runtime_contributions,
reconcile_plugin_mcp_servers,
plugin_workspace_access,
plugin_config_documents,
query_project_structure,
plugin_command_tasks,
plugin_toolchain_diagnostics,
plugin_event_subscriptions,
plugin_package_store: Arc::clone(&plugin_packages),
plugin_registry_store: Arc::clone(&plugin_registry_store),
plugin_manifest_validator: Arc::clone(&plugin_manifest_validator),

View File

@ -366,6 +366,15 @@ pub enum DomainEvent {
/// The project.
project_id: ProjectId,
},
/// A file under a project workspace changed through a public plugin workspace API.
PluginWorkspaceFileChanged {
/// The owning project.
project_id: ProjectId,
/// Normalized path relative to the project root.
path: String,
/// Public operation label, for example `changed`.
operation: String,
},
/// An orchestrator request (dropped under `.ideai/requests/`) was processed
/// by IdeA on behalf of a requester agent (ARCHITECTURE §14.3). Relayed so the
/// frontend can surface orchestration activity; the resulting cell/tab opens

View File

@ -480,6 +480,17 @@ pub struct DirEntry {
pub is_dir: bool,
}
/// Basic metadata returned by [`FileSystem::metadata`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileMetadata {
/// Whether the path points to a regular file.
pub is_file: bool,
/// Whether the path points to a directory.
pub is_dir: bool,
/// File length in bytes when known.
pub len: Option<u64>,
}
/// An owned, boxed stream of PTY output chunks.
///
/// Concrete adapters decide the underlying transport; the domain only sees a
@ -1281,6 +1292,12 @@ pub trait ProcessSpawner: Send + Sync {
async fn run(&self, spec: SpawnSpec) -> Result<Output, ProcessError>;
}
/// Reads host environment variables through an injected adapter.
pub trait EnvironmentReader: Send + Sync {
/// Returns one environment variable value, if present.
fn get(&self, name: &str) -> Option<String>;
}
/// Read a local structured CLI version using only the allowed `--version` probe.
#[async_trait]
pub trait CliVersionReader: Send + Sync {
@ -1526,6 +1543,25 @@ pub trait FileSystem: Send + Sync {
/// [`FsError`] on failure.
async fn exists(&self, path: &RemotePath) -> Result<bool, FsError>;
/// Returns basic metadata for a path.
///
/// The default keeps older remote/test adapters source-compatible. Concrete
/// adapters that can cheaply stat paths should override it.
///
/// # Errors
/// [`FsError`] on failure.
async fn metadata(&self, path: &RemotePath) -> Result<FileMetadata, FsError> {
if self.exists(path).await? {
Ok(FileMetadata {
is_file: false,
is_dir: false,
len: None,
})
} else {
Err(FsError::NotFound(path.as_str().to_owned()))
}
}
/// Removes a single file. A **missing** file is treated as success (idempotent
/// delete), so this is safe to call best-effort.
///

View File

@ -9,7 +9,7 @@ use std::io;
use std::path::Path;
use async_trait::async_trait;
use domain::ports::{DirEntry, FileSystem, FsError, RemotePath};
use domain::ports::{DirEntry, FileMetadata, FileSystem, FsError, RemotePath};
use tokio::fs;
/// Filesystem adapter backed by the local OS via `tokio::fs`.
@ -54,6 +54,17 @@ impl FileSystem for LocalFileSystem {
}
}
async fn metadata(&self, path: &RemotePath) -> Result<FileMetadata, FsError> {
let meta = fs::metadata(path.as_str())
.await
.map_err(|e| map_io(path, &e))?;
Ok(FileMetadata {
is_file: meta.is_file(),
is_dir: meta.is_dir(),
len: Some(meta.len()),
})
}
async fn remove_file(&self, path: &RemotePath) -> Result<(), FsError> {
match fs::remove_file(path.as_str()).await {
Ok(()) => Ok(()),

View File

@ -89,7 +89,7 @@ pub use orchestrator::{
pub use pair_attempt_limiter::InMemoryPairAttemptLimiter;
pub use permission::{ClaudePermissionProjector, CodexPermissionProjector};
pub use plugin::{ExternalMcpPluginSupervisor, FsPluginPackageStore, FsPluginRegistryStore};
pub use process::LocalProcessSpawner;
pub use process::{LocalEnvironmentReader, LocalProcessSpawner};
pub use pty::PortablePtyAdapter;
pub use ratelimit::RateLimitParser;
pub use remote::{remote_host, LocalHost};

View File

@ -9,7 +9,9 @@
use async_trait::async_trait;
use tokio::process::Command;
use domain::ports::{ExitStatus, Output, ProcessError, ProcessSpawner, SpawnSpec};
use domain::ports::{
EnvironmentReader, ExitStatus, Output, ProcessError, ProcessSpawner, SpawnSpec,
};
/// Process spawner backed by the local OS via `tokio::process::Command`.
#[derive(Debug, Default, Clone, Copy)]
@ -23,6 +25,24 @@ impl LocalProcessSpawner {
}
}
/// Environment reader backed by the local process environment.
#[derive(Debug, Default, Clone, Copy)]
pub struct LocalEnvironmentReader;
impl LocalEnvironmentReader {
/// Creates a new [`LocalEnvironmentReader`].
#[must_use]
pub const fn new() -> Self {
Self
}
}
impl EnvironmentReader for LocalEnvironmentReader {
fn get(&self, name: &str) -> Option<String> {
std::env::var(name).ok()
}
}
#[async_trait]
impl ProcessSpawner for LocalProcessSpawner {
async fn run(&self, spec: SpawnSpec) -> Result<Output, ProcessError> {

View File

@ -45,7 +45,12 @@ import {
import {
WebDesktopServerGateway,
WebFocusedProjectGateway,
WebPluginConfigGateway,
WebPluginEventGateway,
WebPluginGateway,
WebPluginTaskGateway,
WebPluginToolchainGateway,
WebPluginWorkspaceGateway,
WebRemoteGateway,
WebWindowGateway,
} from "./unsupported";
@ -141,6 +146,11 @@ export function createHttpWsGateways(config: HttpWsGatewaysConfig = {}): Gateway
// Frontend-owned UI prefs are transport-neutral (localStorage) — reuse as-is.
uiPreferences: new LocalStorageUiPreferencesGateway(),
plugin: new WebPluginGateway(),
pluginWorkspace: new WebPluginWorkspaceGateway(),
pluginTask: new WebPluginTaskGateway(),
pluginToolchain: new WebPluginToolchainGateway(),
pluginEvents: new WebPluginEventGateway(),
pluginConfig: new WebPluginConfigGateway(),
};
}

View File

@ -13,10 +13,21 @@ import type {
EmbeddedServerStatus,
GatewayError,
PluginAdmin,
PluginCommandTask,
PluginConfigDocument,
PluginConfigDocumentWriteResult,
PluginEventBatch,
PluginEventSubscription,
PluginInstallResult,
PluginToolchainDiagnostic,
PluginProjectStructure,
PluginReview,
PluginRuntimeContributionCatalog,
PluginUninstallResult,
PluginWorkspaceBinaryFile,
PluginWorkspaceDirectoryListing,
PluginWorkspaceStat,
PluginWorkspaceTextFile,
ServerExposurePreview,
ServerExposureSettings,
Unsubscribe,
@ -25,7 +36,24 @@ import type {
DesktopServerGateway,
FocusedProject,
FocusedProjectGateway,
PluginConfigDocumentReadInput,
PluginConfigDocumentUpdateInput,
PluginConfigGateway,
PluginEventGateway,
PluginEventPollInput,
PluginEventSubscribeInput,
PluginEventUnsubscribeInput,
PluginGateway,
PluginProjectStructureQuery,
PluginRunCommandInput,
PluginTaskGateway,
PluginTaskStatusInput,
PluginToolchainDiagnosticRequest,
PluginToolchainGateway,
PluginWorkspaceGateway,
PluginWorkspacePathInput,
PluginWorkspaceWriteBinaryInput,
PluginWorkspaceWriteTextInput,
RemoteGateway,
ReviewPluginPackageInput,
ViewWindowClosed,
@ -160,3 +188,78 @@ export class WebPluginGateway implements PluginGateway {
return unsupportedOnWeb("Plugin management");
}
}
/** Web stub: public plugin workspace services are only meaningful where plugins run. */
export class WebPluginWorkspaceGateway implements PluginWorkspaceGateway {
async readText(_input: PluginWorkspacePathInput): Promise<PluginWorkspaceTextFile> {
return unsupportedOnWeb("Plugin workspace access");
}
async readBinary(_input: PluginWorkspacePathInput): Promise<PluginWorkspaceBinaryFile> {
return unsupportedOnWeb("Plugin workspace access");
}
async writeText(_input: PluginWorkspaceWriteTextInput): Promise<void> {
return unsupportedOnWeb("Plugin workspace access");
}
async writeBinary(_input: PluginWorkspaceWriteBinaryInput): Promise<void> {
return unsupportedOnWeb("Plugin workspace access");
}
async listDir(_input: PluginWorkspacePathInput): Promise<PluginWorkspaceDirectoryListing> {
return unsupportedOnWeb("Plugin workspace access");
}
async stat(_input: PluginWorkspacePathInput): Promise<PluginWorkspaceStat> {
return unsupportedOnWeb("Plugin workspace access");
}
async queryProjectStructure(
_input: PluginProjectStructureQuery,
): Promise<PluginProjectStructure> {
return unsupportedOnWeb("Plugin workspace access");
}
}
/** Web stub: plugin command tasks are desktop-hosted in this runtime. */
export class WebPluginTaskGateway implements PluginTaskGateway {
async runCommand(_input: PluginRunCommandInput): Promise<PluginCommandTask> {
return unsupportedOnWeb("Plugin command tasks");
}
async getStatus(_input: PluginTaskStatusInput): Promise<PluginCommandTask | null> {
return unsupportedOnWeb("Plugin command tasks");
}
}
/** Web stub: plugin toolchain diagnostics run on the desktop host. */
export class WebPluginToolchainGateway implements PluginToolchainGateway {
async diagnose(
_input: PluginToolchainDiagnosticRequest,
): Promise<PluginToolchainDiagnostic> {
return unsupportedOnWeb("Plugin toolchain diagnostics");
}
}
/** Web stub: plugin public events are sourced from the desktop host. */
export class WebPluginEventGateway implements PluginEventGateway {
async subscribe(_input: PluginEventSubscribeInput): Promise<PluginEventSubscription> {
return unsupportedOnWeb("Plugin public events");
}
async poll(_input: PluginEventPollInput): Promise<PluginEventBatch> {
return unsupportedOnWeb("Plugin public events");
}
async unsubscribe(_input: PluginEventUnsubscribeInput): Promise<PluginEventSubscription> {
return unsupportedOnWeb("Plugin public events");
}
}
/** Web stub: plugin config documents are read/written by the desktop host. */
export class WebPluginConfigGateway implements PluginConfigGateway {
async readDocument(_input: PluginConfigDocumentReadInput): Promise<PluginConfigDocument> {
return unsupportedOnWeb("Plugin structured config documents");
}
async updateDocument(
_input: PluginConfigDocumentUpdateInput,
): Promise<PluginConfigDocumentWriteResult> {
return unsupportedOnWeb("Plugin structured config documents");
}
}

View File

@ -35,6 +35,11 @@ import { TauriWindowGateway } from "./window";
import { TauriFocusedProjectGateway } from "./focusedProject";
import { LocalStorageUiPreferencesGateway } from "./uiPreferences";
import { TauriPluginGateway } from "./plugin";
import { TauriPluginWorkspaceGateway } from "./pluginWorkspace";
import { TauriPluginTaskGateway } from "./pluginTask";
import { TauriPluginToolchainGateway } from "./pluginToolchain";
import { TauriPluginEventGateway } from "./pluginEvents";
import { TauriPluginConfigGateway } from "./pluginConfig";
function notImplemented(what: string): never {
const err: GatewayError = {
@ -77,6 +82,11 @@ export function createTauriGateways(): Gateways {
focusedProject: new TauriFocusedProjectGateway(),
uiPreferences: new LocalStorageUiPreferencesGateway(),
plugin: new TauriPluginGateway(),
pluginWorkspace: new TauriPluginWorkspaceGateway(),
pluginTask: new TauriPluginTaskGateway(),
pluginToolchain: new TauriPluginToolchainGateway(),
pluginEvents: new TauriPluginEventGateway(),
pluginConfig: new TauriPluginConfigGateway(),
};
}

View File

@ -42,13 +42,30 @@ import type {
PairingCode,
PermissionSet,
PluginAdmin,
PluginCommandTask,
PluginConfigDocument,
PluginConfigDocumentWriteResult,
PluginContributionSummary,
PluginEventBatch,
PluginEventSubscription,
PluginInstallResult,
PluginLifecycleState,
PluginProjectConvention,
PluginProjectModule,
PluginProjectStructure,
PluginProjectStructureEntry,
PluginReview,
PluginRuntimeContributionCatalog,
PluginToolchainDiagnostic,
PluginUninstallResult,
PluginPublicEvent,
PluginWorkspaceBinaryFile,
PluginWorkspaceDirectoryListing,
PluginWorkspaceDirEntry,
PluginWorkspaceStat,
PluginWorkspaceTextFile,
Project,
JsonValue,
ProjectMcpToolPermissions,
ProjectPermissions,
ProjectWorkState,
@ -104,7 +121,24 @@ import type {
ProfileGateway,
ProjectGateway,
PermissionGateway,
PluginConfigDocumentReadInput,
PluginConfigDocumentUpdateInput,
PluginConfigGateway,
PluginEventGateway,
PluginEventPollInput,
PluginEventSubscribeInput,
PluginEventUnsubscribeInput,
PluginGateway,
PluginProjectStructureQuery,
PluginRunCommandInput,
PluginTaskGateway,
PluginTaskStatusInput,
PluginToolchainDiagnosticRequest,
PluginToolchainGateway,
PluginWorkspaceGateway,
PluginWorkspacePathInput,
PluginWorkspaceWriteBinaryInput,
PluginWorkspaceWriteTextInput,
ReattachResult,
RemoteGateway,
ReviewPluginPackageInput,
@ -3540,6 +3574,448 @@ export class MockPluginGateway implements PluginGateway {
}
}
const PROJECT_MARKERS: Record<string, string> = {
"package.json": "node-package",
"Cargo.toml": "rust-cargo",
"pyproject.toml": "python-project",
"go.mod": "go-module",
Makefile: "makefile",
makefile: "makefile",
".git": "git-repository",
};
function invalidWorkspacePath(path: string): GatewayError {
return {
code: "INVALID",
message: `workspace path must be relative to the project root: ${path}`,
};
}
function normalizeWorkspacePath(path: string): string {
const raw = path.trim();
if (raw === "" || raw === ".") return "";
if (raw.includes("\0") || raw.startsWith("/") || raw.startsWith("\\") || raw.includes(":")) {
throw invalidWorkspacePath(path);
}
const parts = raw.replace(/\\/g, "/").split("/");
if (parts.some((part) => part === "" || part === "." || part === "..")) {
throw invalidWorkspacePath(path);
}
return parts.join("/");
}
function basename(path: string): string {
return path.split("/").pop() ?? path;
}
/**
* In-memory plugin workspace gateway for offline plugin development/tests.
* It mirrors the public contract shape, not the host filesystem.
*/
export class MockPluginWorkspaceGateway implements PluginWorkspaceGateway {
private readonly files = new Map<string, Map<string, Uint8Array>>();
private bucket(projectId: string): Map<string, Uint8Array> {
let files = this.files.get(projectId);
if (!files) {
files = new Map();
this.files.set(projectId, files);
}
return files;
}
_seedText(projectId: string, path: string, content: string): void {
this.bucket(projectId).set(normalizeWorkspacePath(path), new TextEncoder().encode(content));
}
async readText(input: PluginWorkspacePathInput): Promise<PluginWorkspaceTextFile> {
const file = await this.readBinary(input);
return { path: file.path, content: new TextDecoder().decode(file.bytes) };
}
async readBinary(input: PluginWorkspacePathInput): Promise<PluginWorkspaceBinaryFile> {
const path = normalizeWorkspacePath(input.path);
const bytes = this.bucket(input.projectId).get(path);
if (!bytes) {
const err: GatewayError = { code: "NOT_FOUND", message: `workspace file ${path} not found` };
throw err;
}
return { path, bytes: new Uint8Array(bytes) };
}
async writeText(input: PluginWorkspaceWriteTextInput): Promise<void> {
const path = normalizeWorkspacePath(input.path);
this.bucket(input.projectId).set(path, new TextEncoder().encode(input.content));
}
async writeBinary(input: PluginWorkspaceWriteBinaryInput): Promise<void> {
const path = normalizeWorkspacePath(input.path);
this.bucket(input.projectId).set(path, new Uint8Array(input.bytes));
}
async listDir(input: PluginWorkspacePathInput): Promise<PluginWorkspaceDirectoryListing> {
const path = normalizeWorkspacePath(input.path);
const prefix = path === "" ? "" : `${path}/`;
const entries = new Map<string, PluginWorkspaceDirEntry>();
for (const filePath of this.bucket(input.projectId).keys()) {
if (!filePath.startsWith(prefix)) continue;
const rest = filePath.slice(prefix.length);
if (rest === "") continue;
const [name, ...tail] = rest.split("/");
const entryPath = path === "" ? name : `${path}/${name}`;
const existing = entries.get(name);
entries.set(name, {
name,
path: entryPath,
isDir: Boolean(existing?.isDir) || tail.length > 0,
});
}
return { path, entries: [...entries.values()].sort((a, b) => a.name.localeCompare(b.name)) };
}
async stat(input: PluginWorkspacePathInput): Promise<PluginWorkspaceStat> {
const path = normalizeWorkspacePath(input.path);
const files = this.bucket(input.projectId);
const bytes = files.get(path);
if (bytes) {
return { path, exists: true, isFile: true, isDir: false, len: bytes.byteLength };
}
const prefix = path === "" ? "" : `${path}/`;
const isDir = [...files.keys()].some((filePath) => filePath.startsWith(prefix));
return { path, exists: isDir, isFile: false, isDir, len: null };
}
async queryProjectStructure(
input: PluginProjectStructureQuery,
): Promise<PluginProjectStructure> {
const rootPath = normalizeWorkspacePath(input.path ?? "");
const maxDepth = Math.min(input.maxDepth ?? 3, 8);
const maxEntries = Math.min(input.maxEntries ?? 500, 5000);
const prefix = rootPath === "" ? "" : `${rootPath}/`;
const entries = new Map<string, PluginProjectStructureEntry>();
const conventions = new Map<string, PluginProjectConvention>();
const modules = new Map<string, PluginProjectModule>();
for (const filePath of this.bucket(input.projectId).keys()) {
if (!filePath.startsWith(prefix)) continue;
const rest = filePath.slice(prefix.length);
const parts = rest.split("/").filter(Boolean);
for (let i = 0; i < parts.length && i <= maxDepth; i += 1) {
const path = [rootPath, ...parts.slice(0, i + 1)].filter(Boolean).join("/");
const isLeaf = i === parts.length - 1;
entries.set(path, {
path,
name: parts[i],
kind: isLeaf ? "file" : "directory",
});
}
const marker = basename(filePath);
const conventionId = PROJECT_MARKERS[marker];
if (conventionId) {
conventions.set(`${conventionId}:${filePath}`, { id: conventionId, markerPath: filePath });
const modulePath = filePath.slice(0, Math.max(0, filePath.length - marker.length - 1));
modules.set(`${conventionId}:${modulePath}`, {
path: modulePath,
markerPath: filePath,
conventionId,
});
}
}
const sortedEntries = [...entries.values()].sort((a, b) => a.path.localeCompare(b.path));
return {
projectId: input.projectId,
rootPath,
entries: sortedEntries.slice(0, maxEntries),
conventions: [...conventions.values()].sort((a, b) =>
a.markerPath.localeCompare(b.markerPath),
),
modules: [...modules.values()].sort((a, b) => a.path.localeCompare(b.path)),
truncated: sortedEntries.length > maxEntries,
};
}
}
/**
* In-memory command-task gateway for plugin runtime tests/dev. It models host
* task creation and status reads; live output remains owned by WorkStateGateway.
*/
export class MockPluginTaskGateway implements PluginTaskGateway {
private readonly tasks = new Map<string, PluginCommandTask>();
private nextId = 1;
async runCommand(input: PluginRunCommandInput): Promise<PluginCommandTask> {
if (input.command.trim() === "") {
const err: GatewayError = { code: "INVALID", message: "command must not be empty" };
throw err;
}
const now = Date.now();
const task: PluginCommandTask = {
taskId: `mock-plugin-task-${this.nextId++}`,
ownerAgentId: input.ownerAgentId,
projectId: input.projectId,
kind: "command",
state: "running",
exitCode: null,
summary: input.label,
stdoutTail: null,
stderrTail: null,
createdAtMs: now,
updatedAtMs: now,
};
this.tasks.set(task.taskId, task);
return task;
}
async getStatus(input: PluginTaskStatusInput): Promise<PluginCommandTask | null> {
return this.tasks.get(input.taskId) ?? null;
}
}
/**
* In-memory generic toolchain diagnostics for plugin tests/dev. It is
* deterministic and does not inspect the real host environment.
*/
export class MockPluginToolchainGateway implements PluginToolchainGateway {
async diagnose(input: PluginToolchainDiagnosticRequest): Promise<PluginToolchainDiagnostic> {
const tools = (input.tools ?? []).map((tool) => {
const missing = tool.executable.includes("missing");
const ok = !missing;
return {
id: tool.id,
executable: tool.executable,
present: ok,
ok,
status: ok ? ("ok" as const) : ("missing" as const),
required: tool.required ?? false,
exitCode: ok ? 0 : null,
version: ok ? `${tool.executable} mock-version` : null,
stdout: ok ? `${tool.executable} mock-version\n` : null,
stderr: null,
error: ok ? null : `executable not found: ${tool.executable}`,
};
});
const env = (input.env ?? []).map((requirement) => {
const present = !requirement.name.includes("MISSING");
const value = present ? (requirement.equals ?? "mock") : null;
const ok = present && (requirement.equals === undefined || value === requirement.equals);
return {
name: requirement.name,
present,
ok,
required: requirement.required ?? false,
value,
status: ok ? ("ok" as const) : present ? ("mismatch" as const) : ("missing" as const),
};
});
const files = (input.files ?? []).map((requirement) => {
const exists = !requirement.path.includes("missing");
const kind = exists ? (requirement.kind === "directory" ? "directory" : "file") : "missing";
const ok =
exists &&
(requirement.kind === undefined || requirement.kind === "any" || requirement.kind === kind);
return {
path: requirement.path,
exists,
ok,
required: requirement.required ?? false,
kind: kind as "file" | "directory" | "missing",
expectedKind: requirement.kind ?? null,
len: exists && kind === "file" ? 12 : null,
};
});
const messages = [
...tools
.filter((tool) => tool.required && !tool.ok)
.map((tool) => ({ level: "error" as const, message: `${tool.id}: ${tool.error}` })),
...env
.filter((item) => item.required && !item.ok)
.map((item) => ({ level: "error" as const, message: `${item.name}: ${item.status}` })),
...files
.filter((file) => file.required && !file.ok)
.map((file) => ({ level: "error" as const, message: `${file.path}: ${file.kind}` })),
];
return {
projectId: input.projectId,
cwd: input.cwd ?? "",
ok: messages.length === 0,
tools,
env,
files,
messages,
};
}
}
interface MockPluginEventSubscriptionState {
subscription: PluginEventSubscription;
queue: PluginPublicEvent[];
dropped: number;
}
/**
* In-memory public plugin event gateway for offline runtime tests/dev.
*/
export class MockPluginEventGateway implements PluginEventGateway {
private readonly subscriptions = new Map<string, MockPluginEventSubscriptionState>();
private nextId = 1;
async subscribe(input: PluginEventSubscribeInput): Promise<PluginEventSubscription> {
const subscription: PluginEventSubscription = {
subscriptionId: `mock-plugin-events-${this.nextId++}`,
projectId: input.projectId,
eventTypes: input.eventTypes?.length
? input.eventTypes
: ["workspaceFileChanged", "backgroundTaskChanged"],
capacity: Math.min(Math.max(input.capacity ?? 100, 1), 1000),
retention: "bestEffortBounded",
};
this.subscriptions.set(subscription.subscriptionId, {
subscription,
queue: [],
dropped: 0,
});
return subscription;
}
async poll(input: PluginEventPollInput): Promise<PluginEventBatch> {
const state = this.subscriptions.get(input.subscriptionId);
if (!state) {
const err: GatewayError = {
code: "NOT_FOUND",
message: "plugin event subscription not found",
};
throw err;
}
const maxEvents = Math.min(Math.max(input.maxEvents ?? 100, 1), 1000);
const events = state.queue.splice(0, maxEvents);
const dropped = state.dropped;
state.dropped = 0;
return { subscriptionId: input.subscriptionId, events, dropped };
}
async unsubscribe(input: PluginEventUnsubscribeInput): Promise<PluginEventSubscription> {
const state = this.subscriptions.get(input.subscriptionId);
this.subscriptions.delete(input.subscriptionId);
return (
state?.subscription ?? {
subscriptionId: input.subscriptionId,
projectId: "",
eventTypes: [],
capacity: 0,
retention: "disposed",
}
);
}
_emit(event: PluginPublicEvent): void {
for (const state of this.subscriptions.values()) {
if (
state.subscription.projectId !== event.projectId ||
!state.subscription.eventTypes.includes(event.type)
) {
continue;
}
if (state.queue.length >= state.subscription.capacity) {
state.queue.shift();
state.dropped += 1;
}
state.queue.push(event);
}
}
}
function cloneJson<T extends JsonValue>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function applyJsonMergePatch(target: JsonValue, patch: JsonValue): JsonValue {
if (patch === null || typeof patch !== "object" || Array.isArray(patch)) return cloneJson(patch);
const base =
target !== null && typeof target === "object" && !Array.isArray(target)
? { ...target }
: {};
for (const [key, value] of Object.entries(patch)) {
if (value === null) {
delete base[key];
} else {
base[key] = applyJsonMergePatch(base[key] ?? null, value);
}
}
return base;
}
/**
* In-memory JSON config-document gateway for plugin tests/dev.
*/
export class MockPluginConfigGateway implements PluginConfigGateway {
private readonly documents = new Map<string, JsonValue>();
_seed(projectId: string, path: string, value: JsonValue): void {
this.documents.set(`${projectId}:${normalizeWorkspacePath(path)}`, cloneJson(value));
}
async readDocument(input: PluginConfigDocumentReadInput): Promise<PluginConfigDocument> {
const path = normalizeWorkspacePath(input.path);
const format = input.format ?? "json";
if (format !== "json") {
const err: GatewayError = {
code: "INVALID",
message: `unsupported structured config format: ${format}; supported formats: json`,
};
throw err;
}
const value = this.documents.get(`${input.projectId}:${path}`);
if (value === undefined) {
const err: GatewayError = { code: "NOT_FOUND", message: `config document ${path} not found` };
throw err;
}
return { projectId: input.projectId, path, format, value: cloneJson(value) };
}
async updateDocument(
input: PluginConfigDocumentUpdateInput,
): Promise<PluginConfigDocumentWriteResult> {
const path = normalizeWorkspacePath(input.path);
const format = input.format ?? "json";
const mode = input.mode ?? "mergePatch";
if (format !== "json") {
const err: GatewayError = {
code: "INVALID",
message: `unsupported structured config format: ${format}; supported formats: json`,
};
throw err;
}
if (mode !== "mergePatch" && mode !== "replace") {
const err: GatewayError = {
code: "INVALID",
message: `unsupported structured config update mode: ${mode}`,
};
throw err;
}
const key = `${input.projectId}:${path}`;
const current = this.documents.get(key);
if (mode === "mergePatch" && current === undefined) {
const err: GatewayError = { code: "NOT_FOUND", message: `config document ${path} not found` };
throw err;
}
const next = mode === "replace" ? cloneJson(input.value) : applyJsonMergePatch(current!, input.value);
this.documents.set(key, next);
return {
projectId: input.projectId,
path,
format,
mode,
bytesWritten: JSON.stringify(next, null, 2).length + 1,
};
}
}
/** Builds the full set of mock gateways. */
export function createMockGateways(): Gateways {
const agentGateway = new MockAgentGateway();
@ -3569,6 +4045,11 @@ export function createMockGateways(): Gateways {
focusedProject: new MockFocusedProjectGateway(),
uiPreferences: new MockUiPreferencesGateway(),
plugin: new MockPluginGateway(),
pluginWorkspace: new MockPluginWorkspaceGateway(),
pluginTask: new MockPluginTaskGateway(),
pluginToolchain: new MockPluginToolchainGateway(),
pluginEvents: new MockPluginEventGateway(),
pluginConfig: new MockPluginConfigGateway(),
};
}

View File

@ -27,6 +27,11 @@ describe("createMockGateways", () => {
"modelServer",
"permission",
"plugin",
"pluginConfig",
"pluginEvents",
"pluginTask",
"pluginToolchain",
"pluginWorkspace",
"profile",
"project",
"remote",

View File

@ -0,0 +1,24 @@
/**
* Tauri adapter for public plugin structured configuration documents (#130).
*/
import { invoke } from "@tauri-apps/api/core";
import type { PluginConfigDocument, PluginConfigDocumentWriteResult } from "@/domain";
import type {
PluginConfigDocumentReadInput,
PluginConfigDocumentUpdateInput,
PluginConfigGateway,
} from "@/ports";
export class TauriPluginConfigGateway implements PluginConfigGateway {
readDocument(input: PluginConfigDocumentReadInput): Promise<PluginConfigDocument> {
return invoke<PluginConfigDocument>("plugin_config_read_document", { input });
}
updateDocument(
input: PluginConfigDocumentUpdateInput,
): Promise<PluginConfigDocumentWriteResult> {
return invoke<PluginConfigDocumentWriteResult>("plugin_config_update_document", { input });
}
}

View File

@ -0,0 +1,27 @@
/**
* Tauri adapter for stable public plugin events (#127).
*/
import { invoke } from "@tauri-apps/api/core";
import type { PluginEventBatch, PluginEventSubscription } from "@/domain";
import type {
PluginEventGateway,
PluginEventPollInput,
PluginEventSubscribeInput,
PluginEventUnsubscribeInput,
} from "@/ports";
export class TauriPluginEventGateway implements PluginEventGateway {
subscribe(input: PluginEventSubscribeInput): Promise<PluginEventSubscription> {
return invoke<PluginEventSubscription>("plugin_events_subscribe", { input });
}
poll(input: PluginEventPollInput): Promise<PluginEventBatch> {
return invoke<PluginEventBatch>("plugin_events_poll", { input });
}
unsubscribe(input: PluginEventUnsubscribeInput): Promise<PluginEventSubscription> {
return invoke<PluginEventSubscription>("plugin_events_unsubscribe", { input });
}
}

View File

@ -0,0 +1,40 @@
/**
* Tauri adapter for the public plugin command-task SDK facade (#125).
*/
import { invoke } from "@tauri-apps/api/core";
import type { PluginCommandTask } from "@/domain";
import type { PluginRunCommandInput, PluginTaskGateway, PluginTaskStatusInput } from "@/ports";
type PluginCommandTaskDto = Omit<
PluginCommandTask,
"exitCode" | "summary" | "stdoutTail" | "stderrTail"
> & {
exitCode?: number | null;
summary?: string | null;
stdoutTail?: string | null;
stderrTail?: string | null;
};
function normalizeTask(task: PluginCommandTaskDto): PluginCommandTask {
return {
...task,
exitCode: task.exitCode ?? null,
summary: task.summary ?? null,
stdoutTail: task.stdoutTail ?? null,
stderrTail: task.stderrTail ?? null,
};
}
export class TauriPluginTaskGateway implements PluginTaskGateway {
async runCommand(input: PluginRunCommandInput): Promise<PluginCommandTask> {
const task = await invoke<PluginCommandTaskDto>("plugin_task_run_command", { input });
return normalizeTask(task);
}
async getStatus(input: PluginTaskStatusInput): Promise<PluginCommandTask | null> {
const task = await invoke<PluginCommandTaskDto | null>("plugin_task_get_status", { input });
return task ? normalizeTask(task) : null;
}
}

View File

@ -0,0 +1,17 @@
/**
* Tauri adapter for public plugin external-toolchain diagnostics (#126).
*/
import { invoke } from "@tauri-apps/api/core";
import type { PluginToolchainDiagnostic } from "@/domain";
import type {
PluginToolchainDiagnosticRequest,
PluginToolchainGateway,
} from "@/ports";
export class TauriPluginToolchainGateway implements PluginToolchainGateway {
diagnose(input: PluginToolchainDiagnosticRequest): Promise<PluginToolchainDiagnostic> {
return invoke<PluginToolchainDiagnostic>("plugin_toolchain_diagnose", { input });
}
}

View File

@ -0,0 +1,77 @@
/**
* Tauri adapter for the public plugin workspace/project-structure SDK facade
* (#124 + #129). The commands are plugin-scoped even though the gateway is
* frontend-internal: plugins only see the stable service methods.
*/
import { invoke } from "@tauri-apps/api/core";
import type {
PluginProjectStructure,
PluginWorkspaceBinaryFile,
PluginWorkspaceDirectoryListing,
PluginWorkspaceStat,
PluginWorkspaceTextFile,
} from "@/domain";
import type {
PluginProjectStructureQuery,
PluginWorkspaceGateway,
PluginWorkspacePathInput,
PluginWorkspaceWriteBinaryInput,
PluginWorkspaceWriteTextInput,
} from "@/ports";
type BinaryFileDto = Omit<PluginWorkspaceBinaryFile, "bytes"> & {
bytes: number[] | Uint8Array;
};
function toByteArray(bytes: number[] | Uint8Array): Uint8Array {
return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
}
function normalizeBinaryFile(file: BinaryFileDto): PluginWorkspaceBinaryFile {
return { ...file, bytes: toByteArray(file.bytes) };
}
function binaryInput(input: PluginWorkspaceWriteBinaryInput): {
projectId: string;
path: string;
bytes: number[];
} {
return {
projectId: input.projectId,
path: input.path,
bytes: Array.from(input.bytes),
};
}
export class TauriPluginWorkspaceGateway implements PluginWorkspaceGateway {
readText(input: PluginWorkspacePathInput): Promise<PluginWorkspaceTextFile> {
return invoke<PluginWorkspaceTextFile>("plugin_workspace_read_text", { input });
}
async readBinary(input: PluginWorkspacePathInput): Promise<PluginWorkspaceBinaryFile> {
const file = await invoke<BinaryFileDto>("plugin_workspace_read_binary", { input });
return normalizeBinaryFile(file);
}
async writeText(input: PluginWorkspaceWriteTextInput): Promise<void> {
await invoke("plugin_workspace_write_text", { input });
}
async writeBinary(input: PluginWorkspaceWriteBinaryInput): Promise<void> {
await invoke("plugin_workspace_write_binary", { input: binaryInput(input) });
}
listDir(input: PluginWorkspacePathInput): Promise<PluginWorkspaceDirectoryListing> {
return invoke<PluginWorkspaceDirectoryListing>("plugin_workspace_list_dir", { input });
}
stat(input: PluginWorkspacePathInput): Promise<PluginWorkspaceStat> {
return invoke<PluginWorkspaceStat>("plugin_workspace_stat", { input });
}
queryProjectStructure(input: PluginProjectStructureQuery): Promise<PluginProjectStructure> {
return invoke<PluginProjectStructure>("plugin_query_project_structure", { input });
}
}

View File

@ -1760,6 +1760,234 @@ export interface PluginRuntimeContributionCatalog {
plugins: PluginRuntimePlugin[];
}
// ---------------------------------------------------------------------------
// Plugin SDK workspace/project-structure API (#124 + #129)
// ---------------------------------------------------------------------------
/** A UTF-8 workspace file returned by the public plugin workspace API. */
export interface PluginWorkspaceTextFile {
path: string;
content: string;
}
/** A binary workspace file returned by the public plugin workspace API. */
export interface PluginWorkspaceBinaryFile {
path: string;
bytes: Uint8Array;
}
/** One entry in a plugin-visible workspace directory listing. */
export interface PluginWorkspaceDirEntry {
name: string;
path: string;
isDir: boolean;
}
/** Directory listing returned by the public plugin workspace API. */
export interface PluginWorkspaceDirectoryListing {
path: string;
entries: PluginWorkspaceDirEntry[];
}
/** Basic plugin-visible stat result for one workspace path. */
export interface PluginWorkspaceStat {
path: string;
exists: boolean;
isFile: boolean;
isDir: boolean;
len: number | null;
}
export type PluginProjectStructureEntryKind = "file" | "directory";
/** One bounded project-structure entry returned to plugins. */
export interface PluginProjectStructureEntry {
path: string;
name: string;
kind: PluginProjectStructureEntryKind;
}
/** Generic convention detected from marker files. */
export interface PluginProjectConvention {
id: string;
markerPath: string;
}
/** Generic logical module inferred from marker files. */
export interface PluginProjectModule {
path: string;
markerPath: string;
conventionId: string;
}
/** Bounded, generic project-structure query result for plugins. */
export interface PluginProjectStructure {
projectId: string;
rootPath: string;
entries: PluginProjectStructureEntry[];
conventions: PluginProjectConvention[];
modules: PluginProjectModule[];
truncated: boolean;
}
// ---------------------------------------------------------------------------
// Plugin SDK command-task API (#125)
// ---------------------------------------------------------------------------
export type PluginCommandTaskState =
| "queued"
| "running"
| "waiting"
| "completed"
| "failed"
| "cancelled"
| "expired";
/** One command-backed task launched through the public plugin task API. */
export interface PluginCommandTask {
taskId: string;
ownerAgentId: string;
projectId: string;
kind: string;
state: PluginCommandTaskState;
exitCode: number | null;
summary: string | null;
stdoutTail: string | null;
stderrTail: string | null;
createdAtMs: number;
updatedAtMs: number;
}
// ---------------------------------------------------------------------------
// Plugin SDK external-toolchain diagnostics API (#126)
// ---------------------------------------------------------------------------
export type PluginToolStatus = "ok" | "failed" | "missing";
export type PluginEnvStatus = "ok" | "missing" | "mismatch";
export type PluginFileKind = "file" | "directory" | "other" | "missing";
export type PluginExpectedFileKind = "file" | "directory" | "any";
export type PluginDiagnosticLevel = "info" | "warning" | "error";
/** Generic diagnostic result for external tools, env vars and workspace files. */
export interface PluginToolchainDiagnostic {
projectId: string;
cwd: string;
ok: boolean;
tools: PluginToolDiagnostic[];
env: PluginEnvDiagnostic[];
files: PluginFileDiagnostic[];
messages: PluginDiagnosticMessage[];
}
export interface PluginToolDiagnostic {
id: string;
executable: string;
present: boolean;
ok: boolean;
status: PluginToolStatus;
required: boolean;
exitCode: number | null;
version: string | null;
stdout: string | null;
stderr: string | null;
error: string | null;
}
export interface PluginEnvDiagnostic {
name: string;
present: boolean;
ok: boolean;
required: boolean;
value: string | null;
status: PluginEnvStatus;
}
export interface PluginFileDiagnostic {
path: string;
exists: boolean;
ok: boolean;
required: boolean;
kind: PluginFileKind;
expectedKind: PluginExpectedFileKind | null;
len: number | null;
}
export interface PluginDiagnosticMessage {
level: PluginDiagnosticLevel;
message: string;
}
// ---------------------------------------------------------------------------
// Plugin SDK public event/watch API (#127)
// ---------------------------------------------------------------------------
export type PluginPublicEventType = "workspaceFileChanged" | "backgroundTaskChanged";
export interface PluginEventSubscription {
subscriptionId: string;
projectId: string;
eventTypes: PluginPublicEventType[];
capacity: number;
retention: "bestEffortBounded" | "disposed" | string;
}
export interface PluginEventBatch {
subscriptionId: string;
events: PluginPublicEvent[];
dropped: number;
}
export type PluginPublicEvent = PluginWorkspaceFileChangedEvent | PluginBackgroundTaskChangedEvent;
export interface PluginWorkspaceFileChangedEvent {
type: "workspaceFileChanged";
sequence: number;
occurredAtMs: number;
projectId: string;
path: string;
operation: string;
}
export interface PluginBackgroundTaskChangedEvent {
type: "backgroundTaskChanged";
sequence: number;
occurredAtMs: number;
projectId: string;
taskId: string;
ownerAgentId: string;
state: string;
}
// ---------------------------------------------------------------------------
// Plugin SDK structured configuration documents API (#130)
// ---------------------------------------------------------------------------
export type JsonValue =
| null
| boolean
| number
| string
| JsonValue[]
| { [key: string]: JsonValue };
export type PluginConfigDocumentFormat = "json";
export type PluginConfigUpdateMode = "mergePatch" | "replace";
export interface PluginConfigDocument {
projectId: string;
path: string;
format: PluginConfigDocumentFormat;
value: JsonValue;
}
export interface PluginConfigDocumentWriteResult {
projectId: string;
path: string;
format: PluginConfigDocumentFormat;
mode: PluginConfigUpdateMode;
bytesWritten: number;
}
/** Manifest declaration of a top-level menu (carnet §7.1). */
export interface PluginTopLevelMenuContribution {
id: string;

View File

@ -30,7 +30,10 @@ function cell(overrides: Partial<CustomPluginLayoutCell> = {}): CustomPluginLayo
};
}
let latestLayoutProps: PluginLayoutProps | null = null;
function MockLayoutComponent(props: PluginLayoutProps) {
latestLayoutProps = props;
return (
<div>
<p data-testid="state">{JSON.stringify(props.state)}</p>
@ -87,8 +90,11 @@ describe("PluginLayoutCellView", () => {
it("renders the mock registered component when the provider is loaded", () => {
const registry = new PluginRuntimeRegistry();
registry.add(stubPlugin());
latestLayoutProps = null;
renderCell(registry);
expect(screen.getByTestId("state").textContent).toBe(JSON.stringify({ commits: 3 }));
expect(latestLayoutProps).not.toBeNull();
expect(Object.prototype.hasOwnProperty.call(latestLayoutProps, "gateways")).toBe(false);
});
it("round-trips state through setState → onStateChange", () => {

View File

@ -13,7 +13,6 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import type { CustomPluginLayoutCell, PluginAdmin } from "@/domain";
import { useGateways } from "@/app/di";
import { usePluginRuntime } from "./PluginRuntimeProvider";
import { PluginLayoutFallback } from "./PluginLayoutFallback";
import { resolvePluginLayoutAvailability } from "./layoutAvailability";
@ -68,7 +67,6 @@ export function PluginLayoutCellView({
onChooseAnotherLayout,
}: PluginLayoutCellViewProps) {
const { registry } = usePluginRuntime();
const gateways = useGateways();
const availability = resolvePluginLayoutAvailability(registry, cell, installedPlugins);
const providerDisplayName =
registry.get(cell.pluginId)?.displayName ??
@ -108,15 +106,6 @@ export function PluginLayoutCellView({
state={cell.state}
setState={onStateChange}
availability="available"
gateways={{
project: gateways.project,
git: gateways.git,
terminal: gateways.terminal,
agents: gateways.agent,
system: gateways.system,
workState: gateways.workState,
focusedProject: gateways.focusedProject,
}}
/>
</PluginLayoutErrorBoundary>
);

View File

@ -75,6 +75,11 @@ export function PluginRuntimeProvider({ children, value: injected }: PluginRunti
system: gateways.system,
workState: gateways.workState,
focusedProject: gateways.focusedProject,
pluginWorkspace: gateways.pluginWorkspace,
pluginTask: gateways.pluginTask,
pluginToolchain: gateways.pluginToolchain,
pluginEvents: gateways.pluginEvents,
pluginConfig: gateways.pluginConfig,
}),
)
.then((result) => {

View File

@ -24,12 +24,52 @@ export {
type BackgroundTaskRetryResult,
type BackgroundTaskService,
type BackgroundTaskStatus,
type ConfigDocument,
type ConfigDocumentFormat,
type ConfigDocumentReadOptions,
type ConfigDocumentService,
type ConfigDocumentUpdateOptions,
type ConfigDocumentWriteResult,
type ConfigUpdateMode,
type CommandTaskStatus,
type DiagnosticMessage,
type EnvDiagnostic,
type EnvRequirement,
type EventHandler,
type EventService,
type EventSubscribeOptions,
type EventSubscription,
type FileDiagnostic,
type FileRequirement,
type PluginServices,
type PublicEvent,
type PublicEventType,
type RunCommandTaskOptions,
type TerminalOpenOptions,
type TerminalReattachOptions,
type TerminalReattachResult,
type TerminalService,
type TerminalSession,
type ToolchainDiagnostic,
type ToolchainDiagnosticRequest,
type ToolDiagnostic,
type ToolingService,
type ToolRequirement,
type ProjectConvention,
type ProjectModule,
type ProjectStructure,
type ProjectStructureEntry,
type ProjectStructureEntryKind,
type WorkspaceBinaryFile,
type WorkspaceDirEntry,
type WorkspaceDirectoryListing,
type WorkspaceResolvedPath,
type WorkspaceStat,
type WorkspaceStructureQuery,
type WorkspaceTextFile,
type WorkspaceWatch,
type WorkspaceWatchEvent,
type WorkspaceWatchHandler,
type WorkspaceProject,
type WorkspaceService,
} from "./services";

View File

@ -196,9 +196,27 @@ describe("loadPlugins", () => {
it("injects the public plugin services facade for plugins declaring tooling", async () => {
const bundle = dataUrl(`
export function activate(ctx) {
globalThis.__activationContextKeys = Object.keys(ctx).sort();
globalThis.__hasPrivateGateway = [
"project",
"git",
"terminal",
"agents",
"system",
"workState",
"focusedProject",
"pluginWorkspace",
"pluginTask",
"pluginToolchain",
"pluginEvents",
"pluginConfig",
].some((key) => key in ctx);
globalThis.__serviceKeys = Object.keys(ctx.services).sort();
globalThis.__workspaceServiceKeys = Object.keys(ctx.services.workspace).sort();
globalThis.__taskServiceKeys = Object.keys(ctx.services.tasks).sort();
globalThis.__toolingServiceKeys = Object.keys(ctx.services.tooling).sort();
globalThis.__eventServiceKeys = Object.keys(ctx.services.events).sort();
globalThis.__configServiceKeys = Object.keys(ctx.services.config).sort();
globalThis.__terminalServiceKeys = Object.keys(ctx.services.terminal).sort();
}
`);
@ -215,23 +233,59 @@ describe("loadPlugins", () => {
);
expect(failures).toEqual([]);
expect((globalThis as Record<string, unknown>).__activationContextKeys).toEqual([
"commands",
"layouts",
"logger",
"menu",
"pluginDisplayName",
"pluginId",
"services",
"subscriptions",
"version",
]);
expect((globalThis as Record<string, unknown>).__hasPrivateGateway).toBe(false);
expect((globalThis as Record<string, unknown>).__serviceKeys).toEqual([
"config",
"events",
"tasks",
"terminal",
"tooling",
"workspace",
]);
expect((globalThis as Record<string, unknown>).__workspaceServiceKeys).toEqual([
"getCurrentProject",
"getProjectRoot",
"listDirectory",
"queryStructure",
"readBinaryFile",
"readProjectContext",
"readTextFile",
"resolvePath",
"stat",
"updateProjectContext",
"watch",
"writeBinaryFile",
"writeTextFile",
]);
expect((globalThis as Record<string, unknown>).__taskServiceKeys).toEqual([
"attachOutput",
"cancel",
"getCommandStatus",
"getStatus",
"list",
"retry",
"runCommand",
]);
expect((globalThis as Record<string, unknown>).__toolingServiceKeys).toEqual([
"diagnose",
]);
expect((globalThis as Record<string, unknown>).__eventServiceKeys).toEqual([
"subscribe",
]);
expect((globalThis as Record<string, unknown>).__configServiceKeys).toEqual([
"readDocument",
"updateDocument",
]);
expect((globalThis as Record<string, unknown>).__terminalServiceKeys).toEqual([
"close",

View File

@ -3,8 +3,8 @@
*
* At UI bootstrap, the app calls {@link loadPlugins} once with the catalog
* from `PluginGateway.listRuntimeContributions()` (already filtered by the
* backend to `enabled && !pendingUninstall`, carnet §1.3) and the stable
* gateways the plugin context exposes. For each entry it dynamically imports
* backend to `enabled && !pendingUninstall`, carnet §1.3) and the gateway set
* used to build the public service facade. For each entry it dynamically imports
* the bundle URL, validates the module shape, and calls `activate(ctx)`,
* scoping the command/layout registries to exactly the ids declared in that
* plugin's manifest (enforced by {@link PluginCommandRegistry}/
@ -29,7 +29,7 @@ import { createPluginServices, type PluginServices } from "./services";
export type { PluginGatewaySet } from "./registry";
export interface IdeaPluginContext extends PluginGatewaySet {
export interface IdeaPluginContext {
pluginId: string;
pluginDisplayName: string;
version: string;
@ -251,7 +251,6 @@ async function loadOne(
commands: createCommandContext(commands),
layouts,
menu,
...gateways,
};
if (hasCapability(entry, "tooling")) {
ctx.services = createPluginServices(gateways);

View File

@ -23,13 +23,18 @@ import type {
AgentGateway,
FocusedProjectGateway,
GitGateway,
PluginConfigGateway,
PluginEventGateway,
PluginTaskGateway,
PluginToolchainGateway,
PluginWorkspaceGateway,
ProjectGateway,
SystemGateway,
TerminalGateway,
WorkStateGateway,
} from "@/ports";
/** The stable gateways a plugin's `activate(ctx)` is allowed to reach (carnet §6). */
/** Internal gateways used to build the public plugin service facade. */
export interface PluginGatewaySet {
project: ProjectGateway;
git: GitGateway;
@ -38,6 +43,11 @@ export interface PluginGatewaySet {
system: SystemGateway;
workState: WorkStateGateway;
focusedProject: FocusedProjectGateway;
pluginWorkspace: PluginWorkspaceGateway;
pluginTask: PluginTaskGateway;
pluginToolchain: PluginToolchainGateway;
pluginEvents: PluginEventGateway;
pluginConfig: PluginConfigGateway;
}
/** A disposable handle returned by every `register*` call. */
@ -97,7 +107,6 @@ export interface PluginLayoutProps {
state: unknown;
setState(next: unknown): void;
availability: "available";
gateways: PluginGatewaySet;
}
export interface PluginLayoutDefinition {

View File

@ -4,6 +4,11 @@ import type { ProjectWorkState } from "@/domain";
import type {
BackgroundTaskAttachment,
FocusedProjectGateway,
PluginConfigGateway,
PluginEventGateway,
PluginTaskGateway,
PluginToolchainGateway,
PluginWorkspaceGateway,
ProjectGateway,
ReattachResult,
TerminalGateway,
@ -27,6 +32,11 @@ function gateways(overrides: {
project?: Partial<ProjectGateway>;
workState?: Partial<WorkStateGateway>;
terminal?: Partial<TerminalGateway>;
pluginWorkspace?: Partial<PluginWorkspaceGateway>;
pluginTask?: Partial<PluginTaskGateway>;
pluginToolchain?: Partial<PluginToolchainGateway>;
pluginEvents?: Partial<PluginEventGateway>;
pluginConfig?: Partial<PluginConfigGateway>;
} = {}) {
const focusedProject: FocusedProjectGateway = {
setFocusedProject: vi.fn(),
@ -79,8 +89,163 @@ function gateways(overrides: {
closeTerminal: vi.fn(),
...overrides.terminal,
};
const pluginWorkspace: PluginWorkspaceGateway = {
readText: vi.fn(async ({ path }) => ({ path, content: "file text" })),
readBinary: vi.fn(async ({ path }) => ({ path, bytes: new Uint8Array([67]) })),
writeText: vi.fn(),
writeBinary: vi.fn(),
listDir: vi.fn(async ({ path }) => ({
path,
entries: [{ name: "main.ts", path: `${path}/main.ts`, isDir: false }],
})),
stat: vi.fn(async ({ path }) => ({
path,
exists: true,
isFile: true,
isDir: false,
len: 9,
})),
queryProjectStructure: vi.fn(async ({ projectId, path }) => ({
projectId,
rootPath: path ?? "",
entries: [{ path: "package.json", name: "package.json", kind: "file" as const }],
conventions: [{ id: "node-package", markerPath: "package.json" }],
modules: [{ path: "", markerPath: "package.json", conventionId: "node-package" }],
truncated: false,
})),
...overrides.pluginWorkspace,
};
const pluginTask: PluginTaskGateway = {
runCommand: vi.fn(async (input) => ({
taskId: "task-command-1",
ownerAgentId: input.ownerAgentId,
projectId: input.projectId,
kind: "command",
state: "running" as const,
exitCode: null,
summary: input.label,
stdoutTail: null,
stderrTail: null,
createdAtMs: 10,
updatedAtMs: 10,
})),
getStatus: vi.fn(async ({ taskId }) => ({
taskId,
ownerAgentId: "agent-1",
projectId: "project-1",
kind: "command",
state: "completed" as const,
exitCode: 0,
summary: "ok",
stdoutTail: "done",
stderrTail: null,
createdAtMs: 10,
updatedAtMs: 20,
})),
...overrides.pluginTask,
};
const pluginToolchain: PluginToolchainGateway = {
diagnose: vi.fn(async ({ projectId, cwd }) => ({
projectId,
cwd: cwd ?? "",
ok: true,
tools: [
{
id: "node",
executable: "node",
present: true,
ok: true,
status: "ok" as const,
required: true,
exitCode: 0,
version: "v20.0.0",
stdout: "v20.0.0\n",
stderr: null,
error: null,
},
],
env: [
{
name: "CI",
present: true,
ok: true,
required: false,
value: "1",
status: "ok" as const,
},
],
files: [
{
path: "package.json",
exists: true,
ok: true,
required: true,
kind: "file" as const,
expectedKind: "file" as const,
len: 42,
},
],
messages: [],
})),
...overrides.pluginToolchain,
};
const pluginEvents: PluginEventGateway = {
subscribe: vi.fn(async ({ projectId, eventTypes, capacity }) => ({
subscriptionId: "subscription-1",
projectId,
eventTypes: eventTypes?.length
? eventTypes
: ["workspaceFileChanged", "backgroundTaskChanged"],
capacity: capacity ?? 100,
retention: "bestEffortBounded",
})),
poll: vi.fn(async ({ subscriptionId }) => ({
subscriptionId,
events: [],
dropped: 0,
})),
unsubscribe: vi.fn(async ({ subscriptionId }) => ({
subscriptionId,
projectId: "project-1",
eventTypes: [],
capacity: 0,
retention: "disposed",
})),
...overrides.pluginEvents,
};
const pluginConfig: PluginConfigGateway = {
readDocument: vi.fn(async ({ projectId, path, format }) => ({
projectId,
path,
format: format ?? "json",
value: { enabled: true, nested: { count: 1 } },
})),
updateDocument: vi.fn(async ({ projectId, path, format, mode }) => ({
projectId,
path,
format: format ?? "json",
mode: mode ?? "mergePatch",
bytesWritten: 42,
})),
...overrides.pluginConfig,
};
return { focusedProject, project, workState, terminal };
return {
focusedProject,
project,
workState,
terminal,
pluginWorkspace,
pluginTask,
pluginToolchain,
pluginEvents,
pluginConfig,
};
}
async function flushMicrotasks(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
}
describe("createPluginServices", () => {
@ -155,6 +320,298 @@ describe("createPluginServices", () => {
expect(detach).toHaveBeenCalled();
});
it("launches command-backed tasks through the public plugin task gateway", async () => {
const g = gateways();
const services = createPluginServices(g);
await expect(
services.tasks.runCommand({
ownerAgentId: "agent-1",
command: "npm",
args: ["test", "--", "workspace"],
cwd: "frontend",
env: { CI: "1" },
recordOnly: true,
deadlineMs: 123_000,
}),
).resolves.toMatchObject({
taskId: "task-command-1",
ownerAgentId: "agent-1",
projectId: "project-1",
state: "running",
summary: "npm test -- workspace",
});
expect(g.pluginTask.runCommand).toHaveBeenCalledWith({
projectId: "project-1",
ownerAgentId: "agent-1",
label: "npm test -- workspace",
command: "npm",
args: ["test", "--", "workspace"],
cwd: "frontend",
env: [["CI", "1"]],
recordOnly: true,
deadlineMs: 123_000,
});
await expect(services.tasks.getCommandStatus("task-command-1")).resolves.toMatchObject({
taskId: "task-command-1",
state: "completed",
exitCode: 0,
stdoutTail: "done",
});
expect(g.pluginTask.getStatus).toHaveBeenCalledWith({ taskId: "task-command-1" });
});
it("delegates workspace file and structure operations through the public plugin gateway", async () => {
const g = gateways();
const services = createPluginServices(g);
await expect(services.workspace.resolvePath("src/main.ts")).resolves.toEqual({
projectId: "project-1",
root: "/workspace/project-one",
path: "src/main.ts",
});
await expect(services.workspace.readTextFile("README.md")).resolves.toEqual({
path: "README.md",
content: "file text",
});
await expect(services.workspace.readBinaryFile("asset.bin")).resolves.toEqual({
path: "asset.bin",
bytes: new Uint8Array([67]),
});
await services.workspace.writeTextFile("generated.txt", "hello");
expect(g.pluginWorkspace.writeText).toHaveBeenCalledWith({
projectId: "project-1",
path: "generated.txt",
content: "hello",
});
await services.workspace.writeBinaryFile("generated.bin", new Uint8Array([1, 2]));
expect(g.pluginWorkspace.writeBinary).toHaveBeenCalledWith({
projectId: "project-1",
path: "generated.bin",
bytes: new Uint8Array([1, 2]),
});
await expect(services.workspace.listDirectory("src")).resolves.toMatchObject({
path: "src",
entries: [{ name: "main.ts", path: "src/main.ts", isDir: false }],
});
await expect(services.workspace.stat("README.md")).resolves.toMatchObject({
path: "README.md",
exists: true,
});
await expect(services.workspace.queryStructure({ maxDepth: 2 })).resolves.toMatchObject({
projectId: "project-1",
conventions: [{ id: "node-package", markerPath: "package.json" }],
});
});
it("delegates generic toolchain diagnostics through the public plugin gateway", async () => {
const g = gateways();
const services = createPluginServices(g);
await expect(
services.tooling.diagnose({
cwd: "frontend",
tools: [
{
id: "node",
executable: "node",
versionArgs: ["--version"],
required: true,
env: { CI: "1" },
},
],
env: [{ name: "CI" }],
files: [{ path: "package.json", required: true, kind: "file" }],
}),
).resolves.toMatchObject({
projectId: "project-1",
ok: true,
tools: [{ id: "node", version: "v20.0.0" }],
});
expect(g.pluginToolchain.diagnose).toHaveBeenCalledWith({
projectId: "project-1",
cwd: "frontend",
tools: [
{
id: "node",
executable: "node",
versionArgs: ["--version"],
required: true,
env: [["CI", "1"]],
},
],
env: [{ name: "CI" }],
files: [{ path: "package.json", required: true, kind: "file" }],
});
});
it("subscribes to public plugin events and disposes the host subscription", async () => {
const handler = vi.fn();
const onDropped = vi.fn();
const g = gateways({
pluginEvents: {
poll: vi.fn(async ({ subscriptionId }) => ({
subscriptionId,
dropped: 2,
events: [
{
type: "backgroundTaskChanged" as const,
sequence: 7,
occurredAtMs: 10,
projectId: "project-1",
taskId: "task-1",
ownerAgentId: "agent-1",
state: "completed",
},
],
})),
},
});
const services = createPluginServices(g);
const subscription = await services.events.subscribe(
{
eventTypes: ["backgroundTaskChanged"],
capacity: 10,
maxEventsPerPoll: 5,
pollIntervalMs: 60_000,
onDropped,
},
handler,
);
await flushMicrotasks();
expect(subscription.subscriptionId).toBe("subscription-1");
expect(g.pluginEvents.subscribe).toHaveBeenCalledWith({
projectId: "project-1",
eventTypes: ["backgroundTaskChanged"],
capacity: 10,
});
expect(g.pluginEvents.poll).toHaveBeenCalledWith({
subscriptionId: "subscription-1",
maxEvents: 5,
});
expect(onDropped).toHaveBeenCalledWith(2);
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({ type: "backgroundTaskChanged", taskId: "task-1" }),
);
subscription.dispose();
expect(g.pluginEvents.unsubscribe).toHaveBeenCalledWith({
subscriptionId: "subscription-1",
});
});
it("implements workspace.watch through public workspace file events", async () => {
const handler = vi.fn();
const g = gateways({
pluginWorkspace: {
stat: vi.fn(async ({ path }) => ({
path,
exists: true,
isFile: false,
isDir: true,
len: null,
})),
},
pluginEvents: {
poll: vi.fn(async ({ subscriptionId }) => ({
subscriptionId,
dropped: 0,
events: [
{
type: "workspaceFileChanged" as const,
sequence: 1,
occurredAtMs: 11,
projectId: "project-1",
path: "src/main.ts",
operation: "writeText",
},
{
type: "workspaceFileChanged" as const,
sequence: 2,
occurredAtMs: 12,
projectId: "project-1",
path: "README.md",
operation: "writeText",
},
],
})),
},
});
const services = createPluginServices(g);
const watch = await services.workspace.watch("src", handler);
await flushMicrotasks();
expect(g.pluginEvents.subscribe).toHaveBeenCalledWith({
projectId: "project-1",
eventTypes: ["workspaceFileChanged"],
capacity: undefined,
});
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith({
path: "src/main.ts",
kind: "created",
operation: "writeText",
projectId: "project-1",
});
watch.dispose();
expect(g.pluginEvents.unsubscribe).toHaveBeenCalledWith({
subscriptionId: "subscription-1",
});
});
it("delegates structured config document operations through the public plugin gateway", async () => {
const g = gateways();
const services = createPluginServices(g);
await expect(
services.config.readDocument({
path: "config/settings.json",
}),
).resolves.toMatchObject({
projectId: "project-1",
path: "config/settings.json",
format: "json",
value: { enabled: true },
});
await expect(
services.config.updateDocument({
path: "config/settings.json",
mode: "mergePatch",
value: { enabled: false, removeMe: null },
}),
).resolves.toMatchObject({
projectId: "project-1",
path: "config/settings.json",
format: "json",
mode: "mergePatch",
bytesWritten: 42,
});
expect(g.pluginConfig.readDocument).toHaveBeenCalledWith({
projectId: "project-1",
path: "config/settings.json",
format: undefined,
});
expect(g.pluginConfig.updateDocument).toHaveBeenCalledWith({
projectId: "project-1",
path: "config/settings.json",
format: undefined,
mode: "mergePatch",
value: { enabled: false, removeMe: null },
});
});
it("opens terminal sessions with project-root defaults and delegates controls", async () => {
const g = gateways();
const services = createPluginServices(g);

View File

@ -1,9 +1,21 @@
import type { BackgroundCompletion } from "@/domain";
import type {
BackgroundCompletion,
JsonValue,
PluginCommandTask,
PluginPublicEvent,
PluginPublicEventType,
} from "@/domain";
import type {
BackgroundTaskAttachment,
FocusedProject,
FocusedProjectGateway,
OpenTerminalOptions,
PluginConfigGateway,
PluginEventGateway,
PluginProjectStructureQuery,
PluginTaskGateway,
PluginToolchainGateway,
PluginWorkspaceGateway,
ProjectGateway,
TerminalGateway,
WorkStateGateway,
@ -12,6 +24,9 @@ import type {
export interface PluginServices {
workspace: WorkspaceService;
tasks: BackgroundTaskService;
tooling: ToolingService;
events: EventService;
config: ConfigDocumentService;
terminal: TerminalService;
}
@ -26,6 +41,98 @@ export interface WorkspaceService {
getProjectRoot(projectId?: string): Promise<string>;
readProjectContext(projectId?: string): Promise<string>;
updateProjectContext(content: string, projectId?: string): Promise<void>;
resolvePath(path: string, projectId?: string): Promise<WorkspaceResolvedPath>;
readTextFile(path: string, projectId?: string): Promise<WorkspaceTextFile>;
readBinaryFile(path: string, projectId?: string): Promise<WorkspaceBinaryFile>;
writeTextFile(path: string, content: string, projectId?: string): Promise<void>;
writeBinaryFile(path: string, bytes: Uint8Array, projectId?: string): Promise<void>;
listDirectory(path?: string, projectId?: string): Promise<WorkspaceDirectoryListing>;
stat(path: string, projectId?: string): Promise<WorkspaceStat>;
watch(path: string, handler: WorkspaceWatchHandler, projectId?: string): Promise<WorkspaceWatch>;
queryStructure(query?: WorkspaceStructureQuery): Promise<ProjectStructure>;
}
export interface WorkspaceResolvedPath {
projectId: string;
root: string;
path: string;
}
export interface WorkspaceTextFile {
path: string;
content: string;
}
export interface WorkspaceBinaryFile {
path: string;
bytes: Uint8Array;
}
export interface WorkspaceDirEntry {
name: string;
path: string;
isDir: boolean;
}
export interface WorkspaceDirectoryListing {
path: string;
entries: WorkspaceDirEntry[];
}
export interface WorkspaceStat {
path: string;
exists: boolean;
isFile: boolean;
isDir: boolean;
len: number | null;
}
export interface WorkspaceWatchEvent {
path: string;
kind: "created" | "modified" | "deleted" | "renamed" | "unknown";
operation: string;
projectId: string;
}
export type WorkspaceWatchHandler = (event: WorkspaceWatchEvent) => void;
export interface WorkspaceWatch {
dispose(): void;
}
export interface WorkspaceStructureQuery {
projectId?: string;
path?: string;
maxDepth?: number;
maxEntries?: number;
}
export type ProjectStructureEntryKind = "file" | "directory";
export interface ProjectStructureEntry {
path: string;
name: string;
kind: ProjectStructureEntryKind;
}
export interface ProjectConvention {
id: string;
markerPath: string;
}
export interface ProjectModule {
path: string;
markerPath: string;
conventionId: string;
}
export interface ProjectStructure {
projectId: string;
rootPath: string;
entries: ProjectStructureEntry[];
conventions: ProjectConvention[];
modules: ProjectModule[];
truncated: boolean;
}
export interface BackgroundTaskStatus {
@ -52,7 +159,177 @@ export interface BackgroundTaskRetryResult {
taskId?: string;
}
export interface RunCommandTaskOptions {
projectId?: string;
ownerAgentId: string;
label?: string;
command: string;
args?: string[];
cwd?: string;
env?: Record<string, string> | Array<[string, string]>;
recordOnly?: boolean;
deadlineMs?: number;
}
export interface CommandTaskStatus {
taskId: string;
ownerAgentId: string;
projectId: string;
kind: string;
state: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "expired";
exitCode: number | null;
summary: string | null;
stdoutTail: string | null;
stderrTail: string | null;
createdAtMs: number;
updatedAtMs: number;
}
export interface ToolRequirement {
id: string;
executable: string;
versionArgs?: string[];
required?: boolean;
env?: Record<string, string> | Array<[string, string]>;
}
export interface EnvRequirement {
name: string;
required?: boolean;
equals?: string;
}
export interface FileRequirement {
path: string;
required?: boolean;
kind?: "file" | "directory" | "any";
}
export interface ToolchainDiagnosticRequest {
projectId?: string;
cwd?: string;
tools?: ToolRequirement[];
env?: EnvRequirement[];
files?: FileRequirement[];
}
export interface ToolchainDiagnostic {
projectId: string;
cwd: string;
ok: boolean;
tools: ToolDiagnostic[];
env: EnvDiagnostic[];
files: FileDiagnostic[];
messages: DiagnosticMessage[];
}
export interface ToolDiagnostic {
id: string;
executable: string;
present: boolean;
ok: boolean;
status: "ok" | "failed" | "missing";
required: boolean;
exitCode: number | null;
version: string | null;
stdout: string | null;
stderr: string | null;
error: string | null;
}
export interface EnvDiagnostic {
name: string;
present: boolean;
ok: boolean;
required: boolean;
value: string | null;
status: "ok" | "missing" | "mismatch";
}
export interface FileDiagnostic {
path: string;
exists: boolean;
ok: boolean;
required: boolean;
kind: "file" | "directory" | "other" | "missing";
expectedKind: "file" | "directory" | "any" | null;
len: number | null;
}
export interface DiagnosticMessage {
level: "info" | "warning" | "error";
message: string;
}
export interface ToolingService {
diagnose(request: ToolchainDiagnosticRequest): Promise<ToolchainDiagnostic>;
}
export type PublicEvent = PluginPublicEvent;
export type PublicEventType = PluginPublicEventType;
export interface EventSubscribeOptions {
projectId?: string;
eventTypes?: PublicEventType[];
capacity?: number;
pollIntervalMs?: number;
maxEventsPerPoll?: number;
onDropped?: (count: number) => void;
}
export interface EventSubscription {
readonly subscriptionId: string;
readonly projectId: string;
readonly eventTypes: PublicEventType[];
readonly retention: string;
dispose(): void;
}
export type EventHandler = (event: PublicEvent) => void;
export interface EventService {
subscribe(options: EventSubscribeOptions, handler: EventHandler): Promise<EventSubscription>;
}
export type ConfigDocumentFormat = "json";
export type ConfigUpdateMode = "mergePatch" | "replace";
export interface ConfigDocumentReadOptions {
projectId?: string;
path: string;
format?: ConfigDocumentFormat;
}
export interface ConfigDocumentUpdateOptions extends ConfigDocumentReadOptions {
mode?: ConfigUpdateMode;
value: JsonValue;
}
export interface ConfigDocument<T extends JsonValue = JsonValue> {
projectId: string;
path: string;
format: ConfigDocumentFormat;
value: T;
}
export interface ConfigDocumentWriteResult {
projectId: string;
path: string;
format: ConfigDocumentFormat;
mode: ConfigUpdateMode;
bytesWritten: number;
}
export interface ConfigDocumentService {
readDocument<T extends JsonValue = JsonValue>(
options: ConfigDocumentReadOptions,
): Promise<ConfigDocument<T>>;
updateDocument(options: ConfigDocumentUpdateOptions): Promise<ConfigDocumentWriteResult>;
}
export interface BackgroundTaskService {
runCommand(options: RunCommandTaskOptions): Promise<CommandTaskStatus>;
getCommandStatus(taskId: string): Promise<CommandTaskStatus | null>;
list(projectId?: string): Promise<BackgroundTaskStatus[]>;
getStatus(taskId: string, projectId?: string): Promise<BackgroundTaskStatus | null>;
attachOutput(
@ -98,10 +375,17 @@ interface PluginServiceGatewaySet {
terminal: TerminalGateway;
workState: WorkStateGateway;
focusedProject: FocusedProjectGateway;
pluginWorkspace: PluginWorkspaceGateway;
pluginTask: PluginTaskGateway;
pluginToolchain: PluginToolchainGateway;
pluginEvents: PluginEventGateway;
pluginConfig: PluginConfigGateway;
}
const DEFAULT_ROWS = 24;
const DEFAULT_COLS = 80;
const DEFAULT_EVENT_POLL_INTERVAL_MS = 1000;
const MIN_EVENT_POLL_INTERVAL_MS = 100;
function noopDataHandler(): void {
// Intentionally empty: plugin code may opt into output bytes per call.
@ -126,6 +410,58 @@ function toBackgroundTaskStatus(task: BackgroundCompletion): BackgroundTaskStatu
};
}
function toCommandTaskStatus(task: PluginCommandTask): CommandTaskStatus {
return {
taskId: task.taskId,
ownerAgentId: task.ownerAgentId,
projectId: task.projectId,
kind: task.kind,
state: task.state,
exitCode: task.exitCode,
summary: task.summary,
stdoutTail: task.stdoutTail,
stderrTail: task.stderrTail,
createdAtMs: task.createdAtMs,
updatedAtMs: task.updatedAtMs,
};
}
function envEntries(env: RunCommandTaskOptions["env"]): Array<[string, string]> {
if (!env) return [];
return Array.isArray(env) ? env : Object.entries(env);
}
function toolEnvEntries(env: ToolRequirement["env"]): Array<[string, string]> {
if (!env) return [];
return Array.isArray(env) ? env : Object.entries(env);
}
function commandLabel(options: RunCommandTaskOptions): string {
if (options.label?.trim()) return options.label;
return [options.command, ...(options.args ?? [])].join(" ");
}
function eventPollIntervalMs(options: EventSubscribeOptions): number {
return Math.max(options.pollIntervalMs ?? DEFAULT_EVENT_POLL_INTERVAL_MS, MIN_EVENT_POLL_INTERVAL_MS);
}
function workspaceWatchKind(operation: string): WorkspaceWatchEvent["kind"] {
const normalized = operation.toLowerCase();
if (normalized.includes("create") || normalized.includes("write")) return "created";
if (normalized.includes("delete") || normalized.includes("remove")) return "deleted";
if (normalized.includes("rename") || normalized.includes("move")) return "renamed";
if (normalized.includes("modify") || normalized.includes("update")) return "modified";
return "unknown";
}
function workspacePathMatches(watchedPath: string, eventPath: string): boolean {
return (
watchedPath === "" ||
eventPath === watchedPath ||
eventPath.startsWith(`${watchedPath}/`)
);
}
export function createPluginServices(gateways: PluginServiceGatewaySet): PluginServices {
async function currentProject(): Promise<WorkspaceProject | null> {
const focused = await gateways.focusedProject.getFocusedProject();
@ -144,6 +480,55 @@ export function createPluginServices(gateways: PluginServiceGatewaySet): PluginS
return focused;
}
async function subscribeToEvents(
options: EventSubscribeOptions,
handler: EventHandler,
): Promise<EventSubscription> {
const project = await requireProject(options.projectId);
const subscription = await gateways.pluginEvents.subscribe({
projectId: project.id,
eventTypes: options.eventTypes ?? [],
capacity: options.capacity,
});
let disposed = false;
let polling = false;
const poll = async () => {
if (disposed || polling) return;
polling = true;
try {
const batch = await gateways.pluginEvents.poll({
subscriptionId: subscription.subscriptionId,
maxEvents: options.maxEventsPerPoll,
});
if (disposed) return;
if (batch.dropped > 0) options.onDropped?.(batch.dropped);
for (const event of batch.events) {
handler(event);
}
} catch (error) {
if (!disposed) console.warn("[plugin-events] poll failed", error);
} finally {
polling = false;
}
};
void poll();
const timer = setInterval(() => void poll(), eventPollIntervalMs(options));
return {
subscriptionId: subscription.subscriptionId,
projectId: subscription.projectId,
eventTypes: subscription.eventTypes,
retention: subscription.retention,
dispose() {
if (disposed) return;
disposed = true;
clearInterval(timer);
void gateways.pluginEvents.unsubscribe({
subscriptionId: subscription.subscriptionId,
});
},
};
}
const workspace: WorkspaceService = {
getCurrentProject: currentProject,
async getProjectRoot(projectId) {
@ -157,6 +542,63 @@ export function createPluginServices(gateways: PluginServiceGatewaySet): PluginS
const project = await requireProject(projectId);
await gateways.project.updateProjectContext(project.id, content);
},
async resolvePath(path, projectId) {
const project = await requireProject(projectId);
const stat = await gateways.pluginWorkspace.stat({ projectId: project.id, path });
return { projectId: project.id, root: project.root, path: stat.path };
},
async readTextFile(path, projectId) {
const project = await requireProject(projectId);
return gateways.pluginWorkspace.readText({ projectId: project.id, path });
},
async readBinaryFile(path, projectId) {
const project = await requireProject(projectId);
return gateways.pluginWorkspace.readBinary({ projectId: project.id, path });
},
async writeTextFile(path, content, projectId) {
const project = await requireProject(projectId);
await gateways.pluginWorkspace.writeText({ projectId: project.id, path, content });
},
async writeBinaryFile(path, bytes, projectId) {
const project = await requireProject(projectId);
await gateways.pluginWorkspace.writeBinary({ projectId: project.id, path, bytes });
},
async listDirectory(path = ".", projectId) {
const project = await requireProject(projectId);
return gateways.pluginWorkspace.listDir({ projectId: project.id, path });
},
async stat(path, projectId) {
const project = await requireProject(projectId);
return gateways.pluginWorkspace.stat({ projectId: project.id, path });
},
async watch(path, handler, projectId) {
const project = await requireProject(projectId);
const stat = await gateways.pluginWorkspace.stat({ projectId: project.id, path });
const subscription = await subscribeToEvents(
{ projectId: project.id, eventTypes: ["workspaceFileChanged"] },
(event) => {
if (event.type !== "workspaceFileChanged") return;
if (!workspacePathMatches(stat.path, event.path)) return;
handler({
path: event.path,
kind: workspaceWatchKind(event.operation),
operation: event.operation,
projectId: event.projectId,
});
},
);
return { dispose: () => subscription.dispose() };
},
async queryStructure(query = {}) {
const project = await requireProject(query.projectId);
const input: PluginProjectStructureQuery = {
projectId: project.id,
path: query.path,
maxDepth: query.maxDepth,
maxEntries: query.maxEntries,
};
return gateways.pluginWorkspace.queryProjectStructure(input);
},
};
async function listTasks(projectId?: string): Promise<BackgroundTaskStatus[]> {
@ -168,6 +610,28 @@ export function createPluginServices(gateways: PluginServiceGatewaySet): PluginS
}
const tasks: BackgroundTaskService = {
async runCommand(options) {
const project = await requireProject(options.projectId);
if (options.ownerAgentId.trim() === "") {
throw new Error("ownerAgentId is required to correlate a plugin command task");
}
const task = await gateways.pluginTask.runCommand({
projectId: project.id,
ownerAgentId: options.ownerAgentId,
label: commandLabel(options),
command: options.command,
args: options.args ?? [],
cwd: options.cwd,
env: envEntries(options.env),
recordOnly: options.recordOnly ?? false,
deadlineMs: options.deadlineMs,
});
return toCommandTaskStatus(task);
},
async getCommandStatus(taskId) {
const task = await gateways.pluginTask.getStatus({ taskId });
return task ? toCommandTaskStatus(task) : null;
},
list: listTasks,
async getStatus(taskId, projectId) {
return (await listTasks(projectId)).find((task) => task.taskId === taskId) ?? null;
@ -191,6 +655,53 @@ export function createPluginServices(gateways: PluginServiceGatewaySet): PluginS
},
};
const tooling: ToolingService = {
async diagnose(request) {
const project = await requireProject(request.projectId);
return gateways.pluginToolchain.diagnose({
projectId: project.id,
cwd: request.cwd,
tools: (request.tools ?? []).map((tool) => ({
id: tool.id,
executable: tool.executable,
versionArgs: tool.versionArgs ?? [],
required: tool.required ?? false,
env: toolEnvEntries(tool.env),
})),
env: request.env ?? [],
files: request.files ?? [],
});
},
};
const events: EventService = {
subscribe: subscribeToEvents,
};
const config: ConfigDocumentService = {
async readDocument<T extends JsonValue = JsonValue>(
options: ConfigDocumentReadOptions,
): Promise<ConfigDocument<T>> {
const project = await requireProject(options.projectId);
const document = await gateways.pluginConfig.readDocument({
projectId: project.id,
path: options.path,
format: options.format,
});
return document as ConfigDocument<T>;
},
async updateDocument(options) {
const project = await requireProject(options.projectId);
return gateways.pluginConfig.updateDocument({
projectId: project.id,
path: options.path,
format: options.format,
mode: options.mode,
value: options.value,
});
},
};
const terminal: TerminalService = {
async open(options = {}) {
const cwd = options.cwd ?? (await workspace.getProjectRoot());
@ -213,5 +724,5 @@ export function createPluginServices(gateways: PluginServiceGatewaySet): PluginS
},
};
return { workspace, tasks, terminal };
return { workspace, tasks, tooling, events, config, terminal };
}

View File

@ -43,11 +43,26 @@ import type {
PairingCode,
PermissionSet,
PluginAdmin,
PluginCommandTask,
PluginConfigDocument,
PluginConfigDocumentFormat,
PluginConfigDocumentWriteResult,
PluginConfigUpdateMode,
PluginEventBatch,
PluginEventSubscription,
PluginPublicEventType,
PluginExpectedFileKind,
PluginInstallResult,
PluginToolchainDiagnostic,
PluginProjectStructure,
PluginReview,
PluginRuntimeContributionCatalog,
PluginSourceKind,
PluginUninstallResult,
PluginWorkspaceBinaryFile,
PluginWorkspaceDirectoryListing,
PluginWorkspaceStat,
PluginWorkspaceTextFile,
ProjectMcpToolPermissions,
PageDirection,
Project,
@ -1361,6 +1376,126 @@ export interface PluginGateway {
openPluginsFolder(pluginId?: string): Promise<void>;
}
export interface PluginWorkspacePathInput {
projectId: string;
path: string;
}
export interface PluginWorkspaceWriteTextInput extends PluginWorkspacePathInput {
content: string;
}
export interface PluginWorkspaceWriteBinaryInput extends PluginWorkspacePathInput {
bytes: Uint8Array;
}
export interface PluginProjectStructureQuery {
projectId: string;
path?: string;
maxDepth?: number;
maxEntries?: number;
}
export interface PluginWorkspaceGateway {
readText(input: PluginWorkspacePathInput): Promise<PluginWorkspaceTextFile>;
readBinary(input: PluginWorkspacePathInput): Promise<PluginWorkspaceBinaryFile>;
writeText(input: PluginWorkspaceWriteTextInput): Promise<void>;
writeBinary(input: PluginWorkspaceWriteBinaryInput): Promise<void>;
listDir(input: PluginWorkspacePathInput): Promise<PluginWorkspaceDirectoryListing>;
stat(input: PluginWorkspacePathInput): Promise<PluginWorkspaceStat>;
queryProjectStructure(input: PluginProjectStructureQuery): Promise<PluginProjectStructure>;
}
export interface PluginRunCommandInput {
projectId: string;
ownerAgentId: string;
label: string;
command: string;
args?: string[];
cwd?: string;
env?: Array<[string, string]>;
recordOnly?: boolean;
deadlineMs?: number;
}
export interface PluginTaskStatusInput {
taskId: string;
}
export interface PluginTaskGateway {
runCommand(input: PluginRunCommandInput): Promise<PluginCommandTask>;
getStatus(input: PluginTaskStatusInput): Promise<PluginCommandTask | null>;
}
export interface PluginToolRequirementInput {
id: string;
executable: string;
versionArgs?: string[];
required?: boolean;
env?: Array<[string, string]>;
}
export interface PluginEnvRequirementInput {
name: string;
required?: boolean;
equals?: string;
}
export interface PluginFileRequirementInput {
path: string;
required?: boolean;
kind?: PluginExpectedFileKind;
}
export interface PluginToolchainDiagnosticRequest {
projectId: string;
cwd?: string;
tools?: PluginToolRequirementInput[];
env?: PluginEnvRequirementInput[];
files?: PluginFileRequirementInput[];
}
export interface PluginToolchainGateway {
diagnose(input: PluginToolchainDiagnosticRequest): Promise<PluginToolchainDiagnostic>;
}
export interface PluginEventSubscribeInput {
projectId: string;
eventTypes?: PluginPublicEventType[];
capacity?: number;
}
export interface PluginEventPollInput {
subscriptionId: string;
maxEvents?: number;
}
export interface PluginEventUnsubscribeInput {
subscriptionId: string;
}
export interface PluginEventGateway {
subscribe(input: PluginEventSubscribeInput): Promise<PluginEventSubscription>;
poll(input: PluginEventPollInput): Promise<PluginEventBatch>;
unsubscribe(input: PluginEventUnsubscribeInput): Promise<PluginEventSubscription>;
}
export interface PluginConfigDocumentReadInput {
projectId: string;
path: string;
format?: PluginConfigDocumentFormat;
}
export interface PluginConfigDocumentUpdateInput extends PluginConfigDocumentReadInput {
mode?: PluginConfigUpdateMode;
value: PluginConfigDocument["value"];
}
export interface PluginConfigGateway {
readDocument(input: PluginConfigDocumentReadInput): Promise<PluginConfigDocument>;
updateDocument(input: PluginConfigDocumentUpdateInput): Promise<PluginConfigDocumentWriteResult>;
}
export interface Gateways {
system: SystemGateway;
agent: AgentGateway;
@ -1386,4 +1521,9 @@ export interface Gateways {
focusedProject: FocusedProjectGateway;
uiPreferences: UiPreferencesGateway;
plugin: PluginGateway;
pluginWorkspace: PluginWorkspaceGateway;
pluginTask: PluginTaskGateway;
pluginToolchain: PluginToolchainGateway;
pluginEvents: PluginEventGateway;
pluginConfig: PluginConfigGateway;
}

View File

@ -7,6 +7,12 @@ This first version intentionally stays small:
- public manifest types for `idea-plugin.json`;
- public runtime types for plugin modules exposing `activate(ctx)`;
- a stable `ctx.services` facade for workspace, background task and terminal operations;
- public workspace file APIs for reading, writing, listing, stat and path resolution;
- a bounded generic project-structure query API;
- public command-task APIs for launching and tracking generic tools;
- public external-toolchain diagnostics for executables, env vars and files;
- public best-effort event subscriptions and workspace watch;
- public structured config-document helpers for JSON documents;
- a lightweight manifest validator;
- a minimal `examples/hello-plugin` plugin.
@ -70,6 +76,59 @@ export function activate(ctx: ActivateContext): void {
}
```
## Layout Runtime
Plugins can contribute custom layout panels by declaring `contributes.layouts`
in `idea-plugin.json` and registering the matching layout type during
`activate(ctx)`.
```json
{
"contributes": {
"layouts": [
{
"type": "com.example.status",
"label": "Status",
"component": "StatusPanel"
}
]
}
}
```
```ts
import type { ActivateContext, PluginLayoutProps } from "@idea/plugin-sdk";
function StatusPanel(props: PluginLayoutProps): string {
return `status for ${props.projectId}`;
}
export function activate(ctx: ActivateContext): void {
const disposable = ctx.layouts?.register({
type: "com.example.status",
component: StatusPanel
});
if (disposable) ctx.subscriptions.push(disposable);
}
```
Public layout props are:
- `projectId`: project hosting the layout cell;
- `nodeId`: stable layout node id for that cell instance;
- `layoutType`: contributed layout type from the manifest;
- `state`: opaque JSON-serializable state persisted by the host;
- `setState(next)`: replaces that state;
- `availability`: currently `"available"` when the component is mounted.
Lifecycle: register layouts during `activate(ctx)`, keep the returned disposable
in `ctx.subscriptions`, and let the host dispose it on plugin unload. Layout
components may be mounted, unmounted and remounted by the host; keep durable UI
state in `state` via `setState`, not in module globals. Call `setState` from
user actions, effects or asynchronous callbacks, not unconditionally while
rendering. Services are available from `ctx.services` to plugins declaring the
`tooling` capability; layout props do not expose private runtime gateways.
## Runtime Services
Plugins declaring the `tooling` capability receive `ctx.services`. Plugins
@ -91,12 +150,215 @@ export async function activate(ctx: ActivateContext): Promise<void> {
}
```
### Workspace Files
Workspace paths are always relative to the project root. Hosts reject absolute
paths, `..`, empty path segments and paths outside the sandbox. Text APIs use
UTF-8; binary APIs use `Uint8Array`. Missing files reject on reads and resolve
to `{ exists: false }` from `stat`.
```ts
import type { ActivateContext } from "@idea/plugin-sdk";
export async function activate(ctx: ActivateContext): Promise<void> {
const workspace = ctx.services?.workspace;
const project = await workspace?.getCurrentProject();
if (!workspace || !project) return;
await workspace.writeTextFile(".ideai/hello-plugin.txt", "hello\n", project.id);
const file = await workspace.readTextFile(".ideai/hello-plugin.txt", project.id);
const listing = await workspace.listDirectory(".ideai", project.id);
const stat = await workspace.stat(file.path, project.id);
ctx.logger.info("workspace file", {
path: file.path,
bytes: stat.len,
entries: listing.entries.length
});
}
```
`watch(path, handler, projectId?)` subscribes to public workspace file-change
events for the given relative path. It is best-effort and bounded: plugins should
handle missed events by refreshing their own derived state when needed.
### Project Structure
`queryStructure()` returns a bounded, generic read model so plugins do not each
need to rescan the whole workspace for common markers:
```ts
const structure = await ctx.services?.workspace.queryStructure({
maxDepth: 3,
maxEntries: 500
});
for (const convention of structure?.conventions ?? []) {
console.log(convention.id, convention.markerPath);
}
```
The MVP detects generic marker-file conventions such as `package.json`,
`Cargo.toml`, `pyproject.toml`, `go.mod`, `Makefile` and `.git`. It deliberately
does not expose language-specific ASTs or Android-specific concepts.
Current terminal scope is intentionally minimal: it opens or reattaches a shell
PTY, writes bytes, resizes, detaches and closes. The background task service is
observation/control only in this SDK version: `list`, `getStatus`, `attachOutput`,
`cancel` and `retry` operate on existing tasks visible through IdeA's Work read
model. Starting new background tasks is not part of the public plugin API in this
lot.
PTY, writes bytes, resizes, detaches and closes.
### Command Tasks
Use `ctx.services.tasks.runCommand()` for non-interactive tools that should be
tracked as IdeA background tasks instead of opening a raw PTY. `command` and
`args` are passed separately, `cwd` is relative to the project root, and `env`
adds process environment variables. The current host requires an `ownerAgentId`
so the task can appear in Work and completion can be correlated to an agent.
```ts
import type { ActivateContext } from "@idea/plugin-sdk";
export async function activate(ctx: ActivateContext): Promise<void> {
const project = await ctx.services?.workspace.getCurrentProject();
if (!project) return;
const task = await ctx.services?.tasks.runCommand({
projectId: project.id,
ownerAgentId: "00000000-0000-0000-0000-000000000000",
label: "Check npm",
command: "npm",
args: ["--version"],
cwd: ".",
env: { CI: "1" },
recordOnly: true
});
const status = await ctx.services?.tasks.getCommandStatus(task.taskId);
ctx.logger.info("command task", {
taskId: task.taskId,
state: status?.state,
exitCode: status?.exitCode
});
}
```
`list`, `getStatus`, `attachOutput`, `cancel` and `retry` continue to operate on
tasks visible through IdeA's Work read model. `getCommandStatus` reads a launched
command task directly from the host task store.
### Toolchain Diagnostics
Use `ctx.services.tooling.diagnose()` to check external prerequisites without
hard-coding one stack into the SDK. A request can probe executables, inspect
environment variables and validate workspace files in one structured result.
```ts
import type { ActivateContext } from "@idea/plugin-sdk";
export async function activate(ctx: ActivateContext): Promise<void> {
const diagnostic = await ctx.services?.tooling.diagnose({
tools: [
{
id: "node",
executable: "node",
versionArgs: ["--version"],
required: true
}
],
env: [{ name: "PATH", required: true }],
files: [{ path: "package.json", kind: "file" }]
});
const node = diagnostic?.tools.find((tool) => tool.id === "node");
ctx.logger.info("tooling diagnostic", {
ok: diagnostic?.ok,
nodePresent: node?.present,
nodeVersion: node?.version,
messages: diagnostic?.messages
});
}
```
The diagnostic API is intentionally generic: it does not install tools, does not
model Android devices or emulators, and does not expose language-specific ASTs.
### Events And Watch
Use `ctx.services.events.subscribe()` for stable public host/project events. The
runtime hides the host polling details and returns a disposable subscription.
```ts
import type { ActivateContext } from "@idea/plugin-sdk";
export async function activate(ctx: ActivateContext): Promise<void> {
const subscription = await ctx.services?.events.subscribe(
{
eventTypes: ["backgroundTaskChanged"],
capacity: 100,
onDropped: (count) => ctx.logger.warn("plugin events dropped", { count })
},
(event) => {
if (event.type === "backgroundTaskChanged") {
ctx.logger.info("task changed", {
taskId: event.taskId,
state: event.state
});
}
}
);
if (subscription) ctx.subscriptions.push(subscription);
const watch = await ctx.services?.workspace.watch("src", (event) => {
ctx.logger.info("workspace changed", {
path: event.path,
kind: event.kind,
operation: event.operation
});
});
if (watch) ctx.subscriptions.push(watch);
}
```
Public event retention is `bestEffortBounded`: events are retained per
subscription up to the requested/host-capped capacity, drained oldest-first, and
`onDropped` reports when older retained events were overwritten.
### Structured Config Documents
Use `ctx.services.config` when a plugin needs to read or update a structured
configuration file without reimplementing parsing and serialization.
First-lot format support is deliberately narrow:
- `json` only;
- inferred from `.json` when `format` is omitted;
- serialized as pretty JSON with a trailing newline;
- update modes: `mergePatch` and `replace`;
- `mergePatch` follows JSON merge-patch semantics: object keys are merged
recursively and `null` removes a key.
```ts
import type { ActivateContext } from "@idea/plugin-sdk";
export async function activate(ctx: ActivateContext): Promise<void> {
const config = await ctx.services?.config.readDocument({
path: ".ideai/hello-plugin.json"
});
await ctx.services?.config.updateDocument({
path: ".ideai/hello-plugin.json",
mode: "mergePatch",
value: {
enabled: true,
lastReadFormat: config?.format ?? "json"
}
});
}
```
YAML, TOML, XML, `.properties` and stack-specific config models are not part of
this first lot.
Declare the additive `tooling` capability to receive `ctx.services` at runtime:

View File

@ -1,29 +1,11 @@
import type { ActivateContext, CommandDisposable, IdeAPluginModule } from "@idea/plugin-sdk";
import type { ActivateContext, IdeAPluginModule, PluginLayoutProps } from "@idea/plugin-sdk";
const COMMAND_ID = "hello-plugin";
const LAYOUT_TYPE = "hello-plugin.hello-world";
type HelloPluginLayoutProps = {
projectId?: string;
nodeId?: string;
layoutType?: string;
state?: unknown;
};
type LayoutRegistry = {
register(definition: {
type: string;
component: (props: HelloPluginLayoutProps) => string;
}): CommandDisposable;
};
type HelloPluginContext = ActivateContext & {
layouts?: LayoutRegistry;
};
let hasLoggedFirstLayoutRender = false;
function HelloWorldLayout(props: HelloPluginLayoutProps): string {
function HelloWorldLayout(props: PluginLayoutProps): string {
if (!hasLoggedFirstLayoutRender) {
hasLoggedFirstLayoutRender = true;
console.info("[hello-plugin] layout first render", {
@ -38,14 +20,13 @@ function HelloWorldLayout(props: HelloPluginLayoutProps): string {
}
export function activate(ctx: ActivateContext): void {
const pluginContext = ctx as HelloPluginContext;
ctx.logger.info("activating hello-plugin", {
pluginId: ctx.pluginId,
hasCommands: Boolean(pluginContext.commands),
hasLayouts: Boolean(pluginContext.layouts)
hasCommands: Boolean(ctx.commands),
hasLayouts: Boolean(ctx.layouts)
});
const commandDisposable = pluginContext.commands?.registerCommand(COMMAND_ID, () => {
const commandDisposable = ctx.commands?.registerCommand(COMMAND_ID, () => {
ctx.logger.info("command executed", { commandId: COMMAND_ID });
return "hello-world";
});
@ -57,7 +38,7 @@ export function activate(ctx: ActivateContext): void {
ctx.logger.warn("command registry unavailable", { commandId: COMMAND_ID });
}
const layoutDisposable = pluginContext.layouts?.register({
const layoutDisposable = ctx.layouts?.register({
type: LAYOUT_TYPE,
component: HelloWorldLayout
});
@ -72,12 +53,130 @@ export function activate(ctx: ActivateContext): void {
ctx.logger.warn("layout registry unavailable", { layoutType: LAYOUT_TYPE });
}
void ctx.services?.workspace.getCurrentProject().then((project) => {
ctx.logger.info("workspace service available", {
projectId: project?.id ?? null,
hasProjectRoot: Boolean(project?.root)
});
void useWorkspaceSdk(ctx);
}
async function useWorkspaceSdk(ctx: ActivateContext): Promise<void> {
const workspace = ctx.services?.workspace;
if (!workspace) return;
const project = await workspace.getCurrentProject();
if (!project) {
ctx.logger.info("workspace service available without a focused project");
return;
}
const fixturePath = ".ideai/hello-plugin.txt";
await workspace.writeTextFile(fixturePath, "hello from @idea/plugin-sdk\n", project.id);
const file = await workspace.readTextFile(fixturePath, project.id);
const stat = await workspace.stat(fixturePath, project.id);
const listing = await workspace.listDirectory(".ideai", project.id);
const structure = await workspace.queryStructure({
projectId: project.id,
maxDepth: 2,
maxEntries: 100
});
ctx.logger.info("workspace file round-trip complete", {
projectId: project.id,
path: file.path,
bytes: stat.len,
ideaiEntries: listing.entries.length,
conventions: structure.conventions.map((convention) => convention.id)
});
const diagnostic = await ctx.services?.tooling.diagnose({
projectId: project.id,
tools: [
{
id: "echo",
executable: "echo",
versionArgs: ["hello-plugin-toolcheck"],
required: true
}
],
env: [{ name: "PATH", required: true }],
files: [{ path: fixturePath, kind: "file" }]
});
ctx.logger.info("tooling diagnostic complete", {
ok: diagnostic?.ok,
echoVersion: diagnostic?.tools.find((tool) => tool.id === "echo")?.version,
messages: diagnostic?.messages
});
const configPath = ".ideai/hello-plugin.json";
await workspace.writeTextFile(
configPath,
JSON.stringify({ enabled: true, launches: 0 }, null, 2) + "\n",
project.id
);
const configDocument = await ctx.services?.config.readDocument({
projectId: project.id,
path: configPath
});
await ctx.services?.config.updateDocument({
projectId: project.id,
path: configPath,
mode: "mergePatch",
value: { lastFormat: configDocument?.format ?? "json", launches: 1 }
});
ctx.logger.info("config document updated", {
path: configDocument?.path,
format: configDocument?.format
});
const watch = await workspace.watch(".ideai", (event) => {
ctx.logger.info("workspace watch event", {
path: event.path,
kind: event.kind,
operation: event.operation
});
}, project.id);
ctx.subscriptions.push(watch);
const events = await ctx.services?.events.subscribe(
{
projectId: project.id,
eventTypes: ["backgroundTaskChanged"],
pollIntervalMs: 2000,
onDropped: (count) => ctx.logger.warn("plugin events dropped", { count })
},
(event) => {
if (event.type === "backgroundTaskChanged") {
ctx.logger.info("background task changed", {
taskId: event.taskId,
state: event.state
});
}
}
);
if (events) ctx.subscriptions.push(events);
const ownerAgentId = await ctx.storage?.get<string>("helloPlugin.ownerAgentId");
if (!ownerAgentId) {
ctx.logger.info("command task example skipped: no owner agent configured");
return;
}
const task = await ctx.services?.tasks.runCommand({
projectId: project.id,
ownerAgentId,
label: "Hello plugin command",
command: "echo",
args: ["hello from @idea/plugin-sdk"],
cwd: ".",
recordOnly: true
});
if (task) {
const status = await ctx.services?.tasks.getCommandStatus(task.taskId);
ctx.logger.info("command task launched", {
taskId: task.taskId,
state: status?.state ?? task.state,
exitCode: status?.exitCode ?? task.exitCode
});
}
}
const plugin: IdeAPluginModule = {

View File

@ -14,22 +14,72 @@ export {
} from "./manifest.js";
export type {
ActivateContext,
BackgroundTaskChangedEvent,
CommandDisposable,
CommandHandler,
CommandRegistry,
CommandTaskStatus,
ConfigDocument,
ConfigDocumentFormat,
ConfigDocumentReadOptions,
ConfigDocumentService,
ConfigDocumentUpdateOptions,
ConfigDocumentWriteResult,
ConfigUpdateMode,
DiagnosticMessage,
EnvDiagnostic,
EnvRequirement,
EventHandler,
EventService,
EventSubscribeOptions,
EventSubscription,
FileDiagnostic,
FileRequirement,
BackgroundTaskOutputAttachment,
BackgroundTaskRetryResult,
BackgroundTaskService,
BackgroundTaskStatus,
IdeAPluginModule,
JsonValue,
LayoutRegistry,
PluginLogger,
PluginLayoutAvailability,
PluginLayoutComponent,
PluginLayoutDefinition,
PluginLayoutProps,
PluginLayoutRenderResult,
PluginLayoutState,
PluginServices,
PluginStorage,
ProjectConvention,
ProjectModule,
ProjectStructure,
ProjectStructureEntry,
ProjectStructureEntryKind,
PublicEvent,
PublicEventType,
RunCommandTaskOptions,
TerminalOpenOptions,
TerminalReattachOptions,
TerminalReattachResult,
TerminalService,
TerminalSession,
ToolchainDiagnostic,
ToolchainDiagnosticRequest,
ToolDiagnostic,
ToolingService,
ToolRequirement,
WorkspaceBinaryFile,
WorkspaceDirEntry,
WorkspaceDirectoryListing,
WorkspaceFileChangedEvent,
WorkspaceProject,
WorkspaceService
WorkspaceResolvedPath,
WorkspaceService,
WorkspaceStat,
WorkspaceStructureQuery,
WorkspaceTextFile,
WorkspaceWatch,
WorkspaceWatchEvent,
WorkspaceWatchHandler
} from "./runtime.js";

View File

@ -3,6 +3,7 @@ export interface ActivateContext {
logger: PluginLogger;
subscriptions: CommandDisposable[];
commands?: CommandRegistry;
layouts?: LayoutRegistry;
storage?: PluginStorage;
/**
* Stable public service facade for plugins that need workspace, background
@ -40,9 +41,47 @@ export interface PluginStorage {
delete(key: string): Promise<void>;
}
export type PluginLayoutState = JsonValue | undefined;
export type PluginLayoutAvailability = "available";
export type PluginLayoutRenderResult = unknown;
export interface PluginLayoutProps<TState extends PluginLayoutState = PluginLayoutState> {
/** Project currently hosting this layout cell. */
projectId: string;
/** Stable layout node id for this cell instance. */
nodeId: string;
/** Layout contribution type declared in `idea-plugin.json`. */
layoutType: string;
/** Opaque JSON-serializable state persisted by the host for this cell. */
state: TState;
/** Replaces the opaque state for this cell. Values must be JSON-serializable. */
setState(next: TState): void;
/** Present layouts are only mounted when available; fallback UI is host-owned. */
availability: PluginLayoutAvailability;
}
export type PluginLayoutComponent<TState extends PluginLayoutState = PluginLayoutState> = (
props: PluginLayoutProps<TState>,
) => PluginLayoutRenderResult;
export interface PluginLayoutDefinition<TState extends PluginLayoutState = PluginLayoutState> {
/** Must match a layout `type` declared in this plugin's manifest. */
type: string;
component: PluginLayoutComponent<TState>;
}
export interface LayoutRegistry {
register<TState extends PluginLayoutState = PluginLayoutState>(
definition: PluginLayoutDefinition<TState>,
): CommandDisposable;
}
export interface PluginServices {
workspace: WorkspaceService;
tasks: BackgroundTaskService;
tooling: ToolingService;
events: EventService;
config: ConfigDocumentService;
terminal: TerminalService;
}
@ -61,6 +100,117 @@ export interface WorkspaceService {
readProjectContext(projectId?: string): Promise<string>;
/** Updates IdeA's shared project context for the given or current project. */
updateProjectContext(content: string, projectId?: string): Promise<void>;
/**
* Resolves and normalizes a plugin-visible path under the project root.
* Rejects absolute paths, `..`, empty segments and other paths the host
* considers outside the workspace sandbox.
*/
resolvePath(path: string, projectId?: string): Promise<WorkspaceResolvedPath>;
/** Reads a UTF-8 text file under the project root. */
readTextFile(path: string, projectId?: string): Promise<WorkspaceTextFile>;
/** Reads raw bytes from a file under the project root. */
readBinaryFile(path: string, projectId?: string): Promise<WorkspaceBinaryFile>;
/** Writes UTF-8 text under the project root using the host's controlled write path. */
writeTextFile(path: string, content: string, projectId?: string): Promise<void>;
/** Writes raw bytes under the project root using the host's controlled write path. */
writeBinaryFile(path: string, bytes: Uint8Array, projectId?: string): Promise<void>;
/** Lists one directory under the project root. Defaults to the workspace root. */
listDirectory(path?: string, projectId?: string): Promise<WorkspaceDirectoryListing>;
/**
* Returns basic metadata. Missing paths resolve to `{ exists: false }`; invalid
* paths and permission errors reject.
*/
stat(path: string, projectId?: string): Promise<WorkspaceStat>;
/**
* Extension point for host file watching. The MVP SDK reserves the public
* shape; hosts may reject with a clear not-implemented error until #127 lands.
*/
watch(path: string, handler: WorkspaceWatchHandler, projectId?: string): Promise<WorkspaceWatch>;
/** Queries a bounded, generic project structure read model. */
queryStructure(query?: WorkspaceStructureQuery): Promise<ProjectStructure>;
}
export interface WorkspaceResolvedPath {
projectId: string;
root: string;
path: string;
}
export interface WorkspaceTextFile {
path: string;
content: string;
}
export interface WorkspaceBinaryFile {
path: string;
bytes: Uint8Array;
}
export interface WorkspaceDirEntry {
name: string;
path: string;
isDir: boolean;
}
export interface WorkspaceDirectoryListing {
path: string;
entries: WorkspaceDirEntry[];
}
export interface WorkspaceStat {
path: string;
exists: boolean;
isFile: boolean;
isDir: boolean;
len: number | null;
}
export interface WorkspaceWatchEvent {
path: string;
kind: "created" | "modified" | "deleted" | "renamed" | "unknown";
operation: string;
projectId: string;
}
export type WorkspaceWatchHandler = (event: WorkspaceWatchEvent) => void;
export interface WorkspaceWatch {
dispose(): void;
}
export interface WorkspaceStructureQuery {
projectId?: string;
path?: string;
maxDepth?: number;
maxEntries?: number;
}
export type ProjectStructureEntryKind = "file" | "directory";
export interface ProjectStructureEntry {
path: string;
name: string;
kind: ProjectStructureEntryKind;
}
export interface ProjectConvention {
id: string;
markerPath: string;
}
export interface ProjectModule {
path: string;
markerPath: string;
conventionId: string;
}
export interface ProjectStructure {
projectId: string;
rootPath: string;
entries: ProjectStructureEntry[];
conventions: ProjectConvention[];
modules: ProjectModule[];
truncated: boolean;
}
export interface BackgroundTaskStatus {
@ -88,7 +238,247 @@ export interface BackgroundTaskRetryResult {
taskId?: string;
}
export interface RunCommandTaskOptions {
/** Project that owns the command workspace. Defaults to the focused project. */
projectId?: string;
/** Agent id used by IdeA Work for ownership, cancellation and completion delivery. */
ownerAgentId: string;
/** Human-facing label shown in Work. Defaults to the command line. */
label?: string;
/** Executable to run. Arguments are passed separately, without shell parsing. */
command: string;
/** Arguments passed to the executable. */
args?: string[];
/** Relative working directory under the project root. Defaults to the root. */
cwd?: string;
/** Extra environment variables for the command. */
env?: Record<string, string> | Array<[string, string]>;
/** When true, completion is recorded without waking the owner agent. */
recordOnly?: boolean;
/** Optional absolute deadline, epoch milliseconds. */
deadlineMs?: number;
}
export interface CommandTaskStatus {
taskId: string;
ownerAgentId: string;
projectId: string;
kind: string;
state: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "expired";
exitCode: number | null;
summary: string | null;
stdoutTail: string | null;
stderrTail: string | null;
createdAtMs: number;
updatedAtMs: number;
}
export interface ToolRequirement {
/** Stable id chosen by the plugin for this executable prerequisite. */
id: string;
/** Executable name or path to probe. */
executable: string;
/** Version/diagnostic arguments. Defaults host-side to `--version`. */
versionArgs?: string[];
/** Whether this tool must pass for the whole diagnostic to be ok. */
required?: boolean;
/** Extra environment variables for this probe. */
env?: Record<string, string> | Array<[string, string]>;
}
export interface EnvRequirement {
/** Environment variable name. */
name: string;
/** Whether the variable must be present and match. */
required?: boolean;
/** Optional exact expected value. */
equals?: string;
}
export interface FileRequirement {
/** Relative workspace path. */
path: string;
/** Whether the path must exist and match `kind`. */
required?: boolean;
/** Expected workspace path kind. */
kind?: "file" | "directory" | "any";
}
export interface ToolchainDiagnosticRequest {
/** Project to inspect. Defaults to the focused project. */
projectId?: string;
/** Relative working directory under the project root. Defaults to the root. */
cwd?: string;
/** Executable probes to run. */
tools?: ToolRequirement[];
/** Environment variable prerequisites to inspect. */
env?: EnvRequirement[];
/** Workspace file prerequisites to validate. */
files?: FileRequirement[];
}
export interface ToolchainDiagnostic {
projectId: string;
cwd: string;
ok: boolean;
tools: ToolDiagnostic[];
env: EnvDiagnostic[];
files: FileDiagnostic[];
messages: DiagnosticMessage[];
}
export interface ToolDiagnostic {
id: string;
executable: string;
present: boolean;
ok: boolean;
status: "ok" | "failed" | "missing";
required: boolean;
exitCode: number | null;
version: string | null;
stdout: string | null;
stderr: string | null;
error: string | null;
}
export interface EnvDiagnostic {
name: string;
present: boolean;
ok: boolean;
required: boolean;
value: string | null;
status: "ok" | "missing" | "mismatch";
}
export interface FileDiagnostic {
path: string;
exists: boolean;
ok: boolean;
required: boolean;
kind: "file" | "directory" | "other" | "missing";
expectedKind: "file" | "directory" | "any" | null;
len: number | null;
}
export interface DiagnosticMessage {
level: "info" | "warning" | "error";
message: string;
}
export interface ToolingService {
/** Runs generic external-toolchain diagnostics for executables, env and files. */
diagnose(request: ToolchainDiagnosticRequest): Promise<ToolchainDiagnostic>;
}
export type PublicEventType = "workspaceFileChanged" | "backgroundTaskChanged";
export type PublicEvent = WorkspaceFileChangedEvent | BackgroundTaskChangedEvent;
export interface WorkspaceFileChangedEvent {
type: "workspaceFileChanged";
sequence: number;
occurredAtMs: number;
projectId: string;
path: string;
operation: string;
}
export interface BackgroundTaskChangedEvent {
type: "backgroundTaskChanged";
sequence: number;
occurredAtMs: number;
projectId: string;
taskId: string;
ownerAgentId: string;
state: string;
}
export interface EventSubscribeOptions {
/** Project to observe. Defaults to the focused project. */
projectId?: string;
/** Public event types to retain. Empty/omitted means every supported event. */
eventTypes?: PublicEventType[];
/** Per-subscription retained capacity. Host clamps to its supported bounds. */
capacity?: number;
/** Polling cadence used by the runtime facade. Defaults to 1000 ms. */
pollIntervalMs?: number;
/** Maximum events drained per poll. Host clamps to its supported bounds. */
maxEventsPerPoll?: number;
/** Called when the host reports dropped retained events for this subscription. */
onDropped?: (count: number) => void;
}
export interface EventSubscription {
readonly subscriptionId: string;
readonly projectId: string;
readonly eventTypes: PublicEventType[];
readonly retention: string;
dispose(): void;
}
export type EventHandler = (event: PublicEvent) => void;
export interface EventService {
/** Subscribes to stable, best-effort bounded public host/project events. */
subscribe(options: EventSubscribeOptions, handler: EventHandler): Promise<EventSubscription>;
}
export type JsonValue =
| null
| boolean
| number
| string
| JsonValue[]
| { [key: string]: JsonValue };
export type ConfigDocumentFormat = "json";
export type ConfigUpdateMode = "mergePatch" | "replace";
export interface ConfigDocumentReadOptions {
/** Project that owns the config document. Defaults to the focused project. */
projectId?: string;
/** Relative path under the project root. */
path: string;
/** Explicit format. Omit to infer from extension. First lot supports only `json`. */
format?: ConfigDocumentFormat;
}
export interface ConfigDocumentUpdateOptions extends ConfigDocumentReadOptions {
/** Update mode. Defaults host-side to `mergePatch`. */
mode?: ConfigUpdateMode;
/** Replacement value or JSON merge patch. */
value: JsonValue;
}
export interface ConfigDocument<T extends JsonValue = JsonValue> {
projectId: string;
path: string;
format: ConfigDocumentFormat;
value: T;
}
export interface ConfigDocumentWriteResult {
projectId: string;
path: string;
format: ConfigDocumentFormat;
mode: ConfigUpdateMode;
bytesWritten: number;
}
export interface ConfigDocumentService {
/** Reads and parses a structured config document. First lot supports JSON only. */
readDocument<T extends JsonValue = JsonValue>(
options: ConfigDocumentReadOptions,
): Promise<ConfigDocument<T>>;
/** Writes a full replacement or JSON merge patch. First lot supports JSON only. */
updateDocument(options: ConfigDocumentUpdateOptions): Promise<ConfigDocumentWriteResult>;
}
export interface BackgroundTaskService {
/** Launches a non-interactive command as a first-class IdeA background task. */
runCommand(options: RunCommandTaskOptions): Promise<CommandTaskStatus>;
/** Reads one command task directly from the host task store. */
getCommandStatus(taskId: string): Promise<CommandTaskStatus | null>;
/** Lists background tasks visible in the project work-state read model. */
list(projectId?: string): Promise<BackgroundTaskStatus[]>;
/** Reads one task status from the project work-state read model. */