Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): invoke explicitly selected skills across chat and issue comments (#10772)

AstralSolipsism0fb8e4a4c833
diff --git a/apps/docs/content/docs/chat.fr.mdx b/apps/docs/content/docs/chat.fr.mdx
index a21f59a9e5..2c5b920dca 100644
--- a/apps/docs/content/docs/chat.fr.mdx
+++ b/apps/docs/content/docs/chat.fr.mdx
@@ -96,11 +96,11 @@ Si l'agent n'avait encore rien produit, le message que vous venez d'envoyer est
## Envoyer des messages pendant une réponse
-Vous pouvez écrire pendant que l’agent répond. Si le runtime le permet, **Envoyer** ajoute un message texte à la réponse en cours sans arrêter l’exécution. L’agent le lit au prochain moment approprié et poursuit la tâche initiale. Mettez votre daemon à jour pour activer cette fonction.
+Vous pouvez écrire pendant que l’agent répond. Si le runtime le permet, **Envoyer** ajoute un message texte sans lien de skill à la réponse en cours sans arrêter l’exécution. L’agent le lit au prochain moment approprié et poursuit la tâche initiale. Mettez votre daemon à jour pour activer cette fonction.
-Sur le web et sur ordinateur, **Ajouter à l'exécution en cours** au-dessus du brouillon indique que votre texte rejoindra la réponse en cours. **Démarrer après cette exécution** indique que le message sera mis en file, par exemple s'il contient des pièces jointes ou si l'exécution ne prend pas en charge cette fonction.
+Sur le web et sur ordinateur, **Ajouter à l'exécution en cours** au-dessus du brouillon indique que votre texte rejoindra la réponse en cours. **Démarrer après cette exécution** indique que le message sera mis en file, par exemple s'il contient des pièces jointes ou un lien de skill, ou si l'exécution ne prend pas en charge cette fonction.
-Les messages avec pièces jointes, envoyés avant le début de la réponse ou à un runtime incompatible sont automatiquement mis en file. Un message non transmis avant la fin de la réponse rejoint automatiquement la file ; inutile de le renvoyer. Si vous arrêtez pendant la transmission, Chat attend son résultat avant de mettre les messages non transmis en file. En cas de nouvelle tentative automatique, les instructions supplémentaires restent associées à la demande initiale pour être traitées ensemble. Lors de la reprise de la même session, les instructions déjà transmises ne sont pas renvoyées.
+Les messages avec pièces jointes ou liens de skill, envoyés avant le début de la réponse ou à un runtime incompatible sont automatiquement mis en file. Un message non transmis avant la fin de la réponse rejoint automatiquement la file ; inutile de le renvoyer. Si vous arrêtez pendant la transmission, Chat attend son résultat avant de mettre les messages non transmis en file. En cas de nouvelle tentative automatique, les instructions supplémentaires restent associées à la demande initiale pour être traitées ensemble. Lors de la reprise de la même session, les instructions déjà transmises ne sont pas renvoyées.
La file apparaît au-dessus du champ de saisie et suit l’ordre des messages. Vous pouvez supprimer un message, le modifier via **⋯**, ou vider la file. **Envoyer maintenant (arrête la réponse)** place le message en tête et arrête la réponse en cours. Cette action nécessite une réponse démarrée et le droit d’exécuter l’agent.
diff --git a/apps/docs/content/docs/chat.ja.mdx b/apps/docs/content/docs/chat.ja.mdx
index 4ec086282d..00d9c92580 100644
--- a/apps/docs/content/docs/chat.ja.mdx
+++ b/apps/docs/content/docs/chat.ja.mdx
@@ -96,11 +96,11 @@ Multica で作成したダイレクトチャットを読めるのは作成者だ
## 返信中に続けてメッセージを送る
-エージェントの返信中も入力できます。ランタイムが対応していれば、**送信**でテキストを現在の返信に追加できます。実行は停止せず、エージェントは次の安全なタイミングで読み取り、元のタスクを続けます。この機能には daemon の更新が必要です。
+エージェントの返信中も入力できます。ランタイムが対応していれば、**送信**でスキルリンクを含まないテキストを現在の返信に追加できます。実行は停止せず、エージェントは次の安全なタイミングで読み取り、元のタスクを続けます。この機能には daemon の更新が必要です。
-ウェブ版とデスクトップ版では、下書きの上に**現在の実行に追加**と表示されていれば、テキストは現在の返信に追加されます。**この実行の後に開始**は、添付ファイルがある場合や現在の実行が非対応の場合など、メッセージがキューに入ることを示します。
+ウェブ版とデスクトップ版では、下書きの上に**現在の実行に追加**と表示されていれば、テキストは現在の返信に追加されます。**この実行の後に開始**は、添付ファイルやスキルリンクがある場合、現在の実行が非対応の場合など、メッセージがキューに入ることを示します。
-添付ファイル付きのメッセージ、返信開始前のメッセージ、非対応ランタイムへのメッセージは自動的にキューに入ります。返信終了までに追加メッセージが届かなかった場合は自動的にキューに戻るので、再送は不要です。配信中に停止した場合、配信結果を待ってから未配信のメッセージをキューに戻します。返信が自動再試行される場合、追加メッセージは元のリクエストと一緒に処理されます。同じセッションを再開する際は、配信済みの追加メッセージを再送しません。
+添付ファイルやスキルリンク付きのメッセージ、返信開始前のメッセージ、非対応ランタイムへのメッセージは自動的にキューに入ります。返信終了までに追加メッセージが届かなかった場合は自動的にキューに戻るので、再送は不要です。配信中に停止した場合、配信結果を待ってから未配信のメッセージをキューに戻します。返信が自動再試行される場合、追加メッセージは元のリクエストと一緒に処理されます。同じセッションを再開する際は、配信済みの追加メッセージを再送しません。
キューは入力欄の上に表示され、順番に処理されます。削除、**⋯** からの編集や全消去も可能です。**今すぐ送信(現在の返信を停止)** はキュー内のメッセージを先頭に移し、現在の返信を停止します。返信が開始済みで、実行権限が必要です。
diff --git a/apps/docs/content/docs/chat.ko.mdx b/apps/docs/content/docs/chat.ko.mdx
index d2c07e1aa2..d63928089c 100644
--- a/apps/docs/content/docs/chat.ko.mdx
+++ b/apps/docs/content/docs/chat.ko.mdx
@@ -96,11 +96,11 @@ Multica에서 만든 직접 대화는 만든 사람만 읽을 수 있고, 다른
## 답변 중에 메시지 이어서 보내기
-에이전트가 응답하는 동안에도 입력할 수 있습니다. 런타임이 지원하면 **보내기**로 텍스트 메시지를 현재 응답에 추가합니다. 실행을 중지하지 않으며 에이전트가 다음 안전한 시점에 읽고 원래 작업을 계속합니다. 사용하려면 daemon을 업그레이드하세요.
+에이전트가 응답하는 동안에도 입력할 수 있습니다. 런타임이 지원하면 **보내기**로 스킬 링크가 없는 텍스트 메시지를 현재 응답에 추가합니다. 실행을 중지하지 않으며 에이전트가 다음 안전한 시점에 읽고 원래 작업을 계속합니다. 사용하려면 daemon을 업그레이드하세요.
-웹과 데스크톱에서는 초안 위의 **현재 실행에 추가**가 텍스트를 현재 응답에 추가한다는 뜻입니다. **이번 실행 후 시작**은 첨부 파일이 있거나 현재 실행이 지원하지 않는 경우처럼 메시지가 대기열에 들어간다는 뜻입니다.
+웹과 데스크톱에서는 초안 위의 **현재 실행에 추가**가 텍스트를 현재 응답에 추가한다는 뜻입니다. **이번 실행 후 시작**은 첨부 파일이나 스킬 링크가 있거나 현재 실행이 지원하지 않는 경우처럼 메시지가 대기열에 들어간다는 뜻입니다.
-첨부 파일이 있는 메시지, 응답 시작 전의 메시지, 미지원 런타임에 보내는 메시지는 자동으로 대기열에 들어갑니다. 현재 응답이 끝날 때까지 전달되지 않은 메시지는 자동으로 대기열로 이동하므로 다시 보낼 필요가 없습니다. 전달 중에 중지하면 전달 결과를 기다린 후 미전달 메시지를 대기열에 넣습니다. 응답을 자동으로 재시도하면 추가 메시지도 원래 요청과 함께 처리됩니다. 같은 세션을 재개할 때 이미 전달된 추가 메시지는 다시 보내지 않습니다.
+첨부 파일이나 스킬 링크가 있는 메시지, 응답 시작 전의 메시지, 미지원 런타임에 보내는 메시지는 자동으로 대기열에 들어갑니다. 현재 응답이 끝날 때까지 전달되지 않은 메시지는 자동으로 대기열로 이동하므로 다시 보낼 필요가 없습니다. 전달 중에 중지하면 전달 결과를 기다린 후 미전달 메시지를 대기열에 넣습니다. 응답을 자동으로 재시도하면 추가 메시지도 원래 요청과 함께 처리됩니다. 같은 세션을 재개할 때 이미 전달된 추가 메시지는 다시 보내지 않습니다.
대기열은 입력창 위에 표시되며 순서대로 처리됩니다. 삭제하거나 **⋯** 에서 편집 또는 전체 삭제할 수 있습니다. **지금 보내기 (현재 응답 중지)** 는 메시지를 맨 앞으로 옮기고 현재 응답을 중지합니다. 응답이 시작된 상태이고 에이전트 실행 권한이 있어야 합니다.
diff --git a/apps/docs/content/docs/chat.mdx b/apps/docs/content/docs/chat.mdx
index b1a51d49fd..87cd0d3e34 100644
--- a/apps/docs/content/docs/chat.mdx
+++ b/apps/docs/content/docs/chat.mdx
@@ -96,11 +96,11 @@ If the agent hadn't produced anything yet, the message you just sent is taken ba
## Send messages while a reply is in progress
-You can keep typing while the agent is replying. **Send** adds a plain text message to the current reply without stopping it, when the runtime supports steering. The agent reads it at its next safe boundary and continues the original task. Upgrade your daemon to enable this.
+You can keep typing while the agent is replying. **Send** adds a plain text message without a skill link to the current reply without stopping it, when the runtime supports steering. The agent reads it at its next safe boundary and continues the original task. Upgrade your daemon to enable this.
-On web and desktop, **Add to current run** above your draft means your text will join the running reply. **Start after this run** means the message will be queued, for example when it has files or the current run doesn't support steering.
+On web and desktop, **Add to current run** above your draft means your text will join the running reply. **Start after this run** means the message will be queued, for example when it has files or a skill link, or the current run doesn't support steering.
-Messages with attachments, and messages sent before a reply starts or to a runtime without steering support, enter the queue. If guidance is not delivered before the reply ends, it automatically becomes a queued message; you do not need to resend it. If you stop while delivery is in progress, Chat waits for its result before queuing undelivered guidance. If the reply is retried automatically, guidance stays with the original request so both are processed together. When resuming the same session, guidance already delivered there is not sent again.
+Messages with attachments or skill links, and messages sent before a reply starts or to a runtime without steering support, enter the queue. If guidance is not delivered before the reply ends, it automatically becomes a queued message; you do not need to resend it. If you stop while delivery is in progress, Chat waits for its result before queuing undelivered guidance. If the reply is retried automatically, guidance stays with the original request so both are processed together. When resuming the same session, guidance already delivered there is not sent again.
Queued messages appear above the input and run in order. You can remove them, use **⋯ → Edit queued message** to restore them to the input, or **⋯ → Clear all** to withdraw them. **Send now (stops current reply)** moves a queued message to the front and stops the current reply. It requires an active reply and permission to run the agent.
diff --git a/apps/docs/content/docs/chat.zh-Hant.mdx b/apps/docs/content/docs/chat.zh-Hant.mdx
index 7b67feefc9..772a679715 100644
--- a/apps/docs/content/docs/chat.zh-Hant.mdx
+++ b/apps/docs/content/docs/chat.zh-Hant.mdx
@@ -96,11 +96,11 @@ AI 代理執行時,介面會顯示當前階段和工具活動。展開**檢視
## 回覆還沒結束時繼續發訊息
-智能體仍在回覆時,可以繼續輸入。執行階段支援插話時,按**傳送**會把純文字訊息加入目前回覆,不會停止執行;智能體在下一個安全時機讀到訊息,繼續完成原任務。需要升級 daemon 才能啟用。
+智能體仍在回覆時,可以繼續輸入。執行階段支援插話時,按**傳送**會把不含 skill 連結的純文字訊息加入目前回覆,不會停止執行;智能體在下一個安全時機讀到訊息,繼續完成原任務。需要升級 daemon 才能啟用。
-在網頁版和桌面版,輸入時顯示的**插話到當前執行**表示文字會加入目前回覆;**本輪結束後開始**表示訊息會排隊,例如帶有附件或目前執行不支援插話時。
+在網頁版和桌面版,輸入時顯示的**插話到當前執行**表示文字會加入目前回覆;**本輪結束後開始**表示訊息會排隊,例如帶有附件、skill 連結或目前執行不支援插話時。
-含附件的訊息、回覆尚未開始時傳送的訊息,以及不支援插話的執行,都會自動進入佇列。插話若未在目前回覆結束前送達,會自動轉成排隊訊息,無需重送。投遞過程中按停止,會先等待投遞結果,再將未送達的插話排隊。如果回覆自動重試,插話會保留在原請求中,一起處理;恢復同一會話時,已送達的插話不會再次傳送。
+含附件或 skill 連結的訊息、回覆尚未開始時傳送的訊息,以及不支援插話的執行,都會自動進入佇列。插話若未在目前回覆結束前送達,會自動轉成排隊訊息,無需重送。投遞過程中按停止,會先等待投遞結果,再將未送達的插話排隊。如果回覆自動重試,插話會保留在原請求中,一起處理;恢復同一會話時,已送達的插話不會再次傳送。
佇列顯示在輸入框上方,依序處理。可以移除、透過 **⋯ → 編輯排隊訊息** 放回輸入框,或用 **⋯ → 全部清空** 撤回。**立即傳送(停止目前回覆)** 會將訊息移到最前並停止目前回覆;需要回覆已開始,且你有執行該智能體的權限。
diff --git a/apps/docs/content/docs/chat.zh.mdx b/apps/docs/content/docs/chat.zh.mdx
index 33cfb7cead..a6d3e30891 100644
--- a/apps/docs/content/docs/chat.zh.mdx
+++ b/apps/docs/content/docs/chat.zh.mdx
@@ -96,11 +96,11 @@ import { ChatDemo } from "@/components/demos/chat-demo";
## 回复还没结束时继续发消息
-智能体还在回复时,可以继续输入。运行时支持插话时,点**发送**会把纯文本消息插入当前回复,不会停止运行;智能体在下一个安全时机读到消息,继续完成原任务。需要升级 daemon 才能启用。
+智能体还在回复时,可以继续输入。运行时支持插话时,点**发送**会把不含 skill 链接的纯文本消息插入当前回复,不会停止运行;智能体在下一个安全时机读到消息,继续完成原任务。需要升级 daemon 才能启用。
-在网页端和桌面端,输入时显示的**插话到当前运行**表示文字会加入当前回复;**本轮结束后开始**表示消息会排队,例如带有附件或当前运行不支持插话时。
+在网页端和桌面端,输入时显示的**插话到当前运行**表示文字会加入当前回复;**本轮结束后开始**表示消息会排队,例如带有附件、skill 链接或当前运行不支持插话时。
-带附件的消息、回复尚未开始时发送的消息,以及不支持插话的运行,都会进入队列。如果插话在当前回复结束前没送达,会自动转成排队消息,无需重发。投递过程中点停止,会先等待投递结果,再将未送达的插话排队。如果回复自动重试,插话会保留在原请求中,一起处理;恢复同一会话时,已送达的插话不会再次发送。
+带附件或 skill 链接的消息、回复尚未开始时发送的消息,以及不支持插话的运行,都会进入队列。如果插话在当前回复结束前没送达,会自动转成排队消息,无需重发。投递过程中点停止,会先等待投递结果,再将未送达的插话排队。如果回复自动重试,插话会保留在原请求中,一起处理;恢复同一会话时,已送达的插话不会再次发送。
排队消息显示在输入框上方,按顺序处理。可以删除,通过 **⋯ → 编辑排队消息** 放回输入框,或用 **⋯ → 全部清空** 撤回。**立即发送(停止当前回复)** 会把排队消息提到队首,并停止当前回复;需要当前回复已开始,且你有运行该智能体的权限。
diff --git a/apps/docs/content/docs/mentioning-agents.fr.mdx b/apps/docs/content/docs/mentioning-agents.fr.mdx
index f50dc85345..a56860582f 100644
--- a/apps/docs/content/docs/mentioning-agents.fr.mdx
+++ b/apps/docs/content/docs/mentioning-agents.fr.mdx
@@ -64,10 +64,10 @@ Quand le destinataire est en cours d'exécution, une étiquette sous la zone de
Après l'envoi, le commentaire affiche d'abord « En attente de lecture par … », puis « Lu par … » une fois le message lu. La liste des étapes du journal d'exécution indique aussi à quelle étape il a été lu. Si la remise échoue, vous pouvez réessayer ou l'envoyer comme nouvelle exécution.
-- Seul du texte peut rejoindre une exécution en cours. Un message avec des pièces jointes est traité après la fin de l'exécution.
+- Seul du texte sans lien de skill peut rejoindre une exécution en cours. Un message avec des pièces jointes ou des liens de skill est traité après la fin de l'exécution.
- La réorientation doit être prise en charge par l'outil de codage IA de l'agent. Sinon, « Ajouter à l'exécution en cours » n'est pas proposé.
- Le choix par défaut se règle dans **Paramètres → Préférences**, sous **En répondant à un agent en cours d'exécution**. Vous pouvez toujours le modifier pour chaque message avant l'envoi.
-- Dans un Chat compatible, envoyer un texte pendant une réponse l’ajoute à cette réponse sans l’arrêter. Les messages avec pièces jointes, envoyés avant le début de la réponse ou à un runtime incompatible sont automatiquement mis en file ; voir [Chat](/chat#envoyer-des-messages-pendant-une-réponse).
+- Dans un Chat compatible, envoyer un texte sans lien de skill pendant une réponse l’ajoute à cette réponse sans l’arrêter. Les messages avec pièces jointes ou liens de skill, envoyés avant le début de la réponse ou à un runtime incompatible sont automatiquement mis en file ; voir [Chat](/chat#envoyer-des-messages-pendant-une-réponse).
## Regroupement des commentaires consécutifs
diff --git a/apps/docs/content/docs/mentioning-agents.ja.mdx b/apps/docs/content/docs/mentioning-agents.ja.mdx
index f56d46a42a..6966ac1696 100644
--- a/apps/docs/content/docs/mentioning-agents.ja.mdx
+++ b/apps/docs/content/docs/mentioning-agents.ja.mdx
@@ -64,10 +64,10 @@ import { SteerDemo } from "@/components/demos/steer-demo";
送信すると、コメントの下にまず「… が読むのを待っています」と表示され、読まれると「… が読みました」に変わります。実行ログのステップ一覧にも、どのステップで読んだかが示されます。届けられなかった場合は、再試行するか、新しい実行として送信できます。
-- 実行中に追加できるのはテキストだけです。ファイル付きのメッセージは、この実行の後に処理されます。
+- 実行中に追加できるのはスキルリンクを含まないテキストだけです。添付ファイルやスキルリンク付きのメッセージは、この実行の後に処理されます。
- 割り込みには、エージェントが使う AI コーディングツールの対応が必要です。対応していない場合、「現在の実行に追加」は選択肢に表示されません。
- 既定の選択肢は **設定 → 環境設定** の **実行中のエージェントに返信するとき** で変えられます。メッセージごとに送信前に変更することもできます。
-- 対応する Chat の返信中にテキストを送信すると、実行を止めずに現在の返信に追加します。添付ファイル付きのメッセージ、返信開始前のメッセージ、非対応ランタイムへのメッセージは自動的にキューに入ります。[チャット](/chat#返信中に続けてメッセージを送る)を参照してください。
+- 対応する Chat の返信中にスキルリンクを含まないテキストを送信すると、実行を止めずに現在の返信に追加します。添付ファイルやスキルリンク付きのメッセージ、返信開始前のメッセージ、非対応ランタイムへのメッセージは自動的にキューに入ります。[チャット](/chat#返信中に続けてメッセージを送る)を参照してください。
## 連続コメントの統合
diff --git a/apps/docs/content/docs/mentioning-agents.ko.mdx b/apps/docs/content/docs/mentioning-agents.ko.mdx
index 80daa4ffba..50c947873a 100644
--- a/apps/docs/content/docs/mentioning-agents.ko.mdx
+++ b/apps/docs/content/docs/mentioning-agents.ko.mdx
@@ -64,10 +64,10 @@ import { SteerDemo } from "@/components/demos/steer-demo";
보내면 댓글 아래에 먼저 "…이(가) 읽기를 기다리는 중"이 표시되고, 에이전트가 읽으면 "…이(가) 읽음"으로 바뀝니다. 실행 로그의 단계 목록에도 어느 단계에서 읽었는지 표시됩니다. 전달에 실패하면 다시 시도하거나 새 실행으로 보낼 수 있습니다.
-- 실행 중에는 텍스트만 추가할 수 있습니다. 첨부 파일이 있는 메시지는 이번 실행이 끝난 뒤 처리됩니다.
+- 실행 중에는 스킬 링크가 없는 텍스트만 추가할 수 있습니다. 첨부 파일이나 스킬 링크가 있는 메시지는 이번 실행이 끝난 뒤 처리됩니다.
- 끼어들기는 에이전트가 쓰는 AI 코딩 도구가 지원해야 합니다. 지원하지 않으면 '현재 실행에 추가'가 옵션에 나오지 않습니다.
- 기본 옵션은 **설정 → 환경설정**의 **실행 중인 에이전트에 답장할 때**에서 바꿀 수 있고, 메시지마다 보내기 전에 따로 바꿀 수도 있습니다.
-- 지원되는 Chat 응답 중에 텍스트를 보내면 실행을 중지하지 않고 현재 응답에 추가합니다. 첨부 파일이 있거나 응답이 아직 시작되지 않았거나 런타임이 지원하지 않는 경우에는 메시지가 자동으로 대기열에 들어갑니다. [채팅](/chat#답변-중에-메시지-이어서-보내기)을 참고하세요.
+- 지원되는 Chat 응답 중에 스킬 링크가 없는 텍스트를 보내면 실행을 중지하지 않고 현재 응답에 추가합니다. 첨부 파일이나 스킬 링크가 있거나 응답이 아직 시작되지 않았거나 런타임이 지원하지 않는 경우에는 메시지가 자동으로 대기열에 들어갑니다. [채팅](/chat#답변-중에-메시지-이어서-보내기)을 참고하세요.
## 연속 댓글 합치기
diff --git a/apps/docs/content/docs/mentioning-agents.mdx b/apps/docs/content/docs/mentioning-agents.mdx
index 914b236a3d..443a33f1c8 100644
--- a/apps/docs/content/docs/mentioning-agents.mdx
+++ b/apps/docs/content/docs/mentioning-agents.mdx
@@ -64,10 +64,10 @@ While the recipient is running, a label under the comment box says how the messa
After you send, the comment shows "Waiting for … to read it", which changes to "Read by …" once the agent has read it. The step list in the execution log also marks the step where it was read. If delivery fails, you can retry or send it as a new run instead.
-- Only text can join a running run. A message with attachments is handled after the run ends.
+- Only text without skill links can join a running run. A message with attachments or skill links is handled after the run ends.
- Steering needs support from the agent's AI coding tool. Without it, **Add to current run** isn't offered.
- Set the default in **Settings → Preferences** under **When replying to a running agent**. You can still change it for any message before sending.
-- In Chat, sending a text message during a supported reply steers that reply without stopping it. Messages with attachments, messages sent before the reply starts, and messages sent to runtimes without steering support are queued automatically; see [Chat](/chat#send-messages-while-a-reply-is-in-progress).
+- In Chat, sending a text message without skill links during a supported reply steers that reply without stopping it. Messages with attachments or skill links, messages sent before the reply starts, and messages sent to runtimes without steering support are queued automatically; see [Chat](/chat#send-messages-while-a-reply-is-in-progress).
## Coalescing consecutive comments
diff --git a/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx b/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx
index c90404fb8c..b5c5244a76 100644
--- a/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx
+++ b/apps/docs/content/docs/mentioning-agents.zh-Hant.mdx
@@ -64,10 +64,10 @@ AI 代理做到一半、方向不對時,不必停下來重來。在評論框
傳送後,評論下方會先顯示"等待 ... 讀取",讀到後變為"... 已讀取";執行日誌的步驟列表裡也會標出它是在哪一步讀到的。送達失敗時,可以重試,或者改為作為新一輪傳送。
-- 插話只支援文字。帶附件的訊息會在本輪結束後處理。
+- 插話只支援不含 skill 連結的文字。帶附件或 skill 連結的訊息會在本輪結束後處理。
- 插話需要 AI 代理使用的 AI 程式設計工具支援;不支援時,選項裡不會出現"插話到當前執行"。
- 預設選項在設定的**回覆正在執行的 AI 代理時**中調整,每條訊息傳送前仍可單獨修改。
-- 一般 Chat 支援插話時,回覆中直接傳送文字就會加入目前回覆,不會停止執行。帶附件、回覆尚未開始或執行階段不支援插話時,訊息會自動排隊,見[聊天](/chat#回覆還沒結束時繼續發訊息)。
+- 一般 Chat 支援插話時,回覆中直接傳送不含 skill 連結的文字就會加入目前回覆,不會停止執行。帶附件或 skill 連結、回覆尚未開始或執行階段不支援插話時,訊息會自動排隊,見[聊天](/chat#回覆還沒結束時繼續發訊息)。
## 連續評論的合併
diff --git a/apps/docs/content/docs/mentioning-agents.zh.mdx b/apps/docs/content/docs/mentioning-agents.zh.mdx
index 89d9e53f9a..4f9bc0b369 100644
--- a/apps/docs/content/docs/mentioning-agents.zh.mdx
+++ b/apps/docs/content/docs/mentioning-agents.zh.mdx
@@ -64,10 +64,10 @@ import { SteerDemo } from "@/components/demos/steer-demo";
发送后,评论下方会先显示"等待 ... 读取",读到后变为"... 已读取";执行日志的步骤列表里也会标出它是在哪一步读到的。送达失败时,可以重试,或者改为作为新一轮发送。
-- 插话只支持文字。带附件的消息会在本轮结束后处理。
+- 插话只支持不含 skill 链接的文字。带附件或 skill 链接的消息会在本轮结束后处理。
- 插话需要智能体使用的 AI 编程工具支持;不支持时,选项里不会出现"插话到当前运行"。
- 默认选项在设置的**回复正在运行的智能体时**中调整,每条消息发送前仍可单独修改。
-- 普通 Chat 支持插话时,回复中直接发送文字就会加入当前回复,不会停止运行。带附件、回复尚未开始或运行时不支持插话时,消息会自动排队,见[聊天](/chat#回复还没结束时继续发消息)。
+- 普通 Chat 支持插话时,回复中直接发送不含 skill 链接的文字就会加入当前回复,不会停止运行。带附件或 skill 链接、回复尚未开始或运行时不支持插话时,消息会自动排队,见[聊天](/chat#回复还没结束时继续发消息)。
## 连续评论的合并
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index b325b4892c..55ef2bdf89 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -1041,6 +1041,24 @@ describe("ChatInput project context", () => {
expect(screen.queryByText("Start after this run")).not.toBeInTheDocument();
});
+ it("shows queuing for a selected skill and restores steering when it is removed", async () => {
+ const onSend = vi.fn<ChatInputOnSend>(async () => true);
+ const props = { isRunning: true, allowSubmitWhileRunning: true, canSteerWhileRunning: true, onSend };
+ const { rerender } = renderInput(props);
+ const editor = screen.getByTestId("editor");
+ const content = "[/release-notes](slash://skill/550e8400-e29b-41d4-a716-446655440000) Write release notes";
+
+ fireEvent.change(editor, { target: { value: content } });
+ expect(screen.getByRole("status")).toHaveTextContent("Start after this run");
+ expect(screen.queryByText("Add to current run")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Send" }));
+ await waitFor(() => expect(onSend).toHaveBeenCalledWith(content, undefined, expect.any(Function), []));
+
+ fireEvent.change(editor, { target: { value: "Write release notes" } });
+ rerender(element(props));
+ expect(screen.getByRole("status")).toHaveTextContent("Add to current run");
+ });
+
it("keeps Stop available and explains queuing while content is uploading", async () => {
let resolveUpload!: (value: UploadResult) => void;
mockApiUploadFile.mockImplementation(
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index bd36934bea..fa86c56e30 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -714,7 +714,8 @@ export function ChatInput({
const canSubmitNow = !disabled && !noAgent && (!isRunning || !!allowSubmitWhileRunning);
const showRunHint = isRunning && allowSubmitWhileRunning && canSteerWhileRunning !== undefined
&& !hasNothingToSend && !disabled && !noAgent;
- const willSteer = canSteerWhileRunning && draftUploads.length === 0;
+ const willSteer = canSteerWhileRunning && draftUploads.length === 0
+ && !inputDraft.includes("](slash://skill/");
const voice = useComposerVoice({
insert: (text) => editorRef.current?.insertText(text) ?? false,
submit: canSubmitNow ? () => void submit() : undefined,
diff --git a/server/internal/daemon/chat_skills.go b/server/internal/daemon/chat_skills.go
new file mode 100644
index 0000000000..bd4160b344
--- /dev/null
+++ b/server/internal/daemon/chat_skills.go
@@ -0,0 +1,293 @@
+package daemon
+
+import (
+ "path/filepath"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+ "github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/yuin/goldmark"
+ "github.com/yuin/goldmark/ast"
+ "github.com/yuin/goldmark/text"
+)
+
+// activeSlashSkillMatches limits the existing slash-link grammar to real Markdown
+// links outside quotations/code. A copied issue excerpt is never a selection.
+func activeSlashSkillMatches(message string) []slashSkillMatch {
+ matches := slashSkillMatches(message)
+ if len(matches) == 0 {
+ return matches
+ }
+ source := []byte(message)
+ active := make(map[int]bool)
+ doc := goldmark.DefaultParser().Parse(text.NewReader(source))
+ _ = ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {
+ if !entering {
+ return ast.WalkContinue, nil
+ }
+ if node.Kind() == ast.KindBlockquote {
+ return ast.WalkSkipChildren, nil
+ }
+ link, ok := node.(*ast.Link)
+ if !ok || !strings.HasPrefix(string(link.Destination), "slash://skill/") {
+ return ast.WalkContinue, nil
+ }
+ _ = ast.Walk(link, func(child ast.Node, entering bool) (ast.WalkStatus, error) {
+ if value, ok := child.(*ast.Text); ok && entering {
+ for _, match := range matches {
+ if match.start <= value.Segment.Start && value.Segment.Stop <= match.end {
+ active[match.start] = true
+ }
+ }
+ }
+ return ast.WalkContinue, nil
+ })
+ return ast.WalkSkipChildren, nil
+ })
+ selected := matches[:0]
+ for _, match := range matches {
+ if active[match.start] {
+ selected = append(selected, match)
+ }
+ }
+ return selected
+}
+
+// memberSkillText pairs an authenticated human-member input with the active
+// matches found inside it. Only the server's own authorship data can put a
+// text here; nothing derived from issue bodies, agent/system comments or
+// legacy payloads without an author type qualifies.
+type memberSkillText struct {
+ text string
+ matches []slashSkillMatch
+}
+
+func chatSkillMatches(task Task) []slashSkillMatch {
+ if task.ChatSkillMessage == nil {
+ // Legacy servers did not distinguish the sender from the originator.
+ // Keep their existing hint, but never issue a native command/injection.
+ return slashSkillMatches(task.ChatMessage)
+ }
+ if *task.ChatSkillMessage == "" {
+ // Known non-member chat keeps bound name hints without earning an
+ // invocation. Quoted/code links are not current selections.
+ return activeSlashSkillMatches(task.ChatMessage)
+ }
+ return activeSlashSkillMatches(*task.ChatSkillMessage)
+}
+
+func memberSkillTurn(task Task) bool {
+ return task.ChatSessionID != "" && !task.ChatIntro && task.ChatSkillMessage != nil && *task.ChatSkillMessage != "" && task.WakeupID == "" && task.IssueID == "" && task.AutopilotRunID == "" && task.Agent != nil
+}
+
+// issueMemberSkillTurn reports whether this run is a comment-triggered issue
+// task whose explicit skill selections may be honored at all. Wakeups and
+// autopilots carry no member comment intent even when they name a trigger
+// comment, and quick-create/assignment tasks have no comment to trust.
+func issueMemberSkillTurn(task Task) bool {
+ return task.IssueID != "" && task.ChatSessionID == "" && task.WakeupID == "" && task.AutopilotRunID == "" &&
+ task.TriggerCommentID != "" && task.Agent != nil
+}
+
+// memberSkillTexts collects the authenticated member inputs this run may act
+// on, in a stable order: a chat turn contributes its direct member message,
+// an issue turn contributes its human-authored comments — coalesced comments
+// oldest first, then the newest trigger comment. Everything else (agent or
+// system authorship, empty author types from legacy payloads, quoted or
+// code-span links via activeSlashSkillMatches) is filtered before it can
+// reach a SkillInvocation.
+func memberSkillTexts(task Task) []memberSkillText {
+ if memberSkillTurn(task) {
+ return []memberSkillText{{text: *task.ChatSkillMessage, matches: activeSlashSkillMatches(*task.ChatSkillMessage)}}
+ }
+ if !issueMemberSkillTurn(task) {
+ return nil
+ }
+ var texts []memberSkillText
+ for _, cc := range task.CoalescedComments {
+ if cc.AuthorType == "member" && cc.Content != "" {
+ texts = append(texts, memberSkillText{text: cc.Content, matches: activeSlashSkillMatches(cc.Content)})
+ }
+ }
+ if task.TriggerAuthorType == "member" && task.TriggerCommentContent != "" {
+ texts = append(texts, memberSkillText{text: task.TriggerCommentContent, matches: activeSlashSkillMatches(task.TriggerCommentContent)})
+ }
+ return texts
+}
+
+// memberSkillRefs deduplicates the refs of member texts by skill ID, keeping
+// first-seen (chronological) order across the merged comments.
+func memberSkillRefs(texts []memberSkillText) []SlashSkillRef {
+ var matches []slashSkillMatch
+ for _, text := range texts {
+ matches = append(matches, text.matches...)
+ }
+ return uniqueSlashSkillRefs(matches)
+}
+
+// buildRuntimePrompt keeps ordinary inputs byte-for-byte unchanged. Only the
+// server's authenticated member input can earn a structured invocation; a
+// human originator on an agent/system/wakeup task is insufficient.
+func buildRuntimePrompt(task Task, provider string, directories map[string]string, options ...PromptOption) (string, *agent.SkillInvocation) {
+ texts := memberSkillTexts(task)
+ var refs []SlashSkillRef
+ if len(texts) > 0 {
+ refs = memberSkillRefs(texts)
+ } else if task.ChatSessionID != "" {
+ // Legacy chat hint: refs stay display-only, never an invocation.
+ refs = uniqueSlashSkillRefs(chatSkillMatches(task))
+ }
+ // The full slice expression copies the caller's variadic backing array:
+ // later appends (the platform-prompt rebuild below, retries) must never
+ // write through spare capacity the caller still owns.
+ options = append(options[:len(options):len(options)], func(o *promptOpts) {
+ o.skillDirectories = directories
+ o.chatSkillRefs = refs
+ })
+ if len(texts) == 0 || len(refs) == 0 {
+ return BuildPrompt(task, provider, options...), nil
+ }
+ assigned := make(map[string]SkillData, len(task.Agent.Skills))
+ for _, skill := range task.Agent.Skills {
+ assigned[skill.ID] = skill
+ }
+ invocation := &agent.SkillInvocation{}
+ selected := make(map[string]string)
+ for _, ref := range refs {
+ skill, ok := assigned[ref.ID]
+ dir := directories[ref.ID]
+ if !ok || !filepath.IsAbs(dir) {
+ continue
+ }
+ invocation.Skills = append(invocation.Skills, agent.ExplicitSkill{
+ Name: filepath.Base(dir), Directory: dir, Body: execenv.SkillBody(skill.Content),
+ })
+ selected[ref.ID] = filepath.Base(dir)
+ }
+ if len(invocation.Skills) == 0 {
+ return BuildPrompt(task, provider, options...), nil
+ }
+ if task.ChatSessionID != "" {
+ return chatRuntimePrompt(task, texts[0], selected, invocation, provider, options...)
+ }
+ return issueRuntimePrompt(task, texts, selected, invocation, provider, options...)
+}
+
+// chatRuntimePrompt finishes a direct chat turn's invocation: the member
+// message is a contiguous part of the claimed batch, and only selected links
+// inside it are replaced by resolved names before the prompt is rebuilt.
+func chatRuntimePrompt(task Task, source memberSkillText, selected map[string]string, invocation *agent.SkillInvocation, provider string, options ...PromptOption) (string, *agent.SkillInvocation) {
+ skillMessage := source.text
+ // Direct chat input is a contiguous suffix of the claimed batch; an older
+ // or inconsistent server payload must not let this field replace user text.
+ start := strings.LastIndex(task.ChatMessage, skillMessage)
+ if start < 0 {
+ return BuildPrompt(task, provider, options...), nil
+ }
+ // Replace only selected links in the actual member text. Unknown IDs and
+ // quoted links remain visible, and cannot become a leading CLI command.
+ prefix, suffix := task.ChatMessage[:start], task.ChatMessage[start+len(skillMessage):]
+ user := replaceSelectedSkillLinks(skillMessage, source.matches, selected)
+ task.ChatMessage = prefix + user + suffix
+ invocation.UserMessage = task.ChatMessage
+ // A resumed retry renders ChatResumeMessage instead of the full batch —
+ // the server already dropped guidance delivered to PriorSessionID there —
+ // and the trailing command block must not repeat it either. The member
+ // batch is shorter in that view, so locate it by the boundary just
+ // verified on the full batch and replace its selected links on its own
+ // terms. The local task value re-points the field, so the caller's
+ // payload stays intact for a later cold retry rebuilding from the task.
+ if task.PriorSessionID != "" && task.ChatResumeMessage != nil {
+ resume := *task.ChatResumeMessage
+ if len(resume) >= len(prefix)+len(suffix) && strings.HasPrefix(resume, prefix) && strings.HasSuffix(resume, suffix) {
+ body := resume[len(prefix) : len(resume)-len(suffix)]
+ rewritten := prefix + replaceSelectedSkillLinks(body, activeSlashSkillMatches(body), selected) + suffix
+ task.ChatResumeMessage = &rewritten
+ invocation.UserMessage = rewritten
+ }
+ }
+ invocation.Prompt = BuildPrompt(task, provider, options...)
+ options = append(options, func(o *promptOpts) { o.omitChatMessage = true })
+ invocation.PlatformPrompt = BuildPrompt(task, provider, options...)
+ return invocation.FallbackPrompt(), invocation
+}
+
+// issueRuntimePrompt finishes a comment-triggered issue turn's invocation.
+// Hit links are replaced in the human member comments embedded in the
+// comment prompt, and UserMessage carries every member ask of the run —
+// including coalesced member comments that carried no skill link — for
+// Claude's trailing slash-command block. PlatformPrompt equals the complete
+// comment prompt: unlike chat there is no separate user-message section to
+// omit, and the issue context, thread metadata and --parent reply routing
+// must survive intact.
+func issueRuntimePrompt(task Task, texts []memberSkillText, selected map[string]string, invocation *agent.SkillInvocation, provider string, options ...PromptOption) (string, *agent.SkillInvocation) {
+ // texts pairs every member comment of this run — coalesced comments
+ // oldest first, then the trigger comment — with the matches
+ // memberSkillTexts already found in it, so each comment is rewritten
+ // exactly once.
+ var user []string
+ next := 0
+ rewritten := func(content string) string {
+ var matches []slashSkillMatch
+ if next < len(texts) {
+ matches = texts[next].matches
+ next++
+ }
+ text := replaceSelectedSkillLinks(content, matches, selected)
+ if message := strings.TrimSpace(text); message != "" {
+ user = append(user, message)
+ }
+ return text
+ }
+ // The task value is a copy, but its slice fields share the caller's
+ // backing array — the retry path rebuilds from the same task, and a
+ // rewritten comment there would hide its links from the second pass.
+ task.CoalescedComments = append([]CoalescedCommentData(nil), task.CoalescedComments...)
+ for i, cc := range task.CoalescedComments {
+ if cc.AuthorType == "member" && cc.Content != "" {
+ task.CoalescedComments[i].Content = rewritten(cc.Content)
+ }
+ }
+ if task.TriggerAuthorType == "member" && task.TriggerCommentContent != "" {
+ content := rewritten(task.TriggerCommentContent)
+ if strings.TrimSpace(content) == "" {
+ // A pure skill-capsule comment strips to nothing. The comment
+ // prompt treats an empty trigger body as "server could not fetch
+ // it", which would silently drop the comment header, edit notes
+ // and every coalesced comment — so keep the section alive with a
+ // placeholder instead.
+ content = ""
+ options = append(options, func(o *promptOpts) { o.triggerCommentStripped = true })
+ }
+ task.TriggerCommentContent = content
+ }
+ invocation.UserMessage = strings.Join(user, "\n\n")
+ invocation.Prompt = BuildPrompt(task, provider, options...)
+ invocation.PlatformPrompt = invocation.Prompt
+ return invocation.FallbackPrompt(), invocation
+}
+
+func replaceSelectedSkillLinks(message string, matches []slashSkillMatch, selected map[string]string) string {
+ var user strings.Builder
+ end := 0
+ replaced, hasArguments := false, false
+ for _, match := range matches {
+ name, ok := selected[match.ref.ID]
+ if !ok {
+ continue
+ }
+ before := message[end:match.start]
+ hasArguments = hasArguments || strings.TrimSpace(before) != ""
+ user.WriteString(before)
+ user.WriteString("/" + name)
+ end = match.end
+ replaced = true
+ }
+ // A message made entirely of selections invokes without arguments;
+ // otherwise keep each resolved name beside the user's target text.
+ if replaced && !hasArguments && strings.TrimSpace(message[end:]) == "" {
+ return ""
+ }
+ user.WriteString(message[end:])
+ return user.String()
+}
diff --git a/server/internal/daemon/chat_skills_issue_test.go b/server/internal/daemon/chat_skills_issue_test.go
new file mode 100644
index 0000000000..1464102cf6
--- /dev/null
+++ b/server/internal/daemon/chat_skills_issue_test.go
@@ -0,0 +1,266 @@
+package daemon
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// issueSkillTask builds a comment-triggered issue task whose trigger comment
+// was authored by a human member.
+func issueSkillTask(content string) Task {
+ return Task{
+ IssueID: "issue-1", TriggerCommentID: "comment-trigger", TriggerThreadID: "comment-trigger",
+ TriggerCommentContent: content, TriggerAuthorType: "member", TriggerAuthorName: "Member",
+ Agent: &AgentData{Skills: []SkillData{
+ {ID: "one", Name: "Review Code", Content: "---\nname: other\ndisable-model-invocation: true\n---\nFIRST BODY"},
+ {ID: "two", Name: "Review-Code", Content: "SECOND BODY"},
+ }},
+ }
+}
+
+func issueSkillDirs(t *testing.T) map[string]string {
+ t.Helper()
+ dir := t.TempDir()
+ return map[string]string{"one": filepath.Join(dir, "review-code"), "two": filepath.Join(dir, "review-code-multica-2")}
+}
+
+func TestBuildRuntimePromptIssueMemberComments(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ task := issueSkillTask("[/spoofed](slash://skill/two) please review")
+ task.CoalescedComments = []CoalescedCommentData{
+ {ID: "c1", AuthorType: "member", Content: "earlier ask with [/first](slash://skill/one)"},
+ {ID: "c2", AuthorType: "agent", Content: "agent also picked [/two](slash://skill/two)"},
+ }
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation == nil || len(invocation.Skills) != 2 || invocation.Skills[0].Name != "review-code" || invocation.Skills[1].Name != "review-code-multica-2" {
+ t.Fatalf("wrong selection order/identity: %+v", invocation)
+ }
+ for _, want := range []string{
+ "Explicitly selected skills:\n- review-code\n- review-code-multica-2\n",
+ "earlier ask with /review-code\n", "/review-code-multica-2 please review", "--parent comment-trigger", dirs["one"], dirs["two"],
+ } {
+ if !strings.Contains(prompt, want) {
+ t.Errorf("prompt missing %q: %s", want, prompt)
+ }
+ }
+ if strings.Contains(prompt, "spoofed") {
+ t.Errorf("prompt keeps acted-on trigger link: %s", prompt)
+ }
+ // The agent-authored coalesced comment is quoted untouched: its link was
+ // never selected, so stripping it would hide an untrusted pick.
+ if !strings.Contains(prompt, "agent also picked [/two](slash://skill/two)") {
+ t.Errorf("agent coalesced comment must keep its link verbatim: %s", prompt)
+ }
+ if invocation.UserMessage != "earlier ask with /review-code\n\n/review-code-multica-2 please review" {
+ // The member texts join chronologically (coalesced first, trigger
+ // last), each with its acted-on link replaced by its resolved name.
+ t.Fatalf("UserMessage=%q", invocation.UserMessage)
+ }
+ // Issue runs keep the complete comment prompt as the platform block: the
+ // reply routing and issue context must survive for Claude's split.
+ if invocation.PlatformPrompt != invocation.Prompt || !strings.Contains(invocation.PlatformPrompt, "--parent comment-trigger") {
+ t.Fatalf("PlatformPrompt lost the comment prompt: %q", invocation.PlatformPrompt)
+ }
+ if strings.Contains(invocation.PlatformPrompt, "User message:\n") {
+ t.Fatalf("issue platform block must not synthesize an empty chat message: %q", invocation.PlatformPrompt)
+ }
+}
+
+func TestBuildRuntimePromptIssueMultiSelectConflictSuffix(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ task := issueSkillTask("[/a](slash://skill/two) and [/b](slash://skill/one) together")
+ _, invocation := buildRuntimePrompt(task, "hermes", dirs)
+ if invocation == nil || len(invocation.Skills) != 2 ||
+ invocation.Skills[0].Name != "review-code-multica-2" || invocation.Skills[1].Name != "review-code" {
+ t.Fatalf("conflict-suffixed names must follow first-seen order: %+v", invocation)
+ }
+ if !strings.Contains(invocation.FallbackPrompt(), "SECOND BODY") || !strings.Contains(invocation.FallbackPrompt(), "FIRST BODY") {
+ t.Fatalf("fallback lost skill bodies: %s", invocation.FallbackPrompt())
+ }
+}
+
+func TestBuildRuntimePromptIssueDoesNotPromoteUntrustedInput(t *testing.T) {
+ link := "[/review](slash://skill/one)"
+ for _, tc := range []struct {
+ name string
+ edit func(*Task)
+ }{
+ {"agent trigger comment", func(t *Task) { t.TriggerAuthorType = "agent" }},
+ {"system trigger comment", func(t *Task) { t.TriggerAuthorType = "system" }},
+ {"legacy empty author type", func(t *Task) { t.TriggerAuthorType = "" }},
+ {"wakeup task", func(t *Task) { t.WakeupID = "wakeup-1" }},
+ {"autopilot task", func(t *Task) { t.AutopilotRunID = "run-1" }},
+ {"assignment task without comment", func(t *Task) { t.TriggerCommentID = ""; t.TriggerCommentContent = "" }},
+ {"quoted trigger comment", func(t *Task) { t.TriggerCommentContent = "> " + link }},
+ {"inline code trigger comment", func(t *Task) { t.TriggerCommentContent = "`" + link + "`" }},
+ {"fenced code trigger comment", func(t *Task) { t.TriggerCommentContent = "```\n" + link + "\n```" }},
+ {"unbound skill id", func(t *Task) { t.TriggerCommentContent = "[/x](slash://skill/stranger)" }},
+ {"plain slash text", func(t *Task) { t.TriggerCommentContent = "/compact" }},
+ {"stale chat_message payload", func(t *Task) { t.TriggerCommentContent = ""; t.ChatMessage = link }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ task := issueSkillTask(link)
+ tc.edit(&task)
+ prompt, invocation := buildRuntimePrompt(task, "claude", issueSkillDirs(t))
+ if invocation != nil || strings.Contains(prompt, "FIRST BODY") || strings.HasPrefix(prompt, "/") ||
+ strings.Contains(prompt, "Explicitly selected skills:") {
+ t.Fatalf("untrusted input became an invocation: %+v, %s", invocation, prompt)
+ }
+ })
+ }
+}
+
+func TestBuildRuntimePromptIssueCoalescedAuthorGate(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ // Only the coalesced member comment carries a link; the trigger is an
+ // agent forward. The member pick still selects, the agent pick does not.
+ task := issueSkillTask("forwarding [/mine](slash://skill/two)")
+ task.TriggerAuthorType = "agent"
+ task.CoalescedComments = []CoalescedCommentData{
+ {ID: "c1", AuthorType: "member", Content: "[/first](slash://skill/one) run review"},
+ {ID: "c2", AuthorType: "system", Content: "[/two](slash://skill/two) platform note"},
+ }
+ prompt, invocation := buildRuntimePrompt(task, "pi", dirs)
+ if invocation == nil || len(invocation.Skills) != 1 || invocation.Skills[0].Name != "review-code" {
+ t.Fatalf("member coalesced pick ignored: %+v", invocation)
+ }
+ if invocation.UserMessage != "/review-code run review" {
+ t.Fatalf("UserMessage must carry only the rewritten member text: %q", invocation.UserMessage)
+ }
+ if !strings.Contains(prompt, "Explicitly selected skills:\n- review-code\n") {
+ t.Errorf("prompt missing selection list: %s", prompt)
+ }
+ if !strings.Contains(prompt, "[/two](slash://skill/two)") || !strings.Contains(prompt, "[/mine](slash://skill/two)") {
+ t.Errorf("unselected links must stay quoted: %s", prompt)
+ }
+}
+
+func TestBuildRuntimePromptIssueMissingInstallation(t *testing.T) {
+ link := "[/review](slash://skill/one)"
+ for _, dirs := range []map[string]string{nil, {}} {
+ task := issueSkillTask(link)
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation != nil || strings.Contains(prompt, "FIRST BODY") {
+ t.Fatalf("missing directory must not invoke: %+v", invocation)
+ }
+ // The selection stays visible as a hint, mirroring chat behavior.
+ if !strings.Contains(prompt, "Explicitly selected skills:\n- Review Code\n") {
+ t.Errorf("hint must fall back to the agent skill name: %s", prompt)
+ }
+ if !strings.Contains(prompt, link) {
+ t.Errorf("unmaterialized link must stay in the quoted comment: %s", prompt)
+ }
+ }
+}
+
+// TestBuildRuntimePromptIssuePureCapsuleTrigger pins the skill-capsule-only
+// comment: stripping its link must not collapse the comment section the way a
+// server fetch failure does — the header, placeholder quote and every
+// coalesced comment still render, and the earlier member ask survives into
+// UserMessage.
+func TestBuildRuntimePromptIssuePureCapsuleTrigger(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ task := issueSkillTask("[/review](slash://skill/one)")
+ task.CoalescedComments = []CoalescedCommentData{
+ {ID: "c-earlier", ThreadID: "c-earlier", AuthorType: "member", Content: "Please check the Safari login redirect bug"},
+ }
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation == nil || len(invocation.Skills) != 1 {
+ t.Fatalf("pure capsule must still select: %+v", invocation)
+ }
+ for _, want := range []string{
+ "[NEW COMMENT]", "(explicit skill selection only",
+ "Please check the Safari login redirect bug",
+ "--parent c-earlier", "Explicitly selected skills:\n- review-code\n",
+ } {
+ if !strings.Contains(prompt, want) {
+ t.Errorf("prompt missing %q: %s", want, prompt)
+ }
+ }
+ if strings.Contains(prompt, "slash://skill") {
+ t.Errorf("acted-on link must be stripped everywhere: %s", prompt)
+ }
+ if invocation.UserMessage != "Please check the Safari login redirect bug" {
+ t.Fatalf("UserMessage must carry the earlier member ask: %q", invocation.UserMessage)
+ }
+ if !strings.Contains(invocation.PlatformPrompt, "Please check the Safari login redirect bug") {
+ t.Fatalf("PlatformPrompt lost the coalesced member ask: %q", invocation.PlatformPrompt)
+ }
+}
+
+// TestBuildRuntimePromptIssuePureCapsuleEditedTrigger keeps the edited-comment
+// notice alive when a resumed session's trigger was edited down to a bare
+// capsule.
+func TestBuildRuntimePromptIssuePureCapsuleEditedTrigger(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ task := issueSkillTask("[/review](slash://skill/one)")
+ task.PriorSessionID = "session-1"
+ task.TriggerCommentEditedAt = "2026-11-16T09:00:00Z"
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation == nil {
+ t.Fatal("pure capsule must still select")
+ }
+ if !strings.Contains(prompt, "[EDITED COMMENT]") || !strings.Contains(prompt, "was edited at") {
+ t.Errorf("edited-trigger notice lost: %s", prompt)
+ }
+ if !strings.Contains(prompt, "(explicit skill selection only") {
+ t.Errorf("placeholder quote lost: %s", prompt)
+ }
+ if invocation.UserMessage != "" {
+ t.Fatalf("no member ask text exists; UserMessage=%q", invocation.UserMessage)
+ }
+}
+
+// TestBuildRuntimePromptIssueUserMessageJoinsMemberTexts covers the join: a
+// capsule-only coalesced comment contributes nothing (no blank segment) and a
+// member comment without any link still reaches UserMessage.
+func TestBuildRuntimePromptIssueUserMessageJoinsMemberTexts(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ task := issueSkillTask("[/two](slash://skill/two) please review")
+ task.CoalescedComments = []CoalescedCommentData{
+ {ID: "c1", AuthorType: "member", Content: "[/first](slash://skill/one)"},
+ {ID: "c2", AuthorType: "member", Content: "and double-check the tests"},
+ }
+ _, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation == nil {
+ t.Fatal("selection missing")
+ }
+ if invocation.UserMessage != "and double-check the tests\n\n/review-code-multica-2 please review" {
+ t.Fatalf("UserMessage must join member asks without blank segments: %q", invocation.UserMessage)
+ }
+}
+
+// TestBuildRuntimePromptIssuePureCapsuleAlone verifies the bare single-comment
+// case: the invocation still exists and the placeholder keeps the comment
+// section from collapsing.
+func TestBuildRuntimePromptIssuePureCapsuleAlone(t *testing.T) {
+ dirs := issueSkillDirs(t)
+ prompt, invocation := buildRuntimePrompt(issueSkillTask("[/review](slash://skill/one)"), "claude", dirs)
+ if invocation == nil || invocation.UserMessage != "" {
+ t.Fatalf("invocation=%+v UserMessage=%q", invocation, invocation.UserMessage)
+ }
+ if !strings.Contains(prompt, "[NEW COMMENT]") || !strings.Contains(prompt, "(explicit skill selection only") {
+ t.Errorf("comment section collapsed: %s", prompt)
+ }
+ if !strings.Contains(prompt, "Explicitly selected skills:\n- review-code\n") {
+ t.Errorf("selection list missing: %s", prompt)
+ }
+}
+
+func TestMemberSkillTextsChatGateUnchanged(t *testing.T) {
+ // A chat task on an issue-less run keeps exactly one member text; an
+ // issue task never consults ChatSkillMessage even when a stale server
+ // populates it.
+ message := "[/x](slash://skill/one)"
+ chat := chatSkillTask(message)
+ if texts := memberSkillTexts(chat); len(texts) != 1 || texts[0].text != message {
+ t.Fatalf("chat member texts changed: %+v", texts)
+ }
+ issue := issueSkillTask("")
+ issue.ChatSessionID = ""
+ issue.ChatSkillMessage = &message
+ if texts := memberSkillTexts(issue); len(texts) != 0 {
+ t.Fatalf("issue task must ignore ChatSkillMessage and empty comments: %+v", texts)
+ }
+}
diff --git a/server/internal/daemon/chat_skills_runtime_test.go b/server/internal/daemon/chat_skills_runtime_test.go
new file mode 100644
index 0000000000..9b2c7bcf5b
--- /dev/null
+++ b/server/internal/daemon/chat_skills_runtime_test.go
@@ -0,0 +1,125 @@
+package daemon
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+// Exercise the complete claim -> environment -> prompt -> backend path. The
+// fixture rejects a resumed session only after capturing its native input, so
+// the next process must receive a freshly rebuilt invocation and continuity
+// notice, not the preceding attempt's warm prompt.
+func TestRunTaskExplicitSkillFirstTurnAndFreshRetry(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script agent fixture is POSIX-only")
+ }
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir())
+ capture := t.TempDir()
+ t.Setenv("SKILL_CAPTURE", capture)
+ fake := filepath.Join(t.TempDir(), "claude-fixture")
+ writeTestExecutable(t, fake, []byte(`#!/bin/sh
+case "$*" in *--version*) echo '2.1.292'; exit 0;; esac
+attempt=1
+if [ -f "$SKILL_CAPTURE/count" ]; then
+ attempt=$(cat "$SKILL_CAPTURE/count")
+ attempt=$((attempt + 1))
+fi
+printf '%s' "$attempt" > "$SKILL_CAPTURE/count"
+printf '%s\n' "$@" > "$SKILL_CAPTURE/args-$attempt"
+IFS= read -r input
+case "$input" in
+ *'"type":"control_request"'*)
+ printf '%s\n' '{"type":"control_response","response":{"subtype":"success","request_id":"multica-supplement-initialize","response":{"commands":[{"name":"review-code","description":"Bound skill (project)"}]}}}'
+ IFS= read -r input;;
+esac
+printf '%s\n' "$input" > "$SKILL_CAPTURE/input-$attempt.json"
+case "$*" in
+ *--resume*) printf '%s\n' 'No conversation found with session ID: skill-session-1' >&2
+ printf '%s\n' '{"type":"result","subtype":"error_during_execution","is_error":true}';;
+ *) printf '{"type":"result","subtype":"success","session_id":"skill-session-%s","result":"done"}\n' "$attempt";;
+esac
+cat >/dev/null
+`))
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer srv.Close()
+ d := &Daemon{
+ client: NewClient(srv.URL), logger: logger,
+ workspaces: make(map[string]*workspaceState), activeEnvRoots: make(map[string]int),
+ runtimeIndex: map[string]Runtime{"test-rt": {ID: "test-rt", Provider: "claude"}},
+ cfg: Config{
+ WorkspacesRoot: t.TempDir(), AgentTimeout: 5 * time.Second, ServerBaseURL: srv.URL,
+ Agents: map[string]AgentEntry{"claude": {Path: fake}},
+ },
+ }
+ message := "[/untrusted label](slash://skill/selected-id) USER_REQUEST"
+ task := Task{
+ ID: "first-task", WorkspaceID: "test-ws", RuntimeID: "test-rt",
+ AgentID: "test-agent", AuthToken: "mat_test_skills", ChatSessionID: "test-chat",
+ ChatMessage: message, ChatSkillMessage: &message,
+ Agent: &AgentData{ID: "test-agent", Name: "test", Skills: []SkillData{
+ {ID: "selected-id", Name: "Review Code", Content: "---\ndisable-model-invocation: true\n---\nSELECTED_BODY"},
+ }},
+ }
+ first, err := d.runTask(t.Context(), task, "claude", 0, logger)
+ if err != nil || first.Status != "completed" || first.SessionID != "skill-session-1" {
+ t.Fatalf("first run=%+v, err=%v", first, err)
+ }
+ task.ID = "followup-task"
+ task.PriorWorkDir, task.PriorSessionID = first.WorkDir, first.SessionID
+ retried, err := d.runTask(t.Context(), task, "claude", 0, logger)
+ if err != nil || retried.Status != "completed" || retried.SessionID != "skill-session-3" || retried.RetiredSessionID != first.SessionID {
+ t.Fatalf("resumed run did not retry fresh: %+v, err=%v", retried, err)
+ }
+ for attempt := 1; attempt <= 3; attempt++ {
+ wire, err := os.ReadFile(filepath.Join(capture, fmt.Sprintf("input-%d.json", attempt)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var input struct {
+ Message struct{ Content []struct{ Text string } }
+ }
+ if err := json.Unmarshal(wire, &input); err != nil {
+ t.Fatal(err)
+ }
+ if len(input.Message.Content) != 2 {
+ t.Fatalf("attempt %d did not receive native skill blocks: %s", attempt, wire)
+ }
+ platform, user := input.Message.Content[0].Text, input.Message.Content[1].Text
+ if !strings.HasPrefix(user, "/review-code ") || !strings.Contains(user, "USER_REQUEST") || strings.Contains(user, "slash://") {
+ t.Errorf("attempt %d lost the ID-resolved native command/user input: %q", attempt, user)
+ }
+ if !strings.Contains(platform, "Explicitly selected skills:\n- review-code\n") || strings.Contains(platform, "SELECTED_BODY") {
+ t.Errorf("attempt %d used fallback instead of the installed skill: %q", attempt, platform)
+ }
+ wantNotices := 0
+ if attempt == 3 {
+ wantNotices = 1
+ }
+ if got := strings.Count(platform+user, execenv.SessionContinuityNoticeChatTranscript); got != wantNotices {
+ t.Errorf("attempt %d continuity notice count=%d, want %d", attempt, got, wantNotices)
+ }
+ args, err := os.ReadFile(filepath.Join(capture, fmt.Sprintf("args-%d", attempt)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Contains(string(args), "--resume\n"); got != (attempt == 2) {
+ t.Errorf("attempt %d resume flag=%v", attempt, got)
+ }
+ }
+}
diff --git a/server/internal/daemon/chat_skills_test.go b/server/internal/daemon/chat_skills_test.go
new file mode 100644
index 0000000000..1d0c0db893
--- /dev/null
+++ b/server/internal/daemon/chat_skills_test.go
@@ -0,0 +1,268 @@
+package daemon
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func chatSkillTask(message string) Task {
+ return Task{
+ ChatSessionID: "chat", ChatMessage: message, ChatSkillMessage: &message,
+ Agent: &AgentData{Skills: []SkillData{
+ {ID: "one", Name: "Review Code", Content: "---\nname: other\ndisable-model-invocation: true\n---\nFIRST BODY"},
+ {ID: "two", Name: "Review-Code", Content: "SECOND BODY"},
+ }},
+ }
+}
+
+func TestBuildRuntimePromptExplicitSkills(t *testing.T) {
+ dir := t.TempDir()
+ directories := map[string]string{"one": filepath.Join(dir, "review-code"), "two": filepath.Join(dir, "review-code-multica-2")}
+ for _, provider := range []string{"claude", "codex", "antigravity", "kimi", "hermes", "pi", "unknown"} {
+ t.Run(provider, func(t *testing.T) {
+ task := chatSkillTask("[/spoofed](slash://skill/two) and [/first](slash://skill/one) [/again](slash://skill/two) check this")
+ task.InitiatorName = "Member"
+ task.ChatMessageAttachments = []ChatAttachmentMeta{{ID: "attachment", Filename: "image.png"}}
+ prompt, invocation := buildRuntimePrompt(task, provider, directories, WithSharedLocalDirectory())
+ if invocation == nil || len(invocation.Skills) != 2 || invocation.Skills[0].Name != "review-code-multica-2" || invocation.Skills[1].Name != "review-code" {
+ t.Fatalf("wrong selection order/identity: %+v", invocation)
+ }
+ for _, want := range []string{"SECOND BODY", "FIRST BODY", directories["two"], "check this", "attachment", "Member", "Explicitly selected skills:\n- review-code-multica-2\n- review-code\n"} {
+ if !strings.Contains(prompt, want) {
+ t.Errorf("fallback missing %q: %s", want, prompt)
+ }
+ }
+ for _, unwanted := range []string{"disable-model-invocation", "name: other", "slash://skill", "spoofed"} {
+ if strings.Contains(prompt, unwanted) {
+ t.Errorf("fallback contains %q: %s", unwanted, prompt)
+ }
+ }
+ if strings.Contains(invocation.PlatformPrompt, "check this") || !strings.Contains(invocation.PlatformPrompt, "attachment") || !strings.Contains(invocation.UserMessage, "check this") {
+ t.Fatalf("platform/user split lost context: %+v", invocation)
+ }
+ })
+ }
+}
+
+func TestBuildRuntimePromptAgentChatKeepsBoundSkillHints(t *testing.T) {
+ message := "[/spoofed](slash://skill/one) and [/unbound](slash://skill/other)"
+ for _, tc := range []struct {
+ name, want string
+ installed bool
+ }{
+ {name: "name hint", want: "Review Code"},
+ {name: "directory hint", want: "review-code", installed: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ task := chatSkillTask(message)
+ task.ChatSkillMessage = new(string)
+ task.InitiatorType = "member" // Delegation can inherit a human originator.
+ var dirs map[string]string
+ if tc.installed {
+ dirs = map[string]string{"one": filepath.Join(t.TempDir(), "review-code")}
+ }
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation != nil || strings.Contains(prompt, "FIRST BODY") || strings.Contains(prompt, "SECOND BODY") {
+ t.Fatalf("agent chat must only receive name hints: invocation=%+v prompt=%s", invocation, prompt)
+ }
+ if !strings.Contains(prompt, "Explicitly selected skills:\n- "+tc.want+"\n\n") || !strings.Contains(prompt, "User message:\n"+message) {
+ t.Fatalf("agent chat lost its bound hint or original message: %s", prompt)
+ }
+ })
+ }
+}
+
+func TestBuildRuntimePromptPreservesSkillTargetMapping(t *testing.T) {
+ message := "对 A 用 [/spoofed-one](slash://skill/one),对 B 用 [/spoofed-two](slash://skill/two),再对 C 用 [/again](slash://skill/one)"
+ want := "对 A 用 /review-code,对 B 用 /review-code-multica-2,再对 C 用 /review-code"
+ for _, surface := range []string{"chat", "issue comment"} {
+ t.Run(surface, func(t *testing.T) {
+ task := chatSkillTask(message)
+ if surface == "issue comment" {
+ task = issueSkillTask(message)
+ }
+ prompt, invocation := buildRuntimePrompt(task, "claude", issueSkillDirs(t))
+ if invocation == nil || invocation.UserMessage != want || !strings.Contains(prompt, want) {
+ t.Fatalf("skill/object mapping lost: invocation=%+v prompt=%s", invocation, prompt)
+ }
+ if strings.Contains(prompt, "spoofed") || strings.Contains(prompt, "slash://skill/") {
+ t.Fatalf("selected labels/links must be replaced by actual directory names: %s", prompt)
+ }
+ })
+ }
+}
+
+func TestBuildRuntimePromptChatPureCapsuleHasNoArguments(t *testing.T) {
+ for _, message := range []string{
+ "[/spoofed](slash://skill/one)",
+ " \n[/spoofed](slash://skill/one)\n\t",
+ "[/one](slash://skill/one) [/two](slash://skill/two)",
+ } {
+ _, invocation := buildRuntimePrompt(chatSkillTask(message), "claude", issueSkillDirs(t))
+ if invocation == nil || invocation.UserMessage != "" {
+ t.Fatalf("capsule-only chat must invoke without arguments: %+v", invocation)
+ }
+ }
+}
+
+func TestBuildRuntimePromptDoesNotPromoteUntrustedContent(t *testing.T) {
+ link := "[/review](slash://skill/one)"
+ dirs := map[string]string{"one": filepath.Join(t.TempDir(), "review-code")}
+ for _, tc := range []struct {
+ name string
+ edit func(*Task)
+ }{
+ {"old server", func(task *Task) { task.ChatSkillMessage = nil }},
+ {"agent with human originator", func(task *Task) { task.ChatSkillMessage = nil; task.InitiatorType = "member" }},
+ {"issue", func(task *Task) { task.IssueID = "issue"; task.ChatSessionID = "" }},
+ {"comment", func(task *Task) {
+ task.ChatSessionID = ""
+ task.TriggerCommentID = "comment"
+ task.TriggerCommentContent = link
+ }},
+ {"intro", func(task *Task) { task.ChatIntro = true }},
+ {"autopilot", func(task *Task) { task.AutopilotRunID = "autopilot" }},
+ {"mismatched payload", func(task *Task) { task.ChatMessage = "different message" }},
+ {"unknown ID", func(task *Task) {
+ task.ChatMessage = "[/Review Code](slash://skill/other)"
+ task.ChatSkillMessage = &task.ChatMessage
+ }},
+ {"plain slash", func(task *Task) { task.ChatMessage = "/compact"; task.ChatSkillMessage = &task.ChatMessage }},
+ {"quoted issue", func(task *Task) { task.ChatMessage = "> " + link; task.ChatSkillMessage = &task.ChatMessage }},
+ {"fenced code", func(task *Task) {
+ task.ChatMessage = "```md\n" + link + "\n```"
+ task.ChatSkillMessage = &task.ChatMessage
+ }},
+ {"inline code", func(task *Task) { task.ChatMessage = "`" + link + "`"; task.ChatSkillMessage = &task.ChatMessage }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ task := chatSkillTask(link)
+ tc.edit(&task)
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation != nil || strings.Contains(prompt, "FIRST BODY") || strings.HasPrefix(prompt, "/") {
+ t.Fatalf("untrusted input became an invocation: %+v, %s", invocation, prompt)
+ }
+ })
+ }
+}
+
+func TestBuildRuntimePromptPreservesOrdinaryMessages(t *testing.T) {
+ for _, message := range []string{"hello", "/compact", "[/unknown](slash://skill/unknown)", ""} {
+ for _, provider := range []string{"claude", "codex", "antigravity", "kimi", "hermes", "pi"} {
+ task := chatSkillTask(message)
+ want := BuildPrompt(task, provider, WithSharedLocalDirectory())
+ got, invocation := buildRuntimePrompt(task, provider, nil, WithSharedLocalDirectory())
+ if invocation != nil || got != want {
+ t.Fatalf("%s changed ordinary input %q", provider, message)
+ }
+ }
+ }
+}
+
+func TestBuildRuntimePromptMissingInstallationKeepsHint(t *testing.T) {
+ link := "[/review](slash://skill/one)"
+ for _, tc := range []struct {
+ name string
+ dirs map[string]string
+ }{
+ {"older preparation helper", nil},
+ {"missing directory", map[string]string{}},
+ {"relative directory", map[string]string{"one": filepath.Join("skills", "review-code")}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ for _, provider := range []string{"claude", "codex", "antigravity", "hermes"} {
+ prompt, invocation := buildRuntimePrompt(chatSkillTask(link), provider, tc.dirs)
+ if invocation != nil || strings.Contains(prompt, "FIRST BODY") || !strings.Contains(prompt, "Explicitly selected skills:\n- ") || !strings.Contains(prompt, "User message:\n"+link) {
+ t.Errorf("%s missing installation must retain hint and original link: invocation=%+v prompt=%s", provider, invocation, prompt)
+ }
+ }
+ })
+ }
+}
+
+func TestBuildRuntimePromptRetainsUnselectedAndQuotedLinks(t *testing.T) {
+ task := chatSkillTask("[/one](slash://skill/one) [/missing](slash://skill/nope)\n> [/same](slash://skill/one)\n> [/two](slash://skill/two)")
+ task.ChatMessage = "System kickoff [/two](slash://skill/two)\n\n" + task.ChatMessage
+ dirs := map[string]string{"one": filepath.Join(t.TempDir(), "one"), "two": filepath.Join(t.TempDir(), "two")}
+ prompt, invocation := buildRuntimePrompt(task, "hermes", dirs)
+ if invocation == nil || len(invocation.Skills) != 1 || strings.Contains(prompt, "SECOND BODY") {
+ t.Fatalf("quoted/system input selected a skill: %+v", invocation)
+ }
+ for _, want := range []string{"[/missing](slash://skill/nope)", "> [/same](slash://skill/one)", "System kickoff [/two](slash://skill/two)"} {
+ if !strings.Contains(prompt, want) {
+ t.Errorf("lost unselected text %q: %s", want, prompt)
+ }
+ }
+}
+
+func TestChatSkillHintsIgnoreQuotedAndCodeInput(t *testing.T) {
+ for _, message := range []string{"> [/review](slash://skill/one)", "`[/review](slash://skill/one)`", "```md\n[/review](slash://skill/one)\n```"} {
+ for _, member := range []bool{false, true} {
+ task := chatSkillTask(message)
+ if !member {
+ task.ChatSkillMessage = new(string)
+ }
+ prompt, invocation := buildRuntimePrompt(task, "claude", issueSkillDirs(t))
+ if invocation != nil || strings.Contains(prompt, "Explicitly selected skills:") || !strings.Contains(prompt, message) {
+ t.Errorf("member=%t quoted/code input changed: invocation=%+v prompt=%s", member, invocation, prompt)
+ }
+ }
+ }
+}
+
+func TestBuildRuntimePromptResumeRetryReplacesResumeLinks(t *testing.T) {
+ dirs := map[string]string{"one": filepath.Join(t.TempDir(), "review-code")}
+ kickoff := "System kickoff [/two](slash://skill/two)\n\n"
+ message := "[/review](slash://skill/one) original objective"
+ // The server's chat_skill_message joins every member-authored part of
+ // the batch — supplements already delivered to the prior session
+ // included — while chat_resume_message drops the delivered ones.
+ memberBatch := message + "\n\ndelivered guidance\n\npending guidance"
+ for _, tc := range []struct {
+ name string
+ prefix string
+ }{
+ {name: "with kickoff context", prefix: kickoff},
+ {name: "plain session", prefix: ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ resume := tc.prefix + message + "\n\npending guidance"
+ task := chatSkillTask(memberBatch)
+ task.PriorSessionID = "session-1"
+ task.ChatMessage = tc.prefix + memberBatch
+ task.ChatResumeMessage = &resume
+ prompt, invocation := buildRuntimePrompt(task, "claude", dirs)
+ if invocation == nil {
+ t.Fatal("resumed retry lost the invocation")
+ }
+ // The resume view drops delivered guidance, keeps the kickoff
+ // context and pending guidance verbatim, and replaces only the
+ // selected link with its actual directory name.
+ want := tc.prefix + "/review-code original objective\n\npending guidance"
+ if invocation.UserMessage != want {
+ t.Fatalf("resumed user = %q, want %q", invocation.UserMessage, want)
+ }
+ if !strings.Contains(prompt, "User message:\n"+want) || strings.Contains(prompt, "delivered guidance") || strings.Contains(prompt, "slash://skill/one") {
+ t.Fatalf("resumed prompt renders the wrong batch: %s", prompt)
+ }
+ if task.ChatResumeMessage == nil || *task.ChatResumeMessage != resume {
+ t.Fatalf("caller resume payload mutated: %v", task.ChatResumeMessage)
+ }
+ // A cold retry keeps the whole member batch — delivered
+ // guidance included — with the same selected link replaced.
+ task.PriorSessionID = ""
+ prompt, invocation = buildRuntimePrompt(task, "claude", dirs)
+ if invocation == nil {
+ t.Fatal("cold retry lost the invocation")
+ }
+ want = tc.prefix + "/review-code original objective\n\ndelivered guidance\n\npending guidance"
+ if invocation.UserMessage != want {
+ t.Fatalf("cold user = %q, want %q", invocation.UserMessage, want)
+ }
+ if strings.Contains(prompt, "slash://skill/one") {
+ t.Fatalf("cold retry kept a selected link: %s", prompt)
+ }
+ })
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 35c963c17f..2a5220a9ed 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9032,7 +9032,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
promptOptions = append(promptOptions, WithWorktreeCommitsAllLeftovers())
}
}
- prompt := BuildPrompt(task, provider, promptOptions...)
+ prompt, skillInvocation := buildRuntimePrompt(task, provider, env.SkillDirectories, promptOptions...)
// Pass task-scoped auth credentials and context so the spawned agent CLI
// can call the Multica API and the local daemon (e.g. `multica repo checkout`).
@@ -9205,7 +9205,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
runtimeBrief = freshBrief
runtimeBriefWritten = true
}
- prompt = BuildPrompt(task, provider, promptOptions...)
+ prompt, skillInvocation = buildRuntimePrompt(task, provider, env.SkillDirectories, promptOptions...)
}
backend, err := agent.ResolveBackend(provider, backendConfig)
if err != nil {
@@ -9278,6 +9278,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
idleWatchdogTimeout = d.cfg.OpenCodeIdleWatchdog
}
execOpts := agent.ExecOptions{
+ SkillInvocation: skillInvocation,
EnableTaskSupplement: taskSupplementNegotiated,
CursorHookCommand: cursorHookCommand,
Cwd: env.WorkDir,
@@ -9487,7 +9488,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
execOpts.SystemPrompt = runtimeBrief
}
}
- freshPrompt := BuildPrompt(task, provider, promptOptions...)
+ freshPrompt, freshSkills := buildRuntimePrompt(task, provider, env.SkillDirectories, promptOptions...)
+ execOpts.SkillInvocation = freshSkills
receiptInput.Prompt = freshPrompt
receiptInput.RuntimeBrief = freshBrief
@@ -11132,6 +11134,7 @@ func convertSkillsForEnv(skills []SkillData) []execenv.SkillContextForEnv {
result := make([]execenv.SkillContextForEnv, len(skills))
for i, s := range skills {
result[i] = execenv.SkillContextForEnv{
+ ID: s.ID,
Name: s.Name,
Description: s.Description,
Content: s.Content,
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index a36bf35a42..50dadf6d17 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -159,6 +159,12 @@ func writeWorkspacesRootMarkerAtomic(path string, data []byte) error {
// cloud-mode tasks whose envRoot is wiped wholesale by the GC loop — may
// pass nil to skip the bookkeeping entirely.
func writeContextFiles(workDir, provider string, ctx TaskContextForEnv, manifest *sidecarManifest) ([]string, error) {
+ return writeContextFilesTracked(workDir, provider, ctx, manifest, nil)
+}
+
+// writeContextFilesTracked additionally records, when installed is non-nil,
+// each successful skill write's absolute directory keyed by skill ID.
+func writeContextFilesTracked(workDir, provider string, ctx TaskContextForEnv, manifest *sidecarManifest, installed map[string]string) ([]string, error) {
if err := writeTaskContextMarker(workDir, ctx, manifest); err != nil {
return nil, err
}
@@ -176,7 +182,7 @@ func writeContextFiles(workDir, provider string, ctx TaskContextForEnv, manifest
}
// Codex skills are written to codex-home in Prepare; skip here.
if provider != "codex" {
- preparedSkillNames, err = writeSkillFilesWithNames(skillsDir, ctx.AgentSkills, manifest)
+ preparedSkillNames, err = writeSkillFilesWithNamesTracked(skillsDir, ctx.AgentSkills, manifest, installed)
if err != nil {
return nil, fmt.Errorf("write skill files: %w", err)
}
@@ -582,6 +588,14 @@ func isFrontmatterValidYAML(content string) bool {
return yaml.Unmarshal([]byte(fmBody), &m) == nil
}
+// SkillBody removes a complete frontmatter block for explicit prompt
+// injection. Malformed/unclosed frontmatter is preserved instead of dropping
+// skill text.
+func SkillBody(content string) string {
+ _, body, _ := frontmatterParts(content)
+ return body
+}
+
// frontmatterParts splits content into the raw YAML frontmatter body (the text
// between the opening `---` line and the closing `---` line) and the document
// body that follows the closing delimiter. ok is false when content has no
@@ -949,13 +963,26 @@ func sanitizeSkillName(name string) string {
// skill entirely (which would silently drop a Multica skill the agent
// expects to see).
func writeSkillFiles(skillsDir string, skills []SkillContextForEnv, manifest *sidecarManifest) error {
- _, err := writeSkillFilesWithNames(skillsDir, skills, manifest)
+ return writeSkillFilesTracked(skillsDir, skills, manifest, nil)
+}
+
+// writeSkillFilesTracked additionally records, when installed is non-nil,
+// each successful write's absolute directory by skill ID.
+func writeSkillFilesTracked(skillsDir string, skills []SkillContextForEnv, manifest *sidecarManifest, installed map[string]string) error {
+ _, err := writeSkillFilesWithNamesTracked(skillsDir, skills, manifest, installed)
return err
}
// writeSkillFilesWithNames returns the allocated invocation names in input
// order, including suffixes needed to preserve user-owned skill directories.
func writeSkillFilesWithNames(skillsDir string, skills []SkillContextForEnv, manifest *sidecarManifest) ([]string, error) {
+ return writeSkillFilesWithNamesTracked(skillsDir, skills, manifest, nil)
+}
+
+// writeSkillFilesWithNamesTracked additionally records, when installed is
+// non-nil, each successful write's absolute directory by skill ID, so
+// explicit invocation never has to repeat the allocator.
+func writeSkillFilesWithNamesTracked(skillsDir string, skills []SkillContextForEnv, manifest *sidecarManifest, installed map[string]string) ([]string, error) {
if err := recordMkdirAll(skillsDir, 0o755, manifest); err != nil {
return nil, fmt.Errorf("create skills dir: %w", err)
}
@@ -1013,6 +1040,9 @@ func writeSkillFilesWithNames(skillsDir string, skills []SkillContextForEnv, man
return nil, err
}
}
+ if installed != nil && skill.ID != "" {
+ installed[skill.ID] = dir
+ }
preparedSkillNames[i] = slug
}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 72d864f862..2f39a8222f 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -256,6 +256,7 @@ type IssueStatusForEnv struct {
}
type SkillContextForEnv struct {
+ ID string
Name string
BuiltinName string // original built-in identity; empty for workspace and plugin skills
Description string
@@ -271,6 +272,10 @@ type SkillFileContextForEnv struct {
// Environment represents a prepared, isolated execution environment.
type Environment struct {
+ // SkillDirectories records successful writes by skill ID, including any
+ // filesystem collision suffix. It crosses the preparation-helper JSON
+ // boundary like PreparedSkillNames.
+ SkillDirectories map[string]string
// RootDir is the top-level env directory ({workspacesRoot}/{task_id_short}/).
RootDir string
// WorkDir is the directory to pass as Cwd to the agent. Normally
@@ -565,6 +570,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
}
env := &Environment{
+ SkillDirectories: make(map[string]string),
RootDir: envRoot,
WorkDir: workDir,
LocalDirectory: params.LocalWorkDir != "",
@@ -613,7 +619,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
}()
}
- preparedSkillNames, err := writeContextFiles(workDir, params.Provider, params.Task, manifest)
+ preparedSkillNames, err := writeContextFilesTracked(workDir, params.Provider, params.Task, manifest, env.SkillDirectories)
if err != nil {
return nil, fmt.Errorf("execenv: write context files: %w", err)
}
@@ -651,7 +657,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "" || params.LocalWorktree != nil, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task), CodexCustomArgs: params.CodexCustomArgs}, logger); err != nil {
return nil, fmt.Errorf("execenv: prepare codex-home: %w", err)
}
- if env.PreparedSkillNames, err = hydrateCodexSkills(codexHome, params.Task.AgentSkills, params.Task.DisabledRuntimeSkills, logger); err != nil {
+ if env.PreparedSkillNames, err = hydrateCodexSkillsTracked(codexHome, params.Task.AgentSkills, params.Task.DisabledRuntimeSkills, logger, env.SkillDirectories); err != nil {
return nil, fmt.Errorf("execenv: hydrate codex skills: %w", err)
}
env.CodexHome = codexHome
@@ -680,7 +686,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// Emptying an agent's own skill list is NOT a way to opt out of the overlay.
if params.Provider == "hermes" && len(params.Task.AgentSkills) > 0 {
hermesHome := filepath.Join(envRoot, "hermes-home")
- sessions, err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, params.HermesSessionStore, logger)
+ sessions, err := prepareHermesHomeTracked(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, params.HermesSessionStore, logger, env.SkillDirectories)
if err != nil {
return nil, fmt.Errorf("execenv: prepare hermes-home: %w", err)
}
@@ -855,10 +861,11 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
rootDir = ""
}
env := &Environment{
- RootDir: rootDir,
- WorkDir: params.WorkDir,
- LocalDirectory: params.LocalDirectory,
- logger: logger,
+ SkillDirectories: make(map[string]string),
+ RootDir: rootDir,
+ WorkDir: params.WorkDir,
+ LocalDirectory: params.LocalDirectory,
+ logger: logger,
}
if env.RootDir != "" {
env.MulticaConfigRoot = filepath.Join(env.RootDir, "multica-config")
@@ -925,7 +932,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
logger.Warn("execenv: roll back incomplete reused sidecars failed", "error", rollbackErr)
}
}
- preparedSkillNames, err := writeContextFiles(params.WorkDir, params.Provider, params.Task, manifest)
+ preparedSkillNames, err := writeContextFilesTracked(params.WorkDir, params.Provider, params.Task, manifest, env.SkillDirectories)
if err != nil {
if preparedSkillNames == nil {
logger.Warn("execenv: refresh context files failed before skill materialization completed; forcing fresh prepare", "error", err)
@@ -960,7 +967,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
return nil
}
env.CodexHome = codexHome
- preparedSkillNames, err := hydrateCodexSkills(codexHome, params.Task.AgentSkills, params.Task.DisabledRuntimeSkills, logger)
+ preparedSkillNames, err := hydrateCodexSkillsTracked(codexHome, params.Task.AgentSkills, params.Task.DisabledRuntimeSkills, logger, env.SkillDirectories)
if err != nil && preparedSkillNames == nil {
logger.Warn("execenv: refresh codex skills failed before materialization completed; forcing fresh prepare", "error", err)
if cleanupErr := os.RemoveAll(filepath.Join(codexHome, "skills")); cleanupErr != nil {
@@ -1015,7 +1022,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
if params.Provider == "hermes" && env.RootDir != "" {
hermesHome := filepath.Join(env.RootDir, "hermes-home")
if len(params.Task.AgentSkills) > 0 {
- sessions, err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, params.HermesSessionStore, logger)
+ sessions, err := prepareHermesHomeTracked(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, params.HermesSessionStore, logger, env.SkillDirectories)
if err != nil {
// Fail closed: a half-built overlay must not run. Returning nil
// makes the daemon fall back to a fresh Prepare, whose error
@@ -1107,6 +1114,12 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
// user-level skills natively (see context.go for the workdir-local paths
// they use for workspace skills).
func hydrateCodexSkills(codexHome string, workspaceSkills []SkillContextForEnv, disabledRuntimeSkills []RuntimeSkillRefForEnv, logger *slog.Logger) ([]string, error) {
+ return hydrateCodexSkillsTracked(codexHome, workspaceSkills, disabledRuntimeSkills, logger, nil)
+}
+
+// hydrateCodexSkillsTracked additionally records, when installed is non-nil,
+// each successful skill write's absolute directory by skill ID.
+func hydrateCodexSkillsTracked(codexHome string, workspaceSkills []SkillContextForEnv, disabledRuntimeSkills []RuntimeSkillRefForEnv, logger *slog.Logger, installed map[string]string) ([]string, error) {
skillsDir := filepath.Join(codexHome, "skills")
if err := os.RemoveAll(skillsDir); err != nil {
return nil, fmt.Errorf("clear codex skills dir: %w", err)
@@ -1117,7 +1130,7 @@ func hydrateCodexSkills(codexHome string, workspaceSkills []SkillContextForEnv,
preparedSkillNames := resolveSkillSlugs(workspaceSkills)
if len(workspaceSkills) > 0 {
var err error
- preparedSkillNames, err = writeSkillFilesWithNames(skillsDir, workspaceSkills, nil)
+ preparedSkillNames, err = writeSkillFilesWithNamesTracked(skillsDir, workspaceSkills, nil, installed)
if err != nil {
return nil, err
}
diff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.go
index 2fbbd7b158..3658b657ca 100644
--- a/server/internal/daemon/execenv/hermes_home.go
+++ b/server/internal/daemon/execenv/hermes_home.go
@@ -339,6 +339,12 @@ func hermesProfileDir(root, name string) (home string, mustExist bool, err error
// store actually holds a transcript, so the caller never
// tells a task it can resume history that is not there.
func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, memoryStore, sessionStore string, logger *slog.Logger) (sessions hermesSessionMount, err error) {
+ return prepareHermesHomeTracked(hermesHome, sourceHome, sourceMustExist, workspaceSkills, env, memoryStore, sessionStore, logger, nil)
+}
+
+// prepareHermesHomeTracked additionally records, when installed is non-nil,
+// each written skill's absolute directory by skill ID.
+func prepareHermesHomeTracked(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, memoryStore, sessionStore string, logger *slog.Logger, installed map[string]string) (sessions hermesSessionMount, err error) {
sharedHome := strings.TrimSpace(sourceHome)
if sharedHome == "" {
sharedHome = platformDefaultHermesHome()
@@ -394,7 +400,7 @@ func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, work
if err := writeDerivedHermesEnv(sharedHome, hermesHome); err != nil {
return hermesSessionMount{}, fmt.Errorf("derive hermes .env: %w", err)
}
- if err := writeHermesBoundSkills(hermesHome, workspaceSkills, logger); err != nil {
+ if err := writeHermesBoundSkills(hermesHome, workspaceSkills, logger, installed); err != nil {
return hermesSessionMount{}, err
}
return sessions, nil
@@ -890,7 +896,7 @@ func computeHermesExternalDirs(sharedHome string, existing []string, env map[str
// skill removed since the last run can't linger, then writes only the
// Multica-bound skills. They keep their natural slug (no user skills share this
// dir) and therefore take precedence over any same-named external skill.
-func writeHermesBoundSkills(hermesHome string, workspaceSkills []SkillContextForEnv, logger *slog.Logger) error {
+func writeHermesBoundSkills(hermesHome string, workspaceSkills []SkillContextForEnv, logger *slog.Logger, installed map[string]string) error {
skillsDir := filepath.Join(hermesHome, "skills")
if err := os.RemoveAll(skillsDir); err != nil {
return fmt.Errorf("clear hermes skills dir: %w", err)
@@ -902,7 +908,7 @@ func writeHermesBoundSkills(hermesHome string, workspaceSkills []SkillContextFor
return os.MkdirAll(skillsDir, 0o700)
}
// This directory is owned by the isolated home and replaced on every run.
- return writeSkillFiles(skillsDir, workspaceSkills, nil)
+ return writeSkillFilesTracked(skillsDir, workspaceSkills, nil, installed)
}
// existingHermesExternalDirs reads the raw skills.external_dirs entries from a
diff --git a/server/internal/daemon/execenv/skill_directories_test.go b/server/internal/daemon/execenv/skill_directories_test.go
new file mode 100644
index 0000000000..337f4c1573
--- /dev/null
+++ b/server/internal/daemon/execenv/skill_directories_test.go
@@ -0,0 +1,106 @@
+package execenv
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestWrittenSkillDirectoriesIncludeEveryCollision(t *testing.T) {
+ root := t.TempDir()
+ if err := os.Mkdir(filepath.Join(root, "a-b"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ skills := []SkillContextForEnv{
+ {ID: "one", Name: "A B", Content: "---\ndisable-model-invocation: true\n---\nfirst"},
+ {ID: "two", Name: "A-B", Content: "second"},
+ }
+ installed := map[string]string{}
+ if err := writeSkillFilesTracked(root, skills, nil, installed); err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]string{"one": filepath.Join(root, "a-b-multica"), "two": filepath.Join(root, "a-b-multica-multica")}
+ if !reflect.DeepEqual(installed, want) {
+ t.Fatalf("installed=%v want=%v", installed, want)
+ }
+ for id, dir := range installed {
+ body, err := os.ReadFile(filepath.Join(dir, "SKILL.md"))
+ if err != nil || !strings.Contains(string(body), "name: "+filepath.Base(dir)) {
+ t.Fatalf("%s: %s, %v", id, body, err)
+ }
+ }
+}
+
+func TestPrepareAndReuseReturnSkillDirectories(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("USERPROFILE", t.TempDir())
+ t.Setenv("CODEX_HOME", t.TempDir())
+ t.Setenv("HERMES_HOME", t.TempDir())
+ task := TaskContextForEnv{ChatSessionID: "chat", AgentSkills: []SkillContextForEnv{{ID: "selected", Name: "Review Code", Content: "Use references/file.txt"}}}
+ for _, provider := range []string{"amp", "codex", "hermes"} {
+ t.Run(provider, func(t *testing.T) {
+ root := t.TempDir()
+ sourceHome := t.TempDir()
+ env, err := Prepare(PrepareParams{WorkspacesRoot: root, WorkspaceID: "workspace", TaskID: "task-skill-directories", Provider: provider, HermesSourceHome: sourceHome, Task: task}, testLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := filepath.Join(env.WorkDir, ".agents", "skills", "review-code")
+ switch provider {
+ case "codex":
+ want = filepath.Join(env.RootDir, "codex-home", "skills", "review-code")
+ if filepath.Dir(filepath.Dir(want)) != env.CodexHome {
+ t.Fatalf("Codex skill is outside the private home: %+v", env)
+ }
+ case "hermes":
+ want = filepath.Join(env.RootDir, "hermes-home", "skills", "review-code")
+ if filepath.Dir(filepath.Dir(want)) != env.HermesHome {
+ t.Fatalf("Hermes skill is outside the overlay: %+v", env)
+ }
+ }
+ if env.SkillDirectories["selected"] != want {
+ t.Fatalf("Prepare directories=%v", env.SkillDirectories)
+ }
+ // The isolated preparer returns JSON, not the in-process slice/map.
+ encoded, err := json.Marshal(env)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded Environment
+ if err := json.Unmarshal(encoded, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ if decoded.SkillDirectories["selected"] != want {
+ t.Fatal("helper response lost directory")
+ }
+ for _, stage := range []string{"Prepare", "Reuse"} {
+ if stage == "Reuse" {
+ env = Reuse(ReuseParams{WorkspacesRoot: root, WorkDir: env.WorkDir, Provider: provider, HermesSourceHome: sourceHome, Task: task}, testLogger())
+ }
+ if env == nil || env.SkillDirectories["selected"] != want {
+ t.Fatalf("%s directories=%+v", stage, env)
+ }
+ body, err := os.ReadFile(filepath.Join(env.SkillDirectories["selected"], "SKILL.md"))
+ if err != nil || !strings.Contains(string(body), "Use references/file.txt") {
+ t.Fatalf("%s mapping does not locate the selected body: %s, %v", stage, body, err)
+ }
+ prepared := ApplyPreparedSkillNames(task, env.PreparedSkillNames)
+ receipt := env.SkillReceipts(provider, prepared.AgentSkills)[0]
+ if !receipt.Available || receipt.Bytes != len(body) || receipt.Path != SkillDeliveryLocation(env.WorkDir, provider)+"/review-code/SKILL.md" {
+ t.Fatalf("%s receipt does not match the selected directory: %+v", stage, receipt)
+ }
+ }
+ })
+ }
+}
+
+func TestSkillBodyStripsOnlyFrontmatter(t *testing.T) {
+ for _, input := range []string{"---\nname: x\n---\nbody\n---\ntail", "---\r\nname: x\r\n---\r\nbody\n---\ntail", "body\n---\ntail"} {
+ if got := SkillBody(input); strings.TrimSpace(got) != "body\n---\ntail" {
+ t.Fatalf("SkillBody(%q)=%q", input, got)
+ }
+ }
+}
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 8f89891348..47f6c17c38 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -3,6 +3,7 @@ package daemon
import (
"encoding/json"
"fmt"
+ "path/filepath"
"strings"
"github.com/multica-ai/multica/server/internal/daemon/execenv"
@@ -141,6 +142,10 @@ func buildJoinedWakeupsBlock(notes string) string {
// common BuildPrompt(task, provider) call sites stay unchanged.
type promptOpts struct {
sharedLocalDirectory bool
+ skillDirectories map[string]string
+ omitChatMessage bool
+ chatSkillRefs []SlashSkillRef
+ triggerCommentStripped bool
worktreeReplayConflicts []string
worktreeBranch string
worktreeBase string
@@ -332,7 +337,7 @@ func BuildPrompt(task Task, provider string, options ...PromptOption) string {
for _, apply := range options {
apply(&opts)
}
- body := buildPromptBody(task, provider)
+ body := buildPromptBodyWithOptions(task, provider, opts)
// Run-scoped context is appended, never prepended: everything ahead of it
// is stable across runs of a resumed session, and appending keeps it after
// the cached prefix (MUL-5377).
@@ -346,6 +351,10 @@ func BuildPrompt(task Task, provider string, options ...PromptOption) string {
}
func buildPromptBody(task Task, provider string) string {
+ return buildPromptBodyWithOptions(task, provider, promptOpts{})
+}
+
+func buildPromptBodyWithOptions(task Task, provider string, opts promptOpts) string {
if task.WakeupID != "" {
var b strings.Builder
fmt.Fprintf(&b, "You are running as a local coding agent for a Multica workspace.\n\nYour assigned issue ID is: %s\n\n[WAKEUP]\n%s\n\n", task.IssueID, task.HandoffNote)
@@ -363,10 +372,10 @@ func buildPromptBody(task Task, provider string) string {
return b.String()
}
if task.ChatSessionID != "" {
- return buildChatPrompt(task)
+ return buildChatPromptWithOptions(task, opts)
}
if task.TriggerCommentID != "" {
- return buildCommentPrompt(task, provider)
+ return buildCommentPromptWithOptions(task, provider, opts)
}
if task.AutopilotRunID != "" {
return buildAutopilotPrompt(task)
@@ -493,13 +502,22 @@ func buildQuickCreatePrompt(task Task) string {
// are re-emitted on every turn so resumed sessions cannot carry forward a
// previous turn's --parent UUID.
func buildCommentPrompt(task Task, provider string) string {
+ return buildCommentPromptWithOptions(task, provider, promptOpts{})
+}
+
+func buildCommentPromptWithOptions(task Task, provider string, opts promptOpts) string {
var b strings.Builder
b.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")
fmt.Fprintf(&b, "Your assigned issue ID is: %s\n\n", task.IssueID)
// A real resume: the latest turn's session comes back. Shared by the
// edited-comment notes (MUL-8218) and the reading pointers below.
resumed := task.PriorSessionID != "" && !task.PriorSessionResumeUnavailable
- if task.TriggerCommentContent != "" {
+ // An empty TriggerCommentContent normally means the server could not
+ // fetch the trigger body. triggerCommentStripped marks the other way it
+ // empties: the comment held only explicit skill links, consumed by the
+ // invocation below. The section must still render — headers, edit notes
+ // and every coalesced comment hang off it.
+ if task.TriggerCommentContent != "" || opts.triggerCommentStripped {
authorLabel := "A user"
if task.TriggerAuthorType == "system" {
authorLabel = "The platform"
@@ -520,7 +538,11 @@ func buildCommentPrompt(task Task, provider string) string {
} else {
fmt.Fprintf(&b, "[NEW COMMENT] %s just left a new comment. Focus on THIS comment — do not confuse it with previous ones:\n\n", authorLabel)
}
- fmt.Fprintf(&b, "> %s\n\n", task.TriggerCommentContent)
+ quote := task.TriggerCommentContent
+ if quote == "" {
+ quote = "(explicit skill selection only — the selected link was consumed by the skill invocation)"
+ }
+ fmt.Fprintf(&b, "> %s\n\n", quote)
if editedSinceResume {
b.WriteString(buildEditedTriggerNote(task))
}
@@ -609,6 +631,12 @@ func buildCommentPrompt(task Task, provider string) string {
task.IssueID)
}
}
+ // Explicitly selected skills ride the same claim-scoped refs as chat: the
+ // member's slash-link picks, resolved to their on-disk names, shown once
+ // here so the quoted comments above can drop the links already acted on.
+ if block := explicitSkillSelectionBlock(task, opts.chatSkillRefs, opts.skillDirectories); block != "" {
+ b.WriteString(block)
+ }
// Issue-reading pointer (MUL-7344). Same gate as the comment hint below —
// `resumed` is computed once for both, so one turn can never claim the
// session is warm enough to skip the issue read while treating it as cold
@@ -746,6 +774,10 @@ func commentReplyThreads(task Task) []execenv.ThreadReplyTarget {
// buildChatPrompt constructs a prompt for interactive chat tasks.
func buildChatPrompt(task Task) string {
+ return buildChatPromptWithOptions(task, promptOpts{})
+}
+
+func buildChatPromptWithOptions(task Task, opts promptOpts) string {
// Legacy compatibility for historical proactive-introduction sessions.
// New agent creation no longer creates a chat or runs this prompt.
if task.ChatIntro {
@@ -836,42 +868,20 @@ func buildChatPrompt(task Task) string {
fmt.Fprintf(&b, "Reply to %s with the final outcome only. Do NOT narrate planned or in-progress steps (\"我先读取…\"); completed actions are part of the outcome.\n", platform)
b.WriteString("\n")
}
- if task.Agent != nil && len(task.Agent.Skills) > 0 {
- refs := ExtractSlashSkills(task.ChatMessage)
- if len(refs) > 0 {
- agentSkills := make(map[string]string, len(task.Agent.Skills))
- for _, s := range task.Agent.Skills {
- agentSkills[s.ID] = s.Name
- }
-
- selected := make([]string, 0, len(refs))
- seen := make(map[string]struct{}, len(refs))
- for _, ref := range refs {
- name, ok := agentSkills[ref.ID]
- if !ok {
- continue
- }
- if _, ok := seen[ref.ID]; ok {
- continue
- }
- seen[ref.ID] = struct{}{}
- selected = append(selected, name)
- }
-
- if len(selected) > 0 {
- b.WriteString("Explicitly selected skills:\n")
- for _, name := range selected {
- fmt.Fprintf(&b, "- %s\n", name)
- }
- b.WriteString("\n")
- }
- }
+ refs := opts.chatSkillRefs
+ if refs == nil {
+ refs = uniqueSlashSkillRefs(chatSkillMatches(task))
}
- message := task.ChatMessage
- if task.PriorSessionID != "" && task.ChatResumeMessage != nil {
- message = *task.ChatResumeMessage
+ if block := explicitSkillSelectionBlock(task, refs, opts.skillDirectories); block != "" {
+ b.WriteString(block)
+ }
+ if !opts.omitChatMessage {
+ message := task.ChatMessage
+ if task.PriorSessionID != "" && task.ChatResumeMessage != nil {
+ message = *task.ChatResumeMessage
+ }
+ fmt.Fprintf(&b, "User message:\n%s\n", message)
}
- fmt.Fprintf(&b, "User message:\n%s\n", message)
// List attachments by id + filename so the agent can fetch them via
// the CLI. We deliberately do NOT inline the URL: chat attachments
// live behind a signed CDN with a short TTL, so by the time the agent
@@ -919,6 +929,49 @@ func buildChatPrompt(task Task) string {
return b.String()
}
+// explicitSkillSelectionBlock renders bound skill names for a turn prompt.
+// Shared by the chat and comment prompt builders so both surfaces name
+// skills identically, by materialized directory name when the
+// daemon recorded one and by the agent's skill name otherwise. A ref whose
+// skill is not bound to this agent renders nothing — an unknown id in user
+// text must not announce a skill.
+func explicitSkillSelectionBlock(task Task, refs []SlashSkillRef, directories map[string]string) string {
+ if task.Agent == nil || len(task.Agent.Skills) == 0 || len(refs) == 0 {
+ return ""
+ }
+ agentSkills := make(map[string]string, len(task.Agent.Skills))
+ for _, s := range task.Agent.Skills {
+ agentSkills[s.ID] = s.Name
+ if dir := directories[s.ID]; dir != "" {
+ agentSkills[s.ID] = filepath.Base(dir)
+ }
+ }
+
+ selected := make([]string, 0, len(refs))
+ seen := make(map[string]struct{}, len(refs))
+ for _, ref := range refs {
+ name, ok := agentSkills[ref.ID]
+ if !ok {
+ continue
+ }
+ if _, ok := seen[ref.ID]; ok {
+ continue
+ }
+ seen[ref.ID] = struct{}{}
+ selected = append(selected, name)
+ }
+ if len(selected) == 0 {
+ return ""
+ }
+ var b strings.Builder
+ b.WriteString("Explicitly selected skills:\n")
+ for _, name := range selected {
+ fmt.Fprintf(&b, "- %s\n", name)
+ }
+ b.WriteString("\n")
+ return b.String()
+}
+
// channelDisplayName renders a chat_channel_type for prompt copy. The mapping
// itself lives in execenv so the per-turn prompt (here) and the runtime brief
// (execenv.writeOutput) cannot drift into naming the same platform differently.
diff --git a/server/internal/daemon/skills_for_env_test.go b/server/internal/daemon/skills_for_env_test.go
index 3a1edced71..248f00802c 100644
--- a/server/internal/daemon/skills_for_env_test.go
+++ b/server/internal/daemon/skills_for_env_test.go
@@ -29,7 +29,7 @@ func TestConvertSkillsForEnvPreservesBuiltinIdentity(t *testing.T) {
Files: []SkillFileData{{Path: "references/sub-issues.md", Content: "Sub-issue contracts."}},
}
want := []execenv.SkillContextForEnv{{
- Name: skill.Name, BuiltinName: tc.wantBuiltin, Description: skill.Description, Content: skill.Content,
+ ID: skill.ID, Name: skill.Name, BuiltinName: tc.wantBuiltin, Description: skill.Description, Content: skill.Content,
Files: []execenv.SkillFileContextForEnv{{Path: skill.Files[0].Path, Content: skill.Files[0].Content}},
}}
if got := convertSkillsForEnv([]SkillData{skill}); !reflect.DeepEqual(got, want) {
diff --git a/server/internal/daemon/slash_skill.go b/server/internal/daemon/slash_skill.go
index 42033939d8..0866477668 100644
--- a/server/internal/daemon/slash_skill.go
+++ b/server/internal/daemon/slash_skill.go
@@ -15,20 +15,35 @@ type SlashSkillRef struct {
}
func ExtractSlashSkills(md string) []SlashSkillRef {
- matches := slashSkillRe.FindAllStringSubmatch(md, -1)
+ return uniqueSlashSkillRefs(slashSkillMatches(md))
+}
+
+type slashSkillMatch struct {
+ start, end int
+ ref SlashSkillRef
+}
+
+func slashSkillMatches(md string) []slashSkillMatch {
+ indices := slashSkillRe.FindAllStringSubmatchIndex(md, -1)
+ matches := make([]slashSkillMatch, 0, len(indices))
+ for _, m := range indices {
+ label := strings.ReplaceAll(md[m[2]:m[3]], `\[`, "[")
+ label = strings.ReplaceAll(label, `\]`, "]")
+ matches = append(matches, slashSkillMatch{start: m[0], end: m[1], ref: SlashSkillRef{Label: label, ID: md[m[4]:m[5]]}})
+ }
+ return matches
+}
+
+func uniqueSlashSkillRefs(matches []slashSkillMatch) []SlashSkillRef {
seen := make(map[string]struct{}, len(matches))
refs := make([]SlashSkillRef, 0, len(matches))
for _, m := range matches {
- id := m[2]
- if _, ok := seen[id]; ok {
+ if _, ok := seen[m.ref.ID]; ok {
continue
}
- seen[id] = struct{}{}
-
- label := strings.ReplaceAll(m[1], `\[`, "[")
- label = strings.ReplaceAll(label, `\]`, "]")
- refs = append(refs, SlashSkillRef{Label: label, ID: id})
+ seen[m.ref.ID] = struct{}{}
+ refs = append(refs, m.ref)
}
return refs
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 6eb4447f36..9cb9d8ea67 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -145,6 +145,7 @@ type Task struct {
ChatType string `json:"chat_type,omitempty"` // "group" when the channel conversation is a shared room, "p2p" for a 1:1 with the bot. Empty for a web chat or an old server; the per-turn prompt then reports unknown rather than guessing 1:1
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; selects which read command the prompt tells the agent to start with
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
+ ChatSkillMessage *string `json:"chat_skill_message,omitempty"` // verified member-authored input only; excludes system kickoff and agent messages
ChatResumeMessage *string `json:"chat_resume_message,omitempty"` // input excluding guidance already in PriorSessionID
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments linked to the chat message; agent uses these to `multica attachment download <id>`
ChatIntro bool `json:"chat_intro,omitempty"` // legacy compatibility for historical is_agent_intro sessions; new agent creation no longer creates these chats
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index cf6b893330..e80045a547 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -563,6 +563,7 @@ type AgentTaskResponse struct {
ChatSource *protocol.ChatSource `json:"chat_source,omitempty"`
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
+ ChatSkillMessage *string `json:"chat_skill_message,omitempty"` // verified member-authored input eligible for explicit skill selection
ChatResumeMessage *string `json:"chat_resume_message,omitempty"` // excludes guidance already delivered to the resumed session
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
ChatIntro bool `json:"chat_intro,omitempty"` // legacy compatibility for historical is_agent_intro sessions; new agent creation no longer creates these chats
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 24af1afe3f..3b61e6bbc1 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -333,6 +333,9 @@ func TestDirectChat_RetryClaimDoesNotMoveOriginalInput(t *testing.T) {
if !retry.ChatInputTaskID.Valid || uuidToString(retry.ChatInputTaskID) != rootID {
t.Fatalf("retry input owner = %s, want root %s", uuidToString(retry.ChatInputTaskID), rootID)
}
+ if got := memberChatSkillMessage(retry.Context, inputBefore); got == nil || *got != "retry me" {
+ t.Fatalf("retry lost the authenticated chat sender: %v", got)
+ }
claimed, err := testHandler.TaskService.ClaimTask(ctx, parseUUID(agentID))
if err != nil || claimed == nil {
t.Fatalf("claim retry task: task=%+v err=%v", claimed, err)
diff --git a/server/internal/handler/chat_skill_input.go b/server/internal/handler/chat_skill_input.go
new file mode 100644
index 0000000000..6645ae0711
--- /dev/null
+++ b/server/internal/handler/chat_skill_input.go
@@ -0,0 +1,34 @@
+package handler
+
+import (
+ "encoding/json"
+ "strings"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Only SendDirectChatMessage stamps the authenticated sender. Attribution is
+// deliberately insufficient: delegated agent runs inherit a human originator.
+func memberChatSkillMessage(context []byte, messages []db.ChatMessage) *string {
+ var source struct {
+ ActorType string `json:"chat_input_actor_type"`
+ }
+ if json.Unmarshal(context, &source) != nil || source.ActorType == "" {
+ // A queued task from before sender stamping retains the legacy hint,
+ // just like a claim from an older server. It cannot invoke a skill.
+ return nil
+ }
+ message := ""
+ if source.ActorType != "member" {
+ return &message
+ }
+ var parts []string
+ for _, message := range messages {
+ if message.Role == "user" && message.MessageKind == protocol.ChatMessageKindMessage && !message.ChannelIngested && strings.TrimSpace(message.Content) != "" {
+ parts = append(parts, message.Content)
+ }
+ }
+ message = strings.Join(parts, "\n\n")
+ return &message
+}
diff --git a/server/internal/handler/chat_skill_input_test.go b/server/internal/handler/chat_skill_input_test.go
new file mode 100644
index 0000000000..57ec30af01
--- /dev/null
+++ b/server/internal/handler/chat_skill_input_test.go
@@ -0,0 +1,102 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestMemberChatSkillMessageTrustBoundary(t *testing.T) {
+ messages := []db.ChatMessage{
+ {Role: "user", MessageKind: protocol.ChatMessageKindMessage, Content: "member selection"},
+ {Role: "assistant", MessageKind: protocol.ChatMessageKindMessage, Content: "agent selection"},
+ {Role: "user", MessageKind: "onboarding_kickoff", Content: "system selection"},
+ {Role: "user", MessageKind: protocol.ChatMessageKindMessage, ChannelIngested: true, Content: "channel quotation"},
+ }
+ for _, tc := range []struct {
+ source, want string
+ known bool
+ }{
+ {`{"chat_input_actor_type":"member"}`, "member selection", true},
+ {`{"chat_input_actor_type":"agent"}`, "", true},
+ {`{"chat_input_actor_type":"system"}`, "", true},
+ {`{"originator_source":"direct_human"}`, "", false},
+ {`{}`, "", false}, {`bad`, "", false},
+ } {
+ got := memberChatSkillMessage([]byte(tc.source), messages)
+ if tc.known {
+ if got == nil || *got != tc.want {
+ t.Errorf("source=%s got=%v want=%q", tc.source, got, tc.want)
+ }
+ } else if got != nil {
+ t.Errorf("legacy/unknown source should retain the old hint: %s", tc.source)
+ }
+ }
+}
+
+func TestDirectChatSkillClaimUsesActualSender(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ for _, actor := range []string{"member", "agent"} {
+ t.Run(actor, func(t *testing.T) {
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "skill sender")
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ message := "[/spoofed label](slash://skill/selected) run this"
+ sent, err := testHandler.TaskService.SendDirectChatMessage(ctx, session, agent, parseUUID(testUserID), message, nil, actor, parseUUID(testUserID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A system kickoff shares role=user and the same input owner. It
+ // must remain context without earning a member skill invocation.
+ dbfx.Insert(t, "chat_message", testutil.Cols{"chat_session_id": sessionID, "task_id": uuidToString(sent.Task.ID), "role": "user", "message_kind": protocol.ChatMessageKindOnboardingKickoff, "content": "[/system](slash://skill/system)"})
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, daemonID)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ var wire struct {
+ Task *struct {
+ Message string `json:"chat_message"`
+ Selection string `json:"chat_skill_message"`
+ } `json:"task"`
+ }
+ testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK).JSON(&wire)
+ if wire.Task == nil || !strings.Contains(wire.Task.Message, message) || !strings.Contains(wire.Task.Message, "slash://skill/system") {
+ t.Fatalf("lost chat input: %+v", wire.Task)
+ }
+ want := ""
+ if actor == "member" {
+ want = message
+ }
+ if wire.Task.Selection != want {
+ t.Fatalf("sender %s selection=%q want=%q", actor, wire.Task.Selection, want)
+ }
+ })
+ }
+}
+
+func TestDirectChatSkillCapsuleBypassesSteerSupplement(t *testing.T) {
+ sessionID, taskID, _ := newChatSupplementFixture(t, true)
+ // A member message carrying an explicit skill capsule must not take the
+ // text-only supplement channel: the selection only pays off in a real
+ // turn, so it queues its own task even when steering would merge an
+ // ordinary plain-text message into the running one.
+ sent := sendChatGuidance(t, sessionID, map[string]any{"steer": true, "content": "[/review](slash://skill/selected) review this"})
+ if sent.Steered || !sent.Queued || sent.TaskID == taskID {
+ t.Fatalf("skill capsule steered into the text supplement channel: %+v", sent)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID); n != 2 {
+ t.Fatalf("skill capsule did not create its own turn: %d", n)
+ }
+}
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index b379a4c998..d114dd348a 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1731,16 +1731,18 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // Determine author identity: agent (via X-Agent-ID header) or member.
+ authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
+
// A running turn receives text only, so a comment that carries files is
- // always a normal trigger.
+ // always a normal trigger. A member's explicit skill selection is the
+ // same: the text-only channel cannot invoke a skill, so the comment
+ // needs a turn of its own.
steer := commentSteerRequest{TaskIDs: steerTaskIDs, All: req.Steer}
- if len(attachmentIDs) > 0 {
+ if len(attachmentIDs) > 0 || (authorType == "member" && strings.Contains(req.Content, "](slash://skill/")) {
steer = commentSteerRequest{}
}
- // Determine author identity: agent (via X-Agent-ID header) or member.
- authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
-
// sourceTaskID captures the agent's currently-executing task when it posts
// via the CLI (X-Task-ID header). Stamping it on the comment row keeps the
// originator inheritance chain (resolveOriginatorFromTriggerComment →
diff --git a/server/internal/handler/comment_steer_test.go b/server/internal/handler/comment_steer_test.go
index def8777c94..9634f0ca0a 100644
--- a/server/internal/handler/comment_steer_test.go
+++ b/server/internal/handler/comment_steer_test.go
@@ -310,3 +310,30 @@ func TestUpdateCommentKeepsTheLatestEditsSuppression(t *testing.T) {
t.Fatalf("the latest edit starts A, but an earlier edit's choice stayed: %v", saved.SuppressedAgentIds)
}
}
+
+func TestCreateCommentSteerKeepsSkillCapsuleCommentsAsOwnTurns(t *testing.T) {
+ f := newSupplementFixture(t, "codex", "running", true)
+ dbfx.Exec(t, `UPDATE comment SET content = $2 WHERE id = $1`, f.triggerID,
+ agentMention("Supplement", f.agentID)+" original objective")
+ dbfx.Exec(t, `UPDATE agent_task_queue SET delivered_comment_ids = ARRAY[trigger_comment_id] WHERE id = $1`, f.taskID)
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)
+
+ // A member's explicit skill selection cannot ride the text-only
+ // supplement channel: the comment must keep its own deferred turn even
+ // when the client asked to steer the running one.
+ var created CommentResponse
+ postSteeredComment(t, f.issueID, f.triggerID, "[/review](slash://skill/selected) review this", f.taskID).Want(http.StatusCreated).JSON(&created)
+ if len(created.Supplements) != 0 {
+ t.Fatalf("member skill capsule merged into the running turn's text channel: %+v", created.Supplements)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE comment_id = $1`, created.ID); n != 0 {
+ t.Fatalf("stored %d supplement receipts", n)
+ }
+ completeTaskViaDaemon(t, f.taskID)
+ var trigger string
+ dbfx.QueryRow(t, `SELECT trigger_comment_id FROM agent_task_queue WHERE issue_id = $1 AND id <> $2`,
+ f.issueID, f.taskID).Scan(&trigger)
+ if trigger != created.ID {
+ t.Fatalf("follow-up trigger = %s, want the skill-capsule comment %s", trigger, created.ID)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 36d1412a3b..32d8f314e6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3942,6 +3942,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
}
resp.ChatMessage = strings.Join(parts, "\n\n")
+ resp.ChatSkillMessage = memberChatSkillMessage(task.Context, unanswered)
if task.RetryOfTaskID.Valid && resp.PriorSessionID != "" {
// Keep the full input for cold starts and the daemon's local fresh
// retry. Only a positively identified provider session can omit
diff --git a/server/internal/service/chat_supplement.go b/server/internal/service/chat_supplement.go
index 6413e9606d..a7f86646f2 100644
--- a/server/internal/service/chat_supplement.go
+++ b/server/internal/service/chat_supplement.go
@@ -41,7 +41,9 @@ func requeueChatTaskSupplements(ctx context.Context, q *db.Queries, task db.Agen
attr := attribution.DirectHumanRun(row.AuthorID, attribution.EvidenceChat, row.ChatSessionID)
source, _, evidenceKind, evidenceRef := attributionCreateParams(attr)
next, err := q.CreateChatTask(ctx, db.CreateChatTaskParams{
- ID: dbid.NewV7(), AgentID: task.AgentID, RuntimeID: task.RuntimeID,
+ // Only members create supplements; the requeued turn keeps the
+ // verified member stamp an explicit skill selection requires.
+ Context: []byte(`{"chat_input_actor_type":"member"}`), ID: dbid.NewV7(), AgentID: task.AgentID, RuntimeID: task.RuntimeID,
Priority: 3, ChatSessionID: task.ChatSessionID, InitiatorUserID: row.AuthorID,
OriginatorUserID: row.AuthorID, AccountableUserID: row.AuthorID,
OriginatorSource: source, TriggerEvidenceKind: evidenceKind,
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 9188f804d0..b534760a68 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2498,7 +2498,7 @@ func (s *TaskService) sendDirectChatMessage(
// Only plain human messages use the text-only supplement transport.
// Locking the turn serializes the binding with every terminal transition.
var task db.AgentTaskQueue
- if steer && uploaderType == "member" && len(attachmentIDs) == 0 {
+ if steer && uploaderType == "member" && len(attachmentIDs) == 0 && !strings.Contains(content, "](slash://skill/") {
task, err = qtx.LockRunningChatTaskForSupplement(ctx, session.ID)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("find running chat turn: %w", err)
@@ -2508,7 +2508,13 @@ func (s *TaskService) sendDirectChatMessage(
if out.Steered {
out.Queued = false
} else {
+ // Record the direct sender, not the run's accountable human: an agent
+ // using the chat API can have a human originator too. Old tasks without
+ // this stamp keep text-only skill hints. Retries copy the task context.
+ // A string-to-string map has no fallible JSON encoders.
+ chatContext, _ := json.Marshal(map[string]string{"chat_input_actor_type": uploaderType})
task, err = qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
+ Context: chatContext,
ID: dbid.NewV7(),
AgentID: session.AgentID,
RuntimeID: carrier.RuntimeID,
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 3231a140f8..ce3dedda49 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -24,6 +24,8 @@ type Backend interface {
// ExecOptions configures a single execution.
type ExecOptions struct {
+ // SkillInvocation is set only for validated member-authored skill selections.
+ SkillInvocation *SkillInvocation
// EnableTaskSupplement installs provider hooks only for runs whose daemon/server
// capability handshake enabled additional messages.
EnableTaskSupplement bool
diff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.go
index 210c952df5..010506ca77 100644
--- a/server/pkg/agent/antigravity.go
+++ b/server/pkg/agent/antigravity.go
@@ -381,6 +381,10 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
logPath := logFile.Name()
_ = logFile.Close()
+ if opts.SkillInvocation != nil {
+ prompt = opts.SkillInvocation.antigravityPrompt(supportsAntigravitySlashSkills(runCtx, b.cfg, execPath, opts))
+ }
+
args := buildAntigravityArgs(prompt, logPath, timeout, opts, b.cfg.Logger)
cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 69d46ae14e..4b9cad1c35 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -137,11 +137,15 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
if opts.EnableTaskSupplement {
supplements = newClaudeSupplementSession(runCtx)
}
+ initializer := supplements
+ if initializer == nil && opts.SkillInvocation != nil {
+ initializer = newClaudeSupplementSession(runCtx)
+ }
var closeStdinOnce sync.Once
closeStdin := func() {
closeStdinOnce.Do(func() { _ = stdin.Close() })
- if supplements != nil {
- supplements.end()
+ if initializer != nil {
+ initializer.end()
}
}
// Capture stderr into both the daemon log (as before) and a bounded tail
@@ -186,13 +190,20 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// timeout.
writeDone := make(chan error, 1)
go func() {
- if supplements != nil {
- if initErr := supplements.initialize(inputWriter, opts.HandshakeTimeout); initErr != nil {
- b.cfg.Logger.Warn("Claude additional messages unavailable; continuing normally", "error", initErr)
- supplements.end()
+ var commands map[string]bool
+ if initializer != nil {
+ if initErr := initializer.initialize(inputWriter, opts.HandshakeTimeout, opts.EnableTaskSupplement); initErr != nil {
+ b.cfg.Logger.Warn("Claude initialization unavailable; continuing with text input", "error", initErr)
+ initializer.end()
+ } else if !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {
+ commands = initializer.availableCommands()
}
}
- err := writeClaudeInput(inputWriter, prompt)
+ blocks := []string{prompt}
+ if opts.SkillInvocation != nil {
+ blocks = opts.SkillInvocation.claudeTextBlocks(commands)
+ }
+ err := writeClaudeInput(inputWriter, blocks...)
if err != nil {
closeStdin()
if supplements != nil {
@@ -233,8 +244,8 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
pendingControls := 0
closeRequested := false
closeAfterControls := func() {
- if supplements != nil {
- supplements.end()
+ if initializer != nil {
+ initializer.end()
}
controlMu.Lock()
defer controlMu.Unlock()
@@ -403,8 +414,8 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
}(msg, reply)
case "control_response":
- if supplements != nil {
- supplements.handleResponse(msg.Response)
+ if initializer != nil {
+ initializer.handleResponse(msg.Response)
}
}
}
@@ -1227,8 +1238,8 @@ func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {
return args
}
-func writeClaudeInput(w io.Writer, prompt string) error {
- data, err := buildClaudeInput(prompt)
+func writeClaudeInput(w io.Writer, prompts ...string) error {
+ data, err := buildClaudeInput(prompts...)
if err != nil {
return err
}
@@ -1238,17 +1249,16 @@ func writeClaudeInput(w io.Writer, prompt string) error {
return nil
}
-func buildClaudeInput(prompt string) ([]byte, error) {
+func buildClaudeInput(prompts ...string) ([]byte, error) {
+ content := make([]map[string]string, 0, len(prompts))
+ for _, prompt := range prompts {
+ content = append(content, map[string]string{"type": "text", "text": prompt})
+ }
payload := map[string]any{
"type": "user",
"message": map[string]any{
- "role": "user",
- "content": []map[string]string{
- {
- "type": "text",
- "text": prompt,
- },
- },
+ "role": "user",
+ "content": content,
},
}
data, err := json.Marshal(payload)
diff --git a/server/pkg/agent/claude_supplement.go b/server/pkg/agent/claude_supplement.go
index 8fcab20457..810f5b61c8 100644
--- a/server/pkg/agent/claude_supplement.go
+++ b/server/pkg/agent/claude_supplement.go
@@ -25,6 +25,8 @@ var claudeSupplementEvents = []string{"UserPromptSubmit", "PreToolUse", "PostToo
// instead insert context while the provider is waiting at a turn boundary.
// A Stop hook with pending input continues the same loop; an empty Stop closes
// admission before releasing Claude. No supplement is ever a new user prompt.
+// The same SDK control session discovers commands without installing hooks when
+// only explicit skills need initialization.
// Wire contract: anthropics/claude-agent-sdk-python, _internal/query.py.
type claudeSupplementSession struct {
ctx context.Context
@@ -34,6 +36,7 @@ type claudeSupplementSession struct {
ended bool
pending []*claudeSupplementInput
initialized chan error
+ commands map[string]bool
}
type claudeSupplementInput struct {
@@ -47,15 +50,17 @@ func newClaudeSupplementSession(ctx context.Context) *claudeSupplementSession {
return &claudeSupplementSession{ctx: ctx, initialized: make(chan error, 1)}
}
-func (s *claudeSupplementSession) initialize(w io.Writer, timeout time.Duration) error {
+func (s *claudeSupplementSession) initialize(w io.Writer, timeout time.Duration, installHooks bool) error {
if timeout <= 0 {
timeout = claudeSupplementHandshakeTimeout
}
ctx, cancel := context.WithTimeout(s.ctx, timeout)
defer cancel()
hooks := make(map[string]any, len(claudeSupplementEvents))
- for _, event := range claudeSupplementEvents {
- hooks[event] = []any{map[string]any{"hookCallbackIds": []string{"multica-supplement-" + event}}}
+ if installHooks {
+ for _, event := range claudeSupplementEvents {
+ hooks[event] = []any{map[string]any{"hookCallbackIds": []string{"multica-supplement-" + event}}}
+ }
}
if err := writeClaudeFrame(w, map[string]any{
"type": "control_request", "request_id": claudeSupplementInitializeID,
@@ -67,7 +72,7 @@ func (s *claudeSupplementSession) initialize(w io.Writer, timeout time.Duration)
case err := <-s.initialized:
return err
case <-ctx.Done():
- return fmt.Errorf("claude supplement initialization: %w", ctx.Err())
+ return fmt.Errorf("claude SDK initialization: %w", ctx.Err())
}
}
@@ -76,13 +81,30 @@ func (s *claudeSupplementSession) handleResponse(raw json.RawMessage) {
RequestID string `json:"request_id"`
Subtype string `json:"subtype"`
Error string `json:"error"`
+ Response struct {
+ Commands []struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ } `json:"commands"`
+ } `json:"response"`
}
if json.Unmarshal(raw, &response) != nil || response.RequestID != claudeSupplementInitializeID {
return
}
var err error
if response.Subtype != "success" {
- err = fmt.Errorf("claude supplement initialization rejected: %s", response.Error)
+ err = fmt.Errorf("claude SDK initialization rejected: %s", response.Error)
+ } else {
+ s.mu.Lock()
+ s.commands = make(map[string]bool, len(response.Response.Commands))
+ for _, command := range response.Response.Commands {
+ // Claude resolves personal skills ahead of project skills with the
+ // same name. Only an explicitly project-scoped catalog entry can
+ // authorize native expansion of our installed skill. Unknown scope
+ // (including a changed SDK format) safely falls back to injection.
+ s.commands[command.Name] = strings.HasSuffix(command.Description, " (project)")
+ }
+ s.mu.Unlock()
}
select {
case s.initialized <- err:
@@ -90,6 +112,12 @@ func (s *claudeSupplementSession) handleResponse(raw json.RawMessage) {
}
}
+func (s *claudeSupplementSession) availableCommands() map[string]bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.commands
+}
+
func (s *claudeSupplementSession) ready() bool {
s.mu.Lock()
defer s.mu.Unlock()
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 9489929d08..a0de3ef842 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -1618,9 +1618,10 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// Whether that notice asks the agent to tell the USER is the caller's
// call, not ours: it depends on whether this surface's conversation is
// still readable, which this package cannot see (MUL-5722).
+ turnPrompt := b.skillTurnPrompt(runCtx, c, prompt, opts)
turnParams := map[string]any{
"threadId": threadID,
- "input": codexTurnInput(prompt, opts.ResumeExpected, resumed, opts.ResumeContinuityNotice),
+ "input": codexTurnInput(turnPrompt, opts.ResumeExpected, resumed, opts.ResumeContinuityNotice),
}
// Per-turn reasoning override. Mirrors the per-thread injection in
// startOrResumeThread; keeping both in sync is enforced by the
diff --git a/server/pkg/agent/explicit_skills.go b/server/pkg/agent/explicit_skills.go
new file mode 100644
index 0000000000..1131dd0ac0
--- /dev/null
+++ b/server/pkg/agent/explicit_skills.go
@@ -0,0 +1,190 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// ExplicitSkill is a member-selected, assigned skill whose directory was
+// materialized by the execution environment. Never construct it from a label.
+type ExplicitSkill struct {
+ Name string
+ Directory string
+ Body string
+}
+
+// SkillInvocation preserves both message parts until the provider has checked
+// its native capabilities. Prompt is the complete text input; PlatformPrompt
+// excludes UserMessage for Claude's last-text-block slash-command contract.
+type SkillInvocation struct {
+ Prompt string
+ PlatformPrompt string
+ UserMessage string
+ Skills []ExplicitSkill
+}
+
+func injectExplicitSkills(prompt string, skills []ExplicitSkill) string {
+ var b strings.Builder
+ b.WriteString(prompt)
+ for _, skill := range skills {
+ fmt.Fprintf(&b, "\n\nThe user explicitly selected this skill in this message: %s\nSkill directory (resolve relative files here): %s\n<selected-skill>\n%s\n</selected-skill>\n", skill.Name, skill.Directory, skill.Body)
+ }
+ return b.String()
+}
+
+// FallbackPrompt carries the selection to providers without a native
+// user-level skill invocation: the complete prompt with every selected
+// skill injected inline.
+func (s *SkillInvocation) FallbackPrompt() string {
+ return injectExplicitSkills(s.Prompt, s.Skills)
+}
+
+func (s *SkillInvocation) claudeTextBlocks(available map[string]bool) []string {
+ if len(s.Skills) == 0 || !available[s.Skills[0].Name] {
+ return []string{s.FallbackPrompt()}
+ }
+ // A capsule-only member text strips to nothing and must not leave a
+ // trailing space; a real ask joins the command with exactly one.
+ command := "/" + s.Skills[0].Name
+ if message := strings.TrimSpace(s.UserMessage); message != "" {
+ command += " " + message
+ }
+ return []string{
+ injectExplicitSkills(s.PlatformPrompt, s.Skills[1:]),
+ command,
+ }
+}
+
+func (s *SkillInvocation) codexPrompt(catalog json.RawMessage) string {
+ var response struct {
+ Data []struct {
+ Skills []struct {
+ Name string `json:"name"`
+ Path string `json:"path"`
+ Enabled *bool `json:"enabled"`
+ } `json:"skills"`
+ } `json:"data"`
+ }
+ if json.Unmarshal(catalog, &response) != nil {
+ return s.FallbackPrompt()
+ }
+ prompt := s.Prompt
+ var fallback []ExplicitSkill
+ for _, selected := range s.Skills {
+ found := false
+ for _, entry := range response.Data {
+ for _, skill := range entry.Skills {
+ if skill.Name == selected.Name && filepath.Clean(skill.Path) == filepath.Join(selected.Directory, "SKILL.md") && skill.Enabled != nil && *skill.Enabled {
+ found = true
+ }
+ }
+ }
+ if found {
+ prompt += "\n\n$" + selected.Name + "\n"
+ } else {
+ fallback = append(fallback, selected)
+ }
+ }
+ return injectExplicitSkills(prompt, fallback)
+}
+
+func (b *codexBackend) skillTurnPrompt(ctx context.Context, client *codexClient, prompt string, opts ExecOptions) string {
+ if opts.SkillInvocation == nil {
+ return prompt
+ }
+ probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ catalog, err := client.request(probeCtx, "skills/list", map[string]any{"cwds": []string{opts.Cwd}})
+ if err != nil {
+ b.cfg.Logger.Warn("Codex skill discovery unavailable; injecting selected skills", "error", err)
+ return opts.SkillInvocation.FallbackPrompt()
+ }
+ return opts.SkillInvocation.codexPrompt(catalog)
+}
+
+func (s *SkillInvocation) antigravityPrompt(supported bool) string {
+ if !supported || len(s.Skills) == 0 {
+ return s.FallbackPrompt()
+ }
+ // Print mode expands one leading command. Further selections stay explicit
+ // through injection, as they do on Claude.
+ return "/" + s.Skills[0].Name + "\n" + injectExplicitSkills(s.Prompt, s.Skills[1:])
+}
+
+// piSkillPrompt renders Pi's native leading skill invocation. Pi expands a
+// message whose text begins with `/skill:<name> ` inside session.prompt —
+// both print mode (the stdin prompt) and RPC mode (a `prompt` command): the
+// token is replaced by the skill's full body block and every remaining byte,
+// newlines included, is preserved verbatim after it (pi's
+// _expandSkillCommand splits the name at the first space; the slug charset
+// has no spaces). The lookup runs over the daemon's `--skill` files by
+// frontmatter name, which writeContextFiles keeps equal to the directory
+// name used here, so a listed file is the capability probe.
+//
+// omp (oh-my-pi) shares this backend but removed that expansion: its print
+// mode never dispatches the stdin prompt as a command, so a `/skill:` prefix
+// would reach the model as literal text. omp and every skill file missing
+// from this dispatch therefore keep the injection fallback.
+func (s *SkillInvocation) piSkillPrompt(skillFiles []string, args ...[]string) string {
+ if len(s.Skills) == 0 || piSkillsDisabled(args...) {
+ return s.FallbackPrompt()
+ }
+ want := filepath.Clean(filepath.Join(s.Skills[0].Directory, "SKILL.md"))
+ for _, path := range skillFiles {
+ if filepath.Clean(path) == want {
+ return "/skill:" + s.Skills[0].Name + " " + injectExplicitSkills(s.Prompt, s.Skills[1:])
+ }
+ }
+ return s.FallbackPrompt()
+}
+
+// piSkillsDisabled reports whether any argument group — launch prefix, extra
+// or custom args — asked Pi not to load skills. Pi still merges the daemon's
+// `--skill` paths under --no-skills, but a user who disabled skills must not
+// receive a native skill command; the plain injection fallback carries the
+// selection instead, matching how a disabled antigravity falls back.
+func piSkillsDisabled(args ...[]string) bool {
+ for _, group := range args {
+ for _, arg := range group {
+ if arg == "--no-skills" || arg == "-ns" {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func slashCommandsDisabled(args ...[]string) bool {
+ for _, group := range args {
+ for _, arg := range group {
+ if arg == "--disable-slash-commands" || strings.HasPrefix(arg, "--disable-slash-commands=") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// Probe only on selected-skill turns. Do not cache across executable upgrades
+// or infer capabilities from version strings. Failure is an injection fallback.
+func supportsAntigravitySlashSkills(ctx context.Context, cfg Config, executable string, opts ExecOptions) bool {
+ if slashCommandsDisabled(cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {
+ return false
+ }
+ probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ cmd := cfg.commandAt(executable).exec(probeCtx, "--help")
+ cmd.Dir = opts.Cwd
+ cmd.Env = buildEnv(cfg.Env)
+ cmd.WaitDelay = time.Second
+ output := &tailBuffer{max: 128 << 10}
+ cmd.Stdout, cmd.Stderr = output, output
+ if runOwned(cmd, cfg.Logger) != nil {
+ return false
+ }
+ return strings.Contains(string(output.Bytes()), "--disable-slash-commands")
+}
diff --git a/server/pkg/agent/explicit_skills_integration_test.go b/server/pkg/agent/explicit_skills_integration_test.go
new file mode 100644
index 0000000000..fb42ba8315
--- /dev/null
+++ b/server/pkg/agent/explicit_skills_integration_test.go
@@ -0,0 +1,237 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "io/fs"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Run the selected subtest after each runtime upgrade. Native providers must
+// leave runtime-generated expansion evidence as well as obey the skill; an
+// injected fallback alone must not make their smoke check pass.
+func TestExplicitSkillRealSmoke(t *testing.T) {
+ requireRealAgentSmoke(t)
+ if runtime.GOOS == "windows" {
+ t.Skip("wire capture uses a bash wrapper")
+ }
+ for _, scenario := range []string{"claude", "codex", "codex-fallback", "antigravity", "hermes"} {
+ t.Run(scenario, func(t *testing.T) {
+ provider := strings.TrimSuffix(scenario, "-fallback")
+ command := provider
+ if provider == "antigravity" {
+ command = "agy"
+ }
+ if override := os.Getenv(strings.ToUpper(provider) + "_SKILL_SMOKE_BIN"); override != "" {
+ command = override
+ }
+ binary, err := exec.LookPath(command)
+ if err != nil {
+ t.Skipf("%s unavailable: %v", provider, err)
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 150*time.Second)
+ defer cancel()
+ if version, err := exec.CommandContext(ctx, binary, "--version").CombinedOutput(); err == nil {
+ t.Logf("%s", strings.TrimSpace(string(version)))
+ }
+ root := t.TempDir()
+ cwd := filepath.Join(root, "workdir")
+ if err := os.MkdirAll(cwd, 0755); err != nil {
+ t.Fatal(err)
+ }
+ config := Config{Logger: slog.Default(), Env: map[string]string{"IS_SANDBOX": "1"}}
+ skillParent := filepath.Join(cwd, ".agents", "skills")
+ evidenceRoot := root
+ switch provider {
+ case "claude":
+ skillParent = filepath.Join(cwd, ".claude", "skills")
+ home := filepath.Join(root, "claude-home")
+ copySkillSmokeConfig(t, "CLAUDE_CONFIG_DIR", ".claude", home, []string{"settings.json", ".credentials.json", ".claude.json"})
+ if os.Getenv("CLAUDE_CONFIG_DIR") == "" {
+ // Without a config-dir override, Claude's global state lives
+ // beside ~/.claude, not inside it. Copy into the isolated dir;
+ // never update the original account or project configuration.
+ copySkillSmokeConfig(t, "HOME", "", home, []string{".claude.json"})
+ }
+ config.Env["CLAUDE_CONFIG_DIR"] = home
+ case "codex":
+ home := filepath.Join(root, "codex-home")
+ copySkillSmokeConfig(t, "CODEX_HOME", ".codex", home, []string{"config.toml", "auth.json"})
+ config.Env["CODEX_HOME"] = home
+ skillParent = filepath.Join(home, "skills")
+ if scenario == "codex-fallback" {
+ // A materialized skill outside Codex's discovery paths must
+ // reach the real runtime through the injection fallback.
+ skillParent = filepath.Join(root, "materialized-skills")
+ }
+ }
+ dir := filepath.Join(skillParent, "explicit-probe")
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ body := "Reply with exactly: EXPLICIT_SKILL followed by the platform token and then the user token, separated by spaces. Do not call any tools."
+ skill := "---\nname: explicit-probe\ndescription: Explicit invocation smoke test\ndisable-model-invocation: true\n---\n" + body
+ if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(skill), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if provider == "codex" {
+ if err := os.MkdirAll(filepath.Join(dir, "agents"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "agents", "openai.yaml"), []byte("policy:\n allow_implicit_invocation: false\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ invocation := &SkillInvocation{PlatformPrompt: "Platform token: PLATFORM_OK", UserMessage: "User token: USER_OK. Apply my selected skill.", Skills: []ExplicitSkill{{Name: "explicit-probe", Directory: dir, Body: body}}}
+ invocation.Prompt = invocation.PlatformPrompt + "\nUser message:\n" + invocation.UserMessage
+ wrapper := filepath.Join(root, "runtime-wrapper")
+ writeTestExecutable(t, wrapper, []byte(`#!/usr/bin/env bash
+set -o pipefail
+log_path=''
+previous=''
+for arg in "$@"; do
+ if [ "$previous" = '--log-file' ]; then log_path="$arg"; fi
+ previous="$arg"
+done
+tee "$SKILL_SMOKE_INPUT" | "$SKILL_SMOKE_BINARY" "$@" | tee "$SKILL_SMOKE_WIRE"
+result=${PIPESTATUS[1]}
+if [ -n "$log_path" ] && [ -f "$log_path" ]; then cp "$log_path" "$SKILL_SMOKE_LOG"; fi
+exit "$result"
+`))
+ config.ExecutablePath = wrapper
+ config.Env["SKILL_SMOKE_BINARY"] = binary
+ config.Env["SKILL_SMOKE_INPUT"] = filepath.Join(root, "input.jsonl")
+ config.Env["SKILL_SMOKE_WIRE"] = filepath.Join(root, "wire.jsonl")
+ config.Env["SKILL_SMOKE_LOG"] = filepath.Join(root, "runtime.log")
+ backend, err := New(provider, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ opts := ExecOptions{Cwd: cwd, Timeout: 120 * time.Second, SkillInvocation: invocation, Model: os.Getenv(strings.ToUpper(provider) + "_SKILL_SMOKE_MODEL")}
+ result := runSkillSmokeTurn(t, ctx, backend, invocation.FallbackPrompt(), opts)
+ t.Logf("Skill response: %q", result.Output)
+ if !strings.Contains(result.Output, "EXPLICIT_SKILL PLATFORM_OK USER_OK") {
+ t.Errorf("skill or message context lost: %q", result.Output)
+ }
+ switch provider {
+ case "claude":
+ expanded := skillSmokeEvidence(evidenceRoot, "<command-name>/explicit-probe</command-name>")
+ t.Logf("Claude native command-name evidence: %t", expanded)
+ if !expanded {
+ t.Fatal("no Claude command-name evidence; fallback is not native expansion")
+ }
+ case "codex":
+ if scenario == "codex-fallback" {
+ input, err := os.ReadFile(config.Env["SKILL_SMOKE_INPUT"])
+ if err != nil {
+ t.Fatal(err)
+ }
+ injected := false
+ for _, line := range strings.Split(strings.TrimSpace(string(input)), "\n") {
+ var request struct {
+ Method string `json:"method"`
+ Params struct {
+ Input []struct {
+ Text string `json:"text"`
+ } `json:"input"`
+ } `json:"params"`
+ }
+ if err := json.Unmarshal([]byte(line), &request); err != nil {
+ t.Fatal(err)
+ }
+ if request.Method == "turn/start" {
+ for _, block := range request.Params.Input {
+ injected = injected || (strings.Contains(block.Text, "<selected-skill>") && strings.Contains(block.Text, dir) && strings.Contains(block.Text, body))
+ }
+ }
+ }
+ t.Logf("Codex fallback body and directory evidence: %t", injected)
+ if !injected || skillSmokeEvidence(filepath.Join(root, "codex-home", "sessions"), "<name>explicit-probe</name>") {
+ t.Fatal("expected injected skill body and directory without native skill expansion")
+ }
+ break
+ }
+ if !skillSmokeEvidence(filepath.Join(root, "codex-home", "sessions"), "<skill>") || !skillSmokeEvidence(filepath.Join(root, "codex-home", "sessions"), "<name>explicit-probe</name>") {
+ t.Fatal("no Codex native skill injection in rollout")
+ }
+ case "antigravity":
+ log, _ := os.ReadFile(config.Env["SKILL_SMOKE_LOG"])
+ if !strings.Contains(string(log), `expanded slash command "explicit-probe"`) {
+ t.Fatal("no agy slash expansion evidence")
+ }
+ }
+ if !t.Failed() {
+ t.Logf("%s selected skill passed; session=%s", scenario, result.SessionID)
+ }
+ })
+ }
+}
+
+func runSkillSmokeTurn(t *testing.T, ctx context.Context, backend Backend, prompt string, opts ExecOptions) Result {
+ t.Helper()
+ session, err := backend.Execute(ctx, prompt, opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for message := range session.Messages {
+ if message.Type == MessageToolUse {
+ t.Errorf("unexpected tool call: %s", message.Tool)
+ }
+ }
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Errorf("status=%s error=%s", result.Status, result.Error)
+ }
+ return result
+}
+
+func copySkillSmokeConfig(t *testing.T, variable, defaultDir, destination string, names []string) {
+ t.Helper()
+ source := os.Getenv(variable)
+ if source == "" {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ source = filepath.Join(home, defaultDir)
+ }
+ if err := os.MkdirAll(destination, 0700); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range names {
+ data, err := os.ReadFile(filepath.Join(source, name))
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(destination, name), data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func skillSmokeEvidence(root, marker string) bool {
+ found := false
+ _ = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
+ if err != nil || entry.IsDir() || !strings.HasSuffix(path, ".jsonl") {
+ return nil
+ }
+ data, err := os.ReadFile(path)
+ if err == nil && strings.Contains(string(data), marker) {
+ found = true
+ }
+ return nil
+ })
+ return found
+}
diff --git a/server/pkg/agent/explicit_skills_test.go b/server/pkg/agent/explicit_skills_test.go
new file mode 100644
index 0000000000..9594970690
--- /dev/null
+++ b/server/pkg/agent/explicit_skills_test.go
@@ -0,0 +1,458 @@
+package agent
+
+import (
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func testSkillInvocation(t *testing.T) *SkillInvocation {
+ t.Helper()
+ return &SkillInvocation{
+ Prompt: "Platform context\nUser message:\n/compact keep this text\nAttachments: file-id",
+ PlatformPrompt: "Platform context\nAttachments: file-id",
+ UserMessage: "/compact keep this text",
+ Skills: []ExplicitSkill{
+ {Name: "first-multica", Directory: filepath.Join(t.TempDir(), "first-multica"), Body: "FIRST REQUIREMENT"},
+ {Name: "second", Directory: filepath.Join(t.TempDir(), "second"), Body: "SECOND REQUIREMENT"},
+ },
+ }
+}
+
+// TestExplicitSkillsIssueTurnClaudeBlocks pins the issue-comment shape: the
+// daemon keeps the complete comment prompt as PlatformPrompt (issue context,
+// thread metadata, --parent reply routing) and carries the stripped member
+// comment as UserMessage, so the trailing slash block never drops the reply
+// routing or ships an empty user ask.
+func TestExplicitSkillsIssueTurnClaudeBlocks(t *testing.T) {
+ s := &SkillInvocation{
+ Prompt: "Issue context\n[NEW COMMENT]\n> please review\nreply with --parent comment-trigger",
+ UserMessage: "please review",
+ Skills: []ExplicitSkill{
+ {Name: "review-code", Directory: filepath.Join(t.TempDir(), "review-code"), Body: "FIRST BODY"},
+ {Name: "second", Directory: filepath.Join(t.TempDir(), "second"), Body: "SECOND BODY"},
+ },
+ }
+ s.PlatformPrompt = s.Prompt
+ blocks := s.claudeTextBlocks(map[string]bool{"review-code": true})
+ if len(blocks) != 2 || blocks[1] != "/review-code please review" {
+ t.Fatalf("trailing block must carry the member ask: %q", blocks)
+ }
+ if !strings.Contains(blocks[0], "--parent comment-trigger") || !strings.Contains(blocks[0], "SECOND BODY") {
+ t.Fatalf("platform block lost routing or injected skill: %q", blocks[0])
+ }
+}
+
+// TestClaudeSkillCommandBlockSpacing pins the trailing block's shape for
+// capsule-only turns: no trailing space once the member ask strips to
+// nothing, and exactly one separating space for a real ask.
+func TestClaudeSkillCommandBlockSpacing(t *testing.T) {
+ s := &SkillInvocation{
+ PlatformPrompt: "platform",
+ Skills: []ExplicitSkill{{Name: "review-code", Directory: filepath.Join(t.TempDir(), "review-code"), Body: "BODY"}},
+ }
+ available := map[string]bool{"review-code": true}
+ s.UserMessage = " "
+ if blocks := s.claudeTextBlocks(available); blocks[1] != "/review-code" {
+ t.Fatalf("whitespace-only ask must not leave a trailing space: %q", blocks[1])
+ }
+ s.UserMessage = " padded ask "
+ if blocks := s.claudeTextBlocks(available); blocks[1] != "/review-code padded ask" {
+ t.Fatalf("ask must join the command with exactly one space: %q", blocks[1])
+ }
+}
+
+func TestExplicitSkillsProviderInputs(t *testing.T) {
+ s := testSkillInvocation(t)
+ blocks := s.claudeTextBlocks(map[string]bool{"first-multica": true})
+ wire, err := buildClaudeInput(blocks...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var input struct {
+ Message struct{ Content []struct{ Type, Text string } }
+ }
+ if err := json.Unmarshal(wire, &input); err != nil {
+ t.Fatal(err)
+ }
+ if len(input.Message.Content) != 2 || input.Message.Content[1].Text != "/first-multica /compact keep this text" {
+ t.Fatalf("Claude command must start last block: %s", wire)
+ }
+ if !strings.Contains(blocks[0], "Attachments: file-id") || !strings.Contains(blocks[0], "SECOND REQUIREMENT") || strings.Contains(blocks[0], "FIRST REQUIREMENT") {
+ t.Fatalf("Claude platform block=%q", blocks[0])
+ }
+ agy := s.antigravityPrompt(true)
+ if !strings.HasPrefix(agy, "/first-multica\nPlatform context") || !strings.Contains(agy, "SECOND REQUIREMENT") || strings.Contains(agy, "FIRST REQUIREMENT") {
+ t.Fatalf("agy prompt=%q", agy)
+ }
+ catalog, _ := json.Marshal(map[string]any{"data": []any{map[string]any{"skills": []any{
+ map[string]any{"name": s.Skills[0].Name, "path": filepath.Join(s.Skills[0].Directory, "SKILL.md"), "enabled": true},
+ map[string]any{"name": s.Skills[1].Name, "path": filepath.Join(s.Skills[1].Directory, "SKILL.md"), "enabled": true},
+ }}}})
+ codex := s.codexPrompt(catalog)
+ if !strings.Contains(codex, "$first-multica\n") || !strings.Contains(codex, "$second\n") || strings.Contains(codex, "REQUIREMENT") || !strings.Contains(codex, s.UserMessage) {
+ t.Fatalf("Codex prompt=%q", codex)
+ }
+}
+
+func TestExplicitSkillsMissingCapabilitiesFallBack(t *testing.T) {
+ s := testSkillInvocation(t)
+ for _, catalog := range []string{`{}`, `{"data":[]}`, `{"data":[{"skills":[{"name":"first-multica","path":"/some-other/SKILL.md","enabled":true}]}]}`, `not json`} {
+ if got := s.codexPrompt(json.RawMessage(catalog)); got != s.FallbackPrompt() {
+ t.Fatalf("unsupported Codex: %q", got)
+ }
+ }
+ for _, commands := range []map[string]bool{nil, {}, {"second": true}} {
+ blocks := s.claudeTextBlocks(commands)
+ if len(blocks) != 1 || blocks[0] != s.FallbackPrompt() {
+ t.Fatalf("unsupported Claude: %v", blocks)
+ }
+ }
+ if s.antigravityPrompt(false) != s.FallbackPrompt() {
+ t.Fatal("unsupported agy lost fallback")
+ }
+ for _, want := range []string{s.UserMessage, "FIRST REQUIREMENT", "SECOND REQUIREMENT", s.Skills[0].Directory, "user explicitly selected"} {
+ if !strings.Contains(s.FallbackPrompt(), want) {
+ t.Errorf("fallback lost %q", want)
+ }
+ }
+}
+
+func TestCodexExplicitSkillDisabledOrMalformedEntryFallsBack(t *testing.T) {
+ s := testSkillInvocation(t)
+ for _, enabled := range []any{false, nil, "true"} {
+ catalog, _ := json.Marshal(map[string]any{"data": []any{map[string]any{"skills": []any{map[string]any{"name": s.Skills[0].Name, "path": filepath.Join(s.Skills[0].Directory, "SKILL.md"), "enabled": enabled}}}}})
+ if got := s.codexPrompt(catalog); got != s.FallbackPrompt() {
+ t.Fatalf("disabled/malformed skill invoked: %q", got)
+ }
+ }
+}
+
+func TestAntigravityExplicitSkillCapabilityProbe(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ for _, tc := range []struct {
+ name, script string
+ disabled, want bool
+ }{
+ {"supported", "echo --disable-slash-commands", false, true},
+ {"old CLI", "echo usage", false, false},
+ {"failed help", "exit 2", false, false},
+ {"explicitly disabled", "echo --disable-slash-commands", true, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "fake-agy")
+ writeTestExecutable(t, path, []byte("#!/bin/sh\n"+tc.script+"\n"))
+ opts := ExecOptions{}
+ if tc.disabled {
+ opts.CustomArgs = []string{"--disable-slash-commands"}
+ }
+ if got := supportsAntigravitySlashSkills(t.Context(), Config{Logger: slog.Default()}, path, opts); got != tc.want {
+ t.Fatalf("capability=%v want=%v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestClaudeExplicitSkillsExecute(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ for _, tc := range []struct {
+ name, description string
+ rejected, native bool
+ }{
+ {name: "project command", description: "Bound skill (project)", native: true},
+ {name: "personal skill shadows project", description: "Personal review (user)"},
+ {name: "plugin command", description: "Plugin review (plugin)"},
+ {name: "unknown command origin", description: "Review code"},
+ {name: "missing command origin"},
+ {name: "unsupported initialization", rejected: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := testSkillInvocation(t)
+ dir := t.TempDir()
+ capture := filepath.Join(dir, "input.json")
+ path := filepath.Join(dir, "fake-claude")
+ response := `{"subtype":"error","request_id":"multica-supplement-initialize","error":"unsupported"}`
+ if !tc.rejected {
+ response = fmt.Sprintf(`{"subtype":"success","request_id":"multica-supplement-initialize","response":{"commands":[{"name":"first-multica","description":%q}]}}`, tc.description)
+ }
+ script := "#!/bin/sh\nIFS= read -r init\nprintf '%s\\n' \"$init\" > \"$INIT_CAPTURE\"\nprintf '%s\\n' '{\"type\":\"control_response\",\"response\":" + response + "}'\nIFS= read -r input\nprintf '%s\\n' \"$input\" > \"$CAPTURE\"\nprintf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"result\":\"done\"}'\ncat >/dev/null\n"
+ writeTestExecutable(t, path, []byte(script))
+ initCapture := filepath.Join(dir, "initialize.json")
+ backend := &claudeBackend{cfg: Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{"CAPTURE": capture, "INIT_CAPTURE": initCapture, "IS_SANDBOX": "1"}}}
+ session, err := backend.Execute(t.Context(), s.FallbackPrompt(), ExecOptions{SkillInvocation: s, Timeout: 10 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range session.Messages {
+ }
+ if result := <-session.Result; result.Status != "completed" {
+ t.Fatalf("result=%+v", result)
+ }
+ wire, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var input struct {
+ Message struct{ Content []struct{ Text string } }
+ }
+ if err := json.Unmarshal(wire, &input); err != nil {
+ t.Fatal(err)
+ }
+ initWire, err := os.ReadFile(initCapture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var init struct {
+ Request struct{ Hooks map[string]json.RawMessage }
+ }
+ if err := json.Unmarshal(initWire, &init); err != nil {
+ t.Fatal(err)
+ }
+ if len(init.Request.Hooks) != 0 {
+ t.Errorf("skill discovery enabled supplement hooks: %s", initWire)
+ }
+ if tc.native {
+ if len(input.Message.Content) != 2 || !strings.HasPrefix(input.Message.Content[1].Text, "/first-multica ") {
+ t.Fatalf("native input=%s", wire)
+ }
+ } else if len(input.Message.Content) != 1 || input.Message.Content[0].Text != s.FallbackPrompt() {
+ t.Fatalf("fallback input=%s", wire)
+ }
+ })
+ }
+}
+
+func TestCodexExplicitSkillsExecuteCapabilityFallback(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ for _, supported := range []bool{true, false} {
+ t.Run(fmt.Sprintf("supported=%t", supported), func(t *testing.T) {
+ s := testSkillInvocation(t)
+ response := `{"jsonrpc":"2.0","id":3,"error":{"code":-32601,"message":"Method not found"}}`
+ if supported {
+ catalog, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 3, "result": map[string]any{"data": []any{map[string]any{"skills": []any{map[string]any{"name": s.Skills[0].Name, "path": filepath.Join(s.Skills[0].Directory, "SKILL.md"), "enabled": true}}}}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ response = string(catalog)
+ }
+ path := writeFakeCodexAppServer(t, `read line
+echo '{"jsonrpc":"2.0","id":1,"result":{}}'
+read line
+read line
+echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"skill-thread"}}}'
+read line
+echo '`+response+`'
+IFS= read -r line
+printf '%s\n' "$line" > "$CAPTURE"
+echo '{"jsonrpc":"2.0","id":4,"result":{"turn":{"id":"skill-turn"}}}'
+echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"skill-thread","turn":{"id":"skill-turn"}}}'
+echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"skill-thread","item":{"type":"agentMessage","id":"response","text":"Done"}}}'
+echo '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"skill-thread","turn":{"id":"skill-turn","status":"completed"}}}'
+`)
+ capture := filepath.Join(t.TempDir(), "input.json")
+ backend, err := New("codex", Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{"CAPTURE": capture}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(t.Context(), s.FallbackPrompt(), ExecOptions{SkillInvocation: s, Cwd: t.TempDir(), Timeout: 10 * time.Second, ResumeExpected: true, ResumeContinuityNotice: "History unavailable.\n"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range session.Messages {
+ }
+ if result := <-session.Result; result.Status != "completed" {
+ t.Fatalf("result=%+v", result)
+ }
+ wire, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var request struct {
+ Method string
+ Params struct{ Input []struct{ Text string } }
+ }
+ if err := json.Unmarshal(wire, &request); err != nil {
+ t.Fatal(err)
+ }
+ if request.Method != "turn/start" || len(request.Params.Input) != 1 {
+ t.Fatalf("wrong input: %s", wire)
+ }
+ got := request.Params.Input[0].Text
+ for _, want := range []string{s.UserMessage, "History unavailable.", "SECOND REQUIREMENT"} {
+ if !strings.Contains(got, want) {
+ t.Fatalf("lost %q: %s", want, got)
+ }
+ }
+ if supported {
+ if !strings.Contains(got, "$first-multica") || strings.Contains(got, "FIRST REQUIREMENT") {
+ t.Fatalf("missing native input: %s", got)
+ }
+ } else if !strings.Contains(got, "FIRST REQUIREMENT") || strings.Contains(got, "$first-multica") {
+ t.Fatalf("missing fallback: %s", got)
+ }
+ })
+ }
+}
+
+func TestInjectedSkillsReachACPWithRuntimeBrief(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ for _, provider := range []string{"kimi", "hermes"} {
+ t.Run(provider, func(t *testing.T) {
+ s := testSkillInvocation(t)
+ dir := t.TempDir()
+ path, capture := filepath.Join(dir, "fake-acp"), filepath.Join(dir, "prompt.json")
+ writeTestExecutable(t, path, []byte(`#!/bin/sh
+read line
+echo '{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":false}}}'
+read line
+echo '{"jsonrpc":"2.0","id":1,"result":{"sessionId":"skills-acp"}}'
+IFS= read -r line
+printf '%s\n' "$line" > "$CAPTURE"
+echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"skills-acp","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Done"}}}}'
+echo '{"jsonrpc":"2.0","id":2,"result":{"stopReason":"end_turn"}}'
+`))
+ backend, err := New(provider, Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{"CAPTURE": capture}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(t.Context(), s.FallbackPrompt(), ExecOptions{SkillInvocation: s, Cwd: dir, SystemPrompt: "RUNTIME BRIEF", Timeout: 8 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range session.Messages {
+ }
+ if result := <-session.Result; result.Status != "completed" {
+ t.Fatalf("result=%+v", result)
+ }
+ wire, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var request struct {
+ Method string
+ Params struct{ Prompt []struct{ Type, Text string } }
+ }
+ if err := json.Unmarshal(wire, &request); err != nil {
+ t.Fatal(err)
+ }
+ if request.Method != "session/prompt" || len(request.Params.Prompt) != 1 || request.Params.Prompt[0].Type != "text" {
+ t.Fatalf("wrong ACP input: %s", wire)
+ }
+ want := s.FallbackPrompt()
+ if provider == "kimi" {
+ want = "RUNTIME BRIEF\n\n---\n\n" + want
+ }
+ if request.Params.Prompt[0].Text != want {
+ t.Fatalf("lost injected body/brief: %s", wire)
+ }
+ })
+ }
+}
+
+func TestAntigravityExplicitSkillsExecuteFallback(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ for _, supported := range []bool{true, false} {
+ t.Run(fmt.Sprintf("supported=%t", supported), func(t *testing.T) {
+ s := testSkillInvocation(t)
+ dir := t.TempDir()
+ path, capture := filepath.Join(dir, "fake-agy"), filepath.Join(dir, "prompt.txt")
+ help := "usage"
+ if supported {
+ help = "--disable-slash-commands"
+ }
+ writeTestExecutable(t, path, []byte("#!/bin/sh\nif [ \"$1\" = '--help' ]; then echo '"+help+"'; exit 0; fi\nprintf '%s' \"$2\" > \"$CAPTURE\"\necho Done\n"))
+ backend, err := New("antigravity", Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{"CAPTURE": capture}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(t.Context(), s.FallbackPrompt(), ExecOptions{SkillInvocation: s, Cwd: dir, Timeout: 8 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range session.Messages {
+ }
+ if result := <-session.Result; result.Status != "completed" {
+ t.Fatalf("result=%+v", result)
+ }
+ prompt, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(prompt) != s.antigravityPrompt(supported) {
+ t.Fatalf("wrong agy input: %s", prompt)
+ }
+ })
+ }
+}
+
+func TestClaudeSkillInitializationUsesHandshakeTimeout(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ path := filepath.Join(t.TempDir(), "fake-claude")
+ // Deliberately never answer initialize. The configured budget must release
+ // skill discovery without waiting for the whole execution timeout.
+ writeTestExecutable(t, path, []byte(`#!/bin/sh
+IFS= read -r init
+IFS= read -r input
+printf '%s\n' '{"type":"result","subtype":"success","result":"fallback completed"}'
+cat >/dev/null
+`))
+ backend := &claudeBackend{cfg: Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{"IS_SANDBOX": "1"}}}
+ skill := testSkillInvocation(t)
+ session, err := backend.Execute(t.Context(), skill.FallbackPrompt(), ExecOptions{
+ SkillInvocation: skill, HandshakeTimeout: 30 * time.Millisecond, Timeout: 2 * time.Second,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range session.Messages {
+ }
+ if result := <-session.Result; result.Status != "completed" || result.Output != "fallback completed" {
+ t.Fatalf("skill-only handshake did not honor its budget: %+v", result)
+ }
+}
+
+func TestClaudeSkillInitializationReleasesOnEarlyExit(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell fixture")
+ }
+ path := filepath.Join(t.TempDir(), "fake-claude")
+ // Exit before answering the initialize request: the shutdown path must
+ // release the command-discovery handshake, not the timeout budget.
+ writeTestExecutable(t, path, []byte("#!/bin/sh\nexit 1\n"))
+ backend := &claudeBackend{cfg: Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{"IS_SANDBOX": "1"}}}
+ skill := testSkillInvocation(t)
+ started := time.Now()
+ session, err := backend.Execute(t.Context(), skill.FallbackPrompt(), ExecOptions{
+ SkillInvocation: skill, HandshakeTimeout: 5 * time.Second, Timeout: 10 * time.Second,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range session.Messages {
+ }
+ result := <-session.Result
+ if result.Status == "completed" {
+ t.Fatalf("early exit must fail the run: %+v", result)
+ }
+ if elapsed := time.Since(started); elapsed > 2*time.Second {
+ t.Fatalf("early exit waited for the handshake budget: %s (%+v)", elapsed, result)
+ }
+}
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index da94bf809d..b9904e943f 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -455,6 +455,16 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
} else {
args = buildPiArgs(sessionPath, opts, b.cfg.Logger)
}
+ // Pi natively expands a leading "/skill:<name> " in session.prompt, which
+ // is exactly where both delivery modes land the task text (stdin in print
+ // mode, a prompt command in RPC mode). omp shares this backend but never
+ // command-dispatches the stdin prompt, and a custom runtime profile only
+ // promises the JSON protocol, not the vendor binary's skill grammar — an
+ // unexpanded token would reach the model as literal text. Both keep the
+ // fallback prompt; only the built-in pi binary earns the native one.
+ if label == "pi" && b.cfg.BuiltinRuntime && opts.SkillInvocation != nil {
+ prompt = opts.SkillInvocation.piSkillPrompt(opts.PiSkillPaths, b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs)
+ }
cmd, _, _ := b.cfg.commandAt(execName).execVia(processCtx, choosePiInvocation, lookedUp, args, b.cfg.Logger)
// The joined cleanup below owns TERM, escalation and pipe release.
cmd.Cancel = func() error { return nil }
diff --git a/server/pkg/agent/pi_skill_prompt_unix_test.go b/server/pkg/agent/pi_skill_prompt_unix_test.go
new file mode 100644
index 0000000000..d46e037e20
--- /dev/null
+++ b/server/pkg/agent/pi_skill_prompt_unix_test.go
@@ -0,0 +1,247 @@
+//go:build unix
+
+package agent
+
+import (
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func piSkillInvocation(t *testing.T) (*SkillInvocation, string) {
+ t.Helper()
+ dir := t.TempDir()
+ skillDir := filepath.Join(dir, "first-multica")
+ if err := os.MkdirAll(skillDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ s := &SkillInvocation{
+ Prompt: "Platform context\nsecond line",
+ PlatformPrompt: "Platform context",
+ UserMessage: "run the review",
+ Skills: []ExplicitSkill{
+ {Name: "first-multica", Directory: skillDir, Body: "FIRST BODY"},
+ {Name: "second", Directory: filepath.Join(dir, "second"), Body: "SECOND BODY"},
+ },
+ }
+ return s, filepath.Join(skillDir, "SKILL.md")
+}
+
+func TestPiSkillPromptNativeAndFallback(t *testing.T) {
+ s, skillFile := piSkillInvocation(t)
+
+ native := s.piSkillPrompt([]string{skillFile}, nil)
+ if !strings.HasPrefix(native, "/skill:first-multica Platform context\nsecond line") {
+ t.Fatalf("native prompt must lead with the pi skill token: %q", native)
+ }
+ if strings.Contains(native, "FIRST BODY") || !strings.Contains(native, "SECOND BODY") {
+ t.Fatalf("first skill must expand natively, the rest inject: %q", native)
+ }
+
+ for _, tc := range []struct {
+ name string
+ files []string
+ args [][]string
+ }{
+ {"skill file not in dispatch", nil, nil},
+ {"other files only", []string{filepath.Join(t.TempDir(), "other", "SKILL.md")}, nil},
+ {"skills disabled", []string{skillFile}, [][]string{{"--no-skills"}}},
+ {"skills disabled short flag", []string{skillFile}, [][]string{{"-ns"}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := s.piSkillPrompt(tc.files, tc.args...)
+ if strings.HasPrefix(got, "/skill:") {
+ t.Fatalf("must fall back, got native: %q", got)
+ }
+ if !strings.Contains(got, "FIRST BODY") || !strings.Contains(got, "SECOND BODY") {
+ t.Fatalf("fallback must inject every skill body: %q", got)
+ }
+ })
+ }
+}
+
+// piSkillStdinProbe runs a backend against a fake CLI that records stdin and
+// emits a minimal successful event stream. cfg carries the daemon's Config
+// for the provider under test (BuiltinRuntime, LaunchPrefix, ...).
+func piSkillStdinProbe(t *testing.T, provider string, opts ExecOptions, cfg Config) string {
+ t.Helper()
+ t.Setenv("HOME", t.TempDir())
+ dir := t.TempDir()
+ stdinPath := filepath.Join(dir, "stdin.txt")
+ // omp requires the runtime itself to persist a transcript into its
+ // --session-dir before exit; pi only needs the event stream.
+ script := fmt.Sprintf(`#!/bin/sh
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --session-dir) sessdir="$2" ;;
+ esac
+ shift
+done
+cat > %[1]s
+if [ -n "$sessdir" ]; then
+ printf '%%s\n' '{"type":"session","id":"s"}' > "$sessdir/runtime-chosen.jsonl"
+fi
+printf '%%s\n' '{"type":"agent_end"}'
+`, stdinPath)
+ fakePath := filepath.Join(dir, provider)
+ writeTestExecutable(t, fakePath, []byte(script))
+ backend, err := ResolveBackend(provider, func() Config {
+ cfg.ExecutablePath = fakePath
+ if cfg.Logger == nil {
+ cfg.Logger = slog.Default()
+ }
+ return cfg
+ }())
+ if err != nil {
+ t.Fatal(err)
+ }
+ prompt := "unused prompt"
+ if (provider == "omp" || !cfg.BuiltinRuntime) && opts.SkillInvocation != nil {
+ // The backend never rewrites the prompt for omp or a custom
+ // protocol-family profile; the daemon hands every non-native runtime
+ // the fallback text up front.
+ prompt = opts.SkillInvocation.FallbackPrompt()
+ }
+ session, err := backend.Execute(t.Context(), prompt, opts)
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("result: %+v", result)
+ }
+ data, err := os.ReadFile(stdinPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+}
+
+func TestPiExecuteSendsNativeSkillPromptOnStdin(t *testing.T) {
+ s, skillFile := piSkillInvocation(t)
+ stdin := piSkillStdinProbe(t, "pi", ExecOptions{
+ Timeout: 10 * time.Second,
+ SkillInvocation: s,
+ PiSkillPaths: []string{skillFile},
+ }, Config{BuiltinRuntime: true})
+ if !strings.HasPrefix(stdin, "/skill:first-multica ") {
+ t.Fatalf("pi must receive the native skill token first: %q", stdin)
+ }
+ if !strings.Contains(stdin, "Platform context") || !strings.Contains(stdin, "SECOND BODY") {
+ t.Fatalf("pi prompt lost platform text or injected skills: %q", stdin)
+ }
+}
+
+// TestPiProfileExecuteKeepsInjectionFallback pins the custom-profile gate: a
+// protocol-family profile is not the vendor's binary, so its "/skill:" grammar
+// is unverified and the native token must never be sent.
+func TestPiProfileExecuteKeepsInjectionFallback(t *testing.T) {
+ s, skillFile := piSkillInvocation(t)
+ stdin := piSkillStdinProbe(t, "pi", ExecOptions{
+ Timeout: 10 * time.Second,
+ SkillInvocation: s,
+ PiSkillPaths: []string{skillFile},
+ }, Config{})
+ if strings.HasPrefix(stdin, "/skill:") {
+ t.Fatalf("a custom pi-family profile must not receive the native token: %q", stdin)
+ }
+ if !strings.Contains(stdin, "FIRST BODY") || !strings.Contains(stdin, "Platform context") {
+ t.Fatalf("the profile must receive the full fallback prompt: %q", stdin)
+ }
+}
+
+func TestOmpExecuteKeepsInjectionFallback(t *testing.T) {
+ s, skillFile := piSkillInvocation(t)
+ stdin := piSkillStdinProbe(t, "omp", ExecOptions{
+ Timeout: 10 * time.Second,
+ SkillInvocation: s,
+ PiSkillPaths: []string{skillFile},
+ }, Config{BuiltinRuntime: true})
+ if strings.HasPrefix(stdin, "/skill:") {
+ t.Fatalf("omp never command-dispatches its stdin prompt; native token must not be sent: %q", stdin)
+ }
+ if !strings.Contains(stdin, "FIRST BODY") || !strings.Contains(stdin, "Platform context") {
+ t.Fatalf("omp must receive the full fallback prompt: %q", stdin)
+ }
+}
+
+// TestPiExecuteDisabledSkillsKeepFallback pins the guard's scope: the native
+// token is suppressed whichever argument group asked Pi not to load skills.
+func TestPiExecuteDisabledSkillsKeepFallback(t *testing.T) {
+ s, skillFile := piSkillInvocation(t)
+ for _, tc := range []struct {
+ name string
+ cfg Config
+ opts ExecOptions
+ }{
+ {"launch prefix", Config{LaunchPrefix: []string{"-ns"}}, ExecOptions{}},
+ {"extra args", Config{}, ExecOptions{ExtraArgs: []string{"--no-skills"}}},
+ {"custom args", Config{}, ExecOptions{CustomArgs: []string{"-ns"}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.cfg.BuiltinRuntime = true
+ tc.opts.Timeout = 10 * time.Second
+ tc.opts.SkillInvocation = s
+ tc.opts.PiSkillPaths = []string{skillFile}
+ stdin := piSkillStdinProbe(t, "pi", tc.opts, tc.cfg)
+ if strings.HasPrefix(stdin, "/skill:") {
+ t.Fatalf("disabled skills must keep the fallback: %q", stdin)
+ }
+ if !strings.Contains(stdin, "FIRST BODY") || !strings.Contains(stdin, "Platform context") {
+ t.Fatalf("fallback must carry the full prompt: %q", stdin)
+ }
+ })
+ }
+}
+
+// TestPiExecuteRpcSendsNativeSkillPrompt pins the RPC delivery path: the
+// first initial-prompt command frame carries the same native leading token
+// print mode writes to stdin.
+func TestPiExecuteRpcSendsNativeSkillPrompt(t *testing.T) {
+ s, skillFile := piSkillInvocation(t)
+ t.Setenv("HOME", t.TempDir())
+ dir := t.TempDir()
+ framePath := filepath.Join(dir, "initial-prompt.jsonl")
+ script := fmt.Sprintf(`#!/bin/sh
+IFS= read -r frame
+printf '%%s\n' "$frame" > %[1]s
+printf '%%s\n' '{"type":"response","id":"initial-prompt","command":"prompt","success":true,"data":{"disposition":"handled"}}'
+printf '%%s\n' '{"type":"agent_settled"}'
+printf '%%s\n' '{"type":"agent_end"}'
+`, framePath)
+ fakePath := filepath.Join(dir, "pi")
+ writeTestExecutable(t, fakePath, []byte(script))
+ backend, err := ResolveBackend("pi", Config{ExecutablePath: fakePath, Logger: slog.Default(), BuiltinRuntime: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(t.Context(), "unused prompt", ExecOptions{
+ Timeout: 10 * time.Second, SkillInvocation: s, PiSkillPaths: []string{skillFile}, EnableTaskSupplement: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result := <-session.Result; result.Status != "completed" {
+ t.Fatalf("result: %+v", result)
+ }
+ raw, err := os.ReadFile(framePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var frame struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Message string `json:"message"`
+ }
+ if err := json.Unmarshal(raw, &frame); err != nil {
+ t.Fatalf("initial-prompt frame: %v (%s)", err, raw)
+ }
+ if frame.ID != "initial-prompt" || frame.Type != "prompt" || !strings.HasPrefix(frame.Message, "/skill:first-multica ") {
+ t.Fatalf("RPC first frame must carry the native skill token: %s", raw)
+ }
+}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 2162d97cea..e0524d75f3 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -376,7 +376,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at, channel_context_revision, id
+ fire_at, channel_context_revision, id, context
)
SELECT
$1, $2, NULL,
@@ -392,7 +392,8 @@ SELECT
$14,
$6::timestamptz,
$15::bigint,
- COALESCE($16::uuid, gen_random_uuid())
+ COALESCE($16::uuid, gen_random_uuid()),
+ $17::jsonb
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
@@ -414,6 +415,7 @@ type CreateChatTaskParams struct {
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
ID pgtype.UUID `json:"id"`
+ Context []byte `json:"context"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -441,6 +443,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
arg.TriggerEvidenceRefID,
arg.ChannelContextRevision,
arg.ID,
+ arg.Context,
)
var i AgentTaskQueue
err := row.Scan(
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index d5d09f0387..cfd1e00ef2 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -1148,7 +1148,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at, channel_context_revision, id
+ fire_at, channel_context_revision, id, context
)
SELECT
$1, $2, NULL,
@@ -1164,7 +1164,8 @@ SELECT
sqlc.narg(trigger_evidence_ref_id),
sqlc.narg('fire_at')::timestamptz,
sqlc.narg('channel_context_revision')::bigint,
- COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()),
+ sqlc.narg('context')::jsonb
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING *;