Skip to main content
Skip to content

후크를 사용한 작업

후크를 사용하면 시작되는 순간부터 각 사용자 프롬프트와 도구 호출을 거쳐 종료되는 순간까지 Copilot 세션의 모든 단계에 사용자 지정 논리를 연결할 수 있습니다. 이 가이드에서는 핵심 에이전트 동작을 수정하지 않고 사용 권한, 감사, 알림 등을 제공할 수 있도록 실제 사용 사례를 안내합니다.

Overview

후크는 세션을 만들 때 한 번 등록하는 콜백입니다. SDK는 대화 수명 주기의 잘 정의된 지점에서 호출하고, 상황별 입력을 전달하며, 필요에 따라 세션의 동작을 수정하는 출력을 수락합니다.

다이어그램: 설명된 프로세스를 보여 주는 순서도입니다.

후크실행하는 경우수행 가능한 작업
세션 수명 주기 후크세션 시작(신규 또는 다시 시작)컨텍스트 삽입, 부하 기본 설정
사용자 프롬프트 제출 후크사용자가 메시지를 보냅니다.프롬프트 다시 작성, 컨텍스트 추가, 입력 필터링
변환된 사용자 프롬프트 훅런타임이 모델 프롬프트를 빌드합니다.모델용 콘텐츠 검사 또는 교체
사전 도구 사용 후크도구를 실행하기 전에호출 허용/거부/수정
사후 도구 사용 후크도구가 반환된 후(성공에만 해당)결과 변환, 기밀 편집, 감사
사후 도구 사용 후크도구에서 오류를 반환한 후재시도 지침 삽입, 로그 오류
세션 수명 주기 후크세션 종료클린업, 메트릭 기록하기
오류 처리 후크오류가 발생합니다.사용자 지정 로깅, 다시 시도 논리, 경고

모든 후크는 선택 사항이며 필요한 후크만 등록합니다. null (또는 해당 언어의 동등한 표현)을 후크에서 반환하면 SDK가 기본 동작을 계속합니다.

파일 기반 리포지토리 후크 및 리포지토리 후크 설정은 작업 영역이 신뢰된 후에만 로드됩니다. 작업 영역 신뢰가 부여되기 전에 사용자 후크를 계속 사용할 수 있습니다.

추가 디렉터리의 리포지토리 후크

리포지토리 파일 시스템 후크는 이 가이드에 설명된 SDK 콜백과는 별개입니다. 로컬 세션을 만들거나 콜드 재개하는 동안 추가 디렉터리에서 로드하려면 additionalDirectories를 지정합니다. CLI --add-dir도 기본적으로 참여합니다.

DISABLE_ADDITIONAL_DIRECTORY_HOOKS=true 는 기본 전용 범위를 복원합니다. enableFileHooks 를 통해 session.rpc.options.update리포지토리 후크를 사용하거나 사용하지 않도록 설정할 수 있습니다. 명시적 SDK 후크 디렉터리 및 콜백은 독립적입니다.

검색은 허용되는 각 디렉터리를 포함하는 Git 루트를 사용하거나, Git 리포지토리 외부에 있는 경우 디렉터리 자체를 사용합니다. 예를 들어, B를 리포지토리 B\packages\core 내부에 제공하면 B\packages\core와 B의 리포지토리 후크 설정까지 적용되며, 단지 B\.github\hooks 내부의 구성만이 아닙니다.

경고

신뢰할 수 있는 시작 디렉터리만 지정하십시오. 이렇게 하면 디렉터리별 또는 후크별 추가 승인 없이 모든 적격 시작 디렉터리에서 후크 명령 및 후크 제공 프롬프트에 권한을 부여합니다. 이후 파일 액세스 권한 부여는 후크를 승인하지 않습니다. 기존 관리형 정책, 후크 사용 안 함 컨트롤 및 샌드박스 규칙이 계속 적용됩니다. 이들은 악의적인 후크 콘텐츠를 안전하게 만들지 않습니다.

나중에 부여된 디렉터리 권한은 후크 소스를 추가하지 않습니다. 콜드 재개는 디렉터리를 다시 공급해야 합니다. 이후 권한 또는 escape-hatch 업데이트는 보존된 권한을 변경할 수 없습니다.

후크 등록

콜백 hooks은 파일 기반 hookDirectories과 별도로 유지됩니다. 패키지된 후크 구성 및 인접 리소스는 사용자 지정 탐색 위치을 참조하세요.

에이전트 범위의 선언형 후크

사용자 지정 에이전트는 .agent.md 이벤트 맵을 hooks 프런트매터 또는 SDK의 사용자 지정 에이전트 구성에서 선언할 수 있습니다. 이는 SDK 콜백 함수가 아닌 선언적 명령 또는 HTTP 작업입니다. 해당 에이전트가 선택된 동안에만 실행되며, 적용 가능한 세션, 사용자, 리포지토리, 플러그인 및 관리형 정책 후크에 추가로 실행됩니다. 선택한 에이전트를 변경하거나 지우면 다른 세션 또는 동시 실행 중인 하위 에이전트를 변경하지 않고 다음 호출에 대한 범위가 지정된 후크가 변경됩니다.

---
name: formatter
description: Formats changed files
hooks:
  PostToolUse:
    - type: command
      command: ./scripts/format-changed-files.sh
      windows: ./scripts/format-changed-files.ps1
---
Format the files you change.

postToolUse 같은 런타임 이벤트 이름 및 PostToolUse 같은 지원되는 VS Code 별칭이 모두 허용됩니다. command는 대체 셸 명령을 제공합니다. windows, linux, osx는 해당 플랫폼에서 이를 재정의합니다. 후크 명령은 명시적 작업 디렉터리를 설정하는 경우를 제외하고 실행 중인 세션의 리포지토리 루트를 기준으로 합니다. 후크 페이로드 및 결정은 런타임의 기존 후크 계약을 따릅니다.

로컬 에이전트가 subagent로 실행되면 범위가 지정된 Stop (agentStop) 작업은 일반 턴 중지 시점이 아니라 SubagentStop에서 실행됩니다. 해당 에이전트에 대한 명시적 SubagentStop 작업은 여전히 자체 하위 항목을 관찰합니다. 콜백은 이전 블록 이후에 stop_hook_active: true을(를) 수신합니다. 범위가 지정된 Stop 연속이 8회 연속 발생한 후 런타임은 추가 범위 블록을 무시하고 부모 수명 주기 후크가 여전히 완료를 차단하는 한이 아니라면 자식의 최종 응답을 수락합니다.

리포지토리 및 상속된 에이전트 후크에는 워크스페이스 승인이 필요합니다. 에이전트를 검색하거나 선택하는 것 자체가 신뢰를 부여하지는 않습니다. 기존 후크 사용 안 함 설정, 엔터프라이즈 제한, 샌드박스 권한 및 시간 제한도 범위가 지정된 작업에 적용됩니다. SDK 제공 에이전트는 관리 플러그 인 권한을 요구할 수 없습니다. 원격 또는 조직에서 호스팅하는 에이전트 정의는 범위가 지정된 후크를 실행하지 않으며, 범위가 지정된 중지 디스패치는 외부 AHP 참가자가 아닌 로컬 런타임 하위 에이전트에서 지원됩니다.

지원되지 않는 이벤트 이름은 이벤트 선택 전에 보고됩니다. 작업 준비 오류는 선언된 이벤트에만 영향을 줍니다. 공유 및 관리 정책 후크는 계속 실행됩니다.

hooks 세션을 만들거나 다시 시작할 때 개체를 전달합니다. 아래의 모든 예제는 이 패턴을 따릅니다.

코드 언어 navigation

TypeScript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
await client.start();

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      /* ... */
    },
    onPreToolUse: async (input, invocation) => {
      /* ... */
    },
    onPostToolUse: async (input, invocation) => {
      /* ... */
    },
    // ... add only the hooks you need
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

팁

모든 후크 처리기는 세션별 상태를 유지하고 로그의 상관 관계를 지정하는 데 유용한 invocation을 포함하는 매개 변수 sessionId를 수신합니다.

사용 사례: 권한 제어

에이전트가 실행할 수 있는 도구, 허용되는 인수 및 실행 전에 사용자에게 메시지가 표시되어야 하는지 여부를 결정하는 권한 계층을 빌드하는 데 사용합니다 onPreToolUse .

"안전한 도구 집합을 허용 목록으로 등록"

코드 언어 navigation

TypeScript
const READ_ONLY_TOOLS = ["read_file", "glob", "grep", "view"];

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (!READ_ONLY_TOOLS.includes(input.toolName)) {
        return {
          permissionDecision: "deny",
          permissionDecisionReason: `Only read-only tools are allowed. "${input.toolName}" was blocked.`,
        };
      }
      return { permissionDecision: "allow" };
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

특정 디렉터리에 대한 파일 액세스 제한

const ALLOWED_DIRS = ["/home/user/projects", "/tmp"];

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (["read_file", "write_file", "edit"].includes(input.toolName)) {
        const filePath = (input.toolArgs as { path: string }).path;
        const allowed = ALLOWED_DIRS.some((dir) => filePath.startsWith(dir));

        if (!allowed) {
          return {
            permissionDecision: "deny",
            permissionDecisionReason: `Access to "${filePath}" is outside the allowed directories.`,
          };
        }
      }
      return { permissionDecision: "allow" };
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

파괴적인 작업 전에 사용자에게 문의

const DESTRUCTIVE_TOOLS = ["delete_file", "shell", "bash"];

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (DESTRUCTIVE_TOOLS.includes(input.toolName)) {
        return { permissionDecision: "ask" };
      }
      return { permissionDecision: "allow" };
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

반환하면 "ask" 런타임에 사용자에게 결정을 위임합니다. 이는 사람이 관여해야 하는 파괴적인 작업에서 유용합니다.

사용 사례: 감사 및 규정 준수

onPreToolUse, onPostToolUse 및 세션 수명 주기 후크를 결합하여 에이전트가 수행하는 모든 작업을 기록하는 완전한 감사 추적을 작성합니다.

구조적 감사 로그

코드 언어 navigation

TypeScript
interface AuditEntry {
  timestamp: Date;
  sessionId: string;
  event: string;
  toolName?: string;
  toolArgs?: unknown;
  toolResult?: unknown;
  prompt?: string;
}

const auditLog: AuditEntry[] = [];

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      auditLog.push({
        timestamp: input.timestamp,
        sessionId: invocation.sessionId,
        event: "session_start",
      });
      return null;
    },
    onUserPromptSubmitted: async (input, invocation) => {
      auditLog.push({
        timestamp: input.timestamp,
        sessionId: invocation.sessionId,
        event: "user_prompt",
        prompt: input.prompt,
      });
      return null;
    },
    onPreToolUse: async (input, invocation) => {
      auditLog.push({
        timestamp: input.timestamp,
        sessionId: invocation.sessionId,
        event: "tool_call",
        toolName: input.toolName,
        toolArgs: input.toolArgs,
      });
      return { permissionDecision: "allow" };
    },
    onPostToolUse: async (input, invocation) => {
      auditLog.push({
        timestamp: input.timestamp,
        sessionId: invocation.sessionId,
        event: "tool_result",
        toolName: input.toolName,
        toolResult: input.toolResult,
      });
      return null;
    },
    onSessionEnd: async (input, invocation) => {
      auditLog.push({
        timestamp: input.timestamp,
        sessionId: invocation.sessionId,
        event: "session_end",
      });

      // Persist the log — swap this with your own storage backend
      await fs.promises.writeFile(
        `audit-${invocation.sessionId}.json`,
        JSON.stringify(auditLog, null, 2),
      );
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

도구 결과에서 비밀 항목 제거

const SECRET_PATTERNS = [
  /(?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?[\w\-\.]+["']?/gi,
];

const session = await client.createSession({
  hooks: {
    onPostToolUse: async (input) => {
      if (typeof input.toolResult !== "string") return null;

      let redacted = input.toolResult;
      for (const pattern of SECRET_PATTERNS) {
        redacted = redacted.replace(pattern, "[REDACTED]");
      }

      return redacted !== input.toolResult
        ? { modifiedResult: redacted }
        : null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

사용 사례: 알림 및 소리

후크는 애플리케이션 프로세스에서 실행되므로 데스크톱 알림, 소리, Slack 메시지 또는 웹후크 호출과 같은 다양한 부수 효과가 발생할 수 있습니다.

세션 이벤트에 대한 데스크톱 알림

코드 언어 navigation

TypeScript
import notifier from "node-notifier"; // npm install node-notifier

const session = await client.createSession({
  hooks: {
    onSessionEnd: async (input, invocation) => {
      notifier.notify({
        title: "Copilot Session Complete",
        message: `Session ${invocation.sessionId.slice(0, 8)} finished (${input.reason}).`,
      });
      return null;
    },
    onErrorOccurred: async (input) => {
      notifier.notify({
        title: "Copilot Error",
        message: input.error.slice(0, 200),
      });
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

도구가 작업을 마치면 소리를 재생

import { exec } from "node:child_process";

const session = await client.createSession({
  hooks: {
    onPostToolUse: async (input) => {
      // macOS: play a system sound after every tool call
      exec("afplay /System/Library/Sounds/Pop.aiff");
      return null;
    },
    onErrorOccurred: async () => {
      exec("afplay /System/Library/Sounds/Basso.aiff");
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

오류 발생 후 Slack에 게시

const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL!;

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input, invocation) => {
      if (!input.recoverable) {
        await fetch(SLACK_WEBHOOK_URL, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            text: `🚨 Unrecoverable error in session \`${invocation.sessionId.slice(0, 8)}\`:\n\`\`\`${input.error}\`\`\``,
          }),
        });
      }
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

사용 사례: 프롬프트 강화

onSessionStart 및 onUserPromptSubmitted을 사용하여 자동으로 컨텍스트를 삽입하면 사용자가 스스로 반복할 필요가 없습니다.

세션 시작 시 프로젝트 메타데이터 삽입

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input) => {
      const pkg = JSON.parse(
        await fs.promises.readFile("package.json", "utf-8"),
      );
      return {
        additionalContext: [
          `Project: ${pkg.name} v${pkg.version}`,
          `Node: ${process.version}`,
          `Working directory: ${input.workingDirectory}`,
        ].join("\n"),
      };
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

프롬프트에서 줄임 명령어를 확장하기

const SHORTCUTS: Record<string, string> = {
  "/fix": "Find and fix all errors in the current file",
  "/test": "Write comprehensive unit tests for this code",
  "/explain": "Explain this code in detail",
  "/refactor": "Refactor this code to improve readability",
};

const session = await client.createSession({
  hooks: {
    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: rest ? `${expansion}: ${rest}` : expansion };
        }
      }
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

사용 사례: 오류 처리 및 복구

onErrorOccurred 후크는 오류에 대응할 수 있는 기회를 제공합니다. 여기에는 다시 시도하거나, 사람에게 알리거나, 정상적으로 종료하는 등의 방법이 포함됩니다.

일시적인 모델 오류 다시 시도

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input) => {
      if (input.errorContext === "model_call" && input.recoverable) {
        return {
          errorHandling: "retry",
          retryCount: 3,
          userNotification: "Temporary model issue — retrying…",
        };
      }
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

친숙한 오류 메시지

const FRIENDLY_MESSAGES: Record<string, string> = {
  model_call: "The AI model is temporarily unavailable. Please try again.",
  tool_execution: "A tool encountered an error. Check inputs and try again.",
  system: "A system error occurred. Please try again later.",
};

const session = await client.createSession({
  hooks: {
    onErrorOccurred: async (input) => {
      return {
        userNotification: FRIENDLY_MESSAGES[input.errorContext] ?? input.error,
      };
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

사용 사례: 세션 메트릭

세션 실행 시간, 호출되는 도구 수 및 세션이 종료되는 이유를 추적하여 대시보드 및 비용 모니터링에 유용합니다.

코드 언어 navigation

TypeScript
const metrics = new Map<
  string,
  { start: Date; toolCalls: number; prompts: number }
>();

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      metrics.set(invocation.sessionId, {
        start: input.timestamp,
        toolCalls: 0,
        prompts: 0,
      });
      return null;
    },
    onUserPromptSubmitted: async (_input, invocation) => {
      metrics.get(invocation.sessionId)!.prompts++;
      return null;
    },
    onPreToolUse: async (_input, invocation) => {
      metrics.get(invocation.sessionId)!.toolCalls++;
      return { permissionDecision: "allow" };
    },
    onSessionEnd: async (input, invocation) => {
      const m = metrics.get(invocation.sessionId)!;
      const durationSec =
        (input.timestamp.getTime() - m.start.getTime()) / 1000;

      console.log(
        `Session ${invocation.sessionId.slice(0, 8)}: ` +
          `${durationSec.toFixed(1)}s, ${m.prompts} prompts, ` +
          `${m.toolCalls} tool calls, ended: ${input.reason}`,
      );

      metrics.delete(invocation.sessionId);
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

후크 결합

후크는 자연스럽게 작성됩니다. 단일 hooks 개체는 사용 권한 및 감사 및 알림을 처리할 수 있습니다 . 각 후크는 자체 작업을 수행합니다.

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input) => {
      console.log(`[audit] session started in ${input.workingDirectory}`);
      return { additionalContext: "Project uses TypeScript and Vitest." };
    },
    onPreToolUse: async (input) => {
      console.log(`[audit] tool requested: ${input.toolName}`);
      if (input.toolName === "shell") {
        return { permissionDecision: "ask" };
      }
      return { permissionDecision: "allow" };
    },
    onPostToolUse: async (input) => {
      console.log(`[audit] tool completed: ${input.toolName}`);
      return null;
    },
    onErrorOccurred: async (input) => {
      console.error(`[alert] ${input.errorContext}: ${input.error}`);
      return null;
    },
    onSessionEnd: async (input, invocation) => {
      console.log(
        `[audit] session ${invocation.sessionId.slice(0, 8)} ended: ${input.reason}`,
      );
      return null;
    },
  },
  onPermissionRequest: async () => ({ kind: "approve-once" }),
});

모범 사례

  1. 후크가 빠르게 작동하도록 유지합니다. 모든 후크는 인라인으로 실행되며 느린 후크는 대화를 지연합니다. 가능하면 백그라운드 큐에 많은 작업(데이터베이스 쓰기, HTTP 호출)을 오프로드합니다.

  2. 변경할 내용이 없으면 반환 null 합니다. 이렇게 하면 SDK에서 기본값을 계속 진행하도록 지시하고 불필요한 개체 할당을 방지합니다.

  3. 사용 권한 결정에 명시적이어야 합니다. 도구를 허용하더라도 { permissionDecision: "allow" } 반환은 null 반환보다 더 명확합니다.

  4. 중요한 오류를 삼켜도 안됩니다. 복구 가능한 도구 오류를 표시하지 않는 것은 괜찮지만, 복구할 수 없는 오류에 대해 항상 로그 또는 경고를 표시합니다.

  5. 가능한 경우 대신 additionalContext 사용합니다modifiedPrompt. 컨텍스트를 추가하면 모델을 계속 안내하는 동안 사용자의 원래 의도가 유지됩니다.

  6. 세션 ID별 범위 상태입니다. 세션별 데이터를 추적하는 경우 invocation.sessionId에 키를 설정하고 onSessionEnd에서 정리합니다.

Reference

전체 형식 정의, 입력/출력 필드 테이블 및 모든 후크에 대한 추가 예제는 API 참조를 참조하세요.

참고하십시오