Liking cljdoc? Tell your friends :D

User prompt submitted hook

The onUserPromptSubmitted hook is called when a user submits a message. Use it to:

  • Modify or enhance user prompts
  • Add context before processing
  • Filter or validate user input
  • Implement prompt templates

Hook signature

Node.js / TypeScript
import type { UserPromptSubmittedHookInput, HookInvocation, UserPromptSubmittedHookOutput } from "copilot-sdk-supercharged";
type UserPromptSubmittedHandler = (
  input: UserPromptSubmittedHookInput,
  invocation: HookInvocation
) => Promise<UserPromptSubmittedHookOutput | null | undefined>;
type UserPromptSubmittedHandler = (
  input: UserPromptSubmittedHookInput,
  invocation: HookInvocation
) => Promise<UserPromptSubmittedHookOutput | null | undefined>;
Python
from copilot.session import UserPromptSubmittedHookInput, UserPromptSubmittedHookOutput
from copilot.session import UserPromptSubmittedHandler as SdkUserPromptSubmittedHandler
from typing import Callable, Awaitable

UserPromptSubmittedHandler = Callable[
    [UserPromptSubmittedHookInput, dict[str, str]],
    Awaitable[UserPromptSubmittedHookOutput | None]
]

def check(handler: UserPromptSubmittedHandler) -> SdkUserPromptSubmittedHandler:
    return handler
UserPromptSubmittedHandler = Callable[
    [UserPromptSubmittedHookInput, dict[str, str]],
    Awaitable[UserPromptSubmittedHookOutput | None]
]
Go
package main

import copilot "github.com/microsoft/copilot-sdk/go/v2"

// Aliases let the signature below use the package's own type names.
type (
    UserPromptSubmittedHookInput  = copilot.UserPromptSubmittedHookInput
    HookInvocation                = copilot.HookInvocation
    UserPromptSubmittedHookOutput = copilot.UserPromptSubmittedHookOutput
)

type UserPromptSubmittedHandler func(
    input UserPromptSubmittedHookInput,
    invocation HookInvocation,
) (*UserPromptSubmittedHookOutput, error)

var _ = copilot.UserPromptSubmittedHandler(UserPromptSubmittedHandler(nil))

func main() {}
type UserPromptSubmittedHandler func(
    input UserPromptSubmittedHookInput,
    invocation HookInvocation,
) (*UserPromptSubmittedHookOutput, error)
.NET
using Microsoft.Copilot;

public delegate Task<UserPromptSubmittedHookOutput?> UserPromptSubmittedHandler(
    UserPromptSubmittedHookInput input,
    HookInvocation invocation);

static class UserPromptSubmittedHandlerCheck
{
    static SessionHooks Check(UserPromptSubmittedHandler handler) =>
        new() { OnUserPromptSubmitted = handler.Invoke };
}
public delegate Task<UserPromptSubmittedHookOutput?> UserPromptSubmittedHandler(
    UserPromptSubmittedHookInput input,
    HookInvocation invocation);
Java
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

public class UserPromptSubmittedSignature {
    static class Documented {
        @FunctionalInterface
        public interface UserPromptSubmittedHandler {
            CompletableFuture<UserPromptSubmittedHookOutput> handle(
                UserPromptSubmittedHookInput input,
                HookInvocation invocation);
        }
    }

    // The documented interface and the SDK's accept each other's implementations.
    static UserPromptSubmittedHandler toSdk(Documented.UserPromptSubmittedHandler documented) {
        return documented::handle;
    }

    static Documented.UserPromptSubmittedHandler fromSdk(UserPromptSubmittedHandler sdk) {
        return sdk::handle;
    }

    public static void main(String[] args) {}
}
@FunctionalInterface
public interface UserPromptSubmittedHandler {
    CompletableFuture<UserPromptSubmittedHookOutput> handle(
        UserPromptSubmittedHookInput input,
        HookInvocation invocation);
}

40 languages supported. See the full SDK list with cookbooks for Objective-C, F#, Groovy, Julia, COBOL, OCaml, Zig, Nim, D, Erlang, Crystal, Tcl, Solidity, V, and 18 more.

Input

FieldTypeDescription
timestampSDK timestamp typeWhen the hook was triggered
workingDirectorystringCurrent working directory
promptstringThe user's submitted prompt

Output

Return null or undefined to use the prompt unchanged. Otherwise, return an object with any of these fields:

FieldTypeDescription
modifiedPromptstringModified prompt to use instead of original
additionalContextstringExtra context added to the conversation
suppressOutputbooleanIf true, suppress the assistant's response output
decision"block"Refuse the prompt (see Blocking a prompt)
reasonstringWhy the prompt was blocked; required with decision

Blocking a prompt

Return a block decision to refuse the prompt:

{
  "decision": "block",
  "reason": "Prompts may not include credentials."
}

No model turn runs and no user message is recorded. The session emits an ephemeral session.warning with warningType: "policy_blocked" that carries the reason. The public member names follow each language's conventions:

MeaningNode.js / PythonGo / .NETRustJava
Block the promptdecision: "block"Decision = "block"decision: Some("block".into())UserPromptSubmittedHookOutput.block(reason)
Why it was blockedreasonReasonreasonthe reason argument

In Go, an empty Reason is omitted from the output, and the prompt is blocked only when a reason is present.

Examples

Log all user prompts

Node.js / TypeScript
const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input, invocation) => {
                console.log(`[${invocation.sessionId}] User: ${input.prompt}`);
                return null; // Pass through unchanged
            },
        },
    },
});
Python
from copilot import CopilotClient
from copilot.session import PermissionHandler

client = CopilotClient(mode="coding-agent")


async def on_user_prompt_submitted(input_data, invocation):
    print(f"[{invocation['session_id']}] User: {input_data['prompt']}")
    return None


session = await client.create_session(
    permissions={"on_request": PermissionHandler.approve_all},
    hooks={"handlers": {"on_user_prompt_submitted": on_user_prompt_submitted}},
)
Go
package main

import (
	"context"
	"fmt"
	copilot "github.com/microsoft/copilot-sdk/go/v2"
)

func main() {
	client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})
	session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{
		Hooks: copilot.SessionHookOptions{
			Handlers: &copilot.SessionHooks{
				OnUserPromptSubmitted: func(input copilot.UserPromptSubmittedHookInput, inv copilot.HookInvocation) (*copilot.UserPromptSubmittedHookOutput, error) {
					fmt.Printf("[%s] User: %s\n", inv.SessionID, input.Prompt)
					return nil, nil
				},
			},
		},
	})
	_ = session
}
session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{
	Hooks: copilot.SessionHookOptions{
		Handlers: &copilot.SessionHooks{
			OnUserPromptSubmitted: func(input copilot.UserPromptSubmittedHookInput, inv copilot.HookInvocation) (*copilot.UserPromptSubmittedHookOutput, error) {
				fmt.Printf("[%s] User: %s\n", inv.SessionID, input.Prompt)
				return nil, nil
			},
		},
	},
})

.NET
var session = await client.CreateSessionAsync(new CreateSessionOptions
{
    Hooks = new SessionHookOptions
    {
        Handlers = new SessionHooks
        {
            OnUserPromptSubmitted = (input, invocation) =>
            {
                Console.WriteLine($"[{invocation.SessionId}] User: {input.Prompt}");
                return Task.FromResult<UserPromptSubmittedHookOutput?>(null);
            },
        }
    }
});
Java
import com.microsoft.copilot.*;
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

public class UserPromptSubmittedExample {
    public static void main(String[] args) throws Exception {
        try (var client = new CopilotClient(new CopilotClientOptions().setMode(CopilotClientMode.CODING_AGENT))) {
            var hooks = new SessionHooks()
                    .setOnUserPromptSubmitted((input, invocation) -> {
                        System.out
                                .println("[" + invocation
                                        .getSessionId() + "] User: "
                                        + input
                                                .prompt());
                        return CompletableFuture
                                .completedFuture(null);
                    });

            var session = client
                    .createSession(new CreateSessionOptions()
                            .setPermissions(new SessionPermissionOptions()
                                    .setOnRequest(PermissionHandler.APPROVE_ALL))
                            .setHooks(new SessionHookOptions()
                                    .setHandlers(hooks)))
                    .get();
        }
    }
}
import com.microsoft.copilot.*;
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

var hooks = new SessionHooks()
        .setOnUserPromptSubmitted((input, invocation) -> {
            System.out
                    .println("[" + invocation
                            .getSessionId() + "] User: "
                            + input
                                    .prompt());
            return CompletableFuture
                    .completedFuture(null);
        });

var session = client
        .createSession(new CreateSessionOptions()
                .setPermissions(new SessionPermissionOptions()
                        .setOnRequest(PermissionHandler.APPROVE_ALL))
                .setHooks(new SessionHookOptions()
                        .setHandlers(hooks)))
        .get();

Add project context

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                const projectInfo = await getProjectInfo();

                return {
                    additionalContext: `
Project: ${projectInfo.name}
Language: ${projectInfo.language}
Framework: ${projectInfo.framework}
        `.trim(),
                };
            },
        },
    },
});

Expand shorthand commands

const SHORTCUTS: Record<string, string> = {
    "/fix": "Please fix the errors in the code",
    "/explain": "Please explain this code in detail",
    "/test": "Please write unit tests for this code",
    "/refactor": "Please refactor this code to improve readability and maintainability",
};

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                for (const [shortcut, expansion] of Object.entries(SHORTCUTS)) {
                    if (input.prompt.startsWith(shortcut)) {
                        const rest = input.prompt.slice(shortcut.length).trim();
                        return {
                            modifiedPrompt: `${expansion}${rest ? `: ${rest}` : ""}`,
                        };
                    }
                }
                return null;
            },
        },
    },
});

Content filtering

const BLOCKED_PATTERNS = [/password\s*[:=]/i, /api[_-]?key\s*[:=]/i, /secret\s*[:=]/i];

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                for (const pattern of BLOCKED_PATTERNS) {
                    if (pattern.test(input.prompt)) {
                        // Refuse the prompt; the reason reaches the client as a session.warning
                        return {
                            decision: "block",
                            reason: "Please don't include sensitive credentials in your prompts. Use environment variables instead.",
                        };
                    }
                }
                return null;
            },
        },
    },
});

Enforce prompt length limits

const MAX_PROMPT_LENGTH = 10000;

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                if (input.prompt.length > MAX_PROMPT_LENGTH) {
                    // Truncate the prompt and add context
                    return {
                        modifiedPrompt: input.prompt.substring(0, MAX_PROMPT_LENGTH),
                        additionalContext: `Note: The original prompt was ${input.prompt.length} characters and was truncated to ${MAX_PROMPT_LENGTH} characters.`,
                    };
                }
                return null;
            },
        },
    },
});

Add user preferences

interface UserPreferences {
    codeStyle: "concise" | "verbose";
    preferredLanguage: string;
    experienceLevel: "beginner" | "intermediate" | "expert";
}

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                const prefs: UserPreferences = await loadUserPreferences();

                const contextParts = [];

                if (prefs.codeStyle === "concise") {
                    contextParts.push("User prefers concise code with minimal comments.");
                } else {
                    contextParts.push("User prefers verbose code with detailed comments.");
                }

                if (prefs.experienceLevel === "beginner") {
                    contextParts.push("Explain concepts in simple terms.");
                }

                return {
                    additionalContext: contextParts.join(" "),
                };
            },
        },
    },
});

Usage threshold notices

const promptTimestamps: number[] = [];
const NOTICE_THRESHOLD = 10; // prompts
const RATE_WINDOW = 60000; // 1 minute

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                const now = Date.now();

                // Remove timestamps outside the window
                while (promptTimestamps.length > 0 && promptTimestamps[0] < now - RATE_WINDOW) {
                    promptTimestamps.shift();
                }

                promptTimestamps.push(now);
                if (promptTimestamps.length >= NOTICE_THRESHOLD) {
                    // This is advisory context for the model, not an enforced rate limit.
                    // Enforce hard limits before calling session.send().
                    return {
                        additionalContext: `The user has sent ${promptTimestamps.length} prompts in the last minute. Suggest waiting before sending more.`,
                    };
                }

                return null;
            },
        },
    },
});

Prompt templates

const TEMPLATES: Record<string, (args: string) => string> = {
    "bug:": (desc) => `I found a bug: ${desc}

Please help me:
1. Understand why this is happening
2. Suggest a fix
3. Explain how to prevent similar bugs`,

    "feature:": (desc) => `I want to implement this feature: ${desc}

Please:
1. Outline the implementation approach
2. Identify potential challenges
3. Provide sample code`,
};

const session = await client.createSession({
    hooks: {
        handlers: {
            onUserPromptSubmitted: async (input) => {
                for (const [prefix, template] of Object.entries(TEMPLATES)) {
                    if (input.prompt.toLowerCase().startsWith(prefix)) {
                        const args = input.prompt.slice(prefix.length).trim();
                        return {
                            modifiedPrompt: template(args),
                        };
                    }
                }
                return null;
            },
        },
    },
});

Best practices

  1. Preserve user intent - When modifying prompts, ensure the core intent remains clear.

  2. Be transparent about modifications - If you significantly change a prompt, consider logging or notifying the user.

  3. Use additionalContext over modifiedPrompt - Adding context is less intrusive than rewriting the prompt.

  4. Use additionalContext for advisory guidance: Context informs the model but enforces nothing. To refuse a prompt, return a block decision instead.

  5. Keep processing fast - This hook runs on every user message. Avoid slow operations.

See also

Can you improve this documentation? These fine people already did:
copilot-cli-release-app[bot], Patrick Nikoletich, Jeremiah Isaacson, Brett Cannon, Sunbrye Ly, Ed Burns, Bruno Borges, copilot-sdk-mirror-writer[bot], Steve Sanderson & Andy Feller
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close