import {
  ConnectionName,
  ElicitationId,
  IntegrationSlug,
  OAuthState,
  Owner,
  PolicyId,
  ProviderKey,
  ToolAddress
} from "./chunk-7GJMCW76.js";

// src/policies.ts
import { Match, Schema } from "effect";
var matchPattern = (pattern, toolId) => {
  if (pattern === "*") return true;
  const patternSegments = pattern.split(".");
  const toolSegments = toolId.split(".");
  for (let i = 0; i < patternSegments.length; i++) {
    const seg = patternSegments[i];
    if (seg === "*") {
      if (i === patternSegments.length - 1) return toolSegments.length >= i;
      if (i >= toolSegments.length) return false;
      continue;
    }
    if (i >= toolSegments.length || toolSegments[i] !== seg) return false;
  }
  return patternSegments.length === toolSegments.length;
};
var isValidPattern = (pattern) => {
  if (pattern.length === 0) return false;
  if (pattern === "*") return true;
  if (pattern.startsWith(".") || pattern.endsWith(".")) return false;
  if (pattern.includes("..")) return false;
  if (pattern.startsWith("*")) return false;
  const segments = pattern.split(".");
  for (let i = 0; i < segments.length; i++) {
    const seg = segments[i];
    if (seg.length === 0) return false;
    if (seg.includes("*") && seg !== "*") return false;
  }
  return true;
};
var comparePolicyRow = (a, b) => {
  const pa = a.position;
  const pb = b.position;
  if (pa < pb) return -1;
  if (pa > pb) return 1;
  const ia = a.id;
  const ib = b.id;
  return ia < ib ? -1 : ia > ib ? 1 : 0;
};
var actionRestrictionRank = (action) => Match.value(action).pipe(
  Match.when("block", () => 3),
  Match.when("require_approval", () => 2),
  Match.when("approve", () => 1),
  Match.exhaustive
);
var moreRestrictive = (current, candidate) => {
  if (!current) return candidate;
  const currentRank = actionRestrictionRank(current.action);
  const candidateRank = actionRestrictionRank(candidate.action);
  return candidateRank > currentRank ? candidate : current;
};
var resolveToolPolicy = (toolId, policies, ownerRank) => {
  if (policies.length === 0) return void 0;
  const sorted = [...policies].sort((a, b) => {
    const sa = ownerRank(a);
    const sb = ownerRank(b);
    if (sa !== sb) return sa - sb;
    return comparePolicyRow(a, b);
  });
  const firstMatchByOwner = /* @__PURE__ */ new Map();
  for (const row of sorted) {
    if (firstMatchByOwner.has(row.owner)) continue;
    if (matchPattern(row.pattern, toolId)) {
      firstMatchByOwner.set(row.owner, {
        action: row.action,
        pattern: row.pattern,
        policyId: row.id
      });
    }
  }
  let selected;
  for (const match of firstMatchByOwner.values()) {
    selected = moreRestrictive(selected, match);
  }
  return selected;
};
var liftPlugin = (defaultRequiresApproval) => defaultRequiresApproval ? { action: "require_approval", source: "plugin-default" } : { action: "approve", source: "plugin-default" };
var liftUser = (match) => ({
  action: match.action,
  source: "user",
  pattern: match.pattern,
  policyId: match.policyId
});
var resolveEffectivePolicy = (toolId, policies, ownerRank, defaultRequiresApproval) => {
  const match = resolveToolPolicy(toolId, policies, ownerRank);
  return match ? liftUser(match) : liftPlugin(defaultRequiresApproval);
};
var effectivePolicyFromSorted = (toolId, sortedPolicies, defaultRequiresApproval) => {
  const firstMatchByOwner = /* @__PURE__ */ new Map();
  for (const p of sortedPolicies) {
    const ownerKey = "owner" in p && p.owner ? String(p.owner) : "__flat__";
    if (firstMatchByOwner.has(ownerKey)) continue;
    if (matchPattern(p.pattern, toolId)) {
      firstMatchByOwner.set(ownerKey, {
        action: p.action,
        source: "user",
        pattern: p.pattern,
        policyId: p.id
      });
    }
  }
  let selected;
  for (const match of firstMatchByOwner.values()) {
    selected = moreRestrictive(selected, match);
  }
  return selected ?? liftPlugin(defaultRequiresApproval);
};
var rowToToolPolicy = (row) => ({
  id: PolicyId.make(row.id),
  owner: row.owner,
  pattern: row.pattern,
  action: row.action,
  position: row.position,
  createdAt: row.created_at,
  updatedAt: row.updated_at
});
var ToolPolicyActionSchema = Schema.Literals(["approve", "require_approval", "block"]);

// src/elicitation.ts
import { Schema as Schema2 } from "effect";
var FormElicitation = Schema2.TaggedStruct("FormElicitation", {
  message: Schema2.String,
  /** JSON Schema describing the fields to collect. */
  requestedSchema: Schema2.Record(Schema2.String, Schema2.Unknown)
});
var UrlElicitation = Schema2.TaggedStruct("UrlElicitation", {
  message: Schema2.String,
  url: Schema2.String,
  /** Unique id so the host can correlate the callback. */
  elicitationId: ElicitationId
});
var ElicitationAction = Schema2.Literals(["accept", "decline", "cancel"]);
var ElicitationResponse = Schema2.Struct({
  action: ElicitationAction,
  /** Present when `action` is "accept" — the data the user provided. */
  content: Schema2.optional(Schema2.Record(Schema2.String, Schema2.Unknown))
});
var ElicitationDeclinedError = class extends Schema2.TaggedErrorClass()(
  "ElicitationDeclinedError",
  {
    address: ToolAddress,
    action: Schema2.Literals(["decline", "cancel"])
  }
) {
  // Derived message so telemetry (span status, logs) labels the failure
  // instead of rendering an Error with an empty message.
  get message() {
    return `Tool approval ${this.action === "cancel" ? "cancelled" : "declined"}: ${this.address}`;
  }
};

// src/errors.ts
import { Schema as Schema3 } from "effect";
var ToolNotFoundError = class extends Schema3.TaggedErrorClass()(
  "ToolNotFoundError",
  {
    address: ToolAddress,
    suggestions: Schema3.optional(Schema3.Array(ToolAddress))
  }
) {
  get message() {
    return `Tool not found: ${this.address}`;
  }
};
var ToolInvocationError = class extends Schema3.TaggedErrorClass()(
  "ToolInvocationError",
  {
    address: ToolAddress,
    message: Schema3.String,
    cause: Schema3.optional(Schema3.Unknown)
  }
) {
};
var ToolBlockedError = class extends Schema3.TaggedErrorClass()(
  "ToolBlockedError",
  {
    address: ToolAddress,
    pattern: Schema3.String
  }
) {
  get message() {
    return `Tool blocked by policy "${this.pattern}": ${this.address}`;
  }
};
var PluginNotLoadedError = class extends Schema3.TaggedErrorClass()(
  "PluginNotLoadedError",
  {
    address: ToolAddress,
    pluginId: Schema3.String
  }
) {
  get message() {
    return `Plugin "${this.pluginId}" is not loaded for tool: ${this.address}`;
  }
};
var NoHandlerError = class extends Schema3.TaggedErrorClass()("NoHandlerError", {
  address: ToolAddress,
  pluginId: Schema3.String
}) {
  get message() {
    return `Plugin "${this.pluginId}" has no invokeTool handler for tool: ${this.address}`;
  }
};
var IntegrationNotFoundError = class extends Schema3.TaggedErrorClass()(
  "IntegrationNotFoundError",
  { slug: IntegrationSlug }
) {
  get message() {
    return `Integration not found: ${this.slug}`;
  }
};
var IntegrationAlreadyExistsError = class extends Schema3.TaggedErrorClass()(
  "IntegrationAlreadyExistsError",
  { slug: IntegrationSlug },
  { httpApiStatus: 409 }
) {
  get message() {
    return `Integration already exists: ${this.slug}`;
  }
};
var IntegrationRemovalNotAllowedError = class extends Schema3.TaggedErrorClass()(
  "IntegrationRemovalNotAllowedError",
  { slug: IntegrationSlug }
) {
  get message() {
    return `Integration cannot be removed (declared statically by a plugin): ${this.slug}`;
  }
};
var ConnectionNotFoundError = class extends Schema3.TaggedErrorClass()(
  "ConnectionNotFoundError",
  {
    owner: Owner,
    integration: IntegrationSlug,
    name: ConnectionName
  }
) {
  get message() {
    return `Connection not found: ${this.integration}.${this.owner}.${this.name}`;
  }
};
var InvalidConnectionInputError = class extends Schema3.TaggedErrorClass()(
  "InvalidConnectionInputError",
  { message: Schema3.String }
) {
};
var CredentialProviderNotRegisteredError = class extends Schema3.TaggedErrorClass()(
  "CredentialProviderNotRegisteredError",
  { provider: ProviderKey }
) {
  get message() {
    return `Credential provider not registered: ${this.provider}`;
  }
};
var CredentialResolutionError = class extends Schema3.TaggedErrorClass()(
  "CredentialResolutionError",
  {
    owner: Owner,
    integration: IntegrationSlug,
    name: ConnectionName,
    message: Schema3.String,
    /** True when the stored grant is permanently invalid and the user must
     *  sign in again (RFC 6749 §5.2 invalid_grant and friends). */
    reauthRequired: Schema3.optional(Schema3.Boolean)
  }
) {
};

// src/oauth-client.ts
import { Schema as Schema4 } from "effect";
var OAuthStartError = class extends Schema4.TaggedErrorClass()("OAuthStartError", {
  message: Schema4.String
}) {
};
var OAuthCompleteError = class extends Schema4.TaggedErrorClass()(
  "OAuthCompleteError",
  {
    message: Schema4.String,
    /** True when the auth-code exchange failed in a way the user must restart. */
    restartRequired: Schema4.optional(Schema4.Boolean)
  }
) {
};
var OAuthProbeError = class extends Schema4.TaggedErrorClass()("OAuthProbeError", {
  message: Schema4.String
}) {
};
var OAuthRegisterDynamicError = class extends Schema4.TaggedErrorClass()(
  "OAuthRegisterDynamicError",
  { message: Schema4.String }
) {
};
var OAuthSessionNotFoundError = class extends Schema4.TaggedErrorClass()(
  "OAuthSessionNotFoundError",
  { state: OAuthState }
) {
};

// src/types.ts
import { Schema as Schema5 } from "effect";
var ToolSchemaView = Schema5.Struct({
  address: ToolAddress,
  name: Schema5.optional(Schema5.String),
  description: Schema5.optional(Schema5.String),
  inputSchema: Schema5.optional(Schema5.Unknown),
  outputSchema: Schema5.optional(Schema5.Unknown),
  schemaDefinitions: Schema5.optional(Schema5.Record(Schema5.String, Schema5.Unknown)),
  inputTypeScript: Schema5.optional(Schema5.String),
  outputTypeScript: Schema5.optional(Schema5.String),
  typeScriptDefinitions: Schema5.optional(Schema5.Record(Schema5.String, Schema5.String))
});
var IntegrationDetectionResult = Schema5.Struct({
  /** Plugin id that recognized the URL (e.g. "openapi", "graphql"). */
  kind: Schema5.String,
  /** Confidence tier — UI uses this to pick a winner when multiple plugins
   *  claim a URL. */
  confidence: Schema5.Literals(["high", "medium", "low"]),
  /** The (possibly normalized) endpoint the plugin will use. */
  endpoint: Schema5.String,
  /** Human-readable name suggestion, typically derived from spec title or URL. */
  name: Schema5.String,
  /** Slug suggestion — the plugin's recommendation for the integration slug. */
  slug: Schema5.String
});

export {
  matchPattern,
  isValidPattern,
  comparePolicyRow,
  resolveEffectivePolicy,
  effectivePolicyFromSorted,
  rowToToolPolicy,
  ToolPolicyActionSchema,
  FormElicitation,
  UrlElicitation,
  ElicitationAction,
  ElicitationResponse,
  ElicitationDeclinedError,
  ToolNotFoundError,
  ToolInvocationError,
  ToolBlockedError,
  PluginNotLoadedError,
  NoHandlerError,
  IntegrationNotFoundError,
  IntegrationAlreadyExistsError,
  IntegrationRemovalNotAllowedError,
  ConnectionNotFoundError,
  InvalidConnectionInputError,
  CredentialProviderNotRegisteredError,
  CredentialResolutionError,
  OAuthStartError,
  OAuthCompleteError,
  OAuthProbeError,
  OAuthRegisterDynamicError,
  OAuthSessionNotFoundError,
  ToolSchemaView,
  IntegrationDetectionResult
};
//# sourceMappingURL=chunk-6EED5LAL.js.map