diff --git a/README.org b/README.org index cc17d61a..afc19fa3 100644 --- a/README.org +++ b/README.org @@ -420,7 +420,7 @@ Set the backend to =claude-code=, =codex=, =github-copilot-cli=, =pi=, or =antig Auto-wiring is currently enabled for =claude-code=, =codex=, =github-copilot-cli=, =open-interpreter=, =antigravity=, and =pi=. -Pi sessions load a per-launch temporary extension (=--extension=) that calls =pi.registerMcpServer= with the session token read from the child process environment. Each Pi instance gets its own token, session, and extension file, so several Pi sessions can use the Emacs tools independently. This requires a Pi build with built-in MCP support. +Pi sessions load a per-launch temporary extension (=--extension=) that calls =pi.registerMcpServer= with the session token read from the child process environment. Each Pi instance gets its own token, session, and extension file, so several Pi sessions can use the Emacs tools independently. By default, =ai-code-mcp-agent-pi-exposure= uses ="codemode"= (which automatically enables Pi's =codemode= script runner for parallel tool batching and keeps large tool schemas out of every turn) while =ai-code-mcp-agent-pi-tool-exposure= keeps =diagnostics_baseline=, =get_diagnostics=, and =get_org_heading_context= directly declared; customize either option if you prefer full ="direct"= exposure. This requires a Pi build with built-in MCP support. Antigravity does not expand environment variables in MCP headers, so each Antigravity launch creates a private per-session temporary directory containing =.agents/mcp_config.json= (mode =0700=/=0600=) and passes it via =--add-dir=. Project workspaces stay untouched, multiple concurrent Antigravity sessions stay isolated with independent tokens and contexts, and temporary directories are removed on session exit or Emacs shutdown. @@ -790,9 +790,44 @@ with =C-c a H=. Use its references to revisit the original evidence. scroll, search, and number it; Pi's default fullscreen mode draws on the alternate screen, leaving only the visible rows in the session buffer. Customize =ai-code-pi-tui-mode= to =fullscreen=, or to =nil= to keep Pi's - own setting. In Pi session buffers, Shift+Enter and - Ctrl+Enter insert a newline, and Ctrl+Escape sends Escape to cancel the - current operation. + own setting. Customize =ai-code-pi-project-trust= to =approve= or + =no-approve= if you want AI Code to pass =--approve= or =--no-approve= + instead of using Pi's saved project-trust prompt. + + In Pi session buffers, Shift+Enter and Ctrl+Enter insert a newline, + Alt+Enter (=M-=) submits immediately when idle or queues a + follow-up while Pi is busy, and Ctrl+Escape sends Escape to cancel the + current operation. From any project buffer or Pi session, run + =M-x ai-code-pi-compose= to open Pi's external editor in an Emacs + viewport (=ai-code-editor-viewport=) without =C-g= conflicting with + =keyboard-quit= (leave =externalEditor= unset in + =~/.pi/agent/settings.json= so Pi uses AI Code's =VISUAL=/=EDITOR= + bridge). Use =M-x ai-code-pi-send-follow-up= to queue a follow-up from + Emacs (or customize =ai-code-pi-send-while-busy= to =followup= to make + =ai-code-pi-send-command= queue follow-ups instead of steering), and + =M-x ai-code-pi-slash-command= to send slash commands such as =/model=, + =/thinking=, =/tree=, or =/compact=. + + *Recommended manual Gemini setup for Pi:* AI Code never overrides your Pi + model or credentials automatically. To use Gemini with Pi, export + =GEMINI_API_KEY= (Google AI Studio) or configure Vertex AI + (=GOOGLE_CLOUD_PROJECT=, =GOOGLE_CLOUD_LOCATION=, and Application Default + Credentials), and optionally configure =~/.pi/agent/settings.json= so + =Ctrl+P= cycles cleanly between Pro and Flash with Vertex-safe thinking + levels (avoiding =minimal= on Vertex endpoints): + + #+begin_src json + { + "defaultProvider": "google", + "defaultModel": "gemini-3.1-pro-preview-customtools", + "defaultThinkingLevel": "high", + "enabledModels": [ + "google/gemini-3.1-pro-preview-customtools:high", + "google/gemini-3-flash-preview:medium", + "google/gemini-2.5-pro:high" + ] + } + #+end_src **** Grok CLI setup Install [[https://grokcli.io/][grok-cli]] and ensure the `grok` executable is on your PATH. diff --git a/ai-code-backends-infra.el b/ai-code-backends-infra.el index 824c7596..2fdd6d6b 100644 --- a/ai-code-backends-infra.el +++ b/ai-code-backends-infra.el @@ -1827,6 +1827,8 @@ session buffer. :env-vars is an optional list of environment variable strings. :multiline-input-sequence is an optional terminal sequence for multiline input. +:post-start-fn is an optional function called with (BUFFER PROCESS +INSTANCE-NAME) after session creation. :prepare-launch is an optional function called with (WORKING-DIR ARGV) only when a new session is being created. When :prepare-launch is present, it may return :argv, :env-vars, @@ -1860,7 +1862,7 @@ A legacy :command entry is normalized to argv for compatibility." arg (plist-get options :env-vars) (plist-get options :multiline-input-sequence) - nil)))) + (plist-get options :post-start-fn))))) (defun ai-code-backends-infra--last-accessed-session-buffer (session-prefix) "Return the last accessed buffer when it belongs to SESSION-PREFIX." @@ -2108,6 +2110,9 @@ When PREFIX and WORKING-DIR are provided, select from multiple sessions." (select-window window)) (ai-code-backends-infra--display-buffer-in-side-window buffer)))) +(defvar ai-code-backends-infra--submit-return-function nil + "Optional function called instead of Return when submitting a prompt.") + (defun ai-code-backends-infra--submit-prompt (buffer prompt &optional source-buffer) "Submit PROMPT to the already chosen terminal BUFFER. Refresh MCP context from SOURCE-BUFFER, defaulting to the current buffer, @@ -2127,7 +2132,8 @@ Return result. This does not select a target or change window display." (ai-code-backends-infra--terminal-send-string prompt)) ;; Shorter delays can lose submissions in some CLI backends. (sit-for 0.5) - (ai-code-backends-infra--terminal-send-return)) + (funcall (or ai-code-backends-infra--submit-return-function + #'ai-code-backends-infra--terminal-send-return))) (ai-code-session-note-prompt buffer prompt) (setq ai-code-backends-infra--last-accessed-buffer buffer))) diff --git a/ai-code-mcp-agent.el b/ai-code-mcp-agent.el index d81c686a..f2eb720e 100644 --- a/ai-code-mcp-agent.el +++ b/ai-code-mcp-agent.el @@ -36,6 +36,35 @@ agent launch renews access." :type 'positive-integer :group 'ai-code-mcp-agent) +(defconst ai-code-mcp-agent--pi-valid-exposures + '("codemode" "deferred" "direct" "hidden") + "Exposure strings accepted by Pi's `registerMcpServer'.") + +(defcustom ai-code-mcp-agent-pi-exposure "codemode" + "Default tool exposure passed to `pi.registerMcpServer' for Emacs MCP tools. +\"codemode\" keeps most Emacs MCP schemas out of the direct tool list while +automatically enabling Pi's `codemode' script runner for parallel calls." + :type '(choice (const :tag "Codemode (script-callable)" "codemode") + (const :tag "Deferred (tool_search)" "deferred") + (const :tag "Direct (all tools declared)" "direct") + (const :tag "Hidden" "hidden")) + :group 'ai-code-mcp-agent) + +(defcustom ai-code-mcp-agent-pi-tool-exposure + '(("diagnostics_baseline" . "direct") + ("get_diagnostics" . "direct") + ("get_org_heading_context" . "direct")) + "Per-tool exposure overrides passed as `toolExposure' for Pi MCP sessions. +Each entry is `(TOOL-OR-PATTERN . EXPOSURE)', where EXPOSURE is one of +\"codemode\", \"deferred\", \"direct\", or \"hidden\". When nil, omit +`toolExposure' from the generated Pi extension." + :type '(alist :key-type string + :value-type (choice (const "codemode") + (const "deferred") + (const "direct") + (const "hidden"))) + :group 'ai-code-mcp-agent) + (defconst ai-code-mcp-agent--server-name "emacs_tools" "Server name used in backend MCP config overrides.") @@ -403,6 +432,34 @@ SERVER-WAS-LIVE records whether this launch started the shared HTTP server." token-env-var)))))))))))) config-file)) +(defun ai-code-mcp-agent--validate-pi-exposure (exposure) + "Return EXPOSURE when Pi accepts it, or signal an error." + (unless (and (stringp exposure) + (member exposure ai-code-mcp-agent--pi-valid-exposures)) + (error "Unsupported Pi MCP exposure: %S" exposure)) + exposure) + +(defun ai-code-mcp-agent--pi-tool-exposure-line (entries) + "Return the `toolExposure' property line for ENTRIES, or empty string." + (unless (listp entries) + (error "Invalid Pi MCP tool exposure list: %S" entries)) + (if (null entries) + "" + (let ((pairs + (mapcar + (lambda (entry) + (unless (and (consp entry) + (stringp (car entry)) + (not (string-empty-p (car entry)))) + (error "Invalid Pi MCP tool exposure entry: %S" entry)) + (format "%s: %s" + (json-encode (car entry)) + (json-encode + (ai-code-mcp-agent--validate-pi-exposure (cdr entry))))) + entries))) + (format " toolExposure: { %s },\n" + (mapconcat #'identity pairs ", "))))) + (defun ai-code-mcp-agent--pi-extension-source (url token-env-var) "Return Pi extension source registering the MCP server at URL. The extension reads the bearer token from TOKEN-ENV-VAR at runtime, so the @@ -410,7 +467,14 @@ secret never touches disk. Each Pi process gets its own extension file and token environment, which keeps concurrent Pi sessions independent." (let ((server-name (json-encode ai-code-mcp-agent--server-name)) (url-json (json-encode url)) - (env-json (json-encode token-env-var))) + (env-json (json-encode token-env-var)) + (exposure-json + (json-encode + (ai-code-mcp-agent--validate-pi-exposure + ai-code-mcp-agent-pi-exposure))) + (tool-exposure-line + (ai-code-mcp-agent--pi-tool-exposure-line + ai-code-mcp-agent-pi-tool-exposure))) (concat "// Generated by ai-code-mcp-agent.el for one Pi session.\n" "export default function (pi) {\n" @@ -425,7 +489,8 @@ token environment, which keeps concurrent Pi sessions independent." (format " pi.registerMcpServer(%s, {\n" server-name) (format " url: %s,\n" url-json) " headers: { Authorization: `Bearer ${token}` },\n" - " exposure: \"direct\",\n" + (format " exposure: %s,\n" exposure-json) + tool-exposure-line " description: \"Live Emacs editor, project, and debugging tools\"\n" " });\n" "}\n"))) diff --git a/ai-code-pi.el b/ai-code-pi.el index 09aef0ff..e9f331fd 100644 --- a/ai-code-pi.el +++ b/ai-code-pi.el @@ -11,6 +11,7 @@ ;;; Code: (require 'cl-lib) +(require 'subr-x) (require 'ai-code-backends) (require 'ai-code-backends-infra) (require 'ai-code-mcp-agent) @@ -49,9 +50,59 @@ The default uses the Kitty keyboard protocol sequence documented by Pi." :type 'string :group 'ai-code-pi) +(defcustom ai-code-pi-project-trust nil + "Project-local trust flag passed to Pi on startup. +When nil, pass no trust flag so Pi uses its own saved trust decisions and +prompt. `approve' passes `--approve' and `no-approve' passes +`--no-approve'. An explicit `-a', `--approve', `-na', or `--no-approve' in +`ai-code-pi-program-switches' takes precedence." + :type '(choice (const :tag "Use Pi's trust prompt/settings" nil) + (const :tag "Approve project resources (--approve)" approve) + (const :tag "Ignore project resources (--no-approve)" + no-approve)) + :group 'ai-code-pi) + +(defun ai-code-pi--default-follow-up-sequence (&optional platform) + "Return Pi's default follow-up key sequence for PLATFORM. +PLATFORM defaults to `system-type'. Pi binds follow-up to Ctrl+Q on +Windows and WSL, and to Alt+Enter elsewhere." + (let ((platform (or platform system-type))) + (if (or (eq platform 'windows-nt) + (and (eq platform 'gnu/linux) + (or (getenv "WSL_DISTRO_NAME") (getenv "WSL_INTEROP")))) + "\x11" + "\e[13;3u"))) + +(defcustom ai-code-pi-follow-up-sequence (ai-code-pi--default-follow-up-sequence) + "Terminal sequence Pi recognizes as its follow-up key. +Pi binds follow-up to Alt+Enter, or Ctrl+Q on Windows and WSL; it submits +immediately when idle and queues a follow-up when streaming or compacting. +Update this if you rebind `app.message.followUp' in Pi's keybindings." + :type 'string + :group 'ai-code-pi) + +(defcustom ai-code-pi-compose-sequence "\x07" + "Terminal sequence Pi recognizes as Ctrl+G to open its external editor." + :type 'string + :group 'ai-code-pi) + +(defcustom ai-code-pi-send-while-busy 'steer + "How `ai-code-pi-send-command' submits prompts to Pi. +`steer' sends standard Return, which steers Pi immediately when busy. +`followup' sends `ai-code-pi-follow-up-sequence' (Alt+Enter), which submits +immediately when idle and queues a follow-up until the current turn finishes." + :type '(choice (const :tag "Steer immediately with Return" steer) + (const :tag "Queue follow-up with Alt+Enter" followup)) + :group 'ai-code-pi) + (defconst ai-code-pi--session-prefix "pi" "Session prefix used in Pi buffer names.") +(defconst ai-code-pi--slash-commands + '("/model" "/thinking" "/scoped-models" "/tree" "/compact" + "/mcp" "/reload" "/settings" "/login" "/fork" "/new" "/resume") + "Common built-in Pi interactive slash commands offered for completion.") + (defvar ai-code-pi--processes (make-hash-table :test 'equal) "Hash table mapping Pi session keys to processes.") @@ -59,21 +110,68 @@ The default uses the Kitty keyboard protocol sequence documented by Pi." "Return non-nil when SWITCH selects Pi's TUI mode." (string-match-p "\\`--tui-mode\\(?:=\\|\\'\\)" switch)) +(defun ai-code-pi--project-trust-switch-p (switch) + "Return non-nil when SWITCH selects Pi's project trust mode." + (member switch '("-a" "--approve" "-na" "--no-approve"))) + +(defun ai-code-pi--project-trust-switches (switches) + "Return project-trust flag list to append to SWITCHES." + (pcase ai-code-pi-project-trust + ('nil nil) + ('approve + (unless (cl-some #'ai-code-pi--project-trust-switch-p switches) + '("--approve"))) + ('no-approve + (unless (cl-some #'ai-code-pi--project-trust-switch-p switches) + '("--no-approve"))) + (_ (user-error "Unsupported `ai-code-pi-project-trust': %S" + ai-code-pi-project-trust)))) + (defun ai-code-pi--startup-switches (switches) - "Return SWITCHES with `ai-code-pi-tui-mode' applied. -SWITCHES that already select a TUI mode are returned unchanged." - (if (or (null ai-code-pi-tui-mode) - (cl-some #'ai-code-pi--tui-mode-switch-p switches)) - switches - (append switches - (list "--tui-mode" (symbol-name ai-code-pi-tui-mode))))) + "Return SWITCHES with `ai-code-pi-tui-mode' and trust options applied. +SWITCHES that already select a TUI mode or project trust mode take +precedence over the corresponding option." + (let ((with-tui + (if (or (null ai-code-pi-tui-mode) + (cl-some #'ai-code-pi--tui-mode-switch-p switches)) + switches + (append switches + (list "--tui-mode" (symbol-name ai-code-pi-tui-mode)))))) + (append with-tui (ai-code-pi--project-trust-switches with-tui)))) + +(defun ai-code-pi--submit-return-fn (mode) + "Return the terminal submit function for Pi send MODE." + (pcase mode + ('steer #'ai-code-backends-infra--terminal-send-return) + ('followup #'ai-code-pi-terminal-send-follow-up) + (_ (user-error "Unsupported `ai-code-pi-send-while-busy': %S" mode)))) + +(defun ai-code-pi--viewport-submit () + "Submit restored Pi editor-viewport input per `ai-code-pi-send-while-busy'." + (funcall (ai-code-pi--submit-return-fn ai-code-pi-send-while-busy))) + +(defun ai-code-pi--configure-session-buffer (buffer _process _instance-name) + "Configure Pi-specific keybindings and viewport submission in BUFFER." + (with-current-buffer buffer + (define-key (ai-code-backends-infra--session-keymap) + (kbd "M-") + #'ai-code-pi-terminal-send-follow-up) + (setq-local ai-code-editor-viewport--submit-function + #'ai-code-pi--viewport-submit))) + +(defun ai-code-pi--session-buffer-p (buffer) + "Return non-nil when BUFFER is a live Pi session buffer." + (and (buffer-live-p buffer) + (with-current-buffer buffer + (equal ai-code-backends-infra--session-prefix + ai-code-pi--session-prefix)))) ;;;###autoload (defun ai-code-pi-start (&optional arg) "Start Pi using `ai-code-backends-infra' logic. With prefix ARG, prompt for CLI args using -`ai-code-pi-program-switches', plus the `ai-code-pi-tui-mode' flag, as -the default input." +`ai-code-pi-program-switches', plus the `ai-code-pi-tui-mode' and +`ai-code-pi-project-trust' flags, as the default input." (interactive "P") (ai-code-backends-infra--start-cli-session (list :program ai-code-pi-program @@ -83,6 +181,7 @@ the default input." :session-prefix ai-code-pi--session-prefix :escape-function #'ai-code-pi-send-escape :multiline-input-sequence ai-code-pi-multiline-input-sequence + :post-start-fn #'ai-code-pi--configure-session-buffer :prepare-launch (lambda (working-dir argv) (ai-code-mcp-agent-prepare-launch 'pi working-dir argv))) @@ -98,11 +197,13 @@ When FORCE-PROMPT is non-nil, prompt to select a session." ;;;###autoload (defun ai-code-pi-send-command (line) - "Send LINE to Pi. + "Send LINE to Pi according to `ai-code-pi-send-while-busy'. When called interactively, prompt for the command." (interactive "sPi> ") - (ai-code-backends-infra--cli-send-command - "Pi" ai-code-pi--session-prefix line)) + (let ((ai-code-backends-infra--submit-return-function + (ai-code-pi--submit-return-fn ai-code-pi-send-while-busy))) + (ai-code-backends-infra--cli-send-command + "Pi" ai-code-pi--session-prefix line))) ;;;###autoload (defun ai-code-pi-send-escape () @@ -128,6 +229,74 @@ session directly. Otherwise ARG is passed to the underlying start function." (ai-code-backends-infra--cli-show-resume-picker ai-code-pi--session-prefix)))) +;;;###autoload +(defun ai-code-pi-terminal-send-follow-up () + "Send `ai-code-pi-follow-up-sequence' to Pi in the current session buffer." + (interactive) + (when (fboundp 'ai-code-mcp-agent-touch-session) + (ai-code-mcp-agent-touch-session (current-buffer))) + (ai-code-backends-infra--terminal-send-string + ai-code-pi-follow-up-sequence)) + +;;;###autoload +(defun ai-code-pi-send-follow-up (line) + "Send LINE to Pi using `ai-code-pi-follow-up-sequence' (Alt+Enter). +Submits immediately when Pi is idle and queues a follow-up when busy." + (interactive "sPi follow-up> ") + (let ((ai-code-backends-infra--submit-return-function + #'ai-code-pi-terminal-send-follow-up)) + (ai-code-backends-infra--cli-send-command + "Pi" ai-code-pi--session-prefix line))) + +;;;###autoload +(defun ai-code-pi-compose (&optional force-prompt) + "Open Pi's external editor viewport for the active project session. +When FORCE-PROMPT is non-nil, prompt to select among multiple Pi sessions." + (interactive "P") + (let* ((source-buffer (current-buffer)) + (in-pi-session (ai-code-pi--session-buffer-p source-buffer)) + (working-dir (and (or force-prompt (not in-pi-session)) + (ai-code-backends-infra--session-working-directory))) + (buffer (if (and in-pi-session (not force-prompt)) + source-buffer + (ai-code-backends-infra--resolve-session-buffer + nil + "No Pi session for this project" + ai-code-pi--session-prefix + working-dir + force-prompt + source-buffer)))) + (when working-dir + (with-current-buffer buffer + (ai-code-backends-infra--remember-session-buffer + ai-code-pi--session-prefix working-dir buffer))) + (unless (eq buffer source-buffer) + (ai-code-mcp-agent-refresh-source-context buffer source-buffer)) + (ai-code-mcp-agent-touch-session buffer) + (with-current-buffer buffer + (ai-code-backends-infra--terminal-send-string + ai-code-pi-compose-sequence)) + (setq ai-code-backends-infra--last-accessed-buffer buffer))) + +;;;###autoload +(defun ai-code-pi-slash-command (command) + "Send slash COMMAND to Pi using standard Return. +Leading `/' is added when omitted." + (interactive + (list (completing-read "Pi slash command: " + ai-code-pi--slash-commands + nil nil "/"))) + (let ((trimmed (string-trim (or command "")))) + (when (string-empty-p trimmed) + (user-error "Pi slash command cannot be empty")) + (let ((normalized (if (string-prefix-p "/" trimmed) + trimmed + (concat "/" trimmed))) + (ai-code-backends-infra--submit-return-function + #'ai-code-backends-infra--terminal-send-return)) + (ai-code-backends-infra--cli-send-command + "Pi" ai-code-pi--session-prefix normalized)))) + (provide 'ai-code-pi) ;;; ai-code-pi.el ends here diff --git a/test/test_ai-code-backends-infra.el b/test/test_ai-code-backends-infra.el index 8fabd619..5775b288 100644 --- a/test/test_ai-code-backends-infra.el +++ b/test/test_ai-code-backends-infra.el @@ -478,6 +478,47 @@ the platform makes the literal path a symlink, such as /tmp on macOS." (should (eq (nth 9 captured) cleanup-fn)) (should (eq (nth 11 captured) post-start-fn)))) +(ert-deftest test-ai-code-backends-infra-start-cli-session-composes-post-start-fns () + "Deferred launch preparation should run its post-start hook before options." + (let* ((working-dir "/tmp/ai-code-compose-post-start/") + (process-table (make-hash-table :test 'equal)) + (call-order nil) + captured-post-start) + (cl-letf (((symbol-function 'ai-code-backends-infra--session-working-directory) + (lambda (&optional _prompt-p) working-dir)) + ((symbol-function 'ai-code-backends-infra--resolve-start-command) + (lambda (&rest _args) '(:argv ("pi")))) + ((symbol-function 'ai-code-backends-infra--resolve-session-target) + (lambda (&rest _args) + (list :instance-name "default" + :buffer-name "*pi[ai-code-compose-post-start]*" + :session-key + (cons (test-ai-code-backends-infra--session-dir working-dir) + "default")))) + ((symbol-function 'ai-code-backends-infra--create-new-session) + (lambda (&rest args) + (setq captured-post-start (nth 11 args))))) + (ai-code-backends-infra--start-cli-session + (list :program "pi" + :label "Pi" + :process-table process-table + :session-prefix "pi" + :post-start-fn + (lambda (buffer process instance) + (push (list 'options buffer process instance) call-order)) + :prepare-launch + (lambda (_dir argv) + (list :argv argv + :post-start-fn + (lambda (buffer process instance) + (push (list 'launch buffer process instance) call-order))))) + nil)) + (should (functionp captured-post-start)) + (funcall captured-post-start 'buf 'proc "default") + (should (equal (nreverse call-order) + '((launch buf proc "default") + (options buf proc "default")))))) + (ert-deftest test-ai-code-backends-infra-start-cli-session-prompts-dir-after-args () "Working directory prompting should happen after CLI args prompting. The prefix argument should also force instance-name prompting." diff --git a/test/test_ai-code-mcp-agent.el b/test/test_ai-code-mcp-agent.el index 691022a7..17c08a08 100644 --- a/test/test_ai-code-mcp-agent.el +++ b/test/test_ai-code-mcp-agent.el @@ -813,16 +813,53 @@ (should (memq 'pi (default-value 'ai-code-mcp-agent-enabled-backends)))) (ert-deftest ai-code-test-mcp-agent-pi-extension-source-reads-token-from-env () - "Pi extension should read the token from the environment, not embed it." + "Pi extension should read token from env and expose codemode plus anchors." (let ((source (ai-code-mcp-agent--pi-extension-source "http://127.0.0.1:8765/mcp" "AI_CODE_MCP_BEARER_TOKEN"))) (should (string-match-p "registerMcpServer(\"emacs_tools\"" source)) (should (string-match-p "url: \"http://127.0.0.1:8765/mcp\"" source)) (should (string-match-p "process.env\\[\"AI_CODE_MCP_BEARER_TOKEN\"\\]" source)) - (should (string-match-p "exposure: \"direct\"" source)) + (should (string-match-p "exposure: \"codemode\"" source)) + (should (string-match-p "\"diagnostics_baseline\" *: *\"direct\"" source)) + (should (string-match-p "\"get_diagnostics\" *: *\"direct\"" source)) + (should (string-match-p "\"get_org_heading_context\" *: *\"direct\"" source)) (should (string-match-p "typeof pi.registerMcpServer" source)))) +(ert-deftest ai-code-test-mcp-agent-pi-extension-source-respects-custom-exposure () + "Pi extension should honor custom exposure and omit empty toolExposure." + (let* ((ai-code-mcp-agent-pi-exposure "direct") + (ai-code-mcp-agent-pi-tool-exposure nil) + (source (ai-code-mcp-agent--pi-extension-source + "http://127.0.0.1:8765/mcp" "AI_CODE_MCP_BEARER_TOKEN"))) + (should (string-match-p "exposure: \"direct\"" source)) + (should-not (string-match-p "toolExposure" source)))) + +(ert-deftest ai-code-test-mcp-agent-pi-extension-source-rejects-invalid-exposure () + "Pi extension should fail closed on invalid exposures and serialize valid ones." + (dolist (valid '("codemode" "deferred" "direct" "hidden")) + (let* ((ai-code-mcp-agent-pi-exposure valid) + (ai-code-mcp-agent-pi-tool-exposure + (list (cons "get_*" valid) + (cons "buffer_query" "codemode"))) + (source (ai-code-mcp-agent--pi-extension-source + "http://127.0.0.1:8765/mcp" "AI_CODE_MCP_BEARER_TOKEN"))) + (should (string-match-p (format "exposure: %S" valid) source)) + (should (string-match-p (format "\"get_\\*\" *: *%S" valid) source)) + (should (string-match-p "\"buffer_query\" *: *\"codemode\"" source)))) + (let ((ai-code-mcp-agent-pi-exposure "bogus")) + (should-error + (ai-code-mcp-agent--pi-extension-source + "http://127.0.0.1:8765/mcp" "AI_CODE_MCP_BEARER_TOKEN"))) + (let ((ai-code-mcp-agent-pi-tool-exposure '(("get_diagnostics" . "bogus")))) + (should-error + (ai-code-mcp-agent--pi-extension-source + "http://127.0.0.1:8765/mcp" "AI_CODE_MCP_BEARER_TOKEN"))) + (let ((ai-code-mcp-agent-pi-tool-exposure '(("" . "direct")))) + (should-error + (ai-code-mcp-agent--pi-extension-source + "http://127.0.0.1:8765/mcp" "AI_CODE_MCP_BEARER_TOKEN")))) + (ert-deftest ai-code-test-mcp-agent-pi-launch-adds-extension-and-cleans-up () "Pi launch should append a temp extension and remove it on cleanup." (let ((ai-code-mcp-agent-enabled-backends '(pi)) diff --git a/test/test_ai-code-pi.el b/test/test_ai-code-pi.el index d62e975f..f6b11f35 100644 --- a/test/test_ai-code-pi.el +++ b/test/test_ai-code-pi.el @@ -60,6 +60,30 @@ (should (equal (ai-code-pi--startup-switches '("--tui-modes")) '("--tui-modes" "--tui-mode" "regular"))))) +(ert-deftest ai-code-test-pi-startup-switches-stay-model-and-trust-neutral () + "Default startup switches must not auto-inject Gemini or trust flags." + (let ((process-environment (cons "GEMINI_API_KEY=test-key" + process-environment)) + (ai-code-pi-tui-mode 'regular) + (ai-code-pi-project-trust nil)) + (should (equal (ai-code-pi--startup-switches nil) + '("--tui-mode" "regular"))))) + +(ert-deftest ai-code-test-pi-startup-switches-project-trust-and-precedence () + "Project trust option should append flags unless switches already set trust." + (let ((ai-code-pi-tui-mode 'regular)) + (let ((ai-code-pi-project-trust 'approve)) + (should (equal (ai-code-pi--startup-switches '("--offline")) + '("--offline" "--tui-mode" "regular" "--approve"))) + (dolist (explicit '("-a" "--approve" "-na" "--no-approve")) + (should (equal (ai-code-pi--startup-switches (list explicit)) + (list explicit "--tui-mode" "regular"))))) + (let ((ai-code-pi-project-trust 'no-approve)) + (should (equal (ai-code-pi--startup-switches nil) + '("--tui-mode" "regular" "--no-approve")))) + (let ((ai-code-pi-project-trust 'invalid)) + (should-error (ai-code-pi--startup-switches nil))))) + (ert-deftest ai-code-test-pi-resume-passes-tui-mode-after-resume () "Pi resume should keep --resume and still apply the TUI mode." (let (captured-options) @@ -134,6 +158,234 @@ '(:argv ("pi" "--extension" "x.js")))) (should (equal captured-call '(pi "/tmp/" ("pi")))))))) +(ert-deftest ai-code-test-pi-default-follow-up-sequence-matches-pi-platform-keys () + "Follow-up should use Ctrl+Q where Pi uses Windows keybindings." + (let ((process-environment + (cl-remove-if (lambda (entry) + (string-match-p "\\`WSL_\\(?:DISTRO_NAME\\|INTEROP\\)=" + entry)) + process-environment))) + (should (equal (ai-code-pi--default-follow-up-sequence 'darwin) + "\e[13;3u")) + (should (equal (ai-code-pi--default-follow-up-sequence 'gnu/linux) + "\e[13;3u")) + (should (equal (ai-code-pi--default-follow-up-sequence 'windows-nt) + "\x11")) + (dolist (var '("WSL_DISTRO_NAME" "WSL_INTEROP")) + (let ((process-environment (cons (concat var "=x") process-environment))) + (should (equal (ai-code-pi--default-follow-up-sequence 'gnu/linux) + "\x11")) + (should (equal (ai-code-pi--default-follow-up-sequence 'darwin) + "\e[13;3u")))))) + +(ert-deftest ai-code-test-pi-send-command-respects-busy-policy-and-follow-up () + "Send commands should use Return for steer and Alt+Enter for followup." + ;; Loading `ai-code-pi' must not intern bare `follow-up' into `obarray', + ;; which would make `ai-code-session-link' linkify English prose "follow-up". + (should-not (intern-soft "follow-up")) + (let ((session-buffer (generate-new-buffer " *pi[test-send]*")) + sent-events + touched-buffers) + (unwind-protect + (with-temp-buffer + (cl-letf (((symbol-function 'ai-code-backends-infra--session-working-directory) + (lambda (&optional _prompt) "/tmp/proj/")) + ((symbol-function 'ai-code-backends-infra--resolve-session-buffer) + (lambda (&rest _args) session-buffer)) + ((symbol-function 'ai-code-backends-infra--remember-session-buffer) + #'ignore) + ((symbol-function 'ai-code-mcp-agent-refresh-source-context) + #'ignore) + ((symbol-function 'ai-code-mcp-agent-touch-session) + (lambda (buf) (push buf touched-buffers))) + ((symbol-function 'ai-code-session-note-prompt) + #'ignore) + ((symbol-function 'sit-for) + #'ignore) + ((symbol-function 'ai-code-backends-infra--terminal-send-string) + (lambda (str &optional _paste) + (push (cons 'string str) sent-events))) + ((symbol-function 'ai-code-backends-infra--terminal-send-return) + (lambda () + (push '(return) sent-events)))) + (let ((ai-code-pi-send-while-busy 'steer) + (ai-code-pi-follow-up-sequence "\e[13;3u")) + (ai-code-pi-send-command "fix bug") + (should (equal (nreverse sent-events) + '((string . "fix bug") (return)))) + (setq sent-events nil + touched-buffers nil) + (ai-code-pi-send-follow-up "queued item") + (should (equal (nreverse sent-events) + '((string . "queued item") + (string . "\e[13;3u")))) + (should (equal touched-buffers (list session-buffer)))) + (setq sent-events nil + touched-buffers nil) + (let ((ai-code-pi-send-while-busy 'followup) + (ai-code-pi-follow-up-sequence "\e[13;3u")) + (ai-code-pi-send-command "next step") + (should (equal (nreverse sent-events) + '((string . "next step") + (string . "\e[13;3u")))) + (should (equal touched-buffers (list session-buffer)))) + (let ((ai-code-pi-send-while-busy 'bogus)) + (should-error (ai-code-pi-send-command "bad") + :type 'user-error)))) + (when (buffer-live-p session-buffer) + (kill-buffer session-buffer))))) + +(ert-deftest ai-code-test-pi-post-start-chains-mcp-and-binds-follow-up-key () + "Pi startup should chain MCP post-start, bind M-RET, and wire viewport submit." + (let ((session-buffer (generate-new-buffer " *pi[test-post-start]*")) + captured-post-start + mcp-post-start-args + sent-events) + (unwind-protect + (progn + (cl-letf (((symbol-function 'ai-code-backends-infra--resolve-start-command) + (lambda (program switches _arg _label) + (list :argv (cons program switches)))) + ((symbol-function 'ai-code-backends-infra--session-working-directory) + (lambda (&optional _prompt) "/tmp/proj/")) + ((symbol-function 'ai-code-mcp-agent-prepare-launch) + (lambda (_backend _dir argv) + (list :argv argv + :post-start-fn + (lambda (buf proc inst) + (setq mcp-post-start-args + (list buf proc inst)))))) + ((symbol-function 'ai-code-backends-infra--create-new-session) + (lambda (_buffer-name _working-dir _command _env-vars + _session-key _process-table + _resolved-instance _prefix + _escape-fn _cleanup-fn + _multiline-input-sequence + post-start-fn + &rest _rest) + (setq captured-post-start post-start-fn) + nil)) + ((symbol-function 'ai-code-mcp-agent-touch-session) + #'ignore) + ((symbol-function 'ai-code-backends-infra--terminal-send-string) + (lambda (str &optional _paste) + (push (cons 'string str) sent-events))) + ((symbol-function 'ai-code-backends-infra--terminal-send-return) + (lambda () + (push '(return) sent-events)))) + (let ((ai-code-pi--processes (make-hash-table :test 'equal))) + (ai-code-pi-start)) + (should (functionp captured-post-start)) + (ai-code-backends-infra--configure-session-buffer + session-buffer #'ai-code-pi-send-escape "\e[13;2u") + (funcall captured-post-start session-buffer 'fake-proc "main") + (should (equal mcp-post-start-args + (list session-buffer 'fake-proc "main"))) + (with-current-buffer session-buffer + (should (eq (lookup-key (ai-code-backends-infra--session-keymap) + (kbd "M-")) + #'ai-code-pi-terminal-send-follow-up)) + (let ((ai-code-pi-send-while-busy 'steer)) + (funcall ai-code-editor-viewport--submit-function) + (should (equal sent-events '((return))))) + (setq sent-events nil) + (let ((ai-code-pi-send-while-busy 'followup) + (ai-code-pi-follow-up-sequence "\e[13;3u")) + (funcall ai-code-editor-viewport--submit-function) + (should (equal sent-events '((string . "\e[13;3u")))))))) + (when (buffer-live-p session-buffer) + (kill-buffer session-buffer))))) + +(ert-deftest ai-code-test-pi-compose-sends-ctrl-g-and-refreshes-context () + "Compose command should send Ctrl+G, refresh source context, and fail cleanly." + (let ((session-buffer (generate-new-buffer "*pi[proj]*")) + refreshed + touched + sent-in-buffer) + (unwind-protect + (progn + (with-current-buffer session-buffer + (setq-local ai-code-backends-infra--session-prefix "pi")) + (with-temp-buffer + (let ((source-buffer (current-buffer)) + (ai-code-pi-compose-sequence "\x07")) + (cl-letf (((symbol-function 'ai-code-backends-infra--session-working-directory) + (lambda (&optional _prompt) "/tmp/proj/")) + ((symbol-function 'ai-code-backends-infra--resolve-session-buffer) + (lambda (_buf-name missing-msg &rest _rest) + (or session-buffer (user-error "%s" missing-msg)))) + ((symbol-function 'ai-code-backends-infra--remember-session-buffer) + #'ignore) + ((symbol-function 'ai-code-mcp-agent-refresh-source-context) + (lambda (agent-buf src-buf) + (push (list agent-buf src-buf) refreshed))) + ((symbol-function 'ai-code-mcp-agent-touch-session) + (lambda (buf) (push buf touched))) + ((symbol-function 'ai-code-backends-infra--terminal-send-string) + (lambda (str &optional _paste) + (push (list (current-buffer) str) sent-in-buffer)))) + (ai-code-pi-compose) + (should (equal refreshed + (list (list session-buffer source-buffer)))) + (should (equal touched (list session-buffer))) + (should (equal sent-in-buffer + (list (list session-buffer "\x07")))) + ;; Invoking directly inside the Pi session buffer should not + ;; overwrite source context with the terminal buffer itself. + (setq refreshed nil + touched nil + sent-in-buffer nil) + (with-current-buffer session-buffer + (ai-code-pi-compose)) + (should-not refreshed) + (should (equal touched (list session-buffer))) + (should (equal sent-in-buffer + (list (list session-buffer "\x07")))) + ;; Missing session should signal user-error. + (setq session-buffer nil) + (should-error (ai-code-pi-compose) :type 'user-error))))) + (when (and session-buffer (buffer-live-p session-buffer)) + (kill-buffer session-buffer))))) + +(ert-deftest ai-code-test-pi-slash-command-normalizes-and-uses-standard-return () + "Slash commands should prefix `/', reject blanks, and always use Return." + (let ((session-buffer (generate-new-buffer " *pi[test-slash]*")) + sent-events) + (unwind-protect + (with-temp-buffer + (cl-letf (((symbol-function 'ai-code-backends-infra--session-working-directory) + (lambda (&optional _prompt) "/tmp/proj/")) + ((symbol-function 'ai-code-backends-infra--resolve-session-buffer) + (lambda (&rest _args) session-buffer)) + ((symbol-function 'ai-code-backends-infra--remember-session-buffer) + #'ignore) + ((symbol-function 'ai-code-mcp-agent-refresh-source-context) + #'ignore) + ((symbol-function 'ai-code-session-note-prompt) + #'ignore) + ((symbol-function 'sit-for) + #'ignore) + ((symbol-function 'ai-code-backends-infra--terminal-send-string) + (lambda (str &optional _paste) + (push (cons 'string str) sent-events))) + ((symbol-function 'ai-code-backends-infra--terminal-send-return) + (lambda () + (push '(return) sent-events)))) + (let ((ai-code-pi-send-while-busy 'followup)) + (ai-code-pi-slash-command "model") + (should (equal (nreverse sent-events) + '((string . "/model") (return)))) + (setq sent-events nil) + (ai-code-pi-slash-command " /compact focus ") + (should (equal (nreverse sent-events) + '((string . "/compact focus") (return)))) + (setq sent-events nil) + (should-error (ai-code-pi-slash-command " ") + :type 'user-error) + (should-not sent-events)))) + (when (buffer-live-p session-buffer) + (kill-buffer session-buffer))))) + (provide 'test_ai-code-pi) ;;; test_ai-code-pi.el ends here