Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8927: docs(environments): public Environments page and agent guide for .multica/environments.toml (#10374)
Jiayuan Zhang683240f1b613
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex 7df45ee433..e013a124cb 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -271,6 +271,17 @@ La suppression d'un runtime auquel des agents actifs sont encore liés est refusConsultez [Daemon et runtimes](/daemon-runtimes) pour son fonctionnement et les profils personnalisés.+## Environnements [#environments]++```bash+multica env start web+multica env start web --wait=false+multica env list+multica env stop web+```++`multica env` (forme longue `multica environment`) démarre les environnements qu'un dépôt déclare dans `.multica/environments.toml`. Le daemon les supervise : ils continuent de tourner après la fin de l'exécution, apparaissent dans la barre latérale de la tâche et s'arrêtent à la fin de leur TTL. `start` attend que l'environnement réponde et affiche son URL. Ces commandes utilisent l'identifiant de la tâche en cours : elles ne fonctionnent que pendant l'exécution d'un agent ; depuis votre propre ordinateur, utilisez la barre latérale de la tâche. Voir [Environnements](/environments) pour le format du fichier et des exemples.+## Projets, espaces de travail et automatisations```bash@@ -304,6 +315,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Europ| `workspace` | Créer, consulter et changer d'espace de travail, et inviter des membres || `repo` | Gérer les dépôts de l'espace de travail et les extraire localement || `daemon`, `runtime` | Démarrer et arrêter le daemon local ; consulter et gérer les runtimes |+| `env` | Démarrer, arrêter et lister les environnements déclarés par un dépôt (pendant l'exécution d'un agent uniquement) || `attachment` | Envoyer ou télécharger des pièces jointes || `user profile` | Consulter ou mettre à jour le profil de l'utilisateur actuel || `auth`, `login`, `setup` | Se connecter, vérifier l'état de l'authentification et initialiser une connexion |@@ -431,6 +443,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| `runtime` | `list/usage/activity/update/rename/delete` | Consulter et gérer les runtimes | `usage` : `--days` (90 par défaut, 365 au maximum) ; `update` : `--target-version` (obligatoire), `--wait` ; `delete` : `--cascade` (dissocie les agents liés, préserve leurs données et annule leurs exécutions) || | `profile list/create/update/delete` | Gérer les profils de runtime personnalisés | `create` : `--display-name`, `--command-name` (tous deux obligatoires), `--runtime-type` (ou l'ancien `--protocol-family`), `--description` ; `update` : `--enabled` || | `profile set-path/unset-path <profile-id>` | Fixer le chemin d'un exécutable local (local uniquement, jamais envoyé au serveur) | |+| `env` | `start <name>` / `stop <name>` / `list` | Démarrer, arrêter ou lister les environnements déclarés de cette tâche ; uniquement pendant l'exécution d'un agent. Voir [Environnements](/environments) | `start` : `--wait` (`true` par défaut) ; toutes : `--output` (`table` ou `json`) |### Additionaldiff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 0225dd36dc..d138d590e5 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -271,6 +271,17 @@ multica runtime profile create --display-name "社内 Claude ラッパー" \仕組みとカスタムプロファイルについては[デーモンとランタイム](/daemon-runtimes)を参照してください。+## 環境 [#environments]++```bash+multica env start web+multica env start web --wait=false+multica env list+multica env stop web+```++`multica env`(長い形式は `multica environment`)は、リポジトリが `.multica/environments.toml` に宣言した環境を起動します。環境はデーモンが管理するため、実行が終わっても動き続け、タスクのサイドバーに表示され、TTL が切れると停止します。`start` は環境が応答するまで待ってから URL を表示します。これらのコマンドは実行中のタスクの認証情報を使うので、エージェントの実行の中でしか使えません。自分のコンピューターからはタスクのサイドバーを使ってください。ファイルの形式と例は[環境](/environments)を参照してください。+## プロジェクト、ワークスペース、オートパイロット```bash@@ -304,6 +315,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `workspace` | ワークスペースの作成、表示、切り替えとメンバーの招待 || `repo` | ワークスペースのリポジトリを管理し、ローカルにチェックアウト || `daemon`、`runtime` | ローカルデーモンの起動と停止。ランタイムの表示と管理 |+| `env` | リポジトリが宣言した環境の起動・停止・一覧(エージェントの実行の中でのみ) || `attachment` | 添付ファイルのアップロードとダウンロード || `user profile` | 現在のユーザーのプロフィールを表示・更新 || `auth`、`login`、`setup` | サインイン、認証状態の確認、接続の初期化 |@@ -423,6 +435,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| `runtime` | `list/usage/activity/update/rename/delete` | ランタイムを表示・管理 | `usage`: `--days`(既定 90、最大 365);`update`: `--target-version`(必須)、`--wait`;`delete`: `--cascade`(紐付くエージェントを解除してデータを保持し、その実行をキャンセル) || | `profile list/create/update/delete` | カスタムランタイムプロファイルを管理 | `create`: `--display-name`、`--command-name`(いずれも必須)、`--runtime-type`(または古い `--protocol-family`)、`--description`;`update`: `--enabled` || | `profile set-path/unset-path <profile-id>` | ローカルの実行ファイルパスを固定(ローカルのみ有効。サーバーには送信されません) | |+| `env` | `start <name>` / `stop <name>` / `list` | このタスクの宣言された環境を起動・停止・一覧表示。エージェントの実行の中でのみ使えます。[環境](/environments)を参照 | `start`: `--wait`(既定 `true`);すべて: `--output`(`table` または `json`) |### Additionaldiff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 6c7c22f7cd..e76745494c 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -271,6 +271,17 @@ multica runtime profile create --display-name "사내 Claude 래퍼" \실행 메커니즘과 사용자 지정 profile은 [데몬과 런타임](/daemon-runtimes)을 참고하세요.+## 환경 [#environments]++```bash+multica env start web+multica env start web --wait=false+multica env list+multica env stop web+```++`multica env`(긴 형태 `multica environment`)는 저장소가 `.multica/environments.toml`에 선언한 환경을 시작합니다. 환경은 데몬이 관리하므로 실행이 끝나도 계속 실행되고, 태스크 사이드바에 표시되며, TTL이 끝나면 중지됩니다. `start`는 환경이 응답할 때까지 기다린 뒤 URL을 출력합니다. 이 명령들은 실행 중인 태스크의 자격 증명을 쓰므로 에이전트의 실행 안에서만 동작합니다. 직접 쓰는 컴퓨터에서는 태스크 사이드바를 사용하세요. 파일 형식과 예시는 [환경](/environments)을 참고하세요.+## 프로젝트, 워크스페이스, 오토파일럿```bash@@ -304,6 +315,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `workspace` | 워크스페이스 생성, 확인, 전환 및 멤버 초대 || `repo` | 워크스페이스 저장소 관리 및 로컬 checkout || `daemon`, `runtime` | 로컬 데몬 시작 및 중지, 런타임 확인 및 관리 |+| `env` | 저장소가 선언한 환경 시작, 중지, 나열(에이전트의 실행 안에서만) || `attachment` | 첨부 파일 업로드 또는 다운로드 || `user profile` | 현재 사용자 profile 확인 또는 업데이트 || `auth`, `login`, `setup` | 로그인, 인증 상태 확인, 연결 초기화 |@@ -423,6 +435,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| `runtime` | `list/usage/activity/update/rename/delete` | 런타임 확인 및 관리 | `usage`: `--days`(기본값 90, 최대 365). `update`: `--target-version`(필수), `--wait`. `delete`: `--cascade`(연결된 에이전트의 런타임을 해제하고 데이터를 보존하며 실행 취소) || | `profile list/create/update/delete` | 사용자 지정 런타임 profile 관리 | `create`: `--display-name`, `--command-name`(모두 필수), `--runtime-type`(또는 예전 `--protocol-family`), `--description`. `update`: `--enabled` || | `profile set-path/unset-path <profile-id>` | 로컬 실행 파일 경로 고정(로컬에만 적용되고 서버에 업로드되지 않음) | |+| `env` | `start <name>` / `stop <name>` / `list` | 이 태스크의 선언된 환경을 시작, 중지, 나열. 에이전트의 실행 안에서만 사용할 수 있습니다. [환경](/environments) 참고 | `start`: `--wait`(기본값 `true`). 모두: `--output`(`table` 또는 `json`) |### Additionaldiff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex ef7e8add8a..bdeecbae2c 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -286,6 +286,17 @@ Deleting a runtime that still has active agents bound to it is refused by defaulSee [Daemon and runtimes](/daemon-runtimes) for how it works and for custom profiles.+## Environments [#environments]++```bash+multica env start web+multica env start web --wait=false+multica env list+multica env stop web+```++`multica env` (long form `multica environment`) starts the environments a repository declares in `.multica/environments.toml`. The daemon supervises them, so they keep running after the run ends, show in the issue sidebar, and stop at their TTL. `start` waits until the environment answers and prints its URL. These commands use the running task's credential, so they only work inside an agent run; from your own computer, use the issue sidebar. See [Environments](/environments) for the file format and examples.+## Projects, workspaces, and autopilots```bash@@ -321,6 +332,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Europ| `workspace` | Create, view, and switch workspaces, and invite members || `repo` | Manage workspace repositories and check them out locally || `daemon`, `runtime` | Start and stop the local daemon; view and manage runtimes |+| `env` | Start, stop, and list the environments a repository declares (inside agent runs only) || `attachment` | Upload or download attachments || `user profile` | View or update the current user's profile || `auth`, `login`, `setup` | Log in, check auth status, and initialize a connection |@@ -458,6 +470,7 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| `runtime` | `list/usage/activity/update/rename/delete` | View and manage runtimes | `usage`: `--days` (default 90, max 365); `update`: `--target-version` (required), `--wait`; `delete`: `--cascade` (unbinds bound agents, preserves their data, and cancels their runs) || | `profile list/create/update/delete` | Manage custom runtime profiles | `create`: `--display-name`, `--command-name` (both required), `--runtime-type` (or the older `--protocol-family`), `--description`; `update`: `--enabled` || | `profile set-path/unset-path <profile-id>` | Pin a local executable path (local only, never uploaded to the server) | |+| `env` | `start <name>` / `stop <name>` / `list` | Start, stop, or list this issue's declared environments; only inside an agent run. See [Environments](/environments) | `start`: `--wait` (default `true`); all: `--output` (`table` or `json`) |### Additionaldiff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex 6ed953694b..8dc3e4fcca 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -268,6 +268,17 @@ multica runtime profile create --display-name "內部 Claude 封裝" \執行機制和自定義 profile 見[守護程序與執行時](/daemon-runtimes)。+## 環境 [#environments]++```bash+multica env start web+multica env start web --wait=false+multica env list+multica env stop web+```++`multica env`(完整寫法 `multica environment`)啟動倉庫在 `.multica/environments.toml` 裡宣告的環境。環境由守護程序託管,執行結束後繼續執行,顯示在任務側欄裡,TTL 到期時停止。`start` 會等環境能回應後印出它的 URL。這些命令使用目前執行的憑據,所以只能在 AI 代理的執行中使用;在你自己的電腦上請用任務側欄。檔案格式和範例見[環境](/environments)。+## 專案、工作區和自動化```bash@@ -303,6 +314,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `workspace` | 建立、檢視、切換工作區和邀請成員 || `repo` | 管理工作區倉庫,並把倉庫檢出到本機 || `daemon`、`runtime` | 啟停本機守護程序,檢視和管理執行時 |+| `env` | 啟動、停止和列出倉庫宣告的環境(只能在 AI 代理的執行中使用) || `attachment` | 上傳或下載附件 || `user profile` | 檢視或更新當前使用者資料 || `auth`、`login`、`setup` | 登入、檢視認證狀態和初始化連線 |@@ -432,6 +444,7 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| `runtime` | `list/usage/activity/update/rename/delete` | 檢視和管理執行時 | `usage`:`--days`(預設 90,最多 365);`update`:`--target-version`(必填)、`--wait`;`delete`:`--cascade`(解綁繫結的 AI 代理、保留其資料並取消其執行) || | `profile list/create/update/delete` | 管理自定義執行時 profile | `create`:`--display-name`、`--command-name`(均必填)、`--runtime-type`(或舊的 `--protocol-family`)、`--description`;`update`:`--enabled` || | `profile set-path/unset-path <profile-id>` | 固定本機可執行檔案路徑(僅本地生效,不上傳伺服器) | |+| `env` | `start <name>` / `stop <name>` / `list` | 啟動、停止或列出這條任務的宣告式環境;只能在 AI 代理的執行中使用。見[環境](/environments) | `start`:`--wait`(預設 `true`);全部:`--output`(`table` 或 `json`) |### Additionaldiff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 8a18747d3f..4323d36f1d 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -271,6 +271,17 @@ multica runtime profile create --display-name "内部 Claude 封装" \运行机制和自定义 profile 见[守护进程与运行时](/daemon-runtimes)。+## 环境 [#environments]++```bash+multica env start web+multica env start web --wait=false+multica env list+multica env stop web+```++`multica env`(完整写法 `multica environment`)启动仓库在 `.multica/environments.toml` 里声明的环境。环境由守护进程托管,运行结束后继续运行,显示在任务侧栏里,TTL 到期时停止。`start` 会等环境能响应后打印它的 URL。这些命令使用当前运行的凭据,所以只能在智能体的运行中使用;在你自己的电脑上请用任务侧栏。文件格式和示例见[环境](/environments)。+## 项目、工作区和自动化```bash@@ -306,6 +317,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `workspace` | 创建、查看、切换工作区和邀请成员 || `repo` | 管理工作区仓库,并把仓库检出到本机 || `daemon`、`runtime` | 启停本机守护进程,查看和管理运行时 |+| `env` | 启动、停止和列出仓库声明的环境(只能在智能体的运行中使用) || `attachment` | 上传或下载附件 || `user profile` | 查看或更新当前用户资料 || `auth`、`login`、`setup` | 登录、查看认证状态和初始化连接 |@@ -435,6 +447,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| `runtime` | `list/usage/activity/update/rename/delete` | 查看和管理运行时 | `usage`:`--days`(默认 90,最多 365);`update`:`--target-version`(必填)、`--wait`;`delete`:`--cascade`(解绑绑定的智能体、保留其数据并取消其运行) || | `profile list/create/update/delete` | 管理自定义运行时 profile | `create`:`--display-name`、`--command-name`(均必填)、`--runtime-type`(或旧的 `--protocol-family`)、`--description`;`update`:`--enabled` || | `profile set-path/unset-path <profile-id>` | 固定本机可执行文件路径(仅本地生效,不上传服务器) | |+| `env` | `start <name>` / `stop <name>` / `list` | 启动、停止或列出这条任务的声明式环境;只能在智能体的运行中使用。见[环境](/environments) | `start`:`--wait`(默认 `true`);全部:`--output`(`table` 或 `json`) |### Additionaldiff --git a/apps/docs/content/docs/environments.fr.mdx b/apps/docs/content/docs/environments.fr.mdxnew file mode 100644index 0000000000..82bef85680--- /dev/null+++ b/apps/docs/content/docs/environments.fr.mdx@@ -0,0 +1,248 @@+---+title: Environnements+description: Voir les serveurs de développement et les apps que lancent les exécutions d'une tâche, et les déclarer dans .multica/environments.toml pour que les membres puissent les démarrer, les arrêter et lire leurs journaux depuis la barre latérale.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";++Quand un agent travaille sur une application web, le résultat est souvent quelque chose à ouvrir : un serveur de développement, un aperçu, une app de bureau. La section **Environnements** de la barre latérale d'une tâche liste ce que les exécutions de la tâche font tourner, regroupé par appareil, avec un lien pour ouvrir chaque élément.++Un environnement y apparaît de deux façons :++| | Détecté | Déclaré |+|---|---|---|+| D'où il vient | Le daemon trouve un serveur à l'écoute dans le répertoire d'une exécution | Le dépôt le décrit dans `.multica/environments.toml`, et un agent le démarre avec `multica env start` |+| Mise en place | Aucune | Ajouter le fichier au dépôt |+| Après la fin de l'exécution | Reste affiché tant que le processus tourne | Supervisé par le daemon jusqu'à son arrêt ou la fin de son TTL |+| Depuis la barre latérale | Ouvrir, copier l'URL, arrêter | Ouvrir, copier l'URL, démarrer, arrêter, redémarrer, voir les journaux |++La détection rend la section utile sans configuration. La déclaration rend un environnement reproductible : chaque exécution le démarre de la même façon, sur ses propres ports, avec un journal lisible depuis la barre latérale.++## Serveurs détectés [#detected]++Sur macOS et Linux, le daemon cherche environ toutes les 30 secondes les processus à l'écoute sur un port TCP. Un processus apparaît dans la barre latérale quand :++- son répertoire de travail se trouve dans le répertoire d'une des exécutions de la tâche ;+- il a été trouvé lors de deux analyses consécutives, pour écarter les serveurs de test éphémères.++Sont exclus :++- les outils de codage IA eux-mêmes et le CLI `multica` ;+- les serveurs lancés depuis le [répertoire local](/project-resources) d'un projet, qui sont les vôtres et non ceux d'une exécution ;+- les serveurs qui appartiennent déjà à un environnement déclaré, listés une seule fois, sous cet environnement ;+- les serveurs d'exécutions qui ne sont pas liées à une tâche, comme les sessions de chat.++Une app de bureau (par exemple une app Electron) est listée une seule fois, comme une app, et non port par port. Elle n'a pas d'URL ; depuis Multica Desktop sur le même appareil, **Afficher la fenêtre** la met au premier plan. Ses ports de débogage à distance ne sont pas proposés comme liens.++Un serveur détecté reste affiché après la fin de son exécution, tant qu'il reste à l'écoute. Les membres peuvent l'arrêter depuis la barre latérale, mais le daemon ne sait pas comment il a été lancé : il n'a donc pas de journal et ne peut pas être redémarré. Pour en disposer, déclarez-le.++## Déclarer des environnements [#declare]++Ajoutez `.multica/environments.toml` à la racine du dépôt et committez-le sur la branche que vos exécutions récupèrent. La barre latérale ne trouve le fichier qu'à la racine d'un checkout ou un répertoire en dessous, et ignore un fichier qui contient des erreurs ; `multica env start` indique ce qui ne va pas. Chaque table `[environments.<name>]` est un environnement :++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++Un agent le démarre ensuite depuis son checkout :++```bash+multica env start web+```++La commande attend que l'environnement réponde, puis affiche son URL. L'environnement apparaît dans la barre latérale, continue de tourner après la fin de l'exécution et s'arrête à la fin de son TTL.++### Champs [#fields]++| Champ | Obligatoire | Par défaut | Rôle |+|---|---|---|---|+| `start` | Oui | | Commande shell qui démarre l'environnement. Exécutée avec `/bin/sh -c` depuis le répertoire qui contient `.multica/`. |+| `label` | Non | Le nom | Nom affiché dans la barre latérale. |+| `url` | Non | `http://localhost:$MULTICA_PORT` | Adresse que les membres ouvrent. Mettez `url = ""` pour ce qui n'a pas de page, comme un worker ou une app de bureau. |+| `ready` | Non | Identique à `url` | Adresse interrogée jusqu'à ce qu'elle réponde avec un statut inférieur à 500 (un 404 compte). Sans `ready` ni `url`, l'environnement est en cours dès que `start` est lancé. |+| `stop` | Non | | Commande exécutée avant que le daemon n'envoie un signal aux processus. Utile quand `start` crée quelque chose que ses processus ne possèdent pas, comme des conteneurs. |+| `ttl` | Non | `24h` | Durée avant l'arrêt, de `1m` à `168h`. Utilisez `s`, `m` ou `h` ; `7d` n'est pas accepté. |++Le nom de l'environnement est la partie après `environments.` : lettres minuscules, chiffres, `-` et `_`, 40 caractères au plus, en commençant par une lettre ou un chiffre.++### Ports et variables [#ports]++Chaque environnement reçoit dix ports libres rien qu'à lui, de `MULTICA_PORT` à `MULTICA_PORT+9`. Deux exécutions sur le même appareil, ou deux tâches, n'entrent jamais en conflit : n'écrivez donc jamais un port en dur.++`start` et `stop` reçoivent ces variables :++| Variable | Valeur |+|---|---|+| `MULTICA_PORT` | Le premier port du bloc, par exemple `41000` |+| `MULTICA_ENVIRONMENT` | Le nom de l'environnement |+| `PATH` | Le `PATH` de l'agent qui a lancé `multica env start`, pour que la chaîne d'outils du dépôt soit trouvée. Un démarrage depuis la barre latérale reprend le dernier utilisé par un agent pour cet environnement sur la tâche. |++Ils héritent aussi de l'environnement du daemon, sauf de ses variables `MULTICA_*`, identifiants compris : un environnement ne peut pas agir au nom de l'exécution. Dans `url` et `ready`, seul `$MULTICA_PORT` (ou `${MULTICA_PORT}`) est remplacé. Pour un second port, calculez-le dans le shell, par exemple `API_PORT=$((MULTICA_PORT + 1))`.++### Garder `start` au premier plan [#foreground]++`start` s'exécute en tant que chef d'un nouveau groupe de processus. L'environnement vit tant qu'un processus de ce groupe tourne, et l'arrêter envoie un signal à tout le groupe. Donc :++- Gardez le serveur principal au premier plan. Les processus auxiliaires lancés avec `&` ne posent pas de problème : ils restent dans le groupe.+- Ne confiez pas le travail à quelque chose hors du groupe, comme `docker compose up -d`, un service système ou `setsid`. L'environnement passerait aussitôt à **Terminé**, et l'arrêter n'atteindrait pas ce travail. Lancez ces outils au premier plan et ajoutez une commande `stop`.+- Le checkout d'une exécution démarre sans dépendances installées. Installez-les dans `start` ; les dix minutes pendant lesquelles le daemon attend que l'environnement soit prêt incluent ce temps.++## Exemples [#examples]++Chaque exemple est un `.multica/environments.toml` complet. Remplacez `npm ci` par la commande d'installation de votre gestionnaire de paquets (`pnpm install --frozen-lockfile`, `yarn install --immutable`) selon le dépôt.++<Tabs items={["Next.js", "Vite", "Go API", "Web + API", "docker compose"]}>+<Tab value="Next.js">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"+ttl = "24h"+```++</Tab>+<Tab value="Vite">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++`--strictPort` fait échouer Vite au lieu de le laisser passer discrètement à un autre port, ce qui laisserait le lien de la barre latérale pointer vers rien.++</Tab>+<Tab value="Go API">++```toml+[environments.api]+label = "API"+start = "PORT=$MULTICA_PORT go run ./cmd/server"+ready = "http://localhost:$MULTICA_PORT/healthz"+ttl = "8h"+```++On suppose ici que le serveur lit son port dans `PORT` et expose un contrôle de santé sur `/healthz` ; adaptez les deux à votre code.++</Tab>+<Tab value="Web + API">++```toml+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && PORT=$API_PORT go run .) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""+ttl = "24h"+```++L'API tourne en arrière-plan sur le deuxième port du bloc, et l'application web au premier plan sur le premier. Arrêter l'environnement arrête les deux.++</Tab>+<Tab value="docker compose">++```toml+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+ttl = "8h"+```++Dans `compose.yaml`, publiez le service web sur le port de l'environnement :++```yaml+services:+ web:+ build: .+ ports:+ - "${MULTICA_PORT:-3000}:3000"+```++Sans `-d`, `up` reste au premier plan. Les conteneurs appartiennent à Docker, pas aux processus de l'environnement : c'est `stop` qui les arrête. `-p env-$MULTICA_PORT` donne à chaque environnement son propre projet Compose, pour que des exécutions parallèles ne partagent pas de conteneurs.++</Tab>+</Tabs>++Pour déclarer plusieurs environnements, ajoutez d'autres tables dans le même fichier. Les processus d'un environnement s'arrêtent avec lui, même quand un autre environnement du même checkout les utilise. Les serveurs qui doivent continuer de tourner ensemble, comme une application web et son API, vont dans un seul environnement, comme dans l'exemple Web + API.++## Démarrer et arrêter avec le CLI [#cli]++| Commande | Effet |+|---|---|+| `multica env start <name>` | Démarre l'environnement à partir du `.multica/environments.toml` trouvé dans le répertoire courant ou un parent. Attend qu'il soit prêt, puis affiche son URL. Si cette tâche a déjà un environnement de ce nom en cours depuis le même checkout, le renvoie tel quel. |+| `multica env start <name> --wait=false` | Rend la main dès qu'il a démarré. |+| `multica env list` | Liste les environnements de cette tâche sur cet appareil, avec leur état, leur URL et le chemin de leur journal. |+| `multica env stop <name>` | Arrête l'environnement en cours de ce nom pour cette tâche sur cet appareil : exécute la commande `stop` s'il y en a une, puis envoie `SIGTERM` aux processus restants, et `SIGKILL` 10 secondes plus tard. Si plusieurs tournent sous ce nom, il en arrête un ; pour en arrêter un en particulier, utilisez la barre latérale. |++Les trois acceptent `--output json`. `multica environment` est la forme longue de `multica env`.++<Callout type="info">+Ces commandes utilisent l'identifiant de la tâche en cours : elles **ne fonctionnent que pendant l'exécution d'un agent**. Lancées dans votre propre terminal, elles échouent avec `MULTICA_DAEMON_PORT not set`. Pour démarrer ou arrêter un environnement vous-même, utilisez la barre latérale.+</Callout>++Si la commande de démarrage se termine avant d'être prête, `multica env start` échoue et affiche les dernières lignes de son journal. Si elle ne répond toujours pas après 10 minutes, la commande rend la main, l'environnement reste en **Démarrage** et la raison (par exemple « not answering at http://localhost:41000 ») est affichée avec lui.++Les environnements appartiennent à la tâche, pas à une exécution : une exécution ultérieure sur la même tâche peut lister et arrêter ce qu'une précédente a démarré. Démarrer de nouveau un nom ne réutilise l'environnement en cours que s'il tourne depuis le même checkout sur cet appareil. Une exécution avec un autre checkout démarre une seconde instance sous le même nom, sur ses propres ports : vérifiez `multica env list` avant d'en démarrer une.++## Gérer les environnements dans la barre latérale [#sidebar]++Chaque environnement affiche son état, quand il a démarré ou s'est terminé, quand il expire et qui l'a démarré. **Ouvrir** ouvre son URL et **Copier l'URL** la copie. Les environnements terminés sont regroupés sous « N terminés ».++- **Démarrer** : cliquez sur **+** à côté de **Environnements**. Le menu liste les environnements déclarés par la dernière exécution sur chaque appareil, et démarre celui que vous choisissez avec le code de cette exécution. Si la tâche n'a pas encore été exécutée ou si ce code a été nettoyé, il propose plutôt de le demander à un agent : l'agent prépare le code et lance `multica env start`, ou détermine comment démarrer le projet s'il ne déclare rien.+- **Arrêter, redémarrer, voir les journaux** : ouvrez le menu **Plus d'actions** de l'environnement. **Redémarrer** relit la déclaration dans le checkout ; le checkout et son `.multica/environments.toml` doivent donc encore exister. Un serveur détecté ne propose que **Arrêter**, après confirmation.++Démarrer, arrêter et redémarrer demandent d'être un membre de l'espace de travail qui a accès à la tâche et peut utiliser le runtime de cet appareil (voir [Daemon et runtimes](/daemon-runtimes)). L'appareil doit être en ligne, avec une version de Multica qui prend en charge le contrôle des environnements ; sinon, les boutons indiquent ce qui manque. Lire les journaux demande seulement l'accès à la tâche.++### Journaux [#logs]++**Voir les journaux** affiche les 500 dernières lignes de sortie d'un environnement déclaré, dans la limite de 256 Kio. Tant que l'environnement tourne, l'affichage suit la nouvelle sortie environ toutes les cinq secondes ; vous pouvez suspendre le suivi, actualiser, filtrer, activer le retour à la ligne et copier.++Quand un environnement plante, ses deux dernières lignes de sortie sont conservées avec lui : la barre latérale peut montrer pourquoi il s'est arrêté même une fois l'appareil hors ligne. Une nouvelle lecture nécessite que l'appareil soit en ligne.++Le journal complet reste sur l'appareil, sous `<workspaces root>/.environments/v1/`, et est conservé sept jours après la fin de l'environnement. `multica env start` et `multica env list` affichent son chemin.++<Callout type="warning">+Toute personne ayant accès à la tâche peut lire les journaux d'un environnement. Multica masque les secrets reconnaissables dans les lignes envoyées et supprime les lectures de journaux après dix minutes, mais ne comptez pas dessus : gardez les identifiants hors de la sortie de vos serveurs.+</Callout>++## États [#states]++| État | Signification |+|---|---|+| Démarrage | Démarré ; attend que son adresse `ready` réponde. |+| En cours | Prêt, ou à l'écoute (pour un serveur détecté). |+| Terminé | Ses processus se sont arrêtés d'eux-mêmes, par exemple après un plantage. Le code de sortie et les dernières lignes de sortie sont affichés. |+| Arrêté | Arrêté par un agent, un membre ou son TTL (« Arrêté à l'expiration »). |+| Sans réponse | L'appareil qui le fait tourner ne l'a pas signalé depuis trois minutes : le daemon s'est arrêté, ou l'appareil est en veille ou hors ligne. Il retrouve son état réel dès que le daemon se manifeste. |++Pendant que le daemon est arrêté, rien n'est supervisé ; au redémarrage, il reprend les environnements dont les processus tournent encore. Un répertoire d'exécution où tourne un environnement n'est pas supprimé par le nettoyage des espaces de travail du daemon tant que l'environnement n'est pas arrêté.++## Laisser un agent écrire le fichier [#agent]++Les agents connaissent le format : la compétence de plateforme intégrée à Multica, que reçoit chaque agent, documente `.multica/environments.toml` et la façon de le vérifier. Demandez-le dans une tâche, par exemple :++> Ajoute un `.multica/environments.toml` pour que l'application web de ce dépôt puisse être démarrée avec `multica env start`. Démarre-la une fois pour vérifier qu'elle fonctionne, puis ouvre une PR.++L'agent regarde comment le projet démarre, écrit le fichier avec des ports tirés de `MULTICA_PORT`, démarre l'environnement pour vérifier qu'il répond, et livre le fichier comme n'importe quelle autre modification. Une fois fusionné, chaque exécution suivante peut démarrer l'environnement, et les membres aussi depuis la barre latérale.++## Limites connues [#limitations]++- **macOS et Linux uniquement.** Sous Windows, les serveurs ne sont pas détectés et `multica env start` indique que les environnements ne sont pas encore pris en charge.+- **Une URL localhost ne s'ouvre que sur l'appareil qui l'exécute.** Quand l'environnement tourne sur un autre appareil, comme un serveur de build ou l'ordinateur d'un collègue, la barre latérale l'indique ; ouvrez-le sur cet appareil, ou redirigez le port vous-même.+- **Redémarrages du daemon sous systemd.** Sous Linux avec le [démarrage à l'ouverture de session](/daemon-runtimes#autostart), redémarrer ou mettre à jour le daemon arrête aussi ses environnements déclarés. Redémarrez-les ensuite.+- **Un appareil par environnement.** Un environnement tourne là où a tourné l'exécution qui l'a démarré ; il ne suit pas la tâche.++## Étapes suivantes++- [Daemon et runtimes](/daemon-runtimes) — le daemon qui détecte et supervise les environnements.+- [Utiliser le CLI](/cli#environments) — les commandes `multica env` parmi le reste du CLI.+- [Exécutions](/tasks) — d'où vient le répertoire d'une exécution.diff --git a/apps/docs/content/docs/environments.ja.mdx b/apps/docs/content/docs/environments.ja.mdxnew file mode 100644index 0000000000..7534685a64--- /dev/null+++ b/apps/docs/content/docs/environments.ja.mdx@@ -0,0 +1,248 @@+---+title: 環境+description: タスクの実行が起動した開発サーバーやアプリをタスクのサイドバーで確認し、.multica/environments.toml に宣言して、メンバーがサイドバーから起動・停止・ログ確認できるようにします。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";++エージェントが Web アプリを扱うと、成果は開いて確かめるものになりがちです。開発サーバー、プレビュー、デスクトップアプリなどです。タスクのサイドバーの**環境**セクションには、そのタスクの実行が動かしているものが、動いているマシンごとにまとめて表示され、それぞれを開けます。++環境が表示される経路は 2 つあります。++| | 自動検出 | 宣言 |+|---|---|---|+| どこから来るか | 実行のディレクトリ内で待ち受けているサーバーをデーモンが見つける | リポジトリが `.multica/environments.toml` に記述し、エージェントが `multica env start` で起動する |+| 準備 | 不要 | リポジトリにファイルを追加する |+| 実行が終わったあと | プロセスが動いている間は表示され続ける | 停止されるか TTL が切れるまでデーモンが管理する |+| サイドバーでできること | 開く、URL をコピー、停止 | 開く、URL をコピー、起動、停止、再起動、ログを表示 |++自動検出のおかげで、設定なしでもこのセクションは役に立ちます。宣言すると環境を再現できるようになります。どの実行でも同じ方法で、専用のポートで起動し、ログもサイドバーから読めます。++## 自動検出されるサーバー [#detected]++macOS と Linux では、デーモンが約 30 秒ごとに TCP ポートで待ち受けているプロセスを調べます。次の条件を満たすプロセスがサイドバーに表示されます。++- 作業ディレクトリが、そのタスクのいずれかの実行のディレクトリ内にある+- 2 回続けてスキャンで見つかった(一瞬だけ動くテスト用サーバーは表示されません)++次のものは対象外です。++- AI コーディングツール自体と `multica` CLI+- プロジェクトの[ローカルディレクトリ](/project-resources)から動いているサーバー(実行ではなく、あなたが起動したものです)+- すでに宣言された環境に属しているサーバー(その環境の下に 1 回だけ表示されます)+- チャットセッションなど、タスクに紐づかない実行のサーバー++デスクトップアプリ(Electron アプリなど)は、ポートごとではなく 1 つのアプリとして表示されます。URL はなく、同じマシンの Multica Desktop で**ウィンドウに切り替え**を押すと前面に出せます。リモートデバッグ用のポートはリンクとして表示されません。++自動検出されたサーバーは、実行が終わっても待ち受けている間は表示され続けます。メンバーはサイドバーから停止できますが、デーモンは起動方法を知らないため、ログはなく再起動もできません。それらが必要なら宣言してください。++## 環境を宣言する [#declare]++リポジトリのルートに `.multica/environments.toml` を追加し、実行がチェックアウトするブランチにコミットします。サイドバーはチェックアウトのルートか、その 1 つ下のディレクトリにあるファイルだけを見つけ、エラーのあるファイルは読み飛ばします。何が問題かは `multica env start` が表示します。`[environments.<name>]` テーブル 1 つが 1 つの環境です。++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++エージェントは自分のチェックアウトの中からこれを起動します。++```bash+multica env start web+```++コマンドは環境が応答するまで待ってから URL を表示します。環境はサイドバーに表示され、実行が終わっても動き続け、TTL が切れると停止します。++### フィールド [#fields]++| フィールド | 必須 | 既定値 | 意味 |+|---|---|---|---|+| `start` | はい | | 環境を起動するシェルコマンド。`.multica/` を含むディレクトリで `/bin/sh -c` により実行されます。 |+| `label` | いいえ | 環境名 | サイドバーに表示される名前。 |+| `url` | いいえ | `http://localhost:$MULTICA_PORT` | メンバーが開くアドレス。ワーカーやデスクトップアプリなどページのないものは `url = ""` にします。 |+| `ready` | いいえ | `url` と同じ | 500 未満のステータス(404 を含む)が返るまで確認するアドレス。`ready` も `url` もない場合は、`start` が起動した時点で実行中になります。 |+| `stop` | いいえ | | デーモンがプロセスにシグナルを送る前に実行するコマンド。コンテナなど、`start` のプロセスが所有しないものを作る場合に使います。 |+| `ttl` | いいえ | `24h` | 停止されるまでの時間。`1m` から `168h` まで。単位は `s`、`m`、`h` で、`7d` は使えません。 |++環境名は `environments.` のあとの部分です。小文字、数字、`-`、`_` が使え、先頭は英字か数字、最大 40 文字です。++### ポートと変数 [#ports]++各環境には専用の空きポートが 10 個割り当てられます。`MULTICA_PORT` から `MULTICA_PORT+9` までです。同じマシンの 2 つの実行や 2 つのタスクがぶつかることはないので、ポートを固定で書かないでください。++`start` と `stop` には次の変数が渡されます。++| 変数 | 値 |+|---|---|+| `MULTICA_PORT` | ポート範囲の先頭。例: `41000` |+| `MULTICA_ENVIRONMENT` | 環境名 |+| `PATH` | `multica env start` を実行したエージェントの `PATH`。リポジトリのツールチェーンが見つかるようにするためです。サイドバーから起動した場合は、そのタスクでエージェントがその環境に最後に使った `PATH` を使います。 |++デーモンの環境変数も引き継ぎますが、`MULTICA_*` 変数(認証情報を含む)は除かれます。環境が実行の権限で操作することはできません。`url` と `ready` で置き換えられるのは `$MULTICA_PORT`(または `${MULTICA_PORT}`)だけです。2 つ目のポートが必要なら、`API_PORT=$((MULTICA_PORT + 1))` のようにシェルで計算します。++### `start` はフォアグラウンドで動かす [#foreground]++`start` は新しいプロセスグループのリーダーとして実行されます。グループ内にプロセスが 1 つでも残っている間は環境が続き、停止するとグループ全体にシグナルが送られます。そのため:++- メインのサーバーはフォアグラウンドで動かします。`&` でバックグラウンドに置いた補助プロセスは問題ありません。同じグループに残ります。+- `docker compose up -d`、システムサービス、`setsid` など、グループの外に処理を渡さないでください。環境はすぐに**終了**になり、停止してもその処理には届きません。こうしたツールはフォアグラウンドで動かし、`stop` コマンドを追加します。+- 実行のチェックアウトには依存関係がインストールされていません。`start` の中でインストールしてください。デーモンが準備完了を待つ 10 分にはその時間も含まれます。++## 例 [#examples]++それぞれが `.multica/environments.toml` の全体です。`npm ci` は、リポジトリに合わせてパッケージマネージャーのインストールコマンド(`pnpm install --frozen-lockfile`、`yarn install --immutable`)に置き換えてください。++<Tabs items={["Next.js", "Vite", "Go API", "Web + API", "docker compose"]}>+<Tab value="Next.js">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"+ttl = "24h"+```++</Tab>+<Tab value="Vite">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++`--strictPort` を付けると、Vite はポートが使用中のとき別のポートに黙って移らず失敗します。移ってしまうとサイドバーのリンクが何も指さなくなります。++</Tab>+<Tab value="Go API">++```toml+[environments.api]+label = "API"+start = "PORT=$MULTICA_PORT go run ./cmd/server"+ready = "http://localhost:$MULTICA_PORT/healthz"+ttl = "8h"+```++サーバーが `PORT` からポートを読み、`/healthz` でヘルスチェックを返すことを前提にしています。コードに合わせて調整してください。++</Tab>+<Tab value="Web + API">++```toml+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && PORT=$API_PORT go run .) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""+ttl = "24h"+```++API はポート範囲の 2 つ目でバックグラウンドに、Web アプリは 1 つ目でフォアグラウンドに動きます。環境を停止すると両方止まります。++</Tab>+<Tab value="docker compose">++```toml+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+ttl = "8h"+```++`compose.yaml` では、Web サービスを環境のポートで公開します。++```yaml+services:+ web:+ build: .+ ports:+ - "${MULTICA_PORT:-3000}:3000"+```++`-d` を付けなければ `up` はフォアグラウンドに残ります。コンテナは環境のプロセスではなく Docker に属するため、`stop` で片付けます。`-p env-$MULTICA_PORT` で環境ごとに別の Compose プロジェクトになり、並行する実行がコンテナを共有しません。++</Tab>+</Tabs>++複数の環境を宣言するには、同じファイルにテーブルを追加します。各環境のプロセスはその環境と一緒に止まります。同じチェックアウトの別の環境がそれを使っていても同じです。Web アプリとその API のように一緒に動き続ける必要があるサーバーは、Web + API の例のように 1 つの環境にまとめてください。++## CLI で起動・停止する [#cli]++| コマンド | 内容 |+|---|---|+| `multica env start <name>` | カレントディレクトリか親ディレクトリで見つかった `.multica/environments.toml` から環境を起動します。準備ができるまで待ち、URL を表示します。このタスクで同じ名前の環境が同じチェックアウトから動いていれば、それをそのまま返します。 |+| `multica env start <name> --wait=false` | 起動したらすぐに戻ります。 |+| `multica env list` | このマシンにあるこのタスクの環境を、状態、URL、ログのパスとともに一覧表示します。 |+| `multica env stop <name>` | このマシンで動いている、このタスクの同じ名前の環境を停止します。`stop` コマンドがあれば実行し、残ったプロセスに `SIGTERM`、10 秒後に `SIGKILL` を送ります。同じ名前のものが複数動いている場合はそのうち 1 つを止めます。特定のものを止めるにはサイドバーを使ってください。 |++いずれも `--output json` に対応しています。`multica environment` は `multica env` の長い形式です。++<Callout type="info">+これらのコマンドは実行中のタスクの認証情報を使うため、**エージェントの実行の中でしか使えません**。自分のターミナルで実行すると `MULTICA_DAEMON_PORT not set` で失敗します。自分で起動・停止するにはサイドバーを使います。+</Callout>++起動コマンドが準備完了前に終了すると、`multica env start` は失敗し、ログの最後の数行を表示します。10 分経っても応答がない場合、コマンドは戻り、環境は**起動中**のまま、理由("not answering at http://localhost:41000" など)が表示されます。++環境は個々の実行ではなくタスクに属します。同じタスクのあとの実行は、前の実行が起動した環境を一覧・停止できます。同じ名前でもう一度起動したときに既存の環境が再利用されるのは、このマシンで同じチェックアウトから動いている場合だけです。別のチェックアウトを使う実行は同じ名前で 2 つ目を専用のポートで起動するため、起動前に `multica env list` で確認してください。++## サイドバーで管理する [#sidebar]++各環境には、状態、起動・終了の時刻、期限、起動した人が表示されます。**開く**で URL を開き、**URL をコピー**でコピーします。終了した環境は「終了済み N 件」にまとめられます。++- **起動**: **環境**の横の **+** をクリックします。各マシンで最新の実行が宣言した環境が並び、選んだものをその実行のコードで起動します。タスクがまだ実行されていないか、そのコードが削除されている場合は、代わりにエージェントへの依頼を提案します。エージェントはコードを用意して `multica env start` を実行し、宣言がなければ起動方法を自分で判断します。+- **停止・再起動・ログを表示**: 環境の**その他の操作**メニューを開きます。**再起動**はチェックアウト内の宣言を読み直すため、チェックアウトとその `.multica/environments.toml` が残っている必要があります。自動検出されたサーバーは確認のうえ**停止**だけができます。++起動・停止・再起動には、タスクにアクセスでき、そのマシンのランタイムを使えるワークスペースメンバーである必要があります([デーモンとランタイム](/daemon-runtimes)を参照)。マシンがオンラインで、その Multica が環境の操作に対応したバージョンである必要もあります。足りないものがあればボタンが理由を示します。ログの表示に必要なのはタスクへのアクセスだけです。++### ログ [#logs]++**ログを表示**では、宣言された環境の出力のうち最後の 500 行(最大 256 KiB)が表示されます。環境が動いている間は約 5 秒ごとに新しい出力を追い、追従の一時停止、更新、絞り込み、折り返し、コピーができます。++環境がクラッシュすると最後の 2 行の出力が環境とともに保存されるため、マシンがオフラインになってもサイドバーで終了した理由がわかります。新しく読み込むにはマシンがオンラインである必要があります。++完全なログはマシンの `<workspaces root>/.environments/v1/` に残り、環境の終了後 7 日間保持されます。パスは `multica env start` と `multica env list` が表示します。++<Callout type="warning">+タスクにアクセスできる人は誰でも環境のログを読めます。Multica はアップロードする行から認識できる秘密情報を伏せ、読み込んだログを 10 分後に削除しますが、それに頼らず、サーバーの出力に認証情報を出さないでください。+</Callout>++## 状態 [#states]++| 状態 | 意味 |+|---|---|+| 起動中 | 起動済みで、`ready` のアドレスが応答するのを待っています。 |+| 実行中 | 準備完了、または(自動検出の場合)待ち受け中です。 |+| 終了 | クラッシュなどでプロセスが自分で終わりました。終了コードと最後の出力が表示されます。 |+| 停止 | エージェント、メンバー、または TTL によって停止されました(「期限切れで自動停止」)。 |+| 応答なし | 動かしているマシンから 3 分間報告がありません。デーモンが止まったか、マシンがスリープ中かオフラインです。デーモンが報告を再開すると実際の状態に戻ります。 |++デーモンが止まっている間は何も管理されません。デーモンが再起動すると、プロセスがまだ生きている環境は再び管理下に入ります。環境が動いている実行ディレクトリは、環境が止まるまでデーモンのワークスペース整理で削除されません。++## エージェントにファイルを書かせる [#agent]++エージェントはこの形式を知っています。すべてのエージェントが受け取る Multica 組み込みのプラットフォームスキルに、`.multica/environments.toml` の書き方と確認方法が載っています。タスクで次のように頼めます。++> このリポジトリの Web アプリを `multica env start` で起動できるように `.multica/environments.toml` を追加してください。一度起動して動くことを確かめてから PR を作ってください。++エージェントはプロジェクトの起動方法を調べ、`MULTICA_PORT` のポートを使ってファイルを書き、環境を起動して応答を確かめ、ほかの変更と同じように提出します。マージされれば、以降のどの実行でも、メンバーもサイドバーから、その環境を起動できます。++## 既知の制限 [#limitations]++- **macOS と Linux のみ。** Windows ではサーバーは検出されず、`multica env start` は未対応であることを伝えます。+- **localhost の URL は動かしているマシンでしか開けません。** ビルドサーバーや同僚のコンピューターなど別のマシンで動いている場合はサイドバーにそう表示されます。そのマシンで開くか、自分でポートを転送してください。+- **systemd でのデーモン再起動。** Linux で[ログイン時の自動起動](/daemon-runtimes#autostart)を使っていると、デーモンの再起動や更新で宣言された環境も止まります。そのあと起動し直してください。+- **環境は 1 台のマシンで動きます。** 環境は起動した実行のマシンで動き、タスクと一緒に移動しません。++## 次のステップ++- [デーモンとランタイム](/daemon-runtimes) — 環境を検出・管理するデーモン。+- [CLI を使う](/cli#environments) — `multica env` コマンドとほかの CLI コマンド。+- [実行](/tasks) — 実行のディレクトリがどこから来るか。diff --git a/apps/docs/content/docs/environments.ko.mdx b/apps/docs/content/docs/environments.ko.mdxnew file mode 100644index 0000000000..b34b6d3900--- /dev/null+++ b/apps/docs/content/docs/environments.ko.mdx@@ -0,0 +1,248 @@+---+title: 환경+description: 태스크의 실행이 띄운 개발 서버와 앱을 태스크 사이드바에서 확인하고, .multica/environments.toml에 선언해 멤버가 사이드바에서 시작·중지하고 로그를 볼 수 있게 합니다.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";++에이전트가 웹 앱을 다루면 결과물은 열어서 확인하는 것인 경우가 많습니다. 개발 서버, 미리보기, 데스크톱 앱 같은 것입니다. 태스크 사이드바의 **환경** 영역은 이 태스크의 실행이 띄워 둔 것을 실행 중인 기기별로 묶어 보여 주고, 각각을 바로 열 수 있게 합니다.++환경은 두 가지 경로로 나타납니다.++| | 자동 감지 | 선언 |+|---|---|---|+| 출처 | 데몬이 실행 디렉터리 안에서 포트를 열고 있는 서버를 찾음 | 저장소가 `.multica/environments.toml`에 기술하고, 에이전트가 `multica env start`로 시작 |+| 준비 | 필요 없음 | 저장소에 파일 추가 |+| 실행이 끝난 뒤 | 프로세스가 살아 있는 동안 계속 표시 | 중지되거나 TTL이 끝날 때까지 데몬이 관리 |+| 사이드바에서 할 수 있는 일 | 열기, URL 복사, 중지 | 열기, URL 복사, 시작, 중지, 재시작, 로그 보기 |++자동 감지 덕분에 설정 없이도 이 영역을 쓸 수 있습니다. 선언하면 환경을 반복해서 띄울 수 있습니다. 모든 실행이 같은 방식으로, 자기 포트에서 시작하고, 로그도 사이드바에서 읽을 수 있습니다.++## 자동 감지된 서버 [#detected]++macOS와 Linux에서 데몬은 약 30초마다 TCP 포트를 열고 있는 프로세스를 확인합니다. 다음 조건을 만족하는 프로세스가 사이드바에 표시됩니다.++- 작업 디렉터리가 이 태스크의 어떤 실행 디렉터리 안에 있음+- 두 번 연속 스캔에서 발견됨(잠깐 떴다 사라지는 테스트 서버는 표시되지 않음)++다음은 제외됩니다.++- AI 코딩 도구 자체와 `multica` CLI+- 프로젝트의 [로컬 디렉터리](/project-resources)에서 실행되는 서버(실행이 아니라 사용자가 직접 띄운 것)+- 이미 선언된 환경에 속한 서버(그 환경 아래에 한 번만 표시)+- 채팅 세션처럼 태스크에 속하지 않은 실행의 서버++데스크톱 앱(예: Electron 앱)은 포트별이 아니라 하나의 앱으로 표시됩니다. URL은 없으며, 같은 기기의 Multica Desktop에서 **창으로 전환**을 누르면 앞으로 가져올 수 있습니다. 원격 디버깅 포트는 링크로 표시되지 않습니다.++자동 감지된 서버는 실행이 끝난 뒤에도 포트를 열고 있는 동안 계속 표시됩니다. 멤버는 사이드바에서 중지할 수 있지만, 데몬이 시작 방법을 모르기 때문에 로그가 없고 재시작할 수도 없습니다. 이런 기능이 필요하면 선언하세요.++## 환경 선언하기 [#declare]++저장소 루트에 `.multica/environments.toml`을 추가하고, 실행이 체크아웃하는 브랜치에 커밋합니다. 사이드바는 체크아웃의 루트나 그 바로 아래 디렉터리에 있는 파일만 찾으며, 오류가 있는 파일은 건너뜁니다. 무엇이 잘못됐는지는 `multica env start`가 알려 줍니다. `[environments.<name>]` 테이블 하나가 환경 하나입니다.++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++에이전트는 자기 체크아웃 안에서 이렇게 시작합니다.++```bash+multica env start web+```++명령은 환경이 응답할 때까지 기다린 뒤 URL을 출력합니다. 환경은 사이드바에 표시되고, 실행이 끝나도 계속 실행되며, TTL이 끝나면 중지됩니다.++### 필드 [#fields]++| 필드 | 필수 | 기본값 | 의미 |+|---|---|---|---|+| `start` | 예 | | 환경을 시작하는 셸 명령. `.multica/`가 있는 디렉터리에서 `/bin/sh -c`로 실행됩니다. |+| `label` | 아니요 | 환경 이름 | 사이드바에 표시되는 이름. |+| `url` | 아니요 | `http://localhost:$MULTICA_PORT` | 멤버가 여는 주소. 워커나 데스크톱 앱처럼 페이지가 없으면 `url = ""`로 둡니다. |+| `ready` | 아니요 | `url`과 같음 | 500 미만의 상태 코드(404 포함)를 돌려줄 때까지 확인하는 주소. `ready`도 `url`도 없으면 `start`가 시작되자마자 실행 중이 됩니다. |+| `stop` | 아니요 | | 데몬이 프로세스에 신호를 보내기 전에 실행하는 명령. 컨테이너처럼 `start`의 프로세스가 소유하지 않는 것을 만들 때 필요합니다. |+| `ttl` | 아니요 | `24h` | 중지되기까지의 시간. `1m`부터 `168h`까지. 단위는 `s`, `m`, `h`이며 `7d`는 쓸 수 없습니다. |++환경 이름은 `environments.` 뒤의 부분입니다. 소문자, 숫자, `-`, `_`만 쓸 수 있고, 영문자나 숫자로 시작하며 최대 40자입니다.++### 포트와 변수 [#ports]++환경마다 전용 빈 포트 10개, `MULTICA_PORT`부터 `MULTICA_PORT+9`까지가 할당됩니다. 같은 기기의 두 실행이나 두 태스크가 충돌하지 않으니 포트를 고정해서 쓰지 마세요.++`start`와 `stop`에는 다음 변수가 전달됩니다.++| 변수 | 값 |+|---|---|+| `MULTICA_PORT` | 포트 범위의 첫 번째 포트. 예: `41000` |+| `MULTICA_ENVIRONMENT` | 환경 이름 |+| `PATH` | `multica env start`를 실행한 에이전트의 `PATH`. 저장소의 도구 체인을 찾을 수 있게 합니다. 사이드바에서 시작하면 이 태스크에서 에이전트가 그 환경에 마지막으로 쓴 `PATH`를 다시 씁니다. |++데몬의 환경 변수도 물려받지만 `MULTICA_*` 변수(자격 증명 포함)는 빠집니다. 환경은 실행의 권한으로 동작할 수 없습니다. `url`과 `ready`에서는 `$MULTICA_PORT`(또는 `${MULTICA_PORT}`)만 치환됩니다. 두 번째 포트가 필요하면 `API_PORT=$((MULTICA_PORT + 1))`처럼 셸에서 계산하세요.++### `start`는 포그라운드에 두기 [#foreground]++`start`는 새 프로세스 그룹의 리더로 실행됩니다. 그룹에 프로세스가 하나라도 남아 있는 동안 환경이 유지되고, 중지하면 그룹 전체에 신호가 갑니다. 따라서:++- 메인 서버는 포그라운드에 둡니다. `&`로 백그라운드에 띄운 보조 프로세스는 괜찮습니다. 같은 그룹에 남습니다.+- `docker compose up -d`, 시스템 서비스, `setsid`처럼 작업을 그룹 밖으로 넘기지 마세요. 환경은 바로 **종료됨**이 되고, 중지해도 그 작업에 닿지 않습니다. 이런 도구는 포그라운드로 실행하고 `stop` 명령을 추가하세요.+- 실행의 체크아웃에는 의존성이 설치되어 있지 않습니다. `start` 안에서 설치하세요. 데몬이 준비를 기다리는 10분에 그 시간도 포함됩니다.++## 예시 [#examples]++각 예시는 `.multica/environments.toml` 전체입니다. 저장소에 맞게 `npm ci`를 사용하는 패키지 매니저의 설치 명령(`pnpm install --frozen-lockfile`, `yarn install --immutable`)으로 바꾸세요.++<Tabs items={["Next.js", "Vite", "Go API", "Web + API", "docker compose"]}>+<Tab value="Next.js">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"+ttl = "24h"+```++</Tab>+<Tab value="Vite">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++`--strictPort`를 붙이면 Vite가 포트가 사용 중일 때 다른 포트로 조용히 옮겨 가지 않고 실패합니다. 옮겨 가면 사이드바 링크가 아무것도 가리키지 않게 됩니다.++</Tab>+<Tab value="Go API">++```toml+[environments.api]+label = "API"+start = "PORT=$MULTICA_PORT go run ./cmd/server"+ready = "http://localhost:$MULTICA_PORT/healthz"+ttl = "8h"+```++서버가 `PORT`에서 포트를 읽고 `/healthz`에서 헬스 체크를 제공한다고 가정합니다. 코드에 맞게 조정하세요.++</Tab>+<Tab value="Web + API">++```toml+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && PORT=$API_PORT go run .) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""+ttl = "24h"+```++API는 포트 범위의 두 번째 포트에서 백그라운드로, 웹 앱은 첫 번째 포트에서 포그라운드로 실행됩니다. 환경을 중지하면 둘 다 멈춥니다.++</Tab>+<Tab value="docker compose">++```toml+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+ttl = "8h"+```++`compose.yaml`에서 웹 서비스를 환경의 포트로 공개합니다.++```yaml+services:+ web:+ build: .+ ports:+ - "${MULTICA_PORT:-3000}:3000"+```++`-d` 없이 실행하면 `up`이 포그라운드에 남습니다. 컨테이너는 환경의 프로세스가 아니라 Docker에 속하므로 `stop`으로 내립니다. `-p env-$MULTICA_PORT`로 환경마다 별도의 Compose 프로젝트가 되어, 병렬 실행이 컨테이너를 공유하지 않습니다.++</Tab>+</Tabs>++환경을 여러 개 선언하려면 같은 파일에 테이블을 더 추가합니다. 각 환경의 프로세스는 그 환경과 함께 멈춥니다. 같은 체크아웃의 다른 환경이 그것을 쓰고 있어도 마찬가지입니다. 웹 앱과 그 API처럼 함께 계속 실행되어야 하는 서버는 Web + API 예시처럼 하나의 환경에 넣으세요.++## CLI로 시작·중지하기 [#cli]++| 명령 | 하는 일 |+|---|---|+| `multica env start <name>` | 현재 디렉터리나 상위 디렉터리에서 찾은 `.multica/environments.toml`로 환경을 시작합니다. 준비될 때까지 기다린 뒤 URL을 출력합니다. 이 태스크에서 같은 이름의 환경이 같은 체크아웃에서 실행 중이면 그것을 그대로 돌려줍니다. |+| `multica env start <name> --wait=false` | 시작하자마자 돌아옵니다. |+| `multica env list` | 이 기기에 있는 이 태스크의 환경을 상태, URL, 로그 경로와 함께 나열합니다. |+| `multica env stop <name>` | 이 기기에서 실행 중인 이 태스크의 같은 이름 환경을 중지합니다. `stop` 명령이 있으면 실행한 뒤, 남은 프로세스에 `SIGTERM`을, 10초 뒤 `SIGKILL`을 보냅니다. 같은 이름으로 여러 개가 실행 중이면 그중 하나를 중지합니다. 특정 환경을 중지하려면 사이드바를 사용하세요. |++세 명령 모두 `--output json`을 지원합니다. `multica environment`는 `multica env`의 긴 형태입니다.++<Callout type="info">+이 명령들은 실행 중인 태스크의 자격 증명을 쓰므로 **에이전트의 실행 안에서만 동작합니다**. 직접 터미널에서 실행하면 `MULTICA_DAEMON_PORT not set` 오류가 납니다. 직접 시작하거나 중지하려면 사이드바를 쓰세요.+</Callout>++시작 명령이 준비되기 전에 종료되면 `multica env start`가 실패하고 로그의 마지막 몇 줄을 출력합니다. 10분이 지나도 응답이 없으면 명령은 돌아오고, 환경은 **시작 중**으로 남으며 이유("not answering at http://localhost:41000" 등)가 함께 표시됩니다.++환경은 개별 실행이 아니라 태스크에 속합니다. 같은 태스크의 이후 실행은 이전 실행이 시작한 환경을 나열하고 중지할 수 있습니다. 같은 이름으로 다시 시작할 때 실행 중인 환경을 재사용하는 것은 이 기기에서 같은 체크아웃으로 실행 중일 때뿐입니다. 다른 체크아웃을 쓰는 실행은 같은 이름으로 자기 포트에서 두 번째 인스턴스를 시작하므로, 시작하기 전에 `multica env list`로 확인하세요.++## 사이드바에서 관리하기 [#sidebar]++각 환경에는 상태, 시작·종료 시각, 만료 시각, 시작한 사람이 표시됩니다. **열기**는 URL을 열고 **URL 복사**는 URL을 복사합니다. 종료된 환경은 "종료됨 N개" 아래에 접혀 있습니다.++- **시작**: **환경** 옆의 **+**를 클릭합니다. 각 기기에서 최근 실행이 선언한 환경이 나열되며, 고른 환경을 그 실행의 코드로 시작합니다. 태스크가 아직 실행되지 않았거나 그 코드가 정리되었다면 대신 에이전트에게 맡기도록 제안합니다. 에이전트는 코드를 준비해 `multica env start`를 실행하고, 선언이 없으면 시작 방법을 스스로 판단합니다.+- **중지, 재시작, 로그 보기**: 환경의 **추가 작업** 메뉴를 엽니다. **재시작**은 체크아웃의 선언을 다시 읽으므로 체크아웃과 그 안의 `.multica/environments.toml`이 남아 있어야 합니다. 자동 감지된 서버는 확인 후 **중지**만 할 수 있습니다.++시작, 중지, 재시작은 태스크에 접근할 수 있고 그 기기의 런타임을 사용할 수 있는 워크스페이스 멤버만 할 수 있습니다([데몬과 런타임](/daemon-runtimes) 참고). 기기가 온라인이어야 하고, 그 기기의 Multica가 환경 조작을 지원하는 버전이어야 합니다. 조건이 맞지 않으면 버튼이 무엇이 부족한지 알려 줍니다. 로그를 보는 데는 태스크 접근 권한만 있으면 됩니다.++### 로그 [#logs]++**로그 보기**는 선언된 환경의 출력 중 마지막 500줄(최대 256 KiB)을 보여 줍니다. 환경이 실행 중이면 약 5초마다 새 출력을 따라가며, 따라가기 일시 중지, 새로고침, 필터, 줄바꿈, 복사를 할 수 있습니다.++환경이 비정상 종료되면 마지막 두 줄의 출력이 환경과 함께 저장되므로, 기기가 오프라인이 되어도 사이드바에서 종료 이유를 볼 수 있습니다. 새로 읽으려면 기기가 온라인이어야 합니다.++전체 로그는 기기의 `<workspaces root>/.environments/v1/` 아래에 남고, 환경이 끝난 뒤 7일간 보관됩니다. 경로는 `multica env start`와 `multica env list`가 출력합니다.++<Callout type="warning">+태스크에 접근할 수 있는 사람은 누구나 환경의 로그를 읽을 수 있습니다. Multica는 업로드하는 줄에서 알아볼 수 있는 비밀 값을 가리고 읽은 로그를 10분 뒤 삭제하지만, 여기에 기대지 말고 서버 출력에 자격 증명이 나오지 않게 하세요.+</Callout>++## 상태 [#states]++| 상태 | 의미 |+|---|---|+| 시작 중 | 시작했고 `ready` 주소가 응답하기를 기다리는 중입니다. |+| 실행 중 | 준비됨, 또는 (자동 감지된 서버라면) 포트를 열고 있음. |+| 종료됨 | 비정상 종료 등으로 프로세스가 스스로 끝났습니다. 종료 코드와 마지막 출력이 표시됩니다. |+| 중지됨 | 에이전트, 멤버 또는 TTL에 의해 중지되었습니다("만료되어 자동 중지됨"). |+| 응답 없음 | 실행 중인 기기가 3분 동안 보고하지 않았습니다. 데몬이 멈췄거나 기기가 절전 중이거나 오프라인입니다. 데몬이 다시 보고하면 실제 상태로 돌아옵니다. |++데몬이 멈춘 동안에는 아무것도 관리되지 않습니다. 데몬이 다시 시작되면 프로세스가 살아 있는 환경을 다시 맡습니다. 환경이 실행 중인 실행 디렉터리는 환경이 멈출 때까지 데몬의 워크스페이스 정리에서 삭제되지 않습니다.++## 에이전트에게 파일 맡기기 [#agent]++에이전트는 이 형식을 알고 있습니다. 모든 에이전트가 받는 Multica 내장 플랫폼 스킬에 `.multica/environments.toml` 작성법과 검증 방법이 들어 있습니다. 태스크에서 이렇게 요청하면 됩니다.++> 이 저장소의 웹 앱을 `multica env start`로 시작할 수 있도록 `.multica/environments.toml`을 추가해 주세요. 한 번 시작해서 동작하는지 확인한 뒤 PR을 열어 주세요.++에이전트는 프로젝트를 띄우는 방법을 파악하고, `MULTICA_PORT`의 포트로 파일을 작성하고, 환경을 시작해 응답하는지 확인한 뒤, 다른 변경처럼 제출합니다. 병합되면 이후 모든 실행이 이 환경을 시작할 수 있고, 멤버도 사이드바에서 시작할 수 있습니다.++## 알려진 제한 [#limitations]++- **macOS와 Linux만 지원합니다.** Windows에서는 서버가 감지되지 않고, `multica env start`는 아직 지원하지 않는다고 알립니다.+- **localhost URL은 실행 중인 기기에서만 열립니다.** 빌드 서버나 동료의 컴퓨터처럼 다른 기기에서 실행 중이면 사이드바가 그렇게 표시합니다. 그 기기에서 열거나 직접 포트를 포워딩하세요.+- **systemd에서의 데몬 재시작.** Linux에서 [로그인 시 자동 시작](/daemon-runtimes#autostart)을 쓰면, 데몬을 재시작하거나 업데이트할 때 선언된 환경도 함께 멈춥니다. 그 뒤 다시 시작하세요.+- **환경은 한 기기에서만 실행됩니다.** 환경은 그것을 시작한 실행의 기기에서 실행되며 태스크를 따라 옮겨 가지 않습니다.++## 다음 단계++- [데몬과 런타임](/daemon-runtimes) — 환경을 감지하고 관리하는 데몬.+- [CLI 사용](/cli#environments) — `multica env` 명령과 다른 CLI 명령.+- [실행](/tasks) — 실행 디렉터리가 어디서 오는지.diff --git a/apps/docs/content/docs/environments.mdx b/apps/docs/content/docs/environments.mdxnew file mode 100644index 0000000000..aae76f3c99--- /dev/null+++ b/apps/docs/content/docs/environments.mdx@@ -0,0 +1,248 @@+---+title: Environments+description: See the dev servers and apps an issue's runs start, and declare them in .multica/environments.toml so members can start, stop, and read them from the issue sidebar.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";++When an agent works on a web app, the result is often something to open: a dev server, a preview, a desktop app. The **Environments** section of the issue sidebar lists what the issue's runs have running, grouped by the machine they run on, with a link to open each one.++An environment gets there in one of two ways:++| | Detected | Declared |+|---|---|---|+| Where it comes from | The daemon finds a server listening inside a run's directory | The repository describes it in `.multica/environments.toml`, and an agent starts it with `multica env start` |+| Setup | None | Add the file to the repository |+| After the run ends | Keeps running as long as the process does | Supervised by the daemon until it is stopped or its TTL runs out |+| From the sidebar | Open, copy the URL, stop | Open, copy the URL, start, stop, restart, view logs |++Detection makes the section useful with no setup. Declaring is what makes an environment repeatable: every run starts it the same way, on its own ports, with a log you can read from the sidebar.++## Detected servers [#detected]++On macOS and Linux, the daemon looks for processes listening on a TCP port about every 30 seconds. A process shows up in the sidebar when:++- its working directory is inside the directory of one of the issue's runs, and+- it was found on two scans in a row, so test servers that live for a moment stay out.++These are left out:++- the AI coding tools themselves and the `multica` CLI;+- servers running from a project's own [local directory](/project-resources), which are yours rather than a run's;+- servers that already belong to a declared environment, which are listed once, under that environment;+- servers from runs that are not on an issue, such as chat sessions.++A desktop app (for example an Electron app) is listed once as an app instead of as a list of ports. It has no URL; from Multica Desktop on the same machine, **Switch to window** brings it forward. Its remote-debugging ports are not offered as links.++A detected server keeps showing after its run ends, for as long as it keeps listening. Members can stop it from the sidebar, but the daemon does not know how it was started, so it has no log and cannot be restarted. To get those, declare it.++## Declare environments [#declare]++Add `.multica/environments.toml` at the repository root and commit it on the branch your runs check out. The sidebar only finds the file at the root of a checkout, or one directory below it, and skips a file with errors; `multica env start` reports what is wrong. Each `[environments.<name>]` table is one environment:++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++An agent then starts it from inside its checkout:++```bash+multica env start web+```++The command waits until the environment answers, then prints its URL. The environment shows in the sidebar, keeps running after the run ends, and stops when its TTL runs out.++### Fields [#fields]++| Field | Required | Default | Meaning |+|---|---|---|---|+| `start` | Yes | | Shell command that starts the environment. It runs with `/bin/sh -c` from the directory that holds `.multica/`. |+| `label` | No | The name | Name shown in the sidebar. |+| `url` | No | `http://localhost:$MULTICA_PORT` | Where members open it. Set `url = ""` for something with no page, such as a worker or a desktop app. |+| `ready` | No | Same as `url` | Address checked until it answers with any status below 500 (a 404 counts). With no `ready` and no `url`, the environment counts as running as soon as `start` launches. |+| `stop` | No | | Command run before the daemon signals the processes. Use it when `start` creates something its processes don't own, such as containers. |+| `ttl` | No | `24h` | How long it runs before it is stopped, from `1m` to `168h`. Use `s`, `m`, or `h`; `7d` is not accepted. |++The environment's name is the part after `environments.`: lowercase letters, digits, `-`, and `_`, at most 40 characters, starting with a letter or digit.++### Ports and variables [#ports]++Each environment gets ten free ports of its own, `MULTICA_PORT` through `MULTICA_PORT+9`. Two runs on the same machine, or two issues, never collide, so never hard-code a port.++`start` and `stop` see these variables:++| Variable | Value |+|---|---|+| `MULTICA_PORT` | The first port of the block, for example `41000` |+| `MULTICA_ENVIRONMENT` | The environment's name |+| `PATH` | The `PATH` of the agent that ran `multica env start`, so the repository's toolchain resolves. A start from the sidebar reuses the last one an agent used for that environment on the issue. |++They also inherit the daemon's environment, except its `MULTICA_*` variables, credentials included: an environment cannot act as the run. In `url` and `ready`, only `$MULTICA_PORT` (or `${MULTICA_PORT}`) is substituted. To use a second port, compute it in the shell, for example `API_PORT=$((MULTICA_PORT + 1))`.++### Keep `start` in the foreground [#foreground]++`start` runs as the leader of a new process group. The environment lives as long as any process in that group does, and stopping it signals the whole group. So:++- Keep the main server in the foreground. Background helpers started with `&` are fine; they stay in the group.+- Don't detach work to something outside the group, such as `docker compose up -d`, a system service, or `setsid`. The environment would end as **Exited** at once, and stopping it would not reach that work. Run such tools in the foreground and add a `stop` command.+- A run's checkout starts without dependencies installed. Install them in `start`; the ten minutes the daemon waits for readiness include that time.++## Examples [#examples]++Each example is a complete `.multica/environments.toml`. Swap `npm ci` for your package manager's install command (`pnpm install --frozen-lockfile`, `yarn install --immutable`) to match the repository.++<Tabs items={["Next.js", "Vite", "Go API", "Web + API", "docker compose"]}>+<Tab value="Next.js">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"+ttl = "24h"+```++</Tab>+<Tab value="Vite">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++`--strictPort` makes Vite fail instead of quietly moving to another port, which would leave the sidebar link pointing at nothing.++</Tab>+<Tab value="Go API">++```toml+[environments.api]+label = "API"+start = "PORT=$MULTICA_PORT go run ./cmd/server"+ready = "http://localhost:$MULTICA_PORT/healthz"+ttl = "8h"+```++This assumes the server reads its port from `PORT` and serves a health check at `/healthz`; adjust both to your code.++</Tab>+<Tab value="Web + API">++```toml+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && PORT=$API_PORT go run .) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""+ttl = "24h"+```++The API runs in the background on the second port of the block and the web app in the foreground on the first. Stopping the environment stops both.++</Tab>+<Tab value="docker compose">++```toml+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+ttl = "8h"+```++In `compose.yaml`, publish the web service on the environment's port:++```yaml+services:+ web:+ build: .+ ports:+ - "${MULTICA_PORT:-3000}:3000"+```++`up` stays in the foreground without `-d`. The containers belong to Docker, not to the environment's processes, so `stop` takes them down. `-p env-$MULTICA_PORT` gives every environment its own Compose project, so parallel runs don't share containers.++</Tab>+</Tabs>++To declare more than one environment, add more tables to the same file. Each environment's processes stop with it, even when another environment from the same checkout talks to them. Servers that must keep running together, such as a web app and its API, belong in one environment, as in the Web + API example.++## Start and stop from the CLI [#cli]++| Command | What it does |+|---|---|+| `multica env start <name>` | Starts the environment from the `.multica/environments.toml` found in the current directory or a parent. Waits until it is ready, then prints its URL. If this issue already has one with that name running from the same checkout, returns it unchanged. |+| `multica env start <name> --wait=false` | Returns as soon as it has started. |+| `multica env list` | Lists this issue's environments on this machine, with their state, URL, and log path. |+| `multica env stop <name>` | Stops this issue's running environment with that name on this machine: runs the `stop` command if there is one, then sends `SIGTERM` to the remaining processes, and `SIGKILL` after 10 seconds. If several are running under that name, it stops one of them; to stop a particular one, use the sidebar. |++All three accept `--output json`. `multica environment` is the long form of `multica env`.++<Callout type="info">+These commands use the running task's credential, so they **only work inside an agent run**. Running them in your own terminal fails with `MULTICA_DAEMON_PORT not set`. To start or stop an environment yourself, use the sidebar.+</Callout>++If the start command exits before it is ready, `multica env start` fails and prints the last lines of its log. If it is still not answering after 10 minutes, the command returns, the environment stays **Starting**, and the reason (such as "not answering at http://localhost:41000") is shown with it.++Environments belong to the issue, not to a single run: a later run on the same issue can list and stop what an earlier one started. Starting a name again reuses the running environment only when it runs from the same checkout on this machine. A run with a different checkout starts a second instance under the same name, on its own ports, so check `multica env list` before starting one.++## Manage environments in the sidebar [#sidebar]++Each environment shows its state, when it started or ended, when it expires, and who started it. **Open** opens its URL and **Copy URL** copies it. Environments that ended are folded under "N ended".++- **Start**: click **+** next to **Environments**. The menu lists the environments the latest run on each machine declared, and starts the one you pick in that run's code. If the issue has not run yet or that code has been cleaned up, it offers to ask an agent instead: the agent gets the code ready and runs `multica env start`, or works out how to start the project if it declares nothing.+- **Stop, restart, view logs**: open an environment's **More actions** menu. **Restart** reads the declaration in the checkout again, so the checkout and its `.multica/environments.toml` must still exist. A detected server offers only **Stop**, after a confirmation.++Starting, stopping, and restarting require a workspace member who can access the issue and use that machine's runtime (see [Daemon and runtimes](/daemon-runtimes)). The machine must be online, and its Multica must be recent enough to support environment controls; otherwise the buttons explain what is missing. Reading logs only requires access to the issue.++### Logs [#logs]++**View logs** shows the last 500 lines of a declared environment's output, up to 256 KiB. While the environment runs, the view follows new output about every five seconds; you can pause following, refresh, filter, wrap lines, and copy.++When an environment crashes, its last two lines of output are saved with it, so the sidebar can show why it exited even after the machine goes offline. A fresh read needs the machine online.++The complete log stays on the machine, under `<workspaces root>/.environments/v1/`, and is kept for seven days after the environment ends. `multica env start` and `multica env list` print its path.++<Callout type="warning">+Anyone with access to the issue can read an environment's logs. Multica redacts recognizable secrets from the lines it uploads and deletes log reads after ten minutes, but don't rely on that: keep credentials out of your servers' output.+</Callout>++## States [#states]++| State | Meaning |+|---|---|+| Starting | Started; waiting for its `ready` address to answer. |+| Running | Ready, or listening (for a detected server). |+| Exited | Its processes ended on their own, for example after a crash. The exit code and last lines of output are shown. |+| Stopped | Stopped by an agent, a member, or its TTL ("Stopped when it expired"). |+| Not responding | The machine running it has not reported it for three minutes: the daemon stopped, or the machine is asleep or offline. It shows its real state again once the daemon reports in. |++While the daemon is down, it does not supervise anything; environments whose processes are still alive are picked up again when it restarts. A run directory with a running environment is not removed by the daemon's workspace cleanup until the environment stops.++## Let an agent write the file [#agent]++Agents know the format: Multica's built-in platform skill, which every agent receives, documents `.multica/environments.toml` and how to verify one. Ask in an issue, for example:++> Add a `.multica/environments.toml` so this repository's web app can be started with `multica env start`. Start it once to check it works, then open a PR.++The agent reads how the project starts, writes the file with ports taken from `MULTICA_PORT`, starts the environment to confirm it answers, and ships the file like any other change. Once it is merged, every later run can start the environment, and so can members from the sidebar.++## Known limitations [#limitations]++- **macOS and Linux only.** On Windows, servers are not detected and `multica env start` reports that environments are not supported yet.+- **A localhost URL opens only on the machine running it.** When the environment runs on another machine, such as a build server or a teammate's computer, the sidebar says so; open it on that machine, or forward the port yourself.+- **Daemon restarts under systemd.** On Linux with [start at login](/daemon-runtimes#autostart), restarting or updating the daemon also stops its declared environments. Start them again afterwards.+- **One machine per environment.** An environment runs where the run that started it ran; it does not move with the issue.++## Next steps++- [Daemon and runtimes](/daemon-runtimes) — the daemon that detects and supervises environments.+- [Using the CLI](/cli#environments) — the `multica env` commands among the rest of the CLI.+- [Runs](/tasks) — where a run's directory comes from.diff --git a/apps/docs/content/docs/environments.zh-Hant.mdx b/apps/docs/content/docs/environments.zh-Hant.mdxnew file mode 100644index 0000000000..e4538906f8--- /dev/null+++ b/apps/docs/content/docs/environments.zh-Hant.mdx@@ -0,0 +1,248 @@+---+title: 環境+description: 在任務側欄裡看到任務的執行啟動了哪些開發服務和 App;在 .multica/environments.toml 裡宣告它們,成員就能在側欄裡啟動、停止和查看日誌。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";++AI 代理修改 Web 應用時,成果往往是一個能開啟的東西:開發伺服器、預覽頁、桌面 App。任務側欄的**環境**區域列出這條任務的執行啟動了哪些仍在執行的服務,按所在的機器分組,每個都可以直接開啟。++環境有兩種來源:++| | 自動識別 | 宣告式 |+|---|---|---|+| 從哪裡來 | 守護程序發現某次執行的目錄裡有服務在監聽埠 | 倉庫在 `.multica/environments.toml` 裡描述,AI 代理用 `multica env start` 啟動 |+| 需要設定 | 不需要 | 在倉庫裡加入這個檔案 |+| 執行結束後 | 程序還在就一直顯示 | 由守護程序託管,直到被停止或 TTL 到期 |+| 在側欄裡可以 | 開啟、複製位址、停止 | 開啟、複製位址、啟動、停止、重新啟動、查看日誌 |++自動識別讓這個區域不用設定就能用;宣告則讓環境可以重複啟動:每次執行都用同樣的方式、在自己的埠上啟動,日誌也能在側欄裡看到。++## 自動識別的服務 [#detected]++在 macOS 和 Linux 上,守護程序大約每 30 秒檢查一次哪些程序在監聽 TCP 埠。一個程序滿足下面兩個條件時,會出現在側欄裡:++- 它的工作目錄在這條任務某次執行的目錄裡;+- 連續兩次掃描都發現了它。這樣一閃而過的測試伺服器不會被列進來。++以下不會被列進來:++- AI 程式設計工具本身,以及 `multica` CLI;+- 從專案自己的[本機目錄](/project-resources)執行的服務,那是你自己啟動的,不屬於某次執行;+- 已經屬於某個宣告式環境的服務,它們只在那個環境下面列一次;+- 不在任務上的執行(例如聊天工作階段)啟動的服務。++桌面 App(例如 Electron 應用)只作為一個 App 列出,不會按埠列成好幾條。它沒有 URL;在同一台機器上的 Multica Desktop 裡,點**切到視窗**就能把它切到前景。它的遠端偵錯埠不會作為連結顯示。++自動識別的服務在執行結束後仍會顯示,直到它不再監聽埠。成員可以在側欄裡停止它,但守護程序不知道它是怎麼啟動的,所以沒有日誌,也不能重新啟動。需要這些功能,就把它宣告出來。++## 宣告環境 [#declare]++在倉庫根目錄加入 `.multica/environments.toml`,並提交到執行會檢出的分支上。側欄只在檢出程式碼的根目錄或下一層目錄裡尋找這個檔案,檔案有錯誤時會略過;`multica env start` 會回報具體哪裡有問題。每個 `[environments.<name>]` 表是一個環境:++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++AI 代理在自己檢出的程式碼目錄裡啟動它:++```bash+multica env start web+```++命令會等環境能回應後印出它的 URL。環境出現在側欄裡,執行結束後繼續執行,TTL 到期時自動停止。++### 欄位 [#fields]++| 欄位 | 必填 | 預設值 | 含義 |+|---|---|---|---|+| `start` | 是 | | 啟動環境的 shell 命令。在 `.multica/` 所在的目錄裡用 `/bin/sh -c` 執行。 |+| `label` | 否 | 環境名稱 | 側欄裡顯示的名字。 |+| `url` | 否 | `http://localhost:$MULTICA_PORT` | 成員開啟它的位址。沒有頁面的環境(例如背景 worker 或桌面 App)設為 `url = ""`。 |+| `ready` | 否 | 與 `url` 相同 | 反覆檢查的位址,回傳任意小於 500 的狀態碼即視為就緒(404 也算)。既沒有 `ready` 也沒有 `url` 時,`start` 一啟動就算執行中。 |+| `stop` | 否 | | 守護程序向程序發送訊號之前先執行的命令。`start` 建立了不歸它的程序所有的東西(例如容器)時需要它。 |+| `ttl` | 否 | `24h` | 執行多久後自動停止,範圍 `1m` 到 `168h`。單位用 `s`、`m` 或 `h`;不支援 `7d`。 |++環境名稱是 `environments.` 後面的部分:只能用小寫字母、數字、`-` 和 `_`,以字母或數字開頭,最多 40 個字元。++### 埠和變數 [#ports]++每個環境分到十個自己專用的空閒埠:`MULTICA_PORT` 到 `MULTICA_PORT+9`。同一台機器上的兩次執行、兩條任務都不會衝突,所以不要寫死埠。++`start` 和 `stop` 能取得這些變數:++| 變數 | 值 |+|---|---|+| `MULTICA_PORT` | 埠段的第一個埠,例如 `41000` |+| `MULTICA_ENVIRONMENT` | 環境名稱 |+| `PATH` | 執行 `multica env start` 的 AI 代理的 `PATH`,這樣倉庫的工具鏈能被找到。從側欄啟動時,沿用 AI 代理上一次在這條任務上啟動這個環境時的 `PATH`。 |++它們還會繼承守護程序的環境變數,但不包括 `MULTICA_*` 變數(憑據也在其中):環境不能以這次執行的身分操作。`url` 和 `ready` 裡只會替換 `$MULTICA_PORT`(或 `${MULTICA_PORT}`)。需要第二個埠時,在 shell 裡計算,例如 `API_PORT=$((MULTICA_PORT + 1))`。++### 讓 `start` 留在前景 [#foreground]++`start` 作為一個新程序群組的組長執行。只要群組裡還有程序,環境就一直存在;停止環境時會向整個程序群組發送訊號。所以:++- 讓主服務留在前景。用 `&` 放到背景的輔助程序沒問題,它們仍在這個程序群組裡。+- 不要把工作交給程序群組以外的東西,例如 `docker compose up -d`、系統服務或 `setsid`。那樣環境會立刻變成**已退出**,停止時也碰不到那些工作。這類工具要在前景執行,並配一個 `stop` 命令。+- 執行檢出的程式碼裡還沒有安裝相依套件。在 `start` 裡安裝;守護程序等待就緒的十分鐘包含安裝時間。++## 範例 [#examples]++每個範例都是一份完整的 `.multica/environments.toml`。把 `npm ci` 換成倉庫所用套件管理器的安裝命令(`pnpm install --frozen-lockfile`、`yarn install --immutable`)。++<Tabs items={["Next.js", "Vite", "Go API", "Web + API", "docker compose"]}>+<Tab value="Next.js">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"+ttl = "24h"+```++</Tab>+<Tab value="Vite">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++`--strictPort` 讓 Vite 在埠被佔用時直接失敗,而不是悄悄換到別的埠,導致側欄裡的連結打不開。++</Tab>+<Tab value="Go API">++```toml+[environments.api]+label = "API"+start = "PORT=$MULTICA_PORT go run ./cmd/server"+ready = "http://localhost:$MULTICA_PORT/healthz"+ttl = "8h"+```++這裡假設服務從 `PORT` 讀取埠,並在 `/healthz` 提供健康檢查;按你的程式碼調整這兩處。++</Tab>+<Tab value="Web + API">++```toml+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && PORT=$API_PORT go run .) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""+ttl = "24h"+```++API 在背景執行,用埠段的第二個埠;Web 應用在前景執行,用第一個埠。停止環境時兩者一起停止。++</Tab>+<Tab value="docker compose">++```toml+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+ttl = "8h"+```++在 `compose.yaml` 裡,把 Web 服務發布到環境的埠上:++```yaml+services:+ web:+ build: .+ ports:+ - "${MULTICA_PORT:-3000}:3000"+```++不加 `-d` 時 `up` 留在前景。容器歸 Docker 所有,不屬於環境的程序,所以要靠 `stop` 把它們關掉。`-p env-$MULTICA_PORT` 讓每個環境有自己的 Compose 專案,並行的執行不會共用容器。++</Tab>+</Tabs>++要宣告多個環境,在同一個檔案裡多寫幾個表即可。每個環境的程序都隨它一起停止,即使同一份程式碼啟動的另一個環境還在呼叫它們。需要一起保持執行的服務(例如 Web 應用和它的 API)應放在同一個環境裡,參考 Web + API 範例。++## 用 CLI 啟動和停止 [#cli]++| 命令 | 作用 |+|---|---|+| `multica env start <name>` | 按目前目錄或上層目錄裡找到的 `.multica/environments.toml` 啟動環境。等它就緒後印出 URL。這條任務上已有同名環境從同一份程式碼執行時,直接回傳它。 |+| `multica env start <name> --wait=false` | 啟動後立即回傳。 |+| `multica env list` | 列出這條任務在本機上的環境,包括狀態、URL 和日誌路徑。 |+| `multica env stop <name>` | 停止這條任務在本機上同名的執行中環境:有 `stop` 命令就先執行它,再向剩餘程序發送 `SIGTERM`,10 秒後發送 `SIGKILL`。同名的有好幾個在執行時,只停止其中一個;要停止特定的那個,請用側欄。 |++三個命令都支援 `--output json`。`multica environment` 是 `multica env` 的完整寫法。++<Callout type="info">+這些命令使用目前執行的憑據,所以**只能在 AI 代理的執行中使用**。在你自己的終端機裡執行會報錯 `MULTICA_DAEMON_PORT not set`。想自己啟動或停止環境,請用側欄。+</Callout>++啟動命令在就緒前就退出時,`multica env start` 會失敗,並印出日誌的最後幾行。10 分鐘後仍未回應時,命令會回傳,環境保持**啟動中**,並附上原因(例如 "not answering at http://localhost:41000")。++環境屬於任務,而不是某一次執行:同一條任務上後來的執行可以列出並停止之前執行啟動的環境。再次啟動同名環境時,只有它在本機從同一份程式碼執行,才會重用正在執行的那個。用另一份程式碼的執行會以同樣的名字另起一份,使用自己的埠,所以啟動前先用 `multica env list` 看一下。++## 在側欄裡管理環境 [#sidebar]++每個環境顯示狀態、啟動或結束的時間、到期時間和啟動者。**開啟**會開啟它的 URL,**複製位址**會複製 URL。已經結束的環境收在"N 個已結束"裡。++- **啟動**:點擊**環境**旁邊的 **+**。選單列出每台機器上最近一次執行宣告的環境,選中後用那次執行的程式碼啟動。這條任務還沒執行過、或者那份程式碼已被清理時,選單會改為讓 AI 代理來啟動:AI 代理準備好程式碼後執行 `multica env start`;專案裡沒有宣告時,它會自己判斷怎麼啟動。+- **停止、重新啟動、查看日誌**:開啟環境的**更多操作**選單。**重新啟動**會重新讀取程式碼裡的宣告,所以那份程式碼和其中的 `.multica/environments.toml` 必須還在。自動識別的服務只有**停止**,並且需要確認。++啟動、停止和重新啟動需要工作區成員能存取這條任務,並且能使用那台機器的執行時(參見[守護程序與執行時](/daemon-runtimes))。機器必須在線上,且上面的 Multica 版本支援環境操作;否則按鈕會說明缺了什麼。查看日誌只需要能存取這條任務。++### 日誌 [#logs]++**查看日誌**顯示宣告式環境輸出的最後 500 行,最多 256 KiB。環境執行時,大約每五秒跟隨一次新輸出;可以暫停跟隨、重新整理、篩選、自動換行和複製。++環境當機時,它最後兩行輸出會和環境一起儲存,所以即使機器離線,側欄也能顯示它為什麼退出。重新讀取日誌需要機器在線上。++完整日誌留在那台機器上,位於 `<workspaces root>/.environments/v1/`,環境結束後保留七天。`multica env start` 和 `multica env list` 會印出它的路徑。++<Callout type="warning">+能存取這條任務的人都能讀到環境的日誌。Multica 會對上傳的內容做敏感資訊遮蔽,並在十分鐘後刪除讀取到的日誌,但不要依賴這些:別讓服務把憑據印到輸出裡。+</Callout>++## 狀態 [#states]++| 狀態 | 含義 |+|---|---|+| 啟動中 | 已啟動,正在等 `ready` 位址回應。 |+| 執行中 | 已就緒;自動識別的服務則表示正在監聽。 |+| 已退出 | 程序自己結束了,例如當機。會顯示退出碼和最後幾行輸出。 |+| 已停止 | 被 AI 代理、成員或 TTL 停止("到期自動停止")。 |+| 無回應 | 執行它的機器已經三分鐘沒有回報它:守護程序停了,或者機器休眠、離線。守護程序重新回報後會恢復真實狀態。 |++守護程序停止期間不會託管任何環境;它重新啟動後,程序仍然存活的環境會被重新接管。有環境在執行的執行目錄,在環境停止前不會被守護程序的工作區清理刪除。++## 讓 AI 代理來寫這個檔案 [#agent]++AI 代理知道這個格式:每個 AI 代理都會收到 Multica 內建的平台技能,其中說明了 `.multica/environments.toml` 的寫法和驗證方法。可以直接在任務裡提,例如:++> 給這個倉庫加一個 `.multica/environments.toml`,讓 Web 應用可以用 `multica env start` 啟動。先啟動一次確認能用,再提 PR。++AI 代理會先弄清專案怎麼啟動,用 `MULTICA_PORT` 寫好埠,啟動環境確認能回應,然後像其他改動一樣提交。合併之後,後續每次執行都能啟動這個環境,成員也能在側欄裡啟動。++## 已知限制 [#limitations]++- **只支援 macOS 和 Linux。** 在 Windows 上不會識別服務,`multica env start` 會提示暫不支援。+- **localhost 位址只能在執行它的機器上開啟。** 環境執行在另一台機器上(例如建置機或同事的電腦)時,側欄會註明;請在那台機器上開啟,或者自己轉發埠。+- **systemd 下重新啟動守護程序。** 在 Linux 上開啟了[開機自啟](/daemon-runtimes#autostart)時,重新啟動或更新守護程序會同時停止它託管的宣告式環境,之後需要重新啟動。+- **一個環境只在一台機器上。** 環境執行在啟動它的那次執行所在的機器上,不會隨任務遷移。++## 接下來++- [守護程序與執行時](/daemon-runtimes) — 識別和託管環境的守護程序。+- [使用 CLI](/cli#environments) — `multica env` 命令和 CLI 的其他命令。+- [執行](/tasks) — 執行的目錄從哪裡來。diff --git a/apps/docs/content/docs/environments.zh.mdx b/apps/docs/content/docs/environments.zh.mdxnew file mode 100644index 0000000000..d6e653e8b9--- /dev/null+++ b/apps/docs/content/docs/environments.zh.mdx@@ -0,0 +1,248 @@+---+title: 环境+description: 在任务侧栏里看到任务的运行启动了哪些开发服务和 App;在 .multica/environments.toml 里声明它们,成员就能在侧栏里启动、停止和查看日志。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";++智能体改 Web 应用时,成果往往是一个能打开的东西:开发服务器、预览页、桌面 App。任务侧栏的**环境**区域列出这条任务的运行启动了哪些还在运行的服务,按所在的机器分组,每个都可以直接打开。++环境有两种来源:++| | 自动识别 | 声明式 |+|---|---|---|+| 从哪里来 | 守护进程发现某次运行的目录里有服务在监听端口 | 仓库在 `.multica/environments.toml` 里描述,智能体用 `multica env start` 启动 |+| 需要配置 | 不需要 | 在仓库里加这个文件 |+| 运行结束后 | 进程还在就一直显示 | 由守护进程托管,直到被停止或 TTL 到期 |+| 在侧栏里可以 | 打开、复制地址、停止 | 打开、复制地址、启动、停止、重启、查看日志 |++自动识别让这个区域不用配置就能用;声明则让环境可以重复启动:每次运行都用同样的方式、在自己的端口上启动,日志也能在侧栏里看到。++## 自动识别的服务 [#detected]++在 macOS 和 Linux 上,守护进程大约每 30 秒检查一次哪些进程在监听 TCP 端口。一个进程满足下面两个条件时,会出现在侧栏里:++- 它的工作目录在这条任务某次运行的目录里;+- 连续两次扫描都发现了它。这样一闪而过的测试服务器不会被列进来。++以下不会被列进来:++- AI 编程工具本身,以及 `multica` CLI;+- 从项目自己的[本地目录](/project-resources)运行的服务,那是你自己启动的,不属于某次运行;+- 已经属于某个声明式环境的服务,它们只在那个环境下面列一次;+- 不在任务上的运行(例如聊天会话)启动的服务。++桌面 App(例如 Electron 应用)只作为一个 App 列出,不会按端口列成好几条。它没有 URL;在同一台机器上的 Multica Desktop 里,点**切到窗口**就能把它切到前台。它的远程调试端口不会作为链接显示。++自动识别的服务在运行结束后仍会显示,直到它不再监听端口。成员可以在侧栏里停止它,但守护进程不知道它是怎么启动的,所以没有日志,也不能重启。需要这些功能,就把它声明出来。++## 声明环境 [#declare]++在仓库根目录添加 `.multica/environments.toml`,并提交到运行会检出的分支上。侧栏只在检出代码的根目录或下一级目录里查找这个文件,文件有错误时会跳过;`multica env start` 会报告具体哪里有问题。每个 `[environments.<name>]` 表是一个环境:++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++智能体在自己检出的代码目录里启动它:++```bash+multica env start web+```++命令会等环境能响应后打印它的 URL。环境出现在侧栏里,运行结束后继续运行,TTL 到期时自动停止。++### 字段 [#fields]++| 字段 | 必填 | 默认值 | 含义 |+|---|---|---|---|+| `start` | 是 | | 启动环境的 shell 命令。在 `.multica/` 所在的目录里用 `/bin/sh -c` 执行。 |+| `label` | 否 | 环境名 | 侧栏里显示的名字。 |+| `url` | 否 | `http://localhost:$MULTICA_PORT` | 成员打开它的地址。没有页面的环境(例如后台 worker 或桌面 App)设为 `url = ""`。 |+| `ready` | 否 | 与 `url` 相同 | 反复检查的地址,返回任意小于 500 的状态码即视为就绪(404 也算)。既没有 `ready` 也没有 `url` 时,`start` 一启动就算运行中。 |+| `stop` | 否 | | 守护进程向进程发信号之前先执行的命令。`start` 创建了不归它的进程所有的东西(例如容器)时需要它。 |+| `ttl` | 否 | `24h` | 运行多久后自动停止,范围 `1m` 到 `168h`。单位用 `s`、`m` 或 `h`;不支持 `7d`。 |++环境名是 `environments.` 后面的部分:只能用小写字母、数字、`-` 和 `_`,以字母或数字开头,最多 40 个字符。++### 端口和变量 [#ports]++每个环境分到十个自己专用的空闲端口:`MULTICA_PORT` 到 `MULTICA_PORT+9`。同一台机器上的两次运行、两条任务都不会冲突,所以不要写死端口。++`start` 和 `stop` 能拿到这些变量:++| 变量 | 值 |+|---|---|+| `MULTICA_PORT` | 端口段的第一个端口,例如 `41000` |+| `MULTICA_ENVIRONMENT` | 环境名 |+| `PATH` | 执行 `multica env start` 的智能体的 `PATH`,这样仓库的工具链能被找到。从侧栏启动时,沿用智能体上一次在这条任务上启动这个环境时的 `PATH`。 |++它们还会继承守护进程的环境变量,但不包括 `MULTICA_*` 变量(凭据也在其中):环境不能以这次运行的身份操作。`url` 和 `ready` 里只会替换 `$MULTICA_PORT`(或 `${MULTICA_PORT}`)。需要第二个端口时,在 shell 里计算,例如 `API_PORT=$((MULTICA_PORT + 1))`。++### 让 `start` 留在前台 [#foreground]++`start` 作为一个新进程组的组长运行。只要组里还有进程,环境就一直存在;停止环境时会向整个进程组发信号。所以:++- 让主服务留在前台。用 `&` 放到后台的辅助进程没问题,它们仍在这个进程组里。+- 不要把工作交给进程组以外的东西,例如 `docker compose up -d`、系统服务或 `setsid`。那样环境会立刻变成**已退出**,停止时也碰不到那些工作。这类工具要在前台运行,并配一个 `stop` 命令。+- 运行检出的代码里还没有安装依赖。在 `start` 里安装;守护进程等待就绪的十分钟包含安装时间。++## 示例 [#examples]++每个示例都是一份完整的 `.multica/environments.toml`。把 `npm ci` 换成仓库所用包管理器的安装命令(`pnpm install --frozen-lockfile`、`yarn install --immutable`)。++<Tabs items={["Next.js", "Vite", "Go API", "Web + API", "docker compose"]}>+<Tab value="Next.js">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"+ttl = "24h"+```++</Tab>+<Tab value="Vite">++```toml+[environments.web]+label = "Web app"+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort"+ttl = "24h"+```++`--strictPort` 让 Vite 在端口被占用时直接失败,而不是悄悄换到别的端口,导致侧栏里的链接打不开。++</Tab>+<Tab value="Go API">++```toml+[environments.api]+label = "API"+start = "PORT=$MULTICA_PORT go run ./cmd/server"+ready = "http://localhost:$MULTICA_PORT/healthz"+ttl = "8h"+```++这里假设服务从 `PORT` 读取端口,并在 `/healthz` 提供健康检查;按你的代码调整这两处。++</Tab>+<Tab value="Web + API">++```toml+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && PORT=$API_PORT go run .) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""+ttl = "24h"+```++API 在后台运行,用端口段的第二个端口;Web 应用在前台运行,用第一个端口。停止环境时两者一起停止。++</Tab>+<Tab value="docker compose">++```toml+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+ttl = "8h"+```++在 `compose.yaml` 里,把 Web 服务发布到环境的端口上:++```yaml+services:+ web:+ build: .+ ports:+ - "${MULTICA_PORT:-3000}:3000"+```++不加 `-d` 时 `up` 留在前台。容器归 Docker 所有,不属于环境的进程,所以要靠 `stop` 把它们关掉。`-p env-$MULTICA_PORT` 让每个环境有自己的 Compose 项目,并行的运行不会共用容器。++</Tab>+</Tabs>++要声明多个环境,在同一个文件里多写几个表即可。每个环境的进程都随它一起停止,即使同一份代码启动的另一个环境还在调用它们。需要一起保持运行的服务(例如 Web 应用和它的 API)应放在同一个环境里,参考 Web + API 示例。++## 用 CLI 启动和停止 [#cli]++| 命令 | 作用 |+|---|---|+| `multica env start <name>` | 按当前目录或上级目录里找到的 `.multica/environments.toml` 启动环境。等它就绪后打印 URL。这条任务上已有同名环境从同一份代码运行时,直接返回它。 |+| `multica env start <name> --wait=false` | 启动后立即返回。 |+| `multica env list` | 列出这条任务在本机上的环境,包括状态、URL 和日志路径。 |+| `multica env stop <name>` | 停止这条任务在本机上同名的运行中环境:有 `stop` 命令就先执行它,再向剩余进程发送 `SIGTERM`,10 秒后发送 `SIGKILL`。同名的有好几个在运行时,只停止其中一个;要停止特定的那个,请用侧栏。 |++三个命令都支持 `--output json`。`multica environment` 是 `multica env` 的完整写法。++<Callout type="info">+这些命令使用当前运行的凭据,所以**只能在智能体的运行中使用**。在你自己的终端里执行会报错 `MULTICA_DAEMON_PORT not set`。想自己启动或停止环境,请用侧栏。+</Callout>++启动命令在就绪前就退出时,`multica env start` 会失败,并打印日志的最后几行。10 分钟后仍未响应时,命令会返回,环境保持**启动中**,并附上原因(例如 "not answering at http://localhost:41000")。++环境属于任务,而不是某一次运行:同一条任务上后来的运行可以列出并停止之前运行启动的环境。再次启动同名环境时,只有它在本机从同一份代码运行,才会复用正在运行的那个。用另一份代码的运行会以同样的名字另起一份,使用自己的端口,所以启动前先用 `multica env list` 看一下。++## 在侧栏里管理环境 [#sidebar]++每个环境显示状态、启动或结束的时间、到期时间和启动者。**打开**会打开它的 URL,**复制地址**会复制 URL。已经结束的环境收在"N 个已结束"里。++- **启动**:点击**环境**旁边的 **+**。菜单列出每台机器上最近一次运行声明的环境,选中后用那次运行的代码启动。这条任务还没运行过、或者那份代码已被清理时,菜单会改为让智能体来启动:智能体准备好代码后执行 `multica env start`;项目里没有声明时,它会自己判断怎么启动。+- **停止、重启、查看日志**:打开环境的**更多操作**菜单。**重启**会重新读取代码里的声明,所以那份代码和其中的 `.multica/environments.toml` 必须还在。自动识别的服务只有**停止**,并且需要确认。++启动、停止和重启需要工作区成员能访问这条任务,并且能使用那台机器的运行时(参见[守护进程与运行时](/daemon-runtimes))。机器必须在线,且上面的 Multica 版本支持环境操作;否则按钮会说明缺了什么。查看日志只需要能访问这条任务。++### 日志 [#logs]++**查看日志**显示声明式环境输出的最后 500 行,最多 256 KiB。环境运行时,大约每五秒跟随一次新输出;可以暂停跟随、刷新、筛选、自动换行和复制。++环境崩溃时,它最后两行输出会和环境一起保存,所以即使机器离线,侧栏也能显示它为什么退出。重新读取日志需要机器在线。++完整日志留在那台机器上,位于 `<workspaces root>/.environments/v1/`,环境结束后保留七天。`multica env start` 和 `multica env list` 会打印它的路径。++<Callout type="warning">+能访问这条任务的人都能读到环境的日志。Multica 会对上传的内容做敏感信息脱敏,并在十分钟后删除读取到的日志,但不要依赖这些:别让服务把凭据打印到输出里。+</Callout>++## 状态 [#states]++| 状态 | 含义 |+|---|---|+| 启动中 | 已启动,正在等 `ready` 地址响应。 |+| 运行中 | 已就绪;自动识别的服务则表示正在监听。 |+| 已退出 | 进程自己结束了,例如崩溃。会显示退出码和最后几行输出。 |+| 已停止 | 被智能体、成员或 TTL 停止("到期自动停止")。 |+| 无响应 | 运行它的机器已经三分钟没有报告它:守护进程停了,或者机器休眠、离线。守护进程重新报告后会恢复真实状态。 |++守护进程停止期间不会托管任何环境;它重启后,进程仍然存活的环境会被重新接管。有环境在运行的运行目录,在环境停止前不会被守护进程的工作区清理删除。++## 让智能体来写这个文件 [#agent]++智能体知道这个格式:每个智能体都会收到 Multica 内置的平台技能,其中说明了 `.multica/environments.toml` 的写法和验证方法。可以直接在任务里提,例如:++> 给这个仓库加一个 `.multica/environments.toml`,让 Web 应用可以用 `multica env start` 启动。先启动一次确认能用,再提 PR。++智能体会先弄清项目怎么启动,用 `MULTICA_PORT` 写好端口,启动环境确认能响应,然后像其他改动一样提交。合并之后,后续每次运行都能启动这个环境,成员也能在侧栏里启动。++## 已知限制 [#limitations]++- **只支持 macOS 和 Linux。** 在 Windows 上不会识别服务,`multica env start` 会提示暂不支持。+- **localhost 地址只能在运行它的机器上打开。** 环境运行在另一台机器上(例如构建机或同事的电脑)时,侧栏会注明;请在那台机器上打开,或者自己转发端口。+- **systemd 下重启守护进程。** 在 Linux 上开启了[开机自启](/daemon-runtimes#autostart)时,重启或更新守护进程会同时停止它托管的声明式环境,之后需要重新启动。+- **一个环境只在一台机器上。** 环境运行在启动它的那次运行所在的机器上,不会随任务迁移。++## 接下来++- [守护进程与运行时](/daemon-runtimes) — 识别和托管环境的守护进程。+- [使用 CLI](/cli#environments) — `multica env` 命令和 CLI 的其他命令。+- [运行](/tasks) — 运行的目录从哪里来。diff --git a/apps/docs/content/docs/meta.fr.json b/apps/docs/content/docs/meta.fr.jsonindex 662ec5be52..3cf441b934 100644--- a/apps/docs/content/docs/meta.fr.json+++ b/apps/docs/content/docs/meta.fr.json@@ -37,6 +37,7 @@"daemon-runtimes","install-agent-runtime","providers",+ "environments","---Automatisation---","autopilots","issue-wakeups",diff --git a/apps/docs/content/docs/meta.ja.json b/apps/docs/content/docs/meta.ja.jsonindex a28db4249e..7f0e056161 100644--- a/apps/docs/content/docs/meta.ja.json+++ b/apps/docs/content/docs/meta.ja.json@@ -37,6 +37,7 @@"daemon-runtimes","install-agent-runtime","providers",+ "environments","---自動化---","autopilots","issue-wakeups",diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.jsonindex b990ba5336..488132164e 100644--- a/apps/docs/content/docs/meta.json+++ b/apps/docs/content/docs/meta.json@@ -37,6 +37,7 @@"daemon-runtimes","install-agent-runtime","providers",+ "environments","---Automation---","autopilots","issue-wakeups",diff --git a/apps/docs/content/docs/meta.ko.json b/apps/docs/content/docs/meta.ko.jsonindex 1042049d6c..6f61ec9b85 100644--- a/apps/docs/content/docs/meta.ko.json+++ b/apps/docs/content/docs/meta.ko.json@@ -37,6 +37,7 @@"daemon-runtimes","install-agent-runtime","providers",+ "environments","---자동화---","autopilots","issue-wakeups",diff --git a/apps/docs/content/docs/meta.zh-Hant.json b/apps/docs/content/docs/meta.zh-Hant.jsonindex a1a5c30fa3..75aaa25a34 100644--- a/apps/docs/content/docs/meta.zh-Hant.json+++ b/apps/docs/content/docs/meta.zh-Hant.json@@ -37,6 +37,7 @@"daemon-runtimes","install-agent-runtime","providers",+ "environments","---自動化---","autopilots","issue-wakeups",diff --git a/apps/docs/content/docs/meta.zh.json b/apps/docs/content/docs/meta.zh.jsonindex 4eaa430d87..23ec6c4a15 100644--- a/apps/docs/content/docs/meta.zh.json+++ b/apps/docs/content/docs/meta.zh.json@@ -37,6 +37,7 @@"daemon-runtimes","install-agent-runtime","providers",+ "environments","---自动化---","autopilots","issue-wakeups",diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 389e005048..77191e968f 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -796,7 +796,7 @@ func writeSkills(b *strings.Builder, provider string, ctx TaskContextForEnv) {// what keeps that consolidation from costing recall, and it must therefore// name the skill that actually holds those contracts.if platformSlug != "" {- b.WriteString("For a Multica platform action this brief does not fully cover — issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, skill import — load the `" + platformSlug + "` skill and open the reference(s) its routing table names for the domains your task touches.\n\n")+ b.WriteString("For a Multica platform action this brief does not fully cover — issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import — load the `" + platformSlug + "` skill and open the reference(s) its routing table names for the domains your task touches.\n\n")}}@@ -822,7 +822,7 @@ func writeTraecliSkills(b *strings.Builder, skills []SkillContextForEnv) {}b.WriteString("\n")if platformSlug != "" {- b.WriteString("For a Multica platform action this brief does not fully cover — issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, skill import — read `" + skillPath(platformSlug) + "` and open the reference(s) its routing table names for the domains your task touches.\n\n")+ b.WriteString("For a Multica platform action this brief does not fully cover — issue and PR contracts, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import — read `" + skillPath(platformSlug) + "` and open the reference(s) its routing table names for the domains your task touches.\n\n")}}diff --git a/server/internal/service/builtin_skills.go b/server/internal/service/builtin_skills.goindex 4a1918a891..549df8f486 100644--- a/server/internal/service/builtin_skills.go+++ b/server/internal/service/builtin_skills.go@@ -22,8 +22,8 @@ const ()// PlatformSkillName is the built-in skill carrying Multica's platform-// contracts — issues, mentions, agents, squads, autopilots, projects, runtimes-// and skill import — behind one routing SKILL.md. Every agent receives it.+// contracts — issues, mentions, agents, squads, autopilots, projects, runtimes,+// local environments and skill import — behind one routing SKILL.md. Every agent receives it.//// The daemon's runtime brief names the same skill from its own constant: the// daemon runs on the user's machine and must not import this package, so thediff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.mdindex 8873173483..5b93db77e0 100644--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md@@ -1,6 +1,6 @@---name: multica-platform-description: "Use for Multica platform actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, skill import. Not for the product code you are working on."+description: "Use for Multica platform actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import. Not for the product code you are working on."user-invocable: falseallowed-tools: Bash(multica *), Bash(git *), Bash(gh *)---@@ -27,6 +27,7 @@ Read the invariants below, then open the reference(s) your task actually needs| `references/autopilots.md` | Autopilots: schedule / webhook / manual triggers, `create_issue` vs `run_only`, why one did not fire || `references/projects.md` | Projects and their durable resources (`github_repo`, `local_directory`, worktree mode); project workflows — status columns, handoffs, a `[Project workflow]` block in your prompt, reading or changing a workflow (`multica workflow`, `multica project workflow`) || `references/runtimes.md` | Runtimes, daemons, `repo checkout`, and the task CLI boundary |+| `references/environments.md` | Local environments in the issue sidebar: writing `.multica/environments.toml`, `multica env start` / `stop` / `list`, detected servers || `references/skill-import.md` | Importing a skill into this workspace from a URL or a local archive |Open what the task needs. A single-domain task usually needs one; a task that@@ -34,7 +35,7 @@ crosses domains needs each domain it touches — creating a squad, assigning itissue, then writing a mention needs `squads.md`, `issues.md` and `mentions.md`,and skipping one of those means acting on a contract you have not read.-What is never right is reading all nine because you are not sure. Each+What is never right is reading all ten because you are not sure. Eachreference states its own contracts in full and none depends on another, sopick by domain and skip the rest.diff --git a/server/internal/service/builtin_skills/multica-platform/references/environments.md b/server/internal/service/builtin_skills/multica-platform/references/environments.mdnew file mode 100644index 0000000000..b8937fad1c--- /dev/null+++ b/server/internal/service/builtin_skills/multica-platform/references/environments.md@@ -0,0 +1,131 @@+# Local environments++An environment is a dev server or app that runs for an issue and is listed in+the issue sidebar's **Environments** section. It comes from one of two places:++- **Declared**: the repository describes it in `.multica/environments.toml`,+ and `multica env start <name>` starts it under the daemon. The daemon keeps+ its log, keeps it running after your run ends, stops it at its TTL, and lets+ members stop, restart and read its logs from the sidebar.+- **Detected**: any process listening on a TCP port whose working directory is+ inside an issue run's directory, seen on two scans about 30 seconds apart.+ Members can only stop it; there is no log and no restart.++Both work on macOS and Linux only. A `localhost` URL opens only on the machine+running it.++## CLI++```bash+multica env start <name> # waits until ready, prints the URL+multica env start <name> --wait=false+multica env list --output json+multica env stop <name>+```++These need the run's `MULTICA_DAEMON_PORT` and `MULTICA_TOKEN`, so they work+only inside a run. Run `start` from inside the checkout: it looks for+`.multica/environments.toml` in the current directory and its parents, up to+the run's directory. Environments belong to the issue, so a later run can+list and stop what an earlier run started.++`start` reuses a running environment only when the issue, the machine, the+name and the checkout all match. From a different checkout, the same name+starts a second instance on its own ports, not the service an earlier run+started; run `multica env list --output json` first and use the running one's+URL when that is what you need. With several instances under one name,+`multica env stop <name>` stops one of them, whichever it finds first.++Each environment's processes stop with it, even when another environment+talks to them. Put servers that must keep running together, such as a web app+and its API, in one environment (see the recipes).++`start` fails, and prints the last lines of the log, when the start command+exits before it is ready. When it is still not ready after 10 minutes, `start`+returns with the environment still starting; read the log path it printed.++## Writing `.multica/environments.toml`++Put the file at the repository root, and commit it on the branch runs check+out. The sidebar's start menu only finds it at the root of a repository checked+out into the run's `workdir`, or one directory below that root, and skips a+file that does not parse; `multica env start` reports the parse error.++```toml+[environments.web] # name: a-z 0-9 - _, at most 40, starts with a letter or digit+label = "Web app" # optional; shown in the sidebar+start = "npm ci && npx vite --port $MULTICA_PORT --strictPort" # required+# url = "http://localhost:$MULTICA_PORT" # the default; url = "" for no URL+# ready = "http://localhost:$MULTICA_PORT/health" # defaults to url+# stop = "docker compose down" # optional; runs before the processes are signalled+ttl = "24h" # 1m to 168h, default 24h+```++| Field | Contract |+|---|---|+| `start` | Run with `/bin/sh -c` from the directory that holds `.multica/`, as the leader of a new process group. The environment lives as long as any process in that group does, and stopping it signals that group. A command that hands its work to something outside the group, such as `docker compose up -d`, a system service, or `setsid`, ends the environment as `exited` at once, and stopping it would not reach that work. |+| `url` | Where a member opens it. `$MULTICA_PORT` or `${MULTICA_PORT}` is substituted; no other variable or arithmetic is. Set `url = ""` for a worker or a desktop app. |+| `ready` | Polled once a second until it answers with any status below 500 (a 404 counts). With no `ready` and no `url`, the environment is running as soon as `start` launches. |+| `stop` | Run with the same directory and variables, with a one-minute limit. Afterwards the process group gets `SIGTERM`, then `SIGKILL` 10 seconds later. Needed whenever `start` creates something the process group does not own, such as containers. |+| `ttl` | A Go duration: `30m`, `8h`, `168h`. `7d` is rejected. |++The start and stop commands receive:++- `MULTICA_PORT`: the first of ten free ports reserved for this environment,+ `MULTICA_PORT` through `MULTICA_PORT+9`. Never hard-code a port: parallel+ runs on one machine must not collide. Derive extra ports in the shell, for+ example `API_PORT=$((MULTICA_PORT + 1))`.+- `MULTICA_ENVIRONMENT`: the environment's name.+- The caller's `PATH`, and the daemon's other variables. No other+ `MULTICA_*` variable is passed, credentials included, so the environment+ cannot act as the run.++A run's checkout starts without installed dependencies. Install them in `start`+(`npm ci && ...`); the 10-minute readiness window includes that time.++Output goes to a log file on the machine, and members can read its last 500+lines from the sidebar. Do not print secrets in it.++### Recipes++```toml+# Next.js+[environments.web]+label = "Web app"+start = "npm ci && npx next dev --port $MULTICA_PORT"++# An API that reads PORT and serves a health check+[environments.api]+label = "API"+start = "npm ci && PORT=$MULTICA_PORT npm start"+ready = "http://localhost:$MULTICA_PORT/healthz"++# Web app plus its API, on two ports of one block+[environments.app]+label = "Web + API"+start = """+API_PORT=$((MULTICA_PORT + 1))+(cd api && npm ci && PORT=$API_PORT npm start) &+cd web && npm ci && VITE_API_URL=http://localhost:$API_PORT npx vite --port $MULTICA_PORT --strictPort+"""++# docker compose: stays in the foreground, and the project name keeps runs apart.+# compose.yaml maps the port with "${MULTICA_PORT:-3000}:3000".+[environments.stack]+label = "Full stack"+start = "docker compose -p env-$MULTICA_PORT up --build"+stop = "docker compose -p env-$MULTICA_PORT down"+```++## Boundaries++- Adding or changing `.multica/environments.toml` is a repository change.+ Make it when the task asks for it, and ship it like any other change.+- After writing one, verify it: `multica env start <name>` from the checkout,+ open the URL or `ready` endpoint, read the log, then `multica env stop <name>`+ unless the user wants it kept running.+- When the repository declares nothing and the user wants a service kept+ running, start it yourself under the runtime brief's persistent-service+ rules; the daemon only reports it as a detected server.+- Do not start environments to test something you can test inside your own+ run. Each one holds ports and keeps running until its TTL.diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.goindex 792c26ba50..3347c21bc9 100644--- a/server/internal/service/builtin_skills_test.go+++ b/server/internal/service/builtin_skills_test.go@@ -360,6 +360,7 @@ func TestPlatformSkillDescriptionNamesEveryDomain(t *testing.T) {"references/autopilots.md": "autopilot","references/projects.md": "project","references/runtimes.md": "runtime",+ "references/environments.md": "local environment","references/skill-import.md": "skill import",}@@ -433,6 +434,7 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {"references/autopilots.md","references/projects.md","references/runtimes.md",+ "references/environments.md","references/skill-import.md",// Invariants deduplicated out of the eight merged bodies. Each// was repeated in most of them; the router is now their only@@ -679,6 +681,24 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {"task-local Git metadata",},},+ {+ file: "references/environments.md",+ want: []string{+ ".multica/environments.toml",+ "multica env start <name>",+ // The port block is what keeps parallel runs from colliding;+ // an agent that hard-codes a port breaks the second run.+ "`MULTICA_PORT` through `MULTICA_PORT+9`",+ // A detaching start command ends the environment at once and+ // leaves its work unreachable by stop.+ "`docker compose up -d`",+ // ttl is a Go duration; the day unit fails to parse.+ "`7d` is rejected",+ // Reuse is keyed on the checkout as well as the name, so a run+ // with its own checkout gets a second instance, not the old one.+ "the name and the checkout all match",+ },+ },{file: "references/projects.md",want: []string{