// package.json
var package_default = {
  name: "@posthog/agent",
  version: "2.3.678",
  repository: "https://github.com/PostHog/code",
  description: "TypeScript agent framework wrapping Claude Agent SDK with Git-based task execution for PostHog",
  exports: {
    ".": {
      types: "./dist/index.d.ts",
      import: "./dist/index.js"
    },
    "./agent": {
      types: "./dist/agent.d.ts",
      import: "./dist/agent.js"
    },
    "./gateway-models": {
      types: "./dist/gateway-models.d.ts",
      import: "./dist/gateway-models.js"
    },
    "./posthog-api": {
      types: "./dist/posthog-api.d.ts",
      import: "./dist/posthog-api.js"
    },
    "./pr-url-detector": {
      types: "./dist/pr-url-detector.d.ts",
      import: "./dist/pr-url-detector.js"
    },
    "./types": {
      types: "./dist/types.d.ts",
      import: "./dist/types.js"
    },
    "./adapters/claude/questions/utils": {
      types: "./dist/adapters/claude/questions/utils.d.ts",
      import: "./dist/adapters/claude/questions/utils.js"
    },
    "./adapters/claude/permissions/permission-options": {
      types: "./dist/adapters/claude/permissions/permission-options.d.ts",
      import: "./dist/adapters/claude/permissions/permission-options.js"
    },
    "./adapters/claude/tools": {
      types: "./dist/adapters/claude/tools.d.ts",
      import: "./dist/adapters/claude/tools.js"
    },
    "./adapters/claude/conversion/tool-use-to-acp": {
      types: "./dist/adapters/claude/conversion/tool-use-to-acp.d.ts",
      import: "./dist/adapters/claude/conversion/tool-use-to-acp.js"
    },
    "./adapters/claude/session/jsonl-hydration": {
      types: "./dist/adapters/claude/session/jsonl-hydration.d.ts",
      import: "./dist/adapters/claude/session/jsonl-hydration.js"
    },
    "./adapters/claude/session/models": {
      types: "./dist/adapters/claude/session/models.d.ts",
      import: "./dist/adapters/claude/session/models.js"
    },
    "./adapters/reasoning-effort": {
      types: "./dist/adapters/reasoning-effort.d.ts",
      import: "./dist/adapters/reasoning-effort.js"
    },
    "./adapters/claude/mcp/tool-metadata": {
      types: "./dist/adapters/claude/mcp/tool-metadata.d.ts",
      import: "./dist/adapters/claude/mcp/tool-metadata.js"
    },
    "./execution-mode": {
      types: "./dist/execution-mode.d.ts",
      import: "./dist/execution-mode.js"
    },
    "./resume": {
      types: "./dist/resume.d.ts",
      import: "./dist/resume.js"
    },
    "./handoff-checkpoint": {
      types: "./dist/handoff-checkpoint.d.ts",
      import: "./dist/handoff-checkpoint.js"
    },
    "./server": {
      types: "./dist/server/agent-server.d.ts",
      import: "./dist/server/agent-server.js"
    },
    "./server/schemas": {
      types: "./dist/server/schemas.d.ts",
      import: "./dist/server/schemas.js"
    }
  },
  bin: {
    "agent-server": "./dist/server/bin.cjs"
  },
  type: "module",
  keywords: [
    "posthog",
    "claude",
    "agent",
    "ai",
    "git",
    "typescript"
  ],
  author: "PostHog",
  license: "MIT",
  scripts: {
    build: "node ../../scripts/rimraf.mjs dist && tsup",
    dev: "tsup --watch",
    test: "vitest run",
    "test:watch": "vitest",
    typecheck: "pnpm exec tsc --noEmit",
    prepublishOnly: "pnpm run build",
    clean: "node ../../scripts/rimraf.mjs dist .turbo"
  },
  engines: {
    node: ">=20.0.0"
  },
  devDependencies: {
    "@posthog/shared": "workspace:*",
    "@posthog/git": "workspace:*",
    "@posthog/enricher": "workspace:*",
    "@types/bun": "latest",
    "@types/tar": "^6.1.13",
    msw: "^2.12.7",
    tsup: "^8.5.1",
    tsx: "^4.20.6",
    typescript: "^5.5.0",
    vitest: "^2.1.8"
  },
  dependencies: {
    "@agentclientprotocol/sdk": "0.19.0",
    "@anthropic-ai/claude-agent-sdk": "0.2.112",
    "@anthropic-ai/sdk": "0.89.0",
    "@hono/node-server": "^1.19.9",
    "@opentelemetry/api-logs": "^0.208.0",
    "@opentelemetry/exporter-logs-otlp-http": "^0.208.0",
    "@opentelemetry/resources": "^2.0.0",
    "@opentelemetry/sdk-logs": "^0.208.0",
    "@opentelemetry/semantic-conventions": "^1.28.0",
    "@types/jsonwebtoken": "^9.0.10",
    commander: "^14.0.2",
    hono: "^4.11.7",
    jsonwebtoken: "^9.0.2",
    minimatch: "^10.0.3",
    "@modelcontextprotocol/sdk": "1.29.0",
    tar: "^7.5.0",
    uuid: "13.0.0",
    "yoga-wasm-web": "^0.3.3",
    zod: "^4.2.0"
  },
  files: [
    "dist/**/*",
    "src/**/*",
    "README.md",
    "CLAUDE.md"
  ],
  publishConfig: {
    access: "public"
  }
};

// src/utils/gateway.ts
function getGatewayBaseUrl(posthogHost) {
  const url = new URL(posthogHost);
  const hostname = url.hostname;
  if (hostname === "localhost" || hostname === "127.0.0.1") {
    return `${url.protocol}//localhost:3308`;
  }
  if (hostname === "host.docker.internal") {
    return `${url.protocol}//host.docker.internal:3308`;
  }
  const region = hostname.match(/^(us|eu)\.posthog\.com$/)?.[1] ?? "us";
  return `https://gateway.${region}.posthog.com`;
}
function getLlmGatewayUrl(posthogHost, product = "posthog_code") {
  return `${getGatewayBaseUrl(posthogHost)}/${product}`;
}
function getGatewayUsageUrl(posthogHost, product = "posthog_code") {
  return `${getGatewayBaseUrl(posthogHost)}/v1/usage/${product}`;
}
function getGatewayInvalidatePlanCacheUrl(posthogHost, product = "posthog_code") {
  return `${getGatewayBaseUrl(posthogHost)}/v1/usage/${product}/invalidate-plan-cache`;
}

// src/posthog-api.ts
var DEFAULT_USER_AGENT = `posthog/agent.hog.dev; version: ${package_default.version}`;
var PostHogAPIClient = class {
  config;
  constructor(config) {
    this.config = config;
  }
  get baseUrl() {
    const host = this.config.apiUrl.endsWith("/") ? this.config.apiUrl.slice(0, -1) : this.config.apiUrl;
    return host;
  }
  isAuthFailure(status) {
    return status === 401 || status === 403;
  }
  async resolveApiKey(forceRefresh = false) {
    if (forceRefresh && this.config.refreshApiKey) {
      return this.config.refreshApiKey();
    }
    return this.config.getApiKey();
  }
  async buildHeaders(options, forceRefresh = false) {
    const headers = new Headers(options.headers);
    headers.set(
      "Authorization",
      `Bearer ${await this.resolveApiKey(forceRefresh)}`
    );
    headers.set("Content-Type", "application/json");
    headers.set("User-Agent", this.config.userAgent ?? DEFAULT_USER_AGENT);
    return headers;
  }
  async performRequest(endpoint, options, forceRefresh = false) {
    const url = `${this.baseUrl}${endpoint}`;
    return fetch(url, {
      ...options,
      headers: await this.buildHeaders(options, forceRefresh)
    });
  }
  async performRequestWithRetry(endpoint, options = {}) {
    let response = await this.performRequest(endpoint, options);
    if (!response.ok && this.isAuthFailure(response.status)) {
      response = await this.performRequest(endpoint, options, true);
    }
    return response;
  }
  async apiRequest(endpoint, options = {}) {
    const response = await this.performRequestWithRetry(endpoint, options);
    if (!response.ok) {
      let errorMessage;
      try {
        const errorResponse = await response.json();
        errorMessage = `Failed request: [${response.status}] ${JSON.stringify(errorResponse)}`;
      } catch {
        errorMessage = `Failed request: [${response.status}] ${response.statusText}`;
      }
      throw new Error(errorMessage);
    }
    return response.json();
  }
  getTeamId() {
    return this.config.projectId;
  }
  async getApiKey(forceRefresh = false) {
    return this.resolveApiKey(forceRefresh);
  }
  getLlmGatewayUrl() {
    return getLlmGatewayUrl(this.baseUrl);
  }
  async getTask(taskId) {
    const teamId = this.getTeamId();
    return this.apiRequest(`/api/projects/${teamId}/tasks/${taskId}/`);
  }
  async getTaskRun(taskId, runId) {
    const teamId = this.getTeamId();
    return this.apiRequest(
      `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/`
    );
  }
  async resumeRunInCloud(taskId, runId) {
    const teamId = this.getTeamId();
    return this.apiRequest(
      `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/resume_in_cloud/`,
      { method: "POST" }
    );
  }
  async updateTaskRun(taskId, runId, payload) {
    const teamId = this.getTeamId();
    return this.apiRequest(
      `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/`,
      {
        method: "PATCH",
        body: JSON.stringify(payload)
      }
    );
  }
  async setTaskRunOutput(taskId, runId, output) {
    return this.apiRequest(
      `/api/projects/${this.getTeamId()}/tasks/${taskId}/runs/${runId}/set_output/`,
      {
        method: "PATCH",
        body: JSON.stringify(output)
      }
    );
  }
  async appendTaskRunLog(taskId, runId, entries) {
    const teamId = this.getTeamId();
    return this.apiRequest(
      `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/append_log/`,
      {
        method: "POST",
        body: JSON.stringify({ entries })
      }
    );
  }
  async relayMessage(taskId, runId, text) {
    const teamId = this.getTeamId();
    await this.apiRequest(
      `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/relay_message/`,
      {
        method: "POST",
        body: JSON.stringify({ text })
      }
    );
  }
  async uploadTaskArtifacts(taskId, runId, artifacts) {
    if (!artifacts.length) {
      return [];
    }
    const teamId = this.getTeamId();
    const response = await this.apiRequest(
      `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/`,
      {
        method: "POST",
        body: JSON.stringify({ artifacts })
      }
    );
    const manifest = response.artifacts ?? [];
    return manifest.slice(-artifacts.length);
  }
  /**
   * Download artifact content by storage path
   * Streams the file through the PostHog backend so the sandbox does not need
   * direct access to object storage.
   */
  async downloadArtifact(taskId, runId, storagePath) {
    const teamId = this.getTeamId();
    try {
      const response = await this.performRequestWithRetry(
        `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/artifacts/download/`,
        {
          method: "POST",
          body: JSON.stringify({ storage_path: storagePath })
        }
      );
      if (!response.ok) {
        throw new Error(`Failed to download artifact: ${response.status}`);
      }
      return response.arrayBuffer();
    } catch {
      return null;
    }
  }
  /**
   * Fetch logs for a task run via the logs API endpoint
   * @param taskRun - The task run to fetch logs for
   * @returns Array of stored entries, or empty array if no logs available
   */
  async fetchTaskRunLogs(taskRun) {
    const teamId = this.getTeamId();
    const endpoint = `/api/projects/${teamId}/tasks/${taskRun.task}/runs/${taskRun.id}/logs`;
    try {
      const response = await this.performRequestWithRetry(endpoint);
      if (!response.ok) {
        if (response.status === 404) {
          return [];
        }
        throw new Error(
          `Failed to fetch logs: ${response.status} ${response.statusText}`
        );
      }
      const content = await response.text();
      if (!content.trim()) {
        return [];
      }
      return content.trim().split("\n").map((line) => JSON.parse(line));
    } catch (error) {
      throw new Error(
        `Failed to fetch task run logs: ${error instanceof Error ? error.message : String(error)}`
      );
    }
  }
};
export {
  PostHogAPIClient,
  getGatewayInvalidatePlanCacheUrl,
  getGatewayUsageUrl,
  getLlmGatewayUrl
};
//# sourceMappingURL=posthog-api.js.map