Skip to main content
Reference

CEL functions reference

Keep rule expressions use CEL (Common Expression Language) with custom functions for temporal logic, rate limiting, content detection, string manipulation, and secret detection.

Standard CEL

All built-in CEL operators, macros, and functions are available in Keep expressions. This includes:

  • Arithmetic: +, -, *, /, %
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: &&, ||, !
  • String methods: .contains(), .startsWith(), .endsWith(), .matches(), .size()
  • List operators: .exists(), .all(), .filter(), .map(), in
  • Ternary: condition ? a : b

See the CEL language spec for the full list.

Input variables

Every expression has access to three variables:

VariableTypeDescription
paramsdynCall parameters — fields vary by operation
contextdynCall metadata (agent ID, timestamp, etc.)
nowtimestampCurrent timestamp, injected from context.timestamp

Missing field accesses on params or context evaluate to false rather than returning an error.

Temporal functions

inTimeWindow

inTimeWindow(now, start, end, tz) -> bool

Returns true if now falls within the time-of-day window [start, end) in the given timezone.

ParameterTypeDescription
nowtimestampTimestamp to check (use the now variable)
startstringStart time in "HH:MM" format (24-hour)
endstringEnd time in "HH:MM" format (24-hour)
tzstringIANA timezone name (e.g., "America/New_York")

Example:

inTimeWindow(now, "09:00", "17:00", "America/New_York")

Note: Midnight-wrapping is not supported. If end <= start, the function returns false. To match overnight windows, use two rules or combine with !.

dayOfWeek

dayOfWeek(now) -> string
dayOfWeek(now, tz) -> string

Returns the lowercase weekday name (e.g., "monday", "friday"). The one-argument form uses UTC; the two-argument form converts to the given IANA timezone first.

ParameterTypeDescription
nowtimestampTimestamp to check (use the now variable)
tzstringOptional. IANA timezone name

Example:

dayOfWeek(now) == "saturday" || dayOfWeek(now) == "sunday"
dayOfWeek(now, "Asia/Tokyo") == "monday"

Rate limiting

rateCount

rateCount(key, window) -> int

Increments a counter for key and returns the number of hits within window. Use this to enforce rate limits per agent, per operation, or any arbitrary grouping.

ParameterTypeDescription
keystringCounter key — typically built from context fields
windowstringTime window: "30s", "5m", "1h". Min 1s, max 24h

Example:

rateCount(context.agent_id + ":create_issue", "1h") > 100

Note: rateCount always increments the counter, including during audit_only evaluation. Counters are local to the process and are not shared across instances.

Content detection

containsAny

containsAny(field, terms) -> bool

Returns true if field contains any of the strings in terms. Matching is case-insensitive.

ParameterTypeDescription
fieldstringText to search
termslist(string)Substrings to match against

Example:

containsAny(params.body, ["password", "secret", "api_key"])

estimateTokens

estimateTokens(field) -> int

Returns a rough token count for field, calculated as the character (rune) count of field divided by 4.

ParameterTypeDescription
fieldstringText to estimate

Example:

estimateTokens(params.prompt) > 10000

Note: This is a character-count heuristic, not a tokenizer. Actual token counts vary by model.

String manipulation

lower

lower(field) -> string

Returns field converted to lowercase.

Example:

lower(params.status) == "urgent"

upper

upper(field) -> string

Returns field converted to uppercase.

Example:

upper(params.priority_label) == "P0"

matchesDomain

matchesDomain(email, domains) -> bool

Returns true if the domain part of email matches any entry in domains. Subdomain matching is supported: "eng.example.com" matches "example.com".

ParameterTypeDescription
emailstringEmail address to check
domainslist(string)Allowed domain names

Example:

matchesDomain(context.user_id, ["example.com", "example.org"])

Note: Returns false if email does not contain an @ character. Comparison is case-insensitive.

Secret detection

hasSecrets

hasSecrets(value) -> bool

Returns true if the value contains patterns that look like secrets (API keys, tokens, passwords). Detection uses gitleaks pattern rules.

value may be a string, or a map/list (e.g. a whole request body). For maps and lists, every string leaf is scanned recursively (map values only — keys are treated as field names, not secret material); the function returns true if any leaf matches. Non-string scalars (numbers, booleans, null) never match.

ParameterTypeDescription
valuestring | map | listText, or an object/array whose string leaves are scanned recursively

Example:

hasSecrets(params.message)        // scan a single field
hasSecrets(params.body)           // scan an entire JSON request body
hasSecrets(params.body.headers)   // scan a nested object

Note: Pattern-based detection. It catches common secret formats but does not guarantee detection of all secrets, and false positives are possible.

Request parsing

graphql

graphql(body) -> map

Parses a GraphQL-over-HTTP request body — the decoded JSON object {"query": ..., "variables": ..., "operationName": ...} — and returns its operations and root fields. Use it to write rules against GraphQL APIs, where every request is a POST to one endpoint and the operation lives in the body.

ParameterTypeDescription
bodydynThe decoded request body, typically params.body

The result is a map:

KeyTypeDescription
validboolfalse if the body is not a JSON object, query is missing or not a string, variables is not an object, the document does not parse, or a fragment is unknown, cyclic, or expands past the limits below
errorstringWhy the body is invalid; "" when valid is true
operationslist(map)One entry per operation: {type, name, fields}. type is "query", "mutation", or "subscription"; name is "" for an anonymous operation
querieslist(map)Root fields of every query operation
mutationslist(map)Root fields of every mutation operation
subscriptionslist(map)Root fields of every subscription operation

Each field is {name, alias, args}. alias is "" when the field has none. args maps argument names to values with variables substituted.

Example:

- name: no-issue-deletion
  match:
    operation: "post api.linear.app/graphql"
    when: "graphql(params.body).mutations.exists(m, m.name == 'issueDelete')"
  action: deny
  message: "Deleting issues is not permitted."

- name: unparseable-graphql
  match:
    operation: "post api.linear.app/graphql"
    when: "!graphql(params.body).valid"
  action: deny
  message: "GraphQL request could not be parsed."
graphql(params.body).mutations.exists(m,
  has(m.args.input) && has(m.args.input.repositoryId) &&
  !(m.args.input.repositoryId in ["R_kgDOAbCd"]))

Semantics:

  • Every operation is reported. operationName is ignored, so a mutation is visible to rules even when the client asks the server to run a different operation from the same document.
  • Root fragments are expanded. Fragment spreads and inline fragments in an operation’s root selection set are flattened into its fields. Type conditions and directives are ignored — a field marked @skip(if: true) is still reported.
  • Aliases do not hide fields. name is the field’s real name; alias is reported separately.
  • Variables are substituted. A variable takes its value from variables (an explicit null counts as a value), then from its default in the operation’s variable definitions. A variable with neither is omitted from an object argument and becomes null inside a list. Variables nested in object and list literals are substituted too.
  • Literal values become strings, ints, doubles, booleans, or null. Enum values become strings. String escapes are decoded. An integer outside the 64-bit range is kept as its literal text.
  • Original case. GraphQL names and node IDs are case-sensitive, so graphql(params.body) parses the body as the client sent it, even when the scope lowercases params for matching (the default). Compare names and values with their exact case, or wrap them in lower().
  • Computed bodies. Pass a direct params path, such as params.body or params['body'], to preserve the original query and variable values. Reconstructed maps and other computed expressions use the argument as evaluated; in a case-insensitive scope, values read from params have already been lowercased, including variable values. Use case_sensitive: true when computing a body that must preserve case.
  • Limits. Documents over 100,000 tokens, fragment nesting deeper than 32 levels, or more than 1,000 expanded root fields are invalid.
  • Never errors. Invalid input returns valid: false with empty lists, so .exists() over mutations is always safe. Pair content rules with a !graphql(params.body).valid deny rule so an unparseable body fails closed.

Note: graphql reads params.body, so the scope requires the request body. Pin GraphQL rules to the endpoint with operation (as above) so a gatekeeper using Engine.RequiresBodyFor buffers bodies only for that endpoint. See Inspecting the request body.