diff --git a/.claude/skills/seclai-changelog/SKILL.md b/.claude/skills/seclai-changelog/SKILL.md index 06a0beb..3365c87 100644 --- a/.claude/skills/seclai-changelog/SKILL.md +++ b/.claude/skills/seclai-changelog/SKILL.md @@ -70,7 +70,7 @@ Do not guess the next version. Releases are cut by `seclai/github-tag-action` in - contains `#minor` → minor bump - otherwise → `DEFAULT_BUMP: patch` -So a PR that adds endpoints must say `#minor` in its title/merge commit, or the heading you write will not match the tag that gets cut. Confirm the intended bump with the user when it isn't stated, and flag the mismatch risk if the PR title lacks the keyword. +So a change that adds endpoints must say `#minor` in a commit message, or the heading you write will not match the tag that gets cut. The keyword goes in the commit message, not the PR title. Confirm the intended bump with the user when it isn't stated, and flag the mismatch risk if no commit message carries the keyword. Check `git tag --sort=-v:refname | head -1` for the current latest, then apply the bump. @@ -160,8 +160,10 @@ export type AddEmailDomainInput = Pick See `AddEmailDomainInput` and `CreateExperimentInput` in `src/types.ts`. -**Compile the doc examples.** `npm run typecheck` covers `src/` and `tests/`, not -README or changelog snippets. Paste any example you write into a scratch `.ts` +**Compile the doc examples.** `npm run typecheck` covers `src/` only — its +`tsconfig.json` includes `src/**/*.ts`, and vitest strips types without checking +them, so `tests/` is not type-checked either — let alone README or changelog +snippets. Paste any example you write into a scratch `.ts` that imports from `../src/index` and compile it — that is how the `delegated`-is-required bug above was found, after the snippet had already shipped in a PR. diff --git a/.claude/skills/seclai-sdk-sync/SKILL.md b/.claude/skills/seclai-sdk-sync/SKILL.md index 16818d9..2f72dd5 100644 --- a/.claude/skills/seclai-sdk-sync/SKILL.md +++ b/.claude/skills/seclai-sdk-sync/SKILL.md @@ -74,7 +74,20 @@ and swallowed the helpers below it), and `Search` was reported as never sending required `q` (the extractor read `q["k"] =` but not the map literal that sets it). Four of six Go findings were artefacts. Since both were fixed, all four SDKs report the *same* three findings — independently-written clients agreeing is the signal -that the check is reading them correctly. +that the check is reading them correctly. Twice more since: JavaScript's shorthand +`query: { download }` was read as sending nothing, and Go's `sortableListQuery` +was unknown to the extractor, so four endpoints were reported as never sending +page/limit/sort/order. + +How keys are read, so a finding can be checked against it: + +- **JavaScript** query literals are read member by member: `a: x`, `"a": x` and + the shorthand `a` are keys. A `...spread` or `[computed]` key makes the site + UNPARSED, never clean. +- **Go** package-level functions returning `map[string]string` (`listQuery`, + `sortableListQuery`) are query builders. Their keys are read from their own + bodies, including builders they call, so `listQuery` is credited with + page/limit only. A builder whose body cannot be read makes its callers UNPARSED. ## `returns` — the axis that catches a changed response @@ -142,8 +155,36 @@ diff called 21 JavaScript changes breaking when none were: gone, parameter list changed, or a return type changed in a static language. - **WARN** — compatible but worth checking: a *trailing* optional parameter (source compatible; flagged as binary breaking for C#), `unknown` narrowed to a - concrete type in TypeScript (safe), or a Python return annotation (not enforced - — but confirm the runtime value did not change too). + concrete type in TypeScript (safe), an optional member added to an inline + TypeScript options object such as `opts: { signal?: AbortSignal } = {}` (never + to an empty `{}`, which accepts any value the new type may reject; every + other member unchanged or only widened to accept `undefined`, the parameter's + name and its default unchanged; usually source + compatible, but a caller passing a non-literal object that already carries a + same-named property of another type — `const o = { signal: "abc" }` — no + longer compiles, since excess-property checks only cover literals), an + optional options-object member widened to accept `undefined` + (`x?: T` -> `x?: T | undefined`; source compatible), a TypeScript parameter + type wrapped in `Omit` (usually source compatible: an object literal + that sets an omitted key no longer compiles) or `Partial` (source + compatible), a TypeScript options parameter retyped to another **named** type + whose members, resolved from the declarations under `src/` at the tag and in + the working tree (interfaces, `extends`, aliases, `&`, `Omit`, `Pick`, + `Partial`), keep every old member with the same optionality and type and add + only optional ones — a member whose type names a local type counts as + unchanged only if that type's declaration is identical at both revisions, and + a type that does not resolve (generic, import, indexed access, union) stays + breaking — a required Python or TypeScript parameter made optional in place + (`id: str` -> `id: str | None = None`, `id: string` -> `id?: string`; same + name and position, positional stays positional, type unchanged or only widened + by `None`/`undefined`; not graded this way for C#), or a Python return + annotation (not enforced — but confirm the runtime value did not change too). + The parameter-level kinds combine: each old parameter must be unchanged or + changed in one of these ways, and any added parameter must be optional and at + the end. + +Only exported Go methods are surface. A lowercase method is unreachable outside +the package, so a change to one breaks no caller. An optional parameter inserted *mid-list* is graded breaking, not a warning: in C# a positional `M(id, token)` then tries to bind `token` to the new parameter. @@ -310,5 +351,6 @@ local conventions (`searchDocs` / `search_docs` / `SearchDocs`). ## Release The version comes from the merge commit message, read by `seclai/github-tag-action` -with `DEFAULT_BUMP: patch`. A sync that adds endpoints needs `#minor` in the PR -title, or it ships as a patch and the changelog heading will not match the tag. +with `DEFAULT_BUMP: patch`. A sync that adds endpoints needs `#minor` in a commit +message (not the PR title), or it ships as a patch and the changelog heading +will not match the tag. diff --git a/.claude/skills/seclai-sdk-sync/sdksync.py b/.claude/skills/seclai-sdk-sync/sdksync.py index 6a9d205..428f6a7 100755 --- a/.claude/skills/seclai-sdk-sync/sdksync.py +++ b/.claude/skills/seclai-sdk-sync/sdksync.py @@ -47,14 +47,29 @@ # "this method sends no params" — a silent false pass. # helpers — positional helper calls that expand to a fixed, ordered key list. # Expansion is arity-aware: only as many keys as arguments supplied. +# Signatures, used by `surface`: +# sig_re — a public method's head, ending on its opening `(`. The +# parameter list is then sliced by paren matching, never by a +# `[^)]*` class: a callback type or a `(default: 2000)` doc +# comment would end it early, the method would drop out of the +# surface and be reported REMOVED. +# sig_tail_re — matched straight after the closing `)` (the return type). +# sig_groups — head groups, then "params", then tail groups. +# line_comment — the line-comment marker; `public_surface` strips these, and +# `/* */` too when it is `//`, from the whole file. Default `//`. # Endpoint helpers, used by `params` and `returns` (see `request_blocks`): # helper_re — a NON-public method declaration on the client, name captured. # helper_call — how the client calls one of its own methods; `{name}` is filled # in. Receiver-qualified so `_client.X(` and `t.c.x(` — a typed # façade calling in from another class — are not followed. +_JS_HELPER_RE = (r"^ (?:(?:private|protected) (?:static )?(?:async )?\*?|(?:async )?\*?#)" + r"([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]") + LANGS = { "python": { - "sig_re": r"\n (?:async )?def ([a-z]\w*)\(([^)]*)\)\s*->\s*([^:]+):", + "sig_re": r"\n (?:async )?def ([a-z]\w*)\(", + "sig_tail_re": r"\s*->\s*([^:]+):", + "line_comment": "#", "sig_groups": ("name", "params", "ret"), "detect": "seclai/seclai.py", "sources": ["seclai/seclai.py"], @@ -72,7 +87,8 @@ "skip": {"request", "request_raw", "stream", "paginate"}, }, "javascript": { - "sig_re": r"\n (?:async )?(\w+)\(([^)]*)\)\s*:\s*([^{\n]+?)\s*\{", + "sig_re": r"\n (?:async )?(\w+)\(", + "sig_tail_re": r"\s*:\s*([^{\n]+?)\s*\{", "sig_groups": ("name", "params", "ret"), "detect": "src/client.ts", "sources": ["src/client.ts"], @@ -89,15 +105,27 @@ "return_re": r"\s*:\s*([^{\n]+?)\s*\{", "dict_at": [r"query:\s*"], "dict_key_re": r'["\']?([a-zA-Z_][a-zA-Z0-9_]*)["\']?\s*:', + # Read a query literal member by member rather than with dict_key_re: + # `{ download }` and `{ offset, limit: opts.limit }` send keys the regex + # cannot see (both were reported UNEXPOSED), and a `...spread` or + # `[computed]` member sends keys nobody can read here — UNPARSED, never + # clean. See `object_literal_keys`. + "dict_members": True, # `private`/`protected`/`#name` members only. An unmodified `_name(` is # matched by method_re and already audited as a block of its own. - "helper_re": (r"^ (?:(?:private|protected) (?:static )?(?:async )?\*?|(?:async )?\*?#)" - r"([a-zA-Z_][a-zA-Z0-9_]*)\s*[(<]"), + "helper_re": _JS_HELPER_RE, + # method_re skips helpers, so without this a method's block runs on into + # the helper below it and takes that helper's request as its own. + "boundary_re": _JS_HELPER_RE, "helper_call": r"\bthis\.#?{name}\s*[(<]", "skip": {"request", "requestRaw", "uploadFile", "paginate"}, }, "go": { - "sig_re": r"func \(c \*Client\) (\w+)\(([^)]*)\) \(([^)]*)\)", + # Exported only: a lowercase method is unreachable outside the package, + # so a change to one breaks no caller. `alertConfigsBody` and + # `modelAlertsBody` were graded BREAKING for that reason alone. + "sig_re": r"func \(c \*Client\) ([A-Z]\w*)\(", + "sig_tail_re": r" \(([^)]*)\)", "sig_groups": ("name", "params", "ret"), "detect": "client.go", "sources": ["*.go"], @@ -116,7 +144,12 @@ # false positive twin of the bug this check exists to find. "dict_at": [r"map\[string\]string"], "dict_key_re": r'"([a-zA-Z_][a-zA-Z0-9_]*)"\s*:', - "helpers": {"listQuery(": ["page", "limit"]}, + # Package-level functions that build and return a query map, such as + # `listQuery(page, limit)` and `sortableListQuery(opts)`. Their keys are + # read from their own bodies (see `query_builders`) rather than listed + # here: a hard-coded list missed `sortableListQuery`, so every method + # using it was reported as never sending page/limit/sort/order. + "builder_re": r"^func ([a-z][A-Za-z0-9]*)\([^)]*\)\s*map\[string\]string\s*\{", "helper_re": r"^func \(c \*Client\) ([a-z][A-Za-z0-9]*)\(", "helper_call": r"(?,?\[\]. ]+?) ([A-Z]\w*)\(([^)]*)\)", + "sig_re": r"public (?:async )?([\w<>,?\[\]. ]+?) ([A-Z]\w*)\(", "sig_groups": ("ret", "name", "params"), "detect": "src/Seclai/SeclaiClient.cs", "sources": ["src/Seclai/*.cs"], @@ -216,20 +249,50 @@ def load_spec(ref: str | None, path: str, repo: Path) -> dict: # ── params ─────────────────────────────────────────────────────────────────── +def _quoted_end(text: str, i: int) -> int | None: + """Index just past the string literal opening at `text[i]`, or None. + + Only a literal that closes on the same line counts. Every scanner below runs + over raw source, comments included, so an apostrophe in `// don't` must stay + an ordinary character rather than open a string that swallows the rest of + the block. A backslash escapes the next character. + """ + q = text[i] + j = i + 1 + while j < len(text): + ch = text[j] + if ch == "\\": + j += 2 + continue + if ch == q: + return j + 1 + if ch == "\n": + return None + j += 1 + return None + + def balanced_slice(text: str, at: int, opener: str = "{", closer: str = "}") -> str | None: - """Return the brace-delimited literal starting at or after `at`. + """Return the bracket-delimited literal starting at or after `at`. Regex cannot do this: query literals span lines and nest, and a non-greedy - match silently truncates at the first inner `}`. + match silently truncates at the first inner `}`. Brackets inside a string + literal (`fmt?: "{id}"`, `sep = ")"`) are text, not structure. """ i = text.find(opener, at) if i == -1: return None depth, j = 0, i while j < len(text): - if text[j] == opener: + ch = text[j] + if ch in "\"'`": + end = _quoted_end(text, j) + if end is not None: + j = end + continue + if ch == opener: depth += 1 - elif text[j] == closer: + elif ch == closer: depth -= 1 if depth == 0: return text[i + 1: j] @@ -237,27 +300,71 @@ def balanced_slice(text: str, at: int, opener: str = "{", closer: str = "}") -> return None -def split_args(sig: str) -> list[str]: +def strip_comments(text: str, line: str = "//") -> str: + """`text` with `/* ... */` and `line`-to-end-of-line comments replaced by a + space. String literals are left intact, so `"https://x"` is not a comment. + + Python passes `line="#"` and has no block comments; `/*` there would be + an operator sequence, never a comment, so it is only honoured for `//`. + """ + out, j, n = [], 0, len(text) + while j < n: + ch = text[j] + if ch in "\"'`": + end = _quoted_end(text, j) + if end is not None: + out.append(text[j:end]) + j = end + continue + if line == "//" and text.startswith("/*", j): + end = text.find("*/", j + 2) + j = n if end == -1 else end + 2 + out.append(" ") + continue + if text.startswith(line, j): + end = text.find("\n", j) + j = n if end == -1 else end + out.append(" ") + continue + out.append(ch) + j += 1 + return "".join(out) + + +def split_args(sig: str, seps: str = ",", keep_star: bool = False) -> list[str]: """Split a comma-separated argument or parameter list at depth 0. A naive `split(",")` turns `Dictionary q` into two entries, which over-counts arity for the query helpers and reports a phantom - signature change for `surface`. + signature change for `surface`. The `>` of a TypeScript arrow `=>` is not a + closing bracket: counting it would split `cb: (a: A, b: B) => void` after + the arrow. `seps` lets an object-literal type body split on `;` too. + Separators and brackets inside string literals are text. """ - out, depth, cur = [], 0, "" - for ch in sig: + out, depth, cur, prev = [], 0, [], "" + j, n = 0, len(sig) + while j < n: + ch = sig[j] + if ch in "\"'`": + end = _quoted_end(sig, j) + if end is not None: + cur.append(sig[j:end]) + j = end + continue if ch in "<([{": depth += 1 - elif ch in ">)]}": + elif ch in ")]}" or (ch == ">" and prev != "="): depth -= 1 - if ch == "," and depth == 0: - out.append(cur.strip()) - cur = "" + prev = ch + if ch in seps and depth == 0: + out.append("".join(cur).strip()) + cur = [] else: - cur += ch - if cur.strip(): - out.append(cur.strip()) - return [p for p in out if p and p != "*"] + cur.append(ch) + j += 1 + if "".join(cur).strip(): + out.append("".join(cur).strip()) + return [p for p in out if p and (keep_star or p != "*")] def spec_query_index(spec: dict) -> dict[tuple[str, str], tuple[str, set[str], set[str]]]: @@ -406,12 +513,82 @@ def via_helper_line(n: int) -> str: f" holding the request (one hop)") -def block_query_keys(body: str, cfg: dict) -> tuple[set[str], bool]: +def object_literal_keys(lit: str) -> tuple[set[str], bool]: + """Keys of a JavaScript object literal's body, read member by member. + + `a: x`, `"a": x` and the shorthand `a` each name a key. A `...spread`, a + `[computed]` key or anything else unreadable makes the literal unparsed: + it can send keys nobody can see, so it must never read as clean. Nested + literals are a member's value and contribute no keys of their own. + """ + keys: set[str] = set() + ok = True + for member in split_args(strip_comments(lit)): + m = re.match(r"""(?:"([^"]+)"|'([^']+)'|([A-Za-z_$][\w$]*))\s*:""", member) + if m: + keys.add(next(g for g in m.groups() if g)) + elif re.fullmatch(r"[A-Za-z_$][\w$]*", member): + keys.add(member) + else: + ok = False + return keys, ok + + +def query_builders(texts: list[str], cfg: dict) -> dict[str, tuple[set[str], bool]]: + """Package-level query builder name -> (keys it can set, parsed_ok). + + Keys come from the builder's own body, including any builder it calls, so + `sortableListQuery` inherits `listQuery`'s page/limit and adds sort/order — + and a method calling only `listQuery` is never credited with sort/order. + A builder whose body cannot be read, or that recurses, is not ok: every + method using it is then UNPARSED rather than credited with nothing. + """ + if "builder_re" not in cfg: + return {} + bodies: dict[str, str] = {} + for text in texts: + for m in re.finditer(cfg["builder_re"], text, re.M): + body = balanced_slice(text, m.end() - 1) + bodies.setdefault(m.group(1), body if body is not None else "") + out: dict[str, tuple[set[str], bool]] = {} + + def resolve(name: str, stack: tuple[str, ...]) -> tuple[set[str], bool]: + if name in out: + return out[name] + if name in stack or not bodies[name]: + return set(), False + nested = {n: resolve(n, stack + (name,)) for n in bodies + if n != name and _calls(bodies[name], n)} + res = block_query_keys(bodies[name], cfg, nested) + if any(_calls(bodies[name], n) for n in stack + (name,)): + res = (res[0], False) + out[name] = res + return res + + for name in bodies: + resolve(name, ()) + return out + + +def _calls(body: str, name: str) -> bool: + """A call to the free function `name(` — not `x.name(`, not `othername(`.""" + return re.search(rf"(? tuple[set[str], bool]: """(keys, parsed_ok). parsed_ok is False when a construction site was found - but could not be read — reported as an error, never as "sends nothing".""" + but could not be read — reported as an error, never as "sends nothing". + `builders` is `query_builders(...)`: calls to them add their keys.""" keys: set[str] = set() ok = True + for name, (bkeys, bok) in (builders or {}).items(): + if _calls(body, name): + keys |= bkeys + ok = ok and bok + for anchor, ordered in (cfg.get("helpers") or {}).items(): for m in re.finditer(re.escape(anchor), body): args = balanced_slice(body, m.end() - 1, "(", ")") @@ -438,7 +615,12 @@ def block_query_keys(body: str, cfg: dict) -> tuple[set[str], bool]: if lit is None: ok = False continue - keys |= set(re.findall(cfg["dict_key_re"], lit)) + if cfg.get("dict_members"): + lkeys, lok = object_literal_keys(lit) + keys |= lkeys + ok = ok and lok + else: + keys |= set(re.findall(cfg["dict_key_re"], lit)) if indirect and not keys: ok = False @@ -467,9 +649,10 @@ def cmd_params(args) -> int: via_helper = 0 texts = [f.read_text(errors="replace") for f in files] + builders = query_builders(texts, cfg) for mname, _body, call, request_body, helper in request_blocks(texts, cfg): via_helper += helper is not None - keys, ok = block_query_keys(request_body, cfg) + keys, ok = block_query_keys(request_body, cfg, builders) if not ok: unparsed.add((mname, f"{call[0]} {call[1]}")) if call not in index: @@ -1013,8 +1196,19 @@ def public_surface(text: str, cfg: dict) -> dict[str, set[tuple[str, str]]]: def norm(x: str | None) -> str: return " ".join((x or "").split()) + tail_re = re.compile(cfg.get("sig_tail_re", ""), re.S) + # Comments are not signature, and stripped before slicing so a `)` or an + # apostrophe in one cannot end the parameter list early. + text = strip_comments(text, cfg.get("line_comment", "//")) for m in re.finditer(cfg["sig_re"], text, re.S): - parts = dict(zip(order, m.groups())) + open_paren = m.end() - 1 + params = balanced_slice(text, open_paren, "(", ")") + if params is None: + continue + tail = tail_re.match(text, open_paren + len(params) + 2) + if tail is None: + continue + parts = dict(zip(order, m.groups() + (params,) + tail.groups())) out.setdefault(norm(parts["name"]), set()).add((norm(parts["ret"]), norm(parts["params"]))) return out @@ -1024,7 +1218,517 @@ def norm(x: str | None) -> str: _params = split_args -def classify_change(lang: str, old: tuple[str, str], new: tuple[str, str]) -> tuple[str, str]: +def _ts_inline_object(param: str) -> tuple[str, str, str] | None: + """(prefix, body, suffix) when a TypeScript parameter's type is an inline + object literal: `opts: { a?: string } = {}` -> ("opts:", "a?: string", "= {}"). + + The `{` must follow the annotation colon directly, so a default value such as + `x = {}` or a generic `Partial<{...}>` never qualifies. None otherwise. + """ + m = re.match(r"\s*[\w$]+\s*\??\s*:\s*\{", param) + if not m: + return None + start = m.end() - 1 + body = balanced_slice(param, start) + if body is None: + return None + end = start + len(body) + 1 + return (" ".join(param[:start].split()), body, " ".join(param[end + 1:].split())) + + +def _ts_object_members(body: str) -> dict[str, tuple[bool, str]] | None: + """member name -> (optional, normalised text) for an object-literal type body, + split on depth-0 `;` or `,`. None when any member cannot be named (index + signatures, call signatures, spread-like text) or a name repeats — the caller + then refuses to call the change compatible. Comments are dropped first: + seclai-javascript documents each member with `/** ... */`, which would + otherwise hide the member's name, and a `,` or `;` inside one would split it. + """ + parts = split_args(strip_comments(body), ";,") + out: dict[str, tuple[bool, str]] = {} + for raw in parts: + text = " ".join(raw.split()) + if not text: + continue + m = re.match(r"(?:readonly\s+)?([\w$]+|\"[^\"]*\"|'[^']*')\s*(\?)?\s*[:(]", text) + if not m or m.group(1) in out: + return None + out[m.group(1)] = (bool(m.group(2)), text) + return out + + +_TS_MEMBER_RE = re.compile(r"(?:readonly\s+)?([\w$]+|\"[^\"]*\"|'[^']*')\s*(\?)?\s*:\s*(.*)$", re.S) + + +def _ts_union(t: str) -> list[str]: + """Top-level `|` members of a type, whitespace-normalised and sorted.""" + return sorted(" ".join(x.split()) for x in split_args(t, "|")) + + +def _ts_widened_to_undefined(old: str, new: str) -> bool: + """`x?: T` -> `x?: T | undefined` (or `undefined | T`). Both optional, same + name, and the new union is exactly the old one plus `undefined`. Under + exactOptionalPropertyTypes that admits an explicit `undefined`; without it + the type is unchanged. Either way every old value and old use still fits.""" + mo, mn = _TS_MEMBER_RE.match(old), _TS_MEMBER_RE.match(new) + if not mo or not mn or mo.group(1) != mn.group(1) or not (mo.group(2) and mn.group(2)): + return False + old_u = _ts_union(mo.group(3)) + return "undefined" not in old_u and _ts_union(mn.group(3)) == sorted(old_u + ["undefined"]) + + +def _ts_options_change(o: str, n: str) -> set[str] | None: + """Kinds of compatible change between two inline options-object parameters, + or None when the change is not provably compatible. Same name, optionality + and default; every old member unchanged, in any order ("same"), or only + widened to accept `undefined`; every added member optional, and none added to an empty `{}`.""" + po, pn = _ts_inline_object(o), _ts_inline_object(n) + if po is None or pn is None or po[0] != pn[0] or po[2] != pn[2]: + return None + mo, mn = _ts_object_members(po[1]), _ts_object_members(pn[1]) + if mo is None or mn is None: + return None + # `{}` accepts any non-null value; a weak type such as `{ a?: T }` does not (TS2559). + if not mo and mn: + return None + kinds: set[str] = set() + for k, (opt, text) in mo.items(): + if k not in mn: + return None + if mn[k] == (opt, text): + continue + if not _ts_widened_to_undefined(text, mn[k][1]): + return None + kinds.add("undefined") + added = [v for k, v in mn.items() if k not in mo] + if not all(opt for opt, _ in added): + return None + if added: + kinds.add("props") + return kinds or {"same"} + + +def _ts_wrapped_type(o: str, n: str) -> str | None: + """"omit" or "partial" when the parameter's type `T` became `Omit` + (keys a union of string literals) or `Partial`, with `T`, the name, the + optionality and the default textually unchanged. Every old argument still + fits both. None otherwise — including `Pick<>` and an `Omit<>` of another + type.""" + ho = re.match(r"\s*([\w$]+\s*\??\s*:\s*)", o) + hn = re.match(r"\s*([\w$]+\s*\??\s*:\s*)", n) + if not ho or not hn or " ".join(ho.group(1).split()) != " ".join(hn.group(1).split()): + return None + rest_o, rest_n = o[ho.end():], n[hn.end():] + w = re.match(r"(Omit|Partial)\s*<", rest_n) + if not w: + return None + inner = balanced_slice(rest_n, w.end() - 1, "<", ">") + if inner is None: + return None + after = rest_n[w.end() + len(inner) + 1:] + args = split_args(inner) + kind = w.group(1).lower() + if kind == "omit": + if len(args) != 2: + return None + keys = split_args(args[1], "|") + if not keys or not all(re.fullmatch(r"\"[^\"]*\"|'[^']*'", k) for k in keys): + return None + elif len(args) != 1: + return None + norm = lambda x: " ".join(x.split()) # noqa: E731 + return kind if norm(rest_o) == norm(args[0] + after) else None + + +_TS_COMPATIBLE_LABELS = { + "default": "required parameter made optional in place — source compatible", + "added": "optional parameters added — source compatible", + "props": ("optional property added to an options object — usually source compatible, " + "but breaks a caller passing a non-literal object whose same-named property " + "has another type"), + "undefined": "optional property widened to accept undefined — source compatible", + "omit": ("parameter type wrapped in Omit<…> — usually source compatible: every old value " + "still fits, but an object literal that sets an omitted key no longer compiles"), + "partial": "parameter type wrapped in Partial<…> — source compatible: every old value still fits", + "same": "options object unchanged apart from member order or separators", +} + + +def _ts_compatible_change(old: list[str], new: list[str]) -> str | None: + """Label when every changed TypeScript parameter changed in one of the + provably compatible ways above, with the same count, order and every other + parameter textually unchanged. None — graded breaking — otherwise.""" + if len(old) != len(new) or old == new: + return None + kinds: set[str] = set() + for o, n in zip(old, new): + if o == n: + continue + k = _ts_options_change(o, n) + if k is None: + w = _ts_wrapped_type(o, n) + if w is None: + return None + k = {w} + kinds |= k + if len(kinds) > 1: + kinds.discard("same") + return "; ".join(_TS_COMPATIBLE_LABELS[k] for k in _TS_COMPATIBLE_LABELS if k in kinds) + + +# ── Parameters that gained a default ───────────────────────────────────────── +# `f(id: str)` -> `f(id: str | None = None)` and `f(id: string)` -> `f(id?: string)` +# keep every old call working, but a textual diff called both BREAKING. They +# are accepted only parameter by parameter: same name, same position, same +# kind, the type unchanged or only widened to admit None/undefined, and every +# other parameter unchanged or added as optional at the end. Anything else — +# a default lost, a rename, a reorder, a narrowed type, a positional parameter +# made keyword-only — stays BREAKING. C# is deliberately not included: the +# default lands in metadata the caller compiled against, and it has no case +# that needs it. + +def _top_level_index(s: str, ch: str) -> int: + """Index of the first `ch` at bracket depth 0 outside string literals, or -1. + For `=`, the `=` of `=>`, `==`, `!=`, `<=` and `>=` does not count.""" + depth, j, prev = 0, 0, "" + while j < len(s): + c = s[j] + if c in "\"'`": + end = _quoted_end(s, j) + if end is not None: + j, prev = end, "" + continue + if c in "<([{": + depth += 1 + elif c in ")]}" or (c == ">" and prev != "="): + depth -= 1 + elif c == ch and depth == 0: + nxt = s[j + 1] if j + 1 < len(s) else "" + if ch != "=" or (nxt not in "=>" and prev not in "=!<>"): + return j + prev = c + j += 1 + return -1 + + +def _union_members(t: str) -> set[str]: + m = re.fullmatch(r"\s*Optional\[(.*)\]\s*", t, re.S) + if m: + return {" ".join(x.split()) for x in split_args(m.group(1), "|")} | {"None"} + return {" ".join(x.split()) for x in split_args(t, "|")} + + +def _py_param(p: str) -> tuple[str, str, str | None] | None: + """(name, type, default) of one Python parameter, or None if not plain.""" + eq = _top_level_index(p, "=") + head, default = (p, None) if eq < 0 else (p[:eq], p[eq + 1:].strip()) + m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*(?::\s*(.+?))?\s*", head, re.S) + if not m: + return None + return m.group(1), " ".join((m.group(2) or "").split()), default + + +def _ts_param(p: str) -> tuple[str, bool, str, str | None] | None: + """(name, optional `?`, type, default) of one TypeScript parameter, or None.""" + eq = _top_level_index(p, "=") + head, default = (p, None) if eq < 0 else (p[:eq], " ".join(p[eq + 1:].split())) + m = re.fullmatch(r"\s*([A-Za-z_$][\w$]*)\s*(\?)?\s*(?::\s*(.+?))?\s*", head, re.S) + if not m: + return None + return m.group(1), bool(m.group(2)), " ".join((m.group(3) or "").split()), default + + +def _gained_default(lang: str, o: str, n: str) -> bool: + """`o` was required and `n` is the same parameter made optional, its type + unchanged or only widened by None (Python) / undefined (TypeScript).""" + if lang == "python": + po, pn = _py_param(o), _py_param(n) + if not po or not pn or po[0] != pn[0] or po[2] is not None or pn[2] is None: + return False + nullable = "None" + else: + po, pn = _ts_param(o), _ts_param(n) + if (not po or not pn or po[0] != pn[0] or po[1] or po[3] is not None + or not (pn[1] or pn[3] is not None)): + return False + nullable = "undefined" + type_at = 2 if lang == "javascript" else 1 + old_t, new_t = po[type_at], pn[type_at] + if not old_t: + return not new_t + return new_t == old_t or _union_members(new_t) == _union_members(old_t) | {nullable} + + +def _is_optional(lang: str, p: str) -> bool: + if lang == "python": + q = _py_param(p) + return q is not None and q[2] is not None + q = _ts_param(p) + return q is not None and (q[1] or q[3] is not None) + + +def _py_kinds(raw: str) -> list[tuple[str, str]] | None: + """[(param, "pos"|"kw")] with the bare `*` consumed, or None when the list + has `/`, `*args` or `**kwargs` — shapes this rule does not reason about.""" + out, kind = [], "pos" + for p in split_args(raw, keep_star=True): + if p == "*": + kind = "kw" + elif p == "/" or p.startswith("*"): + return None + else: + out.append((p, kind)) + return out + + +def _gained_default_change(lang: str, old_par: str, new_par: str, + param_change=None) -> set[str] | None: + """Kinds of compatible change, when every old parameter is unchanged, made + optional in place, or (via `param_change`) changed in another provably + compatible way, and every added parameter is optional. None otherwise.""" + if lang == "python": + ok, nk = _py_kinds(old_par), _py_kinds(new_par) + if ok is None or nk is None: + return None + o_pos = [p for p, k in ok if k == "pos"] + n_pos = [p for p, k in nk if k == "pos"] + o_kw = {(_py_param(p) or ("",))[0]: p for p, k in ok if k == "kw"} + n_kw = {(_py_param(p) or ("",))[0]: p for p, k in nk if k == "kw"} + if len(n_pos) < len(o_pos) or "" in o_kw or "" in n_kw: + return None + pairs = list(zip(o_pos, n_pos)) + for name, o in o_kw.items(): + if name not in n_kw: + return None + pairs.append((o, n_kw[name])) + added = n_pos[len(o_pos):] + [p for name, p in n_kw.items() if name not in o_kw] + else: + op, np_ = split_args(old_par), split_args(new_par) + if len(np_) < len(op): + return None + pairs, added = list(zip(op, np_)), np_[len(op):] + kinds: set[str] = set() + for o, n in pairs: + if o == n: + continue + if _gained_default(lang, o, n): + kinds.add("default") + continue + k = param_change(o, n) if param_change else None + if k is None: + return None + kinds |= k + if not all(_is_optional(lang, a) for a in added): + return None + if added: + kinds.add("added") + return kinds or None + + +# ── TypeScript named types ─────────────────────────────────────────────────── +# An options parameter retyped from one named type to another (`ListOptions` -> +# `ListSolutionsOptions`) was graded BREAKING on its text. It is compatible only +# when both types resolve, from source at their own revision, to members where +# every old member survives unchanged and every added one is optional. A type +# that does not resolve — a generic, an import, an indexed access, a top-level +# union — keeps the change BREAKING. + +_TS_BUILTIN = {"string", "number", "boolean", "undefined", "null", "unknown", "any", + "never", "object", "void", "bigint", "symbol", "true", "false", + "Record", "Array", "ReadonlyArray", "Promise", "Date", "Readonly", + "Partial", "Required", "Pick", "Omit", "Map", "Set", "readonly", + "keyof", "typeof"} + + +def _ts_expr_end(text: str, i: int) -> int: + """End of a type-alias expression starting at `i`: the first `;` at depth 0, + or a blank line / new top-level declaration when the `;` is omitted.""" + depth, j, prev = 0, i, "" + while j < len(text): + c = text[j] + if c in "\"'`": + end = _quoted_end(text, j) + if end is not None: + j, prev = end, "" + continue + if c in "<([{": + depth += 1 + elif c in ")]}" or (c == ">" and prev != "="): + depth -= 1 + elif depth == 0 and (c == ";" or (c == "\n" and re.match( + r"\n\s*(?:\n|(?:export\s+)?(?:interface|type|const|function|class|import)\b)", + text[j:]))): + return j + prev = c + j += 1 + return len(text) + + +def ts_declarations(texts: list[str]) -> dict[str, tuple | None]: + """Type name -> ("interface", [extends...], body, text) | ("alias", expr, text), + or None when it cannot be resolved (generic, or declared twice differently).""" + out: dict[str, tuple | None] = {} + + def put(name: str, decl: tuple | None) -> None: + if name in out and out[name] != decl: + out[name] = None + else: + out[name] = decl + + for raw in texts: + text = strip_comments(raw) + for m in re.finditer(r"(?m)^[ \t]*(?:export\s+)?(?:declare\s+)?interface\s+([\w$]+)\s*(<)?", + text): + brace = text.find("{", m.end()) + body = balanced_slice(text, m.end()) if brace >= 0 else None + if m.group(2) or body is None: + put(m.group(1), None) + continue + ext = text[m.end():brace].strip() + bases = split_args(ext[len("extends"):]) if ext.startswith("extends") else [] + if ext and not bases: + put(m.group(1), None) + continue + whole = " ".join(text[m.start():brace + len(body) + 2].split()) + put(m.group(1), ("interface", bases, body, whole)) + for m in re.finditer(r"(?m)^[ \t]*(?:export\s+)?(?:declare\s+)?type\s+([\w$]+)\s*(<)?", text): + if m.group(2): + put(m.group(1), None) + continue + eq = re.match(r"\s*=", text[m.end():]) + if not eq: + continue + start = m.end() + eq.end() + end = _ts_expr_end(text, start) + expr = " ".join(text[start:end].split()) + put(m.group(1), ("alias", expr, " ".join(text[m.start():end].split()))) + return out + + +def _ts_typed_members(body: str) -> dict[str, tuple[bool, str]] | None: + """member -> (optional, type) for an object type body; None if any member + is not a plain `name?: type` property (methods, index signatures, ...).""" + out: dict[str, tuple[bool, str]] = {} + for raw in split_args(strip_comments(body), ";,"): + text = " ".join(raw.split()) + if not text: + continue + m = _TS_MEMBER_RE.match(text) + if not m or m.group(1) in out: + return None + out[m.group(1).strip("\"'")] = (bool(m.group(2)), " ".join(m.group(3).split())) + return out + + +def _ts_string_keys(k: str) -> set[str] | None: + keys = split_args(k, "|") + if not keys or not all(re.fullmatch(r"\"[^\"]*\"|'[^']*'", x) for x in keys): + return None + return {x[1:-1] for x in keys} + + +def ts_resolve(expr: str, decls: dict, seen: tuple[str, ...] = () + ) -> dict[str, tuple[bool, str]] | None: + """Members of a TypeScript object type expression, or None if unresolvable.""" + e = " ".join(expr.split()) + while e.startswith("(") and balanced_slice(e, 0, "(", ")") == e[1:-1]: + e = e[1:-1].strip() + if not e: + return None + if e.startswith("{") and balanced_slice(e, 0) == e[1:-1]: + return _ts_typed_members(e[1:-1]) + if len(split_args(e, "|")) > 1: + return None + parts = split_args(e, "&") + if len(parts) > 1: + merged: dict[str, tuple[bool, str]] = {} + for part in parts: + r = ts_resolve(part, decls, seen) + if r is None: + return None + for k, v in r.items(): + if k in merged and merged[k] != v: + return None + merged[k] = v + return merged + m = re.fullmatch(r"(Omit|Pick|Partial)\s*<(.*)>", e, re.S) + if m: + args = split_args(m.group(2)) + base = ts_resolve(args[0], decls, seen) if args else None + if base is None: + return None + if m.group(1) == "Partial": + return {k: (True, t) for k, (_, t) in base.items()} if len(args) == 1 else None + keys = _ts_string_keys(args[1]) if len(args) == 2 else None + if keys is None: + return None + if m.group(1) == "Omit": + return {k: v for k, v in base.items() if k not in keys} + return {k: v for k, v in base.items() if k in keys} if keys <= set(base) else None + if not re.fullmatch(r"[A-Za-z_$][\w$]*", e) or e in seen: + return None + d = decls.get(e) + if d is None: + return None + if d[0] == "alias": + return ts_resolve(d[1], decls, seen + (e,)) + merged = {} + for b in d[1]: + r = ts_resolve(b, decls, seen + (e,)) + if r is None: + return None + merged.update(r) + own = _ts_typed_members(d[2]) + if own is None: + return None + merged.update(own) + return merged + + +def _ts_type_refs_unchanged(t: str, old_decls: dict, new_decls: dict) -> bool: + """Every identifier a property type names is a builtin, or a local type whose + declaration is textually identical at both revisions. Same text naming a + type that changed underneath is not the same type.""" + bare = re.sub(r"\"[^\"]*\"|'[^']*'|`[^`]*`", "", t) + for ident in set(re.findall(r"[A-Za-z_$][\w$]*", bare)): + if ident in _TS_BUILTIN: + continue + o, n = old_decls.get(ident), new_decls.get(ident) + if o is None or n is None or o[-1] != n[-1]: + return False + return True + + +def ts_named_options_change(o: str, n: str, old_decls: dict, new_decls: dict) -> set[str] | None: + """Kinds of compatible change between two options parameters whose types are + resolved from declarations; None unless provably compatible.""" + po, pn = _ts_param(o), _ts_param(n) + if not po or not pn or (po[0], po[1], po[3]) != (pn[0], pn[1], pn[3]) or not po[2] or not pn[2]: + return None + mo, mn = ts_resolve(po[2], old_decls), ts_resolve(pn[2], new_decls) + if mo is None or mn is None or (not mo and mn): + return None + kinds: set[str] = set() + for k, (opt, typ) in mo.items(): + if k not in mn or mn[k][0] != opt: + return None + if not _ts_type_refs_unchanged(typ, old_decls, new_decls): + return None + if mn[k][1] == typ: + continue + if not _ts_widened_to_undefined(f"{k}?: {typ}", f"{k}?: {mn[k][1]}"): + return None + kinds.add("undefined") + added = [v for k, v in mn.items() if k not in mo] + if not all(opt for opt, _ in added): + return None + if added: + kinds.add("props") + return kinds or {"same"} + + +def classify_change(lang: str, old: tuple[str, str], new: tuple[str, str], + ts_decls: tuple[dict, dict] | None = None) -> tuple[str, str]: """(severity, label) for one signature change. severity is 'break' or 'warn'. Not every signature change breaks a caller, and a check that says it does is @@ -1038,6 +1742,26 @@ def classify_change(lang: str, old: tuple[str, str], new: tuple[str, str]) -> tu new_ret, new_par = new if old_par != new_par: op, np_ = split_args(old_par), split_args(new_par) + if lang == "javascript" and old_ret == new_ret: + label = _ts_compatible_change(op, np_) + if label: + return "warn", label + if lang in ("python", "javascript") and old_ret == new_ret: + def ts_param_change(o: str, n: str) -> set[str] | None: + k = _ts_options_change(o, n) + if k is None: + w = _ts_wrapped_type(o, n) + k = {w} if w else None + if k is None and ts_decls is not None: + k = ts_named_options_change(o, n, *ts_decls) + return k + kinds = _gained_default_change( + lang, old_par, new_par, ts_param_change if lang == "javascript" else None) + if kinds: + if len(kinds) > 1: + kinds.discard("same") + return "warn", "; ".join(_TS_COMPATIBLE_LABELS[k] + for k in _TS_COMPATIBLE_LABELS if k in kinds) # `len(np_) > len(op)` matters: `split_args` drops Python's bare `*`, so # `f(self, a, b)` -> `f(self, a, *, b)` yields two IDENTICAL lists, the # empty tail passes `all()` vacuously, and making a parameter @@ -1060,6 +1784,25 @@ def classify_change(lang: str, old: tuple[str, str], new: tuple[str, str]) -> tu return "warn", "signature reordered" +def _texts_at(repo: Path, rev: str | None, sub: str, suffix: str) -> list[str]: + """Every `*suffix` file under `sub`, at `rev` or in the working tree. A file + that cannot be read is skipped: its types then do not resolve, which keeps + any change that needs them BREAKING.""" + if rev is None: + return [f.read_text(encoding="utf-8", errors="replace") + for f in sorted((repo / sub).rglob(f"*{suffix}"))] + ls = subprocess.run(["git", "-C", str(repo), "ls-tree", "-r", "--name-only", rev, "--", sub], + capture_output=True, text=True) + out = [] + for name in ls.stdout.split(): + if name.endswith(suffix): + p = subprocess.run(["git", "-C", str(repo), "show", f"{rev}:{name}"], + capture_output=True, text=True) + if p.returncode == 0: + out.append(p.stdout) + return out + + def cmd_surface(args) -> int: """Diff the public API surface against a released tag. @@ -1105,6 +1848,10 @@ def cmd_surface(args) -> int: new_text = "\n".join(f.read_text(encoding="utf-8", errors="replace") for f in files) old, new = public_surface(old_text, cfg), public_surface(new_text, cfg) + ts_decls = None + if lang == "javascript": + ts_decls = (ts_declarations(_texts_at(repo, args.rev, "src", ".ts")), + ts_declarations(_texts_at(repo, None, "src", ".ts"))) removed = sorted(set(old) - set(new)) added = sorted(set(new) - set(old)) changed = [k for k in sorted(set(old) & set(new)) if old[k] - new[k]] @@ -1121,7 +1868,7 @@ def cmd_surface(args) -> int: now = sorted(new[k] - old[k]) sev, label = ("break", "signature removed") if len(gone) == 1 and len(now) == 1: - sev, label = classify_change(lang, gone[0], now[0]) + sev, label = classify_change(lang, gone[0], now[0], ts_decls) (breaks if sev == "break" else warns).append((k, label, gone, now)) def show(rows: list) -> None: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ea098c..8e603dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [1.9.0] - 2026-10-31 + +### Changed + +- Sync the bundled OpenAPI spec, adding 2 paths and 8 schemas. The typed models gain the new fields, including `decision` on an agent run step, the run limits, `created_resources` and `solution_id` on an agent, `create_missing_resources` and `resource_bindings` on agent create, `apply_import_run_limits` and the `max_*` and `set_max_*` run limits on agent update, the `max_credits_per_period`, `spend_cap_action`, `spend_cap_delete_order` and `spend_cap_reached` spend-limit fields on a source and its update body, and `release_waiting_reason` on a content status +- Move `LATEST_API_VERSION` to `2026-10-28`. A client built with `api_version=LATEST_API_VERSION` also opts into it: an `if_else` or `switch` step's `output` is the result of the arm it took rather than the `{"branch": ...}` marker. The arm is in the step's `decision` on every version +- Make `agent_id` optional on `get_non_manual_evaluation_summary()`, as the API declares it. Leave it out for the account-wide summary + +### Added + +- Add `list_agent_examples()` to list the agent gallery, filtered by `query` and `use_case`. Pass an entry's `key` as `agent_template` to `create_agent()` +- Add `set_slack_trigger_config()` to configure an agent's `SLACK_COMMAND` trigger +- Add the query filters the API declares to existing list methods, each sent only when given: `status`, `flagged_only`, `time_from` and `time_to` on `list_evaluation_results()`; those and `step` on `list_agent_evaluation_results()`; `status`, `step`, `time_from` and `time_to` on `list_evaluation_runs()`; `started_after` on `list_compatible_runs()`; `days`, `start_date` and `end_date` on `get_non_manual_evaluation_summary()` and `get_memory_bank_stats()`; `limit` and `offset` on `get_ai_assistant_memory_bank_history()` and `get_memory_bank_ai_last_conversation()`; `limit` on `list_governance_ai_conversations()`; `agent_id`, `source_connection_id`, `time_from` and `time_to` on `list_alerts()`; `agent_id`, `source_connection_id` and `scope` on `list_alert_configs()`; `organization_id` and `include_defaults` on `list_organization_alert_preferences()`; `agent_id` and `unread_only` on `list_model_alerts()`; `type` on `list_memory_banks()`; `search` on `list_solutions()`; `supports_input_media` and `supports_output_media` on `list_models()`; and `require_tool_use`, `require_structured_output`, `require_thinking`, `min_context_tokens` and `min_output_tokens` on `get_model_recommendations()` +- Add an `ApiVersion` member for `2026-10-28`, so it can be selected without `allow_unknown_api_version` + ## [1.8.0] - 2026-10-21 ### Changed @@ -240,6 +255,7 @@ _Stable release. Packaging, CI, and documentation deployment only; no API change _Initial release._ +[1.9.0]: https://github.com/seclai/seclai-python/releases/tag/1.9.0 [1.8.0]: https://github.com/seclai/seclai-python/releases/tag/1.8.0 [1.7.2]: https://github.com/seclai/seclai-python/releases/tag/1.7.2 [1.7.1]: https://github.com/seclai/seclai-python/releases/tag/1.7.1 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b9a77e7 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,6 @@ +# seclai-python + +## Git and PRs + +- **Never commit or push.** No `git commit`, `git push`, `gh pr create`, no merging, not after finishing a task, not after addressing review comments, not after checks pass. The user commits all work themselves. Leave the changes in the working tree and say the work is ready. Do not offer to commit either. +- **Never conclude that a branch has no PR. Run `gh pr view`.** `gh pr view --json number,url,state` answers it in one call. A diff target you were handed (`HEAD~1..HEAD`, a commit range, a path) says what to read, never whether a PR exists. With `/code-review --comment`, post the findings to that PR. If the command comes back empty, report that it found none, not that there is no PR. diff --git a/README.md b/README.md index f11953f..69ec5f6 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ client decodes: | `2026-10-18` | A source's `document_images` defaults to true on a text-only embedder as well | | `2026-10-19` | `create_source()` refuses `polling_max_items` with a 400 on any source other than an RSS feed | | `2026-10-21` | An evaluation result whose evaluator returned no verdict (`error`) is left out of `failed` and of the pass and failure rates in `get_non_manual_evaluation_summary()`; `get_evaluation_criteria_summary()`'s `average_score` averages only passed and failed results; `test_draft_evaluation()` returns `score` and `passed` as `None` for an `error` result instead of 0.5 and `False` | +| `2026-10-28` | An `if_else` or `switch` step's `output` is the result of the arm it took (its input when that arm is empty or it took none), rather than the `{"branch": ...}` marker with no `attachments`. The arm is in the step's `decision` on every version | Moving to a later version can still change a value your code branches on, or reject a request that used to work. From `2026-10-05`, a content item held for @@ -255,7 +256,9 @@ find held items stops seeing them: check `held_for_review` instead. (The 400s. From `2026-10-21`, code that reads `passed` from `test_draft_evaluation()` as a bool, or does arithmetic on its `score`, gets `None` when `status` is `error`, and `get_non_manual_evaluation_summary()`'s `failed` no longer counts -those results: read its `error` count. Passing +those results: read its `error` count. From `2026-10-28`, code that parses an +`if_else` or `switch` step's `output` for the `{"branch": ...}` marker gets the +arm's result instead: read `decision`. Passing `api_version=LATEST_API_VERSION` opts into all of these at once. ## Resources @@ -310,6 +313,31 @@ imported = client.create_agent({ "entity_remap": entity_remap, }) # `imported["import_warnings"]` lists any items that couldn't be applied. + +# Run limits are on the agent; an update with `set_max_: True` and no +# value removes that limit +client.update_agent("agent_id", {"max_runs_per_day": 100}) +client.update_agent("agent_id", {"set_max_runs_per_day": True}) +``` + +### Agent examples + +The agent gallery lists example agents to start from. Create one by passing its +`key` as `agent_template`, binding the resources it needs to existing ones or +letting the API create them: + +```python +examples = client.list_agent_examples(query="support", use_case="support") +example = examples["data"][0] + +agent = client.create_agent({ + "name": "Support triage", + "agent_template": example["key"], + "resource_bindings": {"knowledge_base": "kb_id"}, # {slot: resource_id} + "create_missing_resources": True, # create any slot left unbound +}) +# {slot: resource_id} for what was created, grouped in agent["solution_id"] +print(agent.get("created_resources")) ``` ### Agent runs @@ -461,13 +489,23 @@ draft = client.test_draft_evaluation("agent_id", {"criteria": {}, "run_id": "run # Results & summaries results = client.list_evaluation_results("criteria_id") +flagged = client.list_evaluation_results( + "criteria_id", flagged_only=True, time_from="2026-10-01T00:00:00Z" +) summary = client.get_evaluation_criteria_summary("criteria_id") client.create_evaluation_result("criteria_id", {"run_id": "run_id", "score": 0.9}) # Results by run run_results = client.list_run_evaluation_results("agent_id", "run_id") -non_manual = client.get_non_manual_evaluation_summary("agent_id") -compatible = client.list_compatible_runs("criteria_id") +non_manual = client.get_non_manual_evaluation_summary("agent_id", days=7) +account_wide = client.get_non_manual_evaluation_summary(days=7) +compatible = client.list_compatible_runs( + "criteria_id", started_after="2026-10-01T00:00:00Z" +) + +# Across an agent: filter by status, step, flagged and time window +agent_results = client.list_agent_evaluation_results("agent_id", status="failed") +eval_runs = client.list_evaluation_runs("agent_id", step="step_id") ``` ### Knowledge bases @@ -483,14 +521,14 @@ client.delete_knowledge_base("kb_id") ### Memory banks ```python -banks = client.list_memory_banks() +banks = client.list_memory_banks(type="conversation") bank = client.create_memory_bank({"name": "Chat Memory", "type": "conversation"}) fetched = client.get_memory_bank("mb_id") client.update_memory_bank("mb_id", {"name": "Updated"}) client.delete_memory_bank("mb_id") # Stats & compaction -stats = client.get_memory_bank_stats("mb_id") +stats = client.get_memory_bank_stats("mb_id", start_date="2026-10-01", end_date="2026-10-31") client.compact_memory_bank("mb_id") # Test compaction @@ -503,7 +541,7 @@ agents = client.get_agents_using_memory_bank("mb_id") # AI assistant suggestion = client.generate_memory_bank_config({"user_input": "Create a bank"}) -last_conv = client.get_memory_bank_ai_last_conversation() +last_conv = client.get_memory_bank_ai_last_conversation(limit=10) client.accept_memory_bank_ai_suggestion("conversation_id", {"accepted": True}) # Source management @@ -518,6 +556,14 @@ source = client.create_source({"name": "My Source"}) fetched = client.get_source("source_id") client.update_source("source_id", {"name": "Updated"}) client.delete_source("source_id") + +# Spend limit: credits per billing period, then stop or delete entries. +# `None` removes the limit; `spend_cap_reached` reports when it is hit. +client.update_source("source_id", { + "max_credits_per_period": 500, + "spend_cap_action": "delete", + "spend_cap_delete_order": "oldest_added", +}) ``` Indexing status of a source's content, keyed by the `content_version_id` the @@ -653,7 +699,7 @@ finally: ### Solutions ```python -solutions = client.list_solutions() +solutions = client.list_solutions(search="billing") sol = client.create_solution({"name": "My Solution"}) fetched = client.get_solution("solution_id") client.update_solution("solution_id", {"name": "Renamed"}) @@ -686,7 +732,7 @@ client.mark_solution_conversation_turn("solution_id", "conversation_id", {"accep ```python plan = client.generate_governance_ai_plan({"user_input": "Create a content policy"}) -convs = client.list_governance_ai_conversations() +convs = client.list_governance_ai_conversations(limit=5) client.accept_governance_ai_plan("conversation_id") client.decline_governance_ai_plan("conversation_id") ``` @@ -694,7 +740,7 @@ client.decline_governance_ai_plan("conversation_id") ### Alerts ```python -alerts = client.list_alerts(status="active") +alerts = client.list_alerts(status="active", agent_id="agent_id") alert = client.get_alert("alert_id") client.change_alert_status("alert_id", {"status": "resolved"}) client.add_alert_comment("alert_id", {"text": "Investigating"}) @@ -704,14 +750,14 @@ client.subscribe_to_alert("alert_id") client.unsubscribe_from_alert("alert_id") # Alert configs -configs = client.list_alert_configs() +configs = client.list_alert_configs(agent_id="agent_id") client.create_alert_config({"name": "Config"}) config = client.get_alert_config("config_id") client.update_alert_config("config_id", {"name": "Updated"}) client.delete_alert_config("config_id") # Organization preferences -prefs = client.list_organization_alert_preferences() +prefs = client.list_organization_alert_preferences(include_defaults=True) client.update_organization_alert_preference("org_id", "anomaly", {"enabled": True}) ``` @@ -734,6 +780,28 @@ config = client.set_email_trigger_config( print(config["email_addresses"]) ``` +### Agent Slack triggers + +```python +# Configure a SLACK_COMMAND trigger, run from Slack with /seclai or the message +# shortcut; omitted fields are left unchanged +config = client.set_slack_trigger_config( + "agent_id", + "trigger_id", + { + "mcp_client_id": "mcp_client_id", # the account's connected Slack MCP client + "scope": "selected_channels", + "channel_ids": ["C0123456789"], + "activation": "channel_opt_in", # or "everywhere" in scope + "visibility": "private", # or "channel" + "form": [{"key": "ticket", "label": "Ticket", "type": "short_text"}], + "turns_enabled": True, + "max_turns": 5, + }, +) +print(config["missing_scopes"]) # Slack scopes needed for optional features +``` + ### Agent email governance ```python @@ -795,11 +863,11 @@ tiers = client.get_generation_tiers() embedders = client.list_embedding_models()["models"] rerankers = client.list_reranker_models()["models"] -alerts = client.list_model_alerts() +alerts = client.list_model_alerts(unread_only=True) client.mark_model_alert_read("alert_id") client.mark_all_model_alerts_read() unread = client.get_unread_model_alert_count() -recs = client.get_model_recommendations("model_id") +recs = client.get_model_recommendations("model_id", require_tool_use=True) # Model playground experiments experiment = client.create_experiment({"model_ids": ["model_id"], "prompt": "..."}) diff --git a/openapi/seclai.openapi.json b/openapi/seclai.openapi.json index 0ca4052..4220dcc 100644 --- a/openapi/seclai.openapi.json +++ b/openapi/seclai.openapi.json @@ -419,12 +419,30 @@ "title": "AgentEvaluationTier", "type": "string" }, + "AgentExampleListResponse": { + "properties": { + "data": { + "items": {}, + "title": "Data", + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/PaginationResponse" + } + }, + "required": [ + "data", + "pagination" + ], + "title": "AgentExampleListResponse", + "type": "object" + }, "AgentExportResponse": { "description": "Portable JSON snapshot of an agent definition.", "properties": { "agent": { "additionalProperties": true, - "description": "Agent metadata and full definition. Keys: name, description, schema_version, definition, default_evaluation_tier, evaluation_mode, sampling_config, max_retries, retry_on_failure, prompt_model_auto_upgrade_strategy, prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers, created_at, updated_at.", + "description": "Agent metadata and full definition. Keys: name, description, schema_version, definition, default_evaluation_tier, evaluation_mode, sampling_config, max_retries, retry_on_failure, prompt_model_auto_upgrade_strategy, prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers, max_credits_per_run, max_credits_per_period, max_runs_per_hour, max_runs_per_day, max_runs_total, created_at, updated_at.", "title": "Agent", "type": "object" }, @@ -963,6 +981,18 @@ "title": "Credits Used", "type": "number" }, + "decision": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The arm an `if_else` or `switch` step took: `then` or `else`, or the case name or `else`. Null for other step types, until the step has decided, and when a `switch` took no arm.", + "title": "Decision" + }, "duration_seconds": { "anyOf": [ { @@ -1008,7 +1038,7 @@ "type": "null" } ], - "description": "Output text produced by the step, if any; its files are in `attachments`. Below `Seclai-Version: 2026-09-30`, the manifest JSON when the step output files and is not a `for_each`.", + "description": "Output text produced by the step, if any; its files are in `attachments`. Below `Seclai-Version: 2026-09-30`, the manifest JSON when the step output files and is not a `for_each`. For an `if_else` or `switch`, the result of the arm it took (its input when that arm is empty or it took none); below `Seclai-Version: 2026-10-28`, the `{\"branch\": ...}` marker naming that arm, with no `attachments`.", "title": "Output" }, "output_content_type": { @@ -1289,6 +1319,21 @@ "title": "Created At", "type": "string" }, + "created_resources": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "description": "On a create from an `agent_template`: {slot: resource_id} for each resource `create_missing_resources` created.", + "title": "Created Resources" + }, "default_evaluation_tier": { "anyOf": [ { @@ -1369,12 +1414,72 @@ "description": "One entry per item dropped or substituted during import. Present only on endpoints that accept agent_definition; null on non-import calls; [] when the import had no skips.", "title": "Import Warnings" }, + "max_credits_per_period": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Credit limit per billing period; null when none.", + "title": "Max Credits Per Period" + }, + "max_credits_per_run": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Credit limit per run; null when none.", + "title": "Max Credits Per Run" + }, "max_retries": { "default": 3, "description": "Max retries for eval_and_retry mode.", "title": "Max Retries", "type": "integer" }, + "max_runs_per_day": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Runs per day limit; null when none.", + "title": "Max Runs Per Day" + }, + "max_runs_per_hour": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Runs per hour limit; null when none.", + "title": "Max Runs Per Hour" + }, + "max_runs_total": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Limit on runs in total; null when none.", + "title": "Max Runs Total" + }, "name": { "description": "Agent name.", "title": "Name", @@ -1426,6 +1531,18 @@ "description": "Sampling configuration for sample_and_flag mode.", "title": "Sampling Config" }, + "solution_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "On a create from an `agent_template` that created resources: the solution grouping the agent with them.", + "title": "Solution Id" + }, "trigger_id": { "anyOf": [ { @@ -4526,7 +4643,7 @@ "type": "string" }, "reason": { - "description": "Why it was refused: sender_not_allowed, unauthenticated_sender, unreadable_from, sender_blocked, spam, virus, unsafe_content, rate_limited, account_not_chargeable or empty_message; or, for a message the source received before, what became of the earlier one: repeat_stored, repeat_held, repeat_deleted or repeat_in_progress.", + "description": "Why it was refused: sender_not_allowed, unauthenticated_sender, unreadable_from, sender_blocked, spam, virus, unsafe_content, rate_limited, account_not_chargeable, spend_limit_reached or empty_message; or, for a message the source received before, what became of the earlier one: repeat_stored, repeat_held, repeat_deleted or repeat_in_progress.", "title": "Reason", "type": "string" }, @@ -7828,7 +7945,7 @@ "type": "null" } ], - "description": "The input attachments the trigger accepts; ``null`` accepts any files (one attachment named ``files``). Only ``dynamic_input`` and ``email_received`` triggers take files.", + "description": "The input attachments the trigger accepts; ``null`` accepts any files (one attachment named ``files``). Only ``dynamic_input``, ``email_received`` and ``slack_command`` triggers take files.", "title": "Accepted Attachments" } }, @@ -7852,6 +7969,179 @@ "title": "SetAutoBlockModeRequest", "type": "object" }, + "SetSlackTriggerConfigApiRequest": { + "description": "Omitted fields are left unchanged.", + "properties": { + "activation": { + "anyOf": [ + { + "$ref": "#/components/schemas/SlackTriggerActivation" + }, + { + "type": "null" + } + ], + "description": "`everywhere` in scope, or `channel_opt_in`." + }, + "allow_dms": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "description": "Runnable in the app's own DMs.", + "title": "Allow Dms" + }, + "channel_ids": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Channel Ids" + }, + "form": { + "anyOf": [ + { + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Form fields `{key, label, type, required, hint, choices, max_length}`. `type`: short_text, long_text, number, single_choice, multi_choice, yes_no, date, slack_user or slack_channel. Each value reaches the run as `{{metadata.}}`.", + "title": "Form" + }, + "include_invoker_email": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Include Invoker Email" + }, + "input": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The trigger's input template. Each `{{metadata.}}` in it must be a form field key or a platform key; it is checked together with `form`.", + "title": "Input" + }, + "max_turns": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Turns" + }, + "mcp_client_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The account's connected Slack (Bot) MCP client.", + "title": "Mcp Client Id" + }, + "notify_failure_after_answer": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Notify Failure After Answer" + }, + "scope": { + "anyOf": [ + { + "$ref": "#/components/schemas/SlackTriggerScope" + }, + { + "type": "null" + } + ], + "description": "`selected_channels` (see `channel_ids`) or `bot_channels`." + }, + "start_without_form": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Start Without Form" + }, + "turns_anyone": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Turns Anyone" + }, + "turns_enabled": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Turns Enabled" + }, + "visibility": { + "anyOf": [ + { + "$ref": "#/components/schemas/SlackReplyVisibility" + }, + { + "type": "null" + } + ], + "description": "`channel`, or `private` (replies in the person's DM)." + } + }, + "title": "SetSlackTriggerConfigApiRequest", + "type": "object" + }, "SkippedAttachmentReason": { "enum": [ "displayed_in_body", @@ -7908,21 +8198,173 @@ "title": "SkippedAttachmentResponse", "type": "object" }, - "SolutionSourceConnectionResponse": { + "SlackReplyVisibility": { + "enum": [ + "channel", + "private" + ], + "title": "SlackReplyVisibility", + "type": "string" + }, + "SlackTriggerActivation": { + "enum": [ + "everywhere", + "channel_opt_in" + ], + "title": "SlackTriggerActivation", + "type": "string" + }, + "SlackTriggerConfigApiResponse": { "properties": { - "id": { - "format": "uuid", - "title": "Id", + "activation": { + "title": "Activation", "type": "string" }, - "name": { - "title": "Name", + "agent_id": { + "format": "uuid", + "title": "Agent Id", "type": "string" - } - }, - "required": [ - "id", - "name" + }, + "allow_dms": { + "title": "Allow Dms", + "type": "boolean" + }, + "channel_ids": { + "items": { + "type": "string" + }, + "title": "Channel Ids", + "type": "array" + }, + "form": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "title": "Form", + "type": "array" + }, + "include_invoker_email": { + "title": "Include Invoker Email", + "type": "boolean" + }, + "max_turns": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Max Turns" + }, + "mcp_client_id": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mcp Client Id" + }, + "missing_scopes": { + "description": "Scopes the Slack connection lacks for optional features.", + "items": { + "type": "string" + }, + "title": "Missing Scopes", + "type": "array" + }, + "notify_failure_after_answer": { + "title": "Notify Failure After Answer", + "type": "boolean" + }, + "scope": { + "title": "Scope", + "type": "string" + }, + "slack_team_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Slack Team Id" + }, + "start_without_form": { + "title": "Start Without Form", + "type": "boolean" + }, + "trigger_id": { + "format": "uuid", + "title": "Trigger Id", + "type": "string" + }, + "turns_anyone": { + "title": "Turns Anyone", + "type": "boolean" + }, + "turns_enabled": { + "title": "Turns Enabled", + "type": "boolean" + }, + "visibility": { + "title": "Visibility", + "type": "string" + } + }, + "required": [ + "trigger_id", + "agent_id", + "mcp_client_id", + "slack_team_id", + "form", + "scope", + "allow_dms", + "activation", + "visibility", + "start_without_form", + "turns_enabled", + "turns_anyone", + "max_turns", + "include_invoker_email", + "notify_failure_after_answer", + "channel_ids", + "missing_scopes" + ], + "title": "SlackTriggerConfigApiResponse", + "type": "object" + }, + "SlackTriggerScope": { + "enum": [ + "selected_channels", + "bot_channels" + ], + "title": "SlackTriggerScope", + "type": "string" + }, + "SolutionSourceConnectionResponse": { + "properties": { + "id": { + "format": "uuid", + "title": "Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "id", + "name" ], "title": "SolutionSourceConnectionResponse", "type": "object" @@ -8161,7 +8603,7 @@ }, "held_for_review": { "default": false, - "description": "An ENFORCE governance policy blocked this item at import. It is held for review and is not retrievable: resolving its blocking evaluations releases it into the source, and it is purged when the hold window ends.", + "description": "An ENFORCE governance policy blocked this item at import. It is held for review and is not retrievable: resolving its blocking evaluations releases it into the source; left unresolved, it is purged when the hold window ends.", "title": "Held For Review", "type": "boolean" }, @@ -8206,6 +8648,18 @@ "title": "Pulled At", "type": "string" }, + "release_waiting_reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Set on a held item review approved whose release was refused: why it waits, the account being unable to pay for it or the source's spend limit having no room for it. Its release is retried; null until one is refused.", + "title": "Release Waiting Reason" + }, "source_connection_content_version_id": { "anyOf": [ { @@ -8215,7 +8669,7 @@ "type": "null" } ], - "description": "ID to pass to `GET /contents/{id}`. `null` until the item has finished indexing \u2014 an item that is still processing, or that failed, has no retrievable content and keeps this `null`.", + "description": "ID to pass to `GET /contents/{id}`. `null` while the item has no retrievable content.", "title": "Source Connection Content Version Id" }, "title": { @@ -8684,6 +9138,18 @@ ], "description": "Index mode for custom_index sources: fast_and_cheap, balanced, slow_and_thorough, or custom." }, + "max_credits_per_period": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "The source's spend limit: credits it may commit per billing period. Null when it has none.", + "title": "Max Credits Per Period" + }, "media_types": { "description": "Media kinds in a web page's main content that are attached to the page's item and indexed (subset of ['images', 'video']). On a website or RSS source 'images' also covers the images inside PDF, DOCX, PPTX and XLSX files.", "items": { @@ -8780,6 +9246,22 @@ "title": "Source Type", "type": "string" }, + "spend_cap_action": { + "$ref": "#/components/schemas/SpendCapAction", + "default": "stop", + "description": "What the source does once it reaches its spend limit." + }, + "spend_cap_delete_order": { + "$ref": "#/components/schemas/SpendCapDeleteOrder", + "default": "oldest_added", + "description": "Which entries a `delete` spend limit removes first." + }, + "spend_cap_reached": { + "default": false, + "description": "True while the spend limit refuses uploads and email to this source.", + "title": "Spend Cap Reached", + "type": "boolean" + }, "system_managed": { "default": false, "description": "Indicates if this source is automatically managed by the system (e.g., agent traces).", @@ -8823,6 +9305,24 @@ "title": "SourceResponse", "type": "object" }, + "SpendCapAction": { + "enum": [ + "stop", + "delete" + ], + "title": "SpendCapAction", + "type": "string" + }, + "SpendCapDeleteOrder": { + "description": "Which entries a DELETE cap removes first.", + "enum": [ + "oldest_added", + "oldest_published", + "largest_first" + ], + "title": "SpendCapDeleteOrder", + "type": "string" + }, "StandaloneTestCompactionRequest": { "description": "Request body for testing a compaction prompt *without* an existing bank.\n\nUsed on the create-memory-bank page where no bank ID exists yet.\n``compaction_prompt`` is required (no bank to fall back to).\nContent must come from ``sample_entries`` or ``generate_direction``\n(no existing entries to fetch).", "properties": { @@ -9739,6 +10239,19 @@ "description": "Kinds of file listed beside a feed item's content to attach to the item and index, on an RSS source. Subset of ['enclosures', 'item_image', 'media_rss']; any other value is refused. [] attaches none. Applies to items added after it changes. Omit the field to leave it unchanged.", "title": "Feed Attachments" }, + "max_credits_per_period": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Spend limit: the credits this source may commit per billing period \u2014 what the account was charged for it this period plus the storage of what it holds until the period ends. Send null to remove the limit; omit to leave it unchanged.", + "title": "Max Credits Per Period" + }, "media_types": { "anyOf": [ { @@ -9791,6 +10304,28 @@ ], "description": "New retention period in days \u2014 content older than this is deleted permanently. Send null to clear the window: content is then kept indefinitely. Omit the field to leave it unchanged.", "title": "Retention Days" + }, + "spend_cap_action": { + "anyOf": [ + { + "$ref": "#/components/schemas/SpendCapAction" + }, + { + "type": "null" + } + ], + "description": "Once the limit is reached: `stop` refuses new content; `delete` deletes entries, in `spend_cap_delete_order`, to make room, and refuses new content as `stop` does once spend already fills the limit. Deleting does not return credits already spent." + }, + "spend_cap_delete_order": { + "anyOf": [ + { + "$ref": "#/components/schemas/SpendCapDeleteOrder" + }, + { + "type": "null" + } + ], + "description": "Which entries `delete` removes first: `oldest_added`, `oldest_published` or `largest_first`." } }, "title": "UpdateSourceBody", @@ -10325,9 +10860,15 @@ "type": "null" } ], - "description": "Template to initialize the agent from. Values: blank, retrieval_example, simple_qa, summarizer, json_extractor, content_change_notifier, scheduled_report, webhook_pipeline.", + "description": "Agent gallery entry to start from: a `key` from GET /agents/examples, or `blank`. The keys retrieval_example and simple_qa remain accepted for their gallery entries.", "title": "Agent Template" }, + "create_missing_resources": { + "default": false, + "description": "For an `agent_template`: create each creatable resource slot left out of `resource_bindings`, and group the agent with them in a new solution. When false, an unbound slot the template needs is an error.", + "title": "Create Missing Resources", + "type": "boolean" + }, "description": { "anyOf": [ { @@ -10360,11 +10901,33 @@ "title": "Name", "type": "string" }, + "resource_bindings": { + "anyOf": [ + { + "additionalProperties": { + "format": "uuid", + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "description": "For an `agent_template`: the existing resource to use for each of the template's resource slots, as {slot: resource_id}. GET /agents/examples lists each template's slots.", + "title": "Resource Bindings" + }, "trigger_type": { - "default": "dynamic_input", - "description": "Trigger type: dynamic_input, template_input, schedule, new_content, email_received.", - "title": "Trigger Type", - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Defaults to dynamic_input, or to the template's own trigger type for an `agent_template` without `agent_definition`.", + "title": "Trigger Type" } }, "required": [ @@ -10498,6 +11061,12 @@ "description": "Optional payload in the same format produced by GET /agents/{id}/export. When provided, agent metadata fields the request does not set explicitly are taken from the payload, and the agent's workflow is replaced from `agent.definition`. The previous version is preserved in history. Validation errors include line/column references against a canonical pretty-printed echo of the supplied payload.", "title": "Agent Definition" }, + "apply_import_run_limits": { + "default": false, + "description": "With `agent_definition`, also replace the agent's run limits with the payload's (a null there removes a limit). Off by default: the agent keeps its limits.", + "title": "Apply Import Run Limits", + "type": "boolean" + }, "default_evaluation_tier": { "anyOf": [ { @@ -10549,6 +11118,32 @@ "description": "Evaluation mode: 'output_expectation', 'eval_and_retry', or 'sample_and_flag'.", "title": "Evaluation Mode" }, + "max_credits_per_period": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Credit limit per billing period of the paying account: once reached, runs stop at their next step and new runs are refused.", + "title": "Max Credits Per Period" + }, + "max_credits_per_run": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Credit limit per run: a run that reaches it is stopped before its next step.", + "title": "Max Credits Per Run" + }, "max_retries": { "anyOf": [ { @@ -10561,6 +11156,45 @@ "description": "Max retries for eval_and_retry mode (1-10).", "title": "Max Retries" }, + "max_runs_per_day": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Runs per day; at most the plan's run quota.", + "title": "Max Runs Per Day" + }, + "max_runs_per_hour": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Runs per hour; at most the plan's run quota.", + "title": "Max Runs Per Hour" + }, + "max_runs_total": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Runs in total; once reached, new runs are refused.", + "title": "Max Runs Total" + }, "name": { "anyOf": [ { @@ -10642,6 +11276,36 @@ "title": "Set Default Evaluation Tier", "type": "boolean" }, + "set_max_credits_per_period": { + "default": false, + "description": "When true and max_credits_per_period is omitted, removes the limit.", + "title": "Set Max Credits Per Period", + "type": "boolean" + }, + "set_max_credits_per_run": { + "default": false, + "description": "When true and max_credits_per_run is omitted, removes the limit.", + "title": "Set Max Credits Per Run", + "type": "boolean" + }, + "set_max_runs_per_day": { + "default": false, + "description": "When true and max_runs_per_day is omitted, removes the limit.", + "title": "Set Max Runs Per Day", + "type": "boolean" + }, + "set_max_runs_per_hour": { + "default": false, + "description": "When true and max_runs_per_hour is omitted, removes the limit.", + "title": "Set Max Runs Per Hour", + "type": "boolean" + }, + "set_max_runs_total": { + "default": false, + "description": "When true and max_runs_total is omitted, removes the limit.", + "title": "Set Max Runs Total", + "type": "boolean" + }, "set_prompt_model_auto_rollback_triggers": { "default": false, "description": "When true and prompt_model_auto_rollback_triggers is omitted, clears the list to null (revert to system defaults).", @@ -13663,7 +14327,7 @@ ] }, "post": { - "description": "Create a new agent.\n\nTrigger types:\n- `dynamic_input`: triggered via API with user-provided input\n- `template_input`: triggered via API with a predefined template\n- `schedule`: triggered on a schedule\n- `new_content`: triggered when new content arrives\n- `email_received`: a virtual email inbox; runs when mail arrives at the agent's address. Configure the alias/allowlist with `PUT /agents/{agent_id}/triggers/{trigger_id}/email-config`, using the `trigger_id` this response returns.\n\nTemplates: `blank`, `retrieval_example`, `simple_qa`, `summarizer`, `json_extractor`, `content_change_notifier`, `scheduled_report`, `webhook_pipeline`\n\nImporting an existing agent:\n- Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. The full extras suite (alert_configs, evaluation_criteria, governance_policies, schedules, solutions) is applied; items that don't resolve in this account are reported in the response's `import_warnings` array.\n- Use `POST /agents/preview-import` first to surface `unresolved_refs` (workflow refs to KBs, memory banks, source connections, sub-agents that don't exist here). Then pass `entity_remap: {source_uuid: target_uuid}` on this call to substitute them before save.\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token. Agent is created in the caller's account.", + "description": "Create a new agent.\n\nTrigger types:\n- `dynamic_input`: triggered via API with user-provided input\n- `template_input`: triggered via API with a predefined template\n- `email_received`: a virtual email inbox; runs when mail arrives at the agent's address. Configure the alias/allowlist with `PUT /agents/{agent_id}/triggers/{trigger_id}/email-config`, using the `trigger_id` this response returns.\n\nStarting from the agent gallery:\n- Pass a `key` from `GET /agents/examples` as `agent_template`, or `blank` for an empty agent.\n- Bind the template's resource slots to existing resources with `resource_bindings`, or set `create_missing_resources` to have the creatable ones created.\n\nImporting an existing agent:\n- Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. The full extras suite (alert_configs, evaluation_criteria, governance_policies, schedules, solutions) is applied; items that don't resolve in this account are reported in the response's `import_warnings` array.\n- Use `POST /agents/preview-import` first to surface `unresolved_refs` (workflow refs to KBs, memory banks, source connections, sub-agents that don't exist here). Then pass `entity_remap: {source_uuid: target_uuid}` on this call to substitute them before save.\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token. Agent is created in the caller's account.", "operationId": "create_agent_api_agents_post", "parameters": [ { @@ -14883,6 +15547,127 @@ ] } }, + "/agents/examples": { + "get": { + "description": "List the agent gallery: example agents to start from, searchable by text and filterable by use case. Pass an entry's `key` as `agent_template` on POST /agents, with `resource_bindings` for the resources it needs.", + "operationId": "list_agent_examples_api_agents_examples_get", + "parameters": [ + { + "description": "Words every match must contain.", + "in": "query", + "name": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Words every match must contain.", + "title": "Query" + } + }, + { + "description": "Only entries for this use case.", + "in": "query", + "name": "use_case", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only entries for this use case.", + "title": "Use Case" + } + }, + { + "description": "Page number", + "in": "query", + "name": "page", + "required": false, + "schema": { + "default": 1, + "description": "Page number", + "minimum": 1, + "title": "Page", + "type": "integer" + } + }, + { + "description": "Items per page", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 20, + "description": "Items per page", + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "$ref": "#/components/parameters/X-Account-Id" + }, + { + "$ref": "#/components/parameters/Seclai-Version" + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentExampleListResponse" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + }, + "description": "A dependency is unavailable. `database_unavailable` is temporary (for example routine maintenance) and carries a `Retry-After` header, after which the request can be retried unchanged. `vector_store_unavailable` means the vector store backing an embeddings operation is not configured; it carries no `Retry-After` because it does not clear without an operator.", + "headers": { + "Retry-After": { + "description": "Seconds to wait before retrying. Sent only with `database_unavailable`.", + "schema": { + "type": "integer" + } + } + } + } + }, + "summary": "List agent gallery examples", + "tags": [ + "agents" + ] + } + }, "/agents/inbound-email-rejections": { "get": { "description": "List recent inbound emails that were quietly discarded before running an agent (unauthorized sender, unknown alias, spam/virus, flood-shed) for this account's agents.\n\nAuth & scoping: requires `X-API-Key` header or OAuth Bearer token; always scoped to the key's account.", @@ -15524,7 +16309,7 @@ ] }, "put": { - "description": "Update an agent's name, description, evaluation settings, and model lifecycle settings.\n\nEvaluation settings: `evaluation_mode` ('output_expectation', 'eval_and_retry', 'sample_and_flag'), `default_evaluation_tier` ('fast', 'balanced', 'thorough'), `max_retries`, `retry_on_failure`, `sampling_config`.\n\nModel lifecycle settings: `prompt_model_auto_upgrade_strategy` ('none', 'early_adopter', 'middle_of_road', 'cautious_adopter'), `prompt_model_auto_rollback_enabled`, `prompt_model_auto_rollback_triggers` (list of 'agent_eval_fail', 'governance_flag', 'governance_block', 'agent_run_failed').\n\nReplacing the workflow from an export:\n- Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. Update only touches the workflow + agent metadata \u2014 alert_configs, evaluation_criteria, governance_policies, schedules, and solution links from the imported file are NOT applied (use the dedicated endpoints for those, or `POST /agents` to import as a new agent).\n- `entity_remap: {source_uuid: target_uuid}` substitutes workflow entity refs before save (same shape as `POST /agents`).\n\nAt least one field must be provided.\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token. You can only update agents belonging to your account.", + "description": "Update an agent's name, description, evaluation settings, model lifecycle settings and run limits.\n\nEvaluation settings: `evaluation_mode` ('output_expectation', 'eval_and_retry', 'sample_and_flag'), `default_evaluation_tier` ('fast', 'balanced', 'thorough'), `max_retries`, `retry_on_failure`, `sampling_config`.\n\nModel lifecycle settings: `prompt_model_auto_upgrade_strategy` ('none', 'early_adopter', 'middle_of_road', 'cautious_adopter'), `prompt_model_auto_rollback_enabled`, `prompt_model_auto_rollback_triggers` (list of 'agent_eval_fail', 'governance_flag', 'governance_block', 'agent_run_failed').\n\nRun limits (each must be greater than 0; pass the paired `set_: true` with the value omitted to remove one): `max_credits_per_run`, `max_credits_per_period`, `max_runs_per_hour`, `max_runs_per_day`, `max_runs_total`. A runs-per-hour or per-day value above the plan's run quota is rejected with 400.\n\nReplacing the workflow from an export:\n- Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. Update only touches the workflow + agent metadata \u2014 alert_configs, evaluation_criteria, governance_policies, schedules, and solution links from the imported file are NOT applied (use the dedicated endpoints for those, or `POST /agents` to import as a new agent).\n- `entity_remap: {source_uuid: target_uuid}` substitutes workflow entity refs before save (same shape as `POST /agents`).\n\nAt least one field must be provided.\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token. You can only update agents belonging to your account.", "operationId": "update_agent_api_agents__agent_id__put", "parameters": [ { @@ -17658,6 +18443,94 @@ ] } }, + "/agents/{agent_id}/triggers/{trigger_id}/slack-config": { + "put": { + "description": "Set the Slack connection, form, channels, visibility and conversation settings of an agent's SLACK_COMMAND trigger, which people run from Slack with `/seclai` or the message shortcut. Omitted fields are left unchanged.\n\nAuth & scoping: requires `X-API-Key` header or OAuth Bearer token; the trigger must belong to an agent in the key's account.", + "operationId": "set_slack_trigger_config_api_api_agents__agent_id__triggers__trigger_id__slack_config_put", + "parameters": [ + { + "in": "path", + "name": "agent_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Agent Id", + "type": "string" + } + }, + { + "in": "path", + "name": "trigger_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Trigger Id", + "type": "string" + } + }, + { + "$ref": "#/components/parameters/X-Account-Id" + }, + { + "$ref": "#/components/parameters/Seclai-Version" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetSlackTriggerConfigApiRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SlackTriggerConfigApiResponse" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableError" + } + } + }, + "description": "A dependency is unavailable. `database_unavailable` is temporary (for example routine maintenance) and carries a `Retry-After` header, after which the request can be retried unchanged. `vector_store_unavailable` means the vector store backing an embeddings operation is not configured; it carries no `Retry-After` because it does not clear without an operator.", + "headers": { + "Retry-After": { + "description": "Seconds to wait before retrying. Sent only with `database_unavailable`.", + "schema": { + "type": "integer" + } + } + } + } + }, + "summary": "Configure a SLACK_COMMAND trigger", + "tags": [ + "agents" + ] + } + }, "/agents/{agent_id}/upload-input": { "post": { "description": "Upload a file to use as input for a `dynamic_input` agent run. Any other agent rejects the upload with HTTP 400.\n\n**Size limit:** 200 MB per file.\n\nFrom `Seclai-Version: 2026-10-16` a file of any type is accepted and is `ready` at once: pass `input_upload_id` to `POST /agents/{agent_id}/runs`. Each step receives the file itself when its model reads that type, and otherwise its text (OCR, extraction or transcript), made once for the steps that need it; a type nothing reads or converts is passed on as a file only. `input` carries a `# filename` heading per file.\n\nEarlier versions accept only these extensions: avi, bmp, csv, docx, epub, flac, gif, html, jpg, json, m4a, markdown, md, mov, mp3, mp4, msg, ogg, pdf, png, ppt, pptx, svg, tiff, txt, wav, webp, xls, xlsx, xml, zip. They write each file's text into `input`, so poll `GET /agents/{agent_id}/input-uploads/{upload_id}` until `status` is `ready` before running.\n\nThe agent-input-binary janitor sweeps originals once they pass your account's agent-trace retention (the agent-traces source's retention period; free default 7 days).\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token. All resources are scoped to the caller's account.", @@ -18683,7 +19556,7 @@ ] }, "post": { - "description": "Create a new alert configuration.\n\nAgent alert types: run_failed, consecutive_failures, error_rate_spike, run_burst, slow_run, credits_low_threshold, credits_runout_prediction, credits_usage_spike, non_manual_eval_failed, non_manual_eval_flagged, governance_flagged, governance_blocked, model_newer_available, model_deprecated, model_sunset.\nSource alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike.\n\nDistribution types: owner, owner_admins, selected_members. Organization accounts are normalized to owner_admins.\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token.", + "description": "Create a new alert configuration.\n\nAgent alert types: run_failed, consecutive_failures, error_rate_spike, run_burst, slow_run, credits_low_threshold, credits_runout_prediction, credits_usage_spike, non_manual_eval_failed, non_manual_eval_flagged, governance_flagged, governance_blocked, model_newer_available, model_deprecated, model_sunset.\nSource alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike, source_spend_limit_reached (needs source_connection_id).\n\nDistribution types: owner, owner_admins, selected_members. Organization accounts are normalized to owner_admins.\n\nAuth & scoping:\n- Requires `X-API-Key` header or OAuth Bearer token.", "operationId": "create_alert_config_api_alerts_configs_post", "parameters": [ { @@ -26487,7 +27360,7 @@ ] }, "put": { - "description": "Update a content source's configuration. Only provided fields are changed; omitted fields are left unchanged.\n\nSystem-managed sources only allow `retention_days` updates.", + "description": "Update a content source's configuration. Only provided fields are changed; omitted fields are left unchanged.\n\nSystem-managed sources only allow `retention_days` updates.\n\nA source with a spend limit that reaches it refuses new content with a 402 `source_spend_limit_reached` (`spend_cap_action: stop`), or deletes entries to make room (`delete`); a `delete` source whose spend already fills the limit refuses new content too.", "operationId": "update_source_api_sources__source_connection_id__put", "parameters": [ { @@ -28023,8 +28896,9 @@ "2026-10-16", "2026-10-18", "2026-10-19", - "2026-10-21" + "2026-10-21", + "2026-10-28" ], - "latest": "2026-10-21" + "latest": "2026-10-28" } } diff --git a/seclai/_generated/api/agents/create_agent_api_agents_post.py b/seclai/_generated/api/agents/create_agent_api_agents_post.py index 1cd3705..7be5ba8 100644 --- a/seclai/_generated/api/agents/create_agent_api_agents_post.py +++ b/seclai/_generated/api/agents/create_agent_api_agents_post.py @@ -110,14 +110,14 @@ def sync_detailed( Trigger types: - `dynamic_input`: triggered via API with user-provided input - `template_input`: triggered via API with a predefined template - - `schedule`: triggered on a schedule - - `new_content`: triggered when new content arrives - `email_received`: a virtual email inbox; runs when mail arrives at the agent's address. Configure the alias/allowlist with `PUT /agents/{agent_id}/triggers/{trigger_id}/email-config`, using the `trigger_id` this response returns. - Templates: `blank`, `retrieval_example`, `simple_qa`, `summarizer`, `json_extractor`, - `content_change_notifier`, `scheduled_report`, `webhook_pipeline` + Starting from the agent gallery: + - Pass a `key` from `GET /agents/examples` as `agent_template`, or `blank` for an empty agent. + - Bind the template's resource slots to existing resources with `resource_bindings`, or set + `create_missing_resources` to have the creatable ones created. Importing an existing agent: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. The full extras @@ -176,14 +176,14 @@ def sync( Trigger types: - `dynamic_input`: triggered via API with user-provided input - `template_input`: triggered via API with a predefined template - - `schedule`: triggered on a schedule - - `new_content`: triggered when new content arrives - `email_received`: a virtual email inbox; runs when mail arrives at the agent's address. Configure the alias/allowlist with `PUT /agents/{agent_id}/triggers/{trigger_id}/email-config`, using the `trigger_id` this response returns. - Templates: `blank`, `retrieval_example`, `simple_qa`, `summarizer`, `json_extractor`, - `content_change_notifier`, `scheduled_report`, `webhook_pipeline` + Starting from the agent gallery: + - Pass a `key` from `GET /agents/examples` as `agent_template`, or `blank` for an empty agent. + - Bind the template's resource slots to existing resources with `resource_bindings`, or set + `create_missing_resources` to have the creatable ones created. Importing an existing agent: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. The full extras @@ -236,14 +236,14 @@ async def asyncio_detailed( Trigger types: - `dynamic_input`: triggered via API with user-provided input - `template_input`: triggered via API with a predefined template - - `schedule`: triggered on a schedule - - `new_content`: triggered when new content arrives - `email_received`: a virtual email inbox; runs when mail arrives at the agent's address. Configure the alias/allowlist with `PUT /agents/{agent_id}/triggers/{trigger_id}/email-config`, using the `trigger_id` this response returns. - Templates: `blank`, `retrieval_example`, `simple_qa`, `summarizer`, `json_extractor`, - `content_change_notifier`, `scheduled_report`, `webhook_pipeline` + Starting from the agent gallery: + - Pass a `key` from `GET /agents/examples` as `agent_template`, or `blank` for an empty agent. + - Bind the template's resource slots to existing resources with `resource_bindings`, or set + `create_missing_resources` to have the creatable ones created. Importing an existing agent: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. The full extras @@ -300,14 +300,14 @@ async def asyncio( Trigger types: - `dynamic_input`: triggered via API with user-provided input - `template_input`: triggered via API with a predefined template - - `schedule`: triggered on a schedule - - `new_content`: triggered when new content arrives - `email_received`: a virtual email inbox; runs when mail arrives at the agent's address. Configure the alias/allowlist with `PUT /agents/{agent_id}/triggers/{trigger_id}/email-config`, using the `trigger_id` this response returns. - Templates: `blank`, `retrieval_example`, `simple_qa`, `summarizer`, `json_extractor`, - `content_change_notifier`, `scheduled_report`, `webhook_pipeline` + Starting from the agent gallery: + - Pass a `key` from `GET /agents/examples` as `agent_template`, or `blank` for an empty agent. + - Bind the template's resource slots to existing resources with `resource_bindings`, or set + `create_missing_resources` to have the creatable ones created. Importing an existing agent: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. The full extras diff --git a/seclai/_generated/api/agents/list_agent_examples_api_agents_examples_get.py b/seclai/_generated/api/agents/list_agent_examples_api_agents_examples_get.py new file mode 100644 index 0000000..49ec800 --- /dev/null +++ b/seclai/_generated/api/agents/list_agent_examples_api_agents_examples_get.py @@ -0,0 +1,277 @@ +from http import HTTPStatus +from typing import Any +from uuid import UUID + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.agent_example_list_response import AgentExampleListResponse +from ...models.http_validation_error import HTTPValidationError +from ...models.service_unavailable_error import ServiceUnavailableError +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + query: None | str | Unset = UNSET, + use_case: None | str | Unset = UNSET, + page: int | Unset = 1, + limit: int | Unset = 20, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + if not isinstance(x_account_id, Unset): + headers["X-Account-Id"] = x_account_id + + if not isinstance(seclai_version, Unset): + headers["Seclai-Version"] = seclai_version + + params: dict[str, Any] = {} + + json_query: None | str | Unset + if isinstance(query, Unset): + json_query = UNSET + else: + json_query = query + params["query"] = json_query + + json_use_case: None | str | Unset + if isinstance(use_case, Unset): + json_use_case = UNSET + else: + json_use_case = use_case + params["use_case"] = json_use_case + + params["page"] = page + + params["limit"] = limit + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/agents/examples", + "params": params, + } + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError | None: + if response.status_code == 200: + response_200 = AgentExampleListResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 422: + response_422 = HTTPValidationError.from_dict(response.json()) + + return response_422 + + if response.status_code == 503: + response_503 = ServiceUnavailableError.from_dict(response.json()) + + return response_503 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + query: None | str | Unset = UNSET, + use_case: None | str | Unset = UNSET, + page: int | Unset = 1, + limit: int | Unset = 20, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> Response[AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError]: + """List agent gallery examples + + List the agent gallery: example agents to start from, searchable by text and filterable by use case. + Pass an entry's `key` as `agent_template` on POST /agents, with `resource_bindings` for the + resources it needs. + + Args: + query (None | str | Unset): Words every match must contain. + use_case (None | str | Unset): Only entries for this use case. + page (int | Unset): Page number Default: 1. + limit (int | Unset): Items per page Default: 20. + x_account_id (UUID | Unset): + seclai_version (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError] + """ + + kwargs = _get_kwargs( + query=query, + use_case=use_case, + page=page, + limit=limit, + x_account_id=x_account_id, + seclai_version=seclai_version, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + query: None | str | Unset = UNSET, + use_case: None | str | Unset = UNSET, + page: int | Unset = 1, + limit: int | Unset = 20, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError | None: + """List agent gallery examples + + List the agent gallery: example agents to start from, searchable by text and filterable by use case. + Pass an entry's `key` as `agent_template` on POST /agents, with `resource_bindings` for the + resources it needs. + + Args: + query (None | str | Unset): Words every match must contain. + use_case (None | str | Unset): Only entries for this use case. + page (int | Unset): Page number Default: 1. + limit (int | Unset): Items per page Default: 20. + x_account_id (UUID | Unset): + seclai_version (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError + """ + + return sync_detailed( + client=client, + query=query, + use_case=use_case, + page=page, + limit=limit, + x_account_id=x_account_id, + seclai_version=seclai_version, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + query: None | str | Unset = UNSET, + use_case: None | str | Unset = UNSET, + page: int | Unset = 1, + limit: int | Unset = 20, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> Response[AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError]: + """List agent gallery examples + + List the agent gallery: example agents to start from, searchable by text and filterable by use case. + Pass an entry's `key` as `agent_template` on POST /agents, with `resource_bindings` for the + resources it needs. + + Args: + query (None | str | Unset): Words every match must contain. + use_case (None | str | Unset): Only entries for this use case. + page (int | Unset): Page number Default: 1. + limit (int | Unset): Items per page Default: 20. + x_account_id (UUID | Unset): + seclai_version (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError] + """ + + kwargs = _get_kwargs( + query=query, + use_case=use_case, + page=page, + limit=limit, + x_account_id=x_account_id, + seclai_version=seclai_version, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + query: None | str | Unset = UNSET, + use_case: None | str | Unset = UNSET, + page: int | Unset = 1, + limit: int | Unset = 20, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError | None: + """List agent gallery examples + + List the agent gallery: example agents to start from, searchable by text and filterable by use case. + Pass an entry's `key` as `agent_template` on POST /agents, with `resource_bindings` for the + resources it needs. + + Args: + query (None | str | Unset): Words every match must contain. + use_case (None | str | Unset): Only entries for this use case. + page (int | Unset): Page number Default: 1. + limit (int | Unset): Items per page Default: 20. + x_account_id (UUID | Unset): + seclai_version (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AgentExampleListResponse | HTTPValidationError | ServiceUnavailableError + """ + + return ( + await asyncio_detailed( + client=client, + query=query, + use_case=use_case, + page=page, + limit=limit, + x_account_id=x_account_id, + seclai_version=seclai_version, + ) + ).parsed diff --git a/seclai/_generated/api/agents/set_slack_trigger_config_api_api_agents_agent_id_triggers_trigger_id_slack_config_put.py b/seclai/_generated/api/agents/set_slack_trigger_config_api_api_agents_agent_id_triggers_trigger_id_slack_config_put.py new file mode 100644 index 0000000..be75e5f --- /dev/null +++ b/seclai/_generated/api/agents/set_slack_trigger_config_api_api_agents_agent_id_triggers_trigger_id_slack_config_put.py @@ -0,0 +1,276 @@ +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.http_validation_error import HTTPValidationError +from ...models.service_unavailable_error import ServiceUnavailableError +from ...models.set_slack_trigger_config_api_request import ( + SetSlackTriggerConfigApiRequest, +) +from ...models.slack_trigger_config_api_response import SlackTriggerConfigApiResponse +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + agent_id: UUID, + trigger_id: UUID, + *, + body: SetSlackTriggerConfigApiRequest, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + if not isinstance(x_account_id, Unset): + headers["X-Account-Id"] = x_account_id + + if not isinstance(seclai_version, Unset): + headers["Seclai-Version"] = seclai_version + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/agents/{agent_id}/triggers/{trigger_id}/slack-config".format( + agent_id=quote(str(agent_id), safe=""), + trigger_id=quote(str(trigger_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> ( + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse | None +): + if response.status_code == 200: + response_200 = SlackTriggerConfigApiResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 422: + response_422 = HTTPValidationError.from_dict(response.json()) + + return response_422 + + if response.status_code == 503: + response_503 = ServiceUnavailableError.from_dict(response.json()) + + return response_503 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[ + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse +]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + agent_id: UUID, + trigger_id: UUID, + *, + client: AuthenticatedClient | Client, + body: SetSlackTriggerConfigApiRequest, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> Response[ + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse +]: + """Configure a SLACK_COMMAND trigger + + Set the Slack connection, form, channels, visibility and conversation settings of an agent's + SLACK_COMMAND trigger, which people run from Slack with `/seclai` or the message shortcut. Omitted + fields are left unchanged. + + Auth & scoping: requires `X-API-Key` header or OAuth Bearer token; the trigger must belong to an + agent in the key's account. + + Args: + agent_id (UUID): + trigger_id (UUID): + x_account_id (UUID | Unset): + seclai_version (str | Unset): + body (SetSlackTriggerConfigApiRequest): Omitted fields are left unchanged. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse] + """ + + kwargs = _get_kwargs( + agent_id=agent_id, + trigger_id=trigger_id, + body=body, + x_account_id=x_account_id, + seclai_version=seclai_version, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + agent_id: UUID, + trigger_id: UUID, + *, + client: AuthenticatedClient | Client, + body: SetSlackTriggerConfigApiRequest, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> ( + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse | None +): + """Configure a SLACK_COMMAND trigger + + Set the Slack connection, form, channels, visibility and conversation settings of an agent's + SLACK_COMMAND trigger, which people run from Slack with `/seclai` or the message shortcut. Omitted + fields are left unchanged. + + Auth & scoping: requires `X-API-Key` header or OAuth Bearer token; the trigger must belong to an + agent in the key's account. + + Args: + agent_id (UUID): + trigger_id (UUID): + x_account_id (UUID | Unset): + seclai_version (str | Unset): + body (SetSlackTriggerConfigApiRequest): Omitted fields are left unchanged. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse + """ + + return sync_detailed( + agent_id=agent_id, + trigger_id=trigger_id, + client=client, + body=body, + x_account_id=x_account_id, + seclai_version=seclai_version, + ).parsed + + +async def asyncio_detailed( + agent_id: UUID, + trigger_id: UUID, + *, + client: AuthenticatedClient | Client, + body: SetSlackTriggerConfigApiRequest, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> Response[ + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse +]: + """Configure a SLACK_COMMAND trigger + + Set the Slack connection, form, channels, visibility and conversation settings of an agent's + SLACK_COMMAND trigger, which people run from Slack with `/seclai` or the message shortcut. Omitted + fields are left unchanged. + + Auth & scoping: requires `X-API-Key` header or OAuth Bearer token; the trigger must belong to an + agent in the key's account. + + Args: + agent_id (UUID): + trigger_id (UUID): + x_account_id (UUID | Unset): + seclai_version (str | Unset): + body (SetSlackTriggerConfigApiRequest): Omitted fields are left unchanged. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse] + """ + + kwargs = _get_kwargs( + agent_id=agent_id, + trigger_id=trigger_id, + body=body, + x_account_id=x_account_id, + seclai_version=seclai_version, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + agent_id: UUID, + trigger_id: UUID, + *, + client: AuthenticatedClient | Client, + body: SetSlackTriggerConfigApiRequest, + x_account_id: UUID | Unset = UNSET, + seclai_version: str | Unset = UNSET, +) -> ( + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse | None +): + """Configure a SLACK_COMMAND trigger + + Set the Slack connection, form, channels, visibility and conversation settings of an agent's + SLACK_COMMAND trigger, which people run from Slack with `/seclai` or the message shortcut. Omitted + fields are left unchanged. + + Auth & scoping: requires `X-API-Key` header or OAuth Bearer token; the trigger must belong to an + agent in the key's account. + + Args: + agent_id (UUID): + trigger_id (UUID): + x_account_id (UUID | Unset): + seclai_version (str | Unset): + body (SetSlackTriggerConfigApiRequest): Omitted fields are left unchanged. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + HTTPValidationError | ServiceUnavailableError | SlackTriggerConfigApiResponse + """ + + return ( + await asyncio_detailed( + agent_id=agent_id, + trigger_id=trigger_id, + client=client, + body=body, + x_account_id=x_account_id, + seclai_version=seclai_version, + ) + ).parsed diff --git a/seclai/_generated/api/agents/update_agent_api_agents_agent_id_put.py b/seclai/_generated/api/agents/update_agent_api_agents_agent_id_put.py index d3688e3..e11068c 100644 --- a/seclai/_generated/api/agents/update_agent_api_agents_agent_id_put.py +++ b/seclai/_generated/api/agents/update_agent_api_agents_agent_id_put.py @@ -99,7 +99,7 @@ def sync_detailed( ]: """Update agent metadata - Update an agent's name, description, evaluation settings, and model lifecycle settings. + Update an agent's name, description, evaluation settings, model lifecycle settings and run limits. Evaluation settings: `evaluation_mode` ('output_expectation', 'eval_and_retry', 'sample_and_flag'), `default_evaluation_tier` ('fast', 'balanced', 'thorough'), `max_retries`, `retry_on_failure`, @@ -110,6 +110,11 @@ def sync_detailed( `prompt_model_auto_rollback_triggers` (list of 'agent_eval_fail', 'governance_flag', 'governance_block', 'agent_run_failed'). + Run limits (each must be greater than 0; pass the paired `set_: true` with the value omitted + to remove one): `max_credits_per_run`, `max_credits_per_period`, `max_runs_per_hour`, + `max_runs_per_day`, `max_runs_total`. A runs-per-hour or per-day value above the plan's run quota is + rejected with 400. + Replacing the workflow from an export: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. Update only touches the workflow + agent metadata — alert_configs, evaluation_criteria, governance_policies, @@ -167,7 +172,7 @@ def sync( ): """Update agent metadata - Update an agent's name, description, evaluation settings, and model lifecycle settings. + Update an agent's name, description, evaluation settings, model lifecycle settings and run limits. Evaluation settings: `evaluation_mode` ('output_expectation', 'eval_and_retry', 'sample_and_flag'), `default_evaluation_tier` ('fast', 'balanced', 'thorough'), `max_retries`, `retry_on_failure`, @@ -178,6 +183,11 @@ def sync( `prompt_model_auto_rollback_triggers` (list of 'agent_eval_fail', 'governance_flag', 'governance_block', 'agent_run_failed'). + Run limits (each must be greater than 0; pass the paired `set_: true` with the value omitted + to remove one): `max_credits_per_run`, `max_credits_per_period`, `max_runs_per_hour`, + `max_runs_per_day`, `max_runs_total`. A runs-per-hour or per-day value above the plan's run quota is + rejected with 400. + Replacing the workflow from an export: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. Update only touches the workflow + agent metadata — alert_configs, evaluation_criteria, governance_policies, @@ -227,7 +237,7 @@ async def asyncio_detailed( ]: """Update agent metadata - Update an agent's name, description, evaluation settings, and model lifecycle settings. + Update an agent's name, description, evaluation settings, model lifecycle settings and run limits. Evaluation settings: `evaluation_mode` ('output_expectation', 'eval_and_retry', 'sample_and_flag'), `default_evaluation_tier` ('fast', 'balanced', 'thorough'), `max_retries`, `retry_on_failure`, @@ -238,6 +248,11 @@ async def asyncio_detailed( `prompt_model_auto_rollback_triggers` (list of 'agent_eval_fail', 'governance_flag', 'governance_block', 'agent_run_failed'). + Run limits (each must be greater than 0; pass the paired `set_: true` with the value omitted + to remove one): `max_credits_per_run`, `max_credits_per_period`, `max_runs_per_hour`, + `max_runs_per_day`, `max_runs_total`. A runs-per-hour or per-day value above the plan's run quota is + rejected with 400. + Replacing the workflow from an export: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. Update only touches the workflow + agent metadata — alert_configs, evaluation_criteria, governance_policies, @@ -293,7 +308,7 @@ async def asyncio( ): """Update agent metadata - Update an agent's name, description, evaluation settings, and model lifecycle settings. + Update an agent's name, description, evaluation settings, model lifecycle settings and run limits. Evaluation settings: `evaluation_mode` ('output_expectation', 'eval_and_retry', 'sample_and_flag'), `default_evaluation_tier` ('fast', 'balanced', 'thorough'), `max_retries`, `retry_on_failure`, @@ -304,6 +319,11 @@ async def asyncio( `prompt_model_auto_rollback_triggers` (list of 'agent_eval_fail', 'governance_flag', 'governance_block', 'agent_run_failed'). + Run limits (each must be greater than 0; pass the paired `set_: true` with the value omitted + to remove one): `max_credits_per_run`, `max_credits_per_period`, `max_runs_per_hour`, + `max_runs_per_day`, `max_runs_total`. A runs-per-hour or per-day value above the plan's run quota is + rejected with 400. + Replacing the workflow from an export: - Pass `agent_definition` with the JSON shape produced by `GET /agents/{id}/export`. Update only touches the workflow + agent metadata — alert_configs, evaluation_criteria, governance_policies, diff --git a/seclai/_generated/api/alerts/create_alert_config_api_alerts_configs_post.py b/seclai/_generated/api/alerts/create_alert_config_api_alerts_configs_post.py index 0e6ba13..4140c17 100644 --- a/seclai/_generated/api/alerts/create_alert_config_api_alerts_configs_post.py +++ b/seclai/_generated/api/alerts/create_alert_config_api_alerts_configs_post.py @@ -89,7 +89,8 @@ def sync_detailed( credits_low_threshold, credits_runout_prediction, credits_usage_spike, non_manual_eval_failed, non_manual_eval_flagged, governance_flagged, governance_blocked, model_newer_available, model_deprecated, model_sunset. - Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike. + Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike, + source_spend_limit_reached (needs source_connection_id). Distribution types: owner, owner_admins, selected_members. Organization accounts are normalized to owner_admins. @@ -138,7 +139,8 @@ def sync( credits_low_threshold, credits_runout_prediction, credits_usage_spike, non_manual_eval_failed, non_manual_eval_flagged, governance_flagged, governance_blocked, model_newer_available, model_deprecated, model_sunset. - Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike. + Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike, + source_spend_limit_reached (needs source_connection_id). Distribution types: owner, owner_admins, selected_members. Organization accounts are normalized to owner_admins. @@ -182,7 +184,8 @@ async def asyncio_detailed( credits_low_threshold, credits_runout_prediction, credits_usage_spike, non_manual_eval_failed, non_manual_eval_flagged, governance_flagged, governance_blocked, model_newer_available, model_deprecated, model_sunset. - Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike. + Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike, + source_spend_limit_reached (needs source_connection_id). Distribution types: owner, owner_admins, selected_members. Organization accounts are normalized to owner_admins. @@ -229,7 +232,8 @@ async def asyncio( credits_low_threshold, credits_runout_prediction, credits_usage_spike, non_manual_eval_failed, non_manual_eval_flagged, governance_flagged, governance_blocked, model_newer_available, model_deprecated, model_sunset. - Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike. + Source alert types: pull_failed, consecutive_pull_failures, pull_error_rate_spike, + source_spend_limit_reached (needs source_connection_id). Distribution types: owner, owner_admins, selected_members. Organization accounts are normalized to owner_admins. diff --git a/seclai/_generated/api/sources/update_source_api_sources_source_connection_id_put.py b/seclai/_generated/api/sources/update_source_api_sources_source_connection_id_put.py index 24d00ab..0e7fb06 100644 --- a/seclai/_generated/api/sources/update_source_api_sources_source_connection_id_put.py +++ b/seclai/_generated/api/sources/update_source_api_sources_source_connection_id_put.py @@ -93,6 +93,10 @@ def sync_detailed( System-managed sources only allow `retention_days` updates. + A source with a spend limit that reaches it refuses new content with a 402 + `source_spend_limit_reached` (`spend_cap_action: stop`), or deletes entries to make room (`delete`); + a `delete` source whose spend already fills the limit refuses new content too. + Args: source_connection_id (UUID): x_account_id (UUID | Unset): @@ -136,6 +140,10 @@ def sync( System-managed sources only allow `retention_days` updates. + A source with a spend limit that reaches it refuses new content with a 402 + `source_spend_limit_reached` (`spend_cap_action: stop`), or deletes entries to make room (`delete`); + a `delete` source whose spend already fills the limit refuses new content too. + Args: source_connection_id (UUID): x_account_id (UUID | Unset): @@ -174,6 +182,10 @@ async def asyncio_detailed( System-managed sources only allow `retention_days` updates. + A source with a spend limit that reaches it refuses new content with a 402 + `source_spend_limit_reached` (`spend_cap_action: stop`), or deletes entries to make room (`delete`); + a `delete` source whose spend already fills the limit refuses new content too. + Args: source_connection_id (UUID): x_account_id (UUID | Unset): @@ -215,6 +227,10 @@ async def asyncio( System-managed sources only allow `retention_days` updates. + A source with a spend limit that reaches it refuses new content with a 402 + `source_spend_limit_reached` (`spend_cap_action: stop`), or deletes entries to make room (`delete`); + a `delete` source whose spend already fills the limit refuses new content too. + Args: source_connection_id (UUID): x_account_id (UUID | Unset): diff --git a/seclai/_generated/models/__init__.py b/seclai/_generated/models/__init__.py index 64fbf20..4deabc5 100644 --- a/seclai/_generated/models/__init__.py +++ b/seclai/_generated/models/__init__.py @@ -19,6 +19,7 @@ from .agent_email_opt_out_list_response import AgentEmailOptOutListResponse from .agent_email_opt_out_response import AgentEmailOptOutResponse from .agent_evaluation_tier import AgentEvaluationTier +from .agent_example_list_response import AgentExampleListResponse from .agent_export_response import AgentExportResponse from .agent_export_response_agent import AgentExportResponseAgent from .agent_export_response_alert_configs_type_0_item import ( @@ -54,6 +55,9 @@ from .agent_run_stream_request_metadata_type_0 import AgentRunStreamRequestMetadataType0 from .agent_run_tool_call_response import AgentRunToolCallResponse from .agent_summary_response import AgentSummaryResponse +from .agent_summary_response_created_resources_type_0 import ( + AgentSummaryResponseCreatedResourcesType0, +) from .agent_summary_response_sampling_config_type_0 import ( AgentSummaryResponseSamplingConfigType0, ) @@ -128,6 +132,9 @@ CreateAgentRequestAgentDefinitionType0, ) from .create_agent_request_entity_remap_type_0 import CreateAgentRequestEntityRemapType0 +from .create_agent_request_resource_bindings_type_0 import ( + CreateAgentRequestResourceBindingsType0, +) from .create_alert_config_request import CreateAlertConfigRequest from .create_alert_config_request_threshold_type_0 import ( CreateAlertConfigRequestThresholdType0, @@ -344,8 +351,19 @@ from .set_accepted_attachments_request import SetAcceptedAttachmentsRequest from .set_auto_block_mode_request import SetAutoBlockModeRequest from .set_email_trigger_config_request import SetEmailTriggerConfigRequest +from .set_slack_trigger_config_api_request import SetSlackTriggerConfigApiRequest +from .set_slack_trigger_config_api_request_form_type_0_item import ( + SetSlackTriggerConfigApiRequestFormType0Item, +) from .skipped_attachment_reason import SkippedAttachmentReason from .skipped_attachment_response import SkippedAttachmentResponse +from .slack_reply_visibility import SlackReplyVisibility +from .slack_trigger_activation import SlackTriggerActivation +from .slack_trigger_config_api_response import SlackTriggerConfigApiResponse +from .slack_trigger_config_api_response_form_item import ( + SlackTriggerConfigApiResponseFormItem, +) +from .slack_trigger_scope import SlackTriggerScope from .solution_agent_response import SolutionAgentResponse from .solution_conversation_response import SolutionConversationResponse from .solution_conversation_response_actions_taken_type_0 import ( @@ -363,6 +381,8 @@ from .source_index_mode import SourceIndexMode from .source_list_response import SourceListResponse from .source_response import SourceResponse +from .spend_cap_action import SpendCapAction +from .spend_cap_delete_order import SpendCapDeleteOrder from .standalone_test_compaction_request import StandaloneTestCompactionRequest from .start_source_embedding_migration_request import ( StartSourceEmbeddingMigrationRequest, @@ -424,6 +444,7 @@ "AgentEmailOptOutListResponse", "AgentEmailOptOutResponse", "AgentEvaluationTier", + "AgentExampleListResponse", "AgentExportResponse", "AgentExportResponseAgent", "AgentExportResponseAlertConfigsType0Item", @@ -447,6 +468,7 @@ "AgentRunStreamRequestMetadataType0", "AgentRunToolCallResponse", "AgentSummaryResponse", + "AgentSummaryResponseCreatedResourcesType0", "AgentSummaryResponseSamplingConfigType0", "AgentTraceMatchResponse", "AgentTraceSearchRequest", @@ -505,6 +527,7 @@ "CreateAgentRequest", "CreateAgentRequestAgentDefinitionType0", "CreateAgentRequestEntityRemapType0", + "CreateAgentRequestResourceBindingsType0", "CreateAlertConfigRequest", "CreateAlertConfigRequestThresholdType0", "CreateEvaluationCriteriaRequest", @@ -655,8 +678,15 @@ "SetAcceptedAttachmentsRequest", "SetAutoBlockModeRequest", "SetEmailTriggerConfigRequest", + "SetSlackTriggerConfigApiRequest", + "SetSlackTriggerConfigApiRequestFormType0Item", "SkippedAttachmentReason", "SkippedAttachmentResponse", + "SlackReplyVisibility", + "SlackTriggerActivation", + "SlackTriggerConfigApiResponse", + "SlackTriggerConfigApiResponseFormItem", + "SlackTriggerScope", "SolutionAgentResponse", "SolutionConversationResponse", "SolutionConversationResponseActionsTakenType0", @@ -672,6 +702,8 @@ "SourceIndexMode", "SourceListResponse", "SourceResponse", + "SpendCapAction", + "SpendCapDeleteOrder", "StandaloneTestCompactionRequest", "StartSourceEmbeddingMigrationRequest", "TestCompactionRequest", diff --git a/seclai/_generated/models/agent_example_list_response.py b/seclai/_generated/models/agent_example_list_response.py new file mode 100644 index 0000000..7863b1c --- /dev/null +++ b/seclai/_generated/models/agent_example_list_response.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.pagination_response import PaginationResponse + + +T = TypeVar("T", bound="AgentExampleListResponse") + + +@_attrs_define +class AgentExampleListResponse: + """ + Attributes: + data (list[Any]): + pagination (PaginationResponse): Pagination information. + """ + + data: list[Any] + pagination: PaginationResponse + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + data = self.data + + pagination = self.pagination.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "data": data, + "pagination": pagination, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.pagination_response import PaginationResponse + + d = dict(src_dict) + data = cast(list[Any], d.pop("data")) + + pagination = PaginationResponse.from_dict(d.pop("pagination")) + + agent_example_list_response = cls( + data=data, + pagination=pagination, + ) + + agent_example_list_response.additional_properties = d + return agent_example_list_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/agent_export_response.py b/seclai/_generated/models/agent_export_response.py index 1390350..12e1d25 100644 --- a/seclai/_generated/models/agent_export_response.py +++ b/seclai/_generated/models/agent_export_response.py @@ -38,7 +38,8 @@ class AgentExportResponse: agent (AgentExportResponseAgent): Agent metadata and full definition. Keys: name, description, schema_version, definition, default_evaluation_tier, evaluation_mode, sampling_config, max_retries, retry_on_failure, prompt_model_auto_upgrade_strategy, prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers, - created_at, updated_at. + max_credits_per_run, max_credits_per_period, max_runs_per_hour, max_runs_per_day, max_runs_total, created_at, + updated_at. export_version (str): Schema version of the export format (currently "5"). exported_at (str): ISO-8601 timestamp of when the export was generated. software_version (str): Application version that produced this export. diff --git a/seclai/_generated/models/agent_export_response_agent.py b/seclai/_generated/models/agent_export_response_agent.py index b01a142..1b3c3fa 100644 --- a/seclai/_generated/models/agent_export_response_agent.py +++ b/seclai/_generated/models/agent_export_response_agent.py @@ -13,7 +13,8 @@ class AgentExportResponseAgent: """Agent metadata and full definition. Keys: name, description, schema_version, definition, default_evaluation_tier, evaluation_mode, sampling_config, max_retries, retry_on_failure, prompt_model_auto_upgrade_strategy, - prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers, created_at, updated_at. + prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers, max_credits_per_run, + max_credits_per_period, max_runs_per_hour, max_runs_per_day, max_runs_total, created_at, updated_at. """ diff --git a/seclai/_generated/models/agent_run_step_response.py b/seclai/_generated/models/agent_run_step_response.py index 0617c86..98b8a61 100644 --- a/seclai/_generated/models/agent_run_step_response.py +++ b/seclai/_generated/models/agent_run_step_response.py @@ -32,13 +32,17 @@ class AgentRunStepResponse: input_ (None | str): Input text provided to the step, if any. Below `Seclai-Version: 2026-09-30`, the manifest JSON when the step that produced it output files and is not a `for_each`. output (None | str): Output text produced by the step, if any; its files are in `attachments`. Below `Seclai- - Version: 2026-09-30`, the manifest JSON when the step output files and is not a `for_each`. + Version: 2026-09-30`, the manifest JSON when the step output files and is not a `for_each`. For an `if_else` or + `switch`, the result of the arm it took (its input when that arm is empty or it took none); below `Seclai- + Version: 2026-10-28`, the `{"branch": ...}` marker naming that arm, with no `attachments`. output_content_type (None | str): Content type of the step output, if any. started_at (None | str): Timestamp when the step attempt started. status (PendingProcessingCompletedFailedStatus): step_type (str): Type of the agent step. attachments (list[AgentRunFileResponse] | Unset): Files in this step's output, in order. Empty for steps that produced none, for steps run before files were listed here, and once the run's trace is purged. + decision (None | str | Unset): The arm an `if_else` or `switch` step took: `then` or `else`, or the case name or + `else`. Null for other step types, until the step has decided, and when a `switch` took no arm. tool_calls (list[AgentRunToolCallResponse] | Unset): LLM tool calls made during this step (prompt_call steps only), ordered by execution. Empty for steps that invoked no tools. warnings (list[str] | None | Unset): Problems the step ran into, whether or not it then failed, such as a file @@ -56,6 +60,7 @@ class AgentRunStepResponse: status: PendingProcessingCompletedFailedStatus step_type: str attachments: list[AgentRunFileResponse] | Unset = UNSET + decision: None | str | Unset = UNSET tool_calls: list[AgentRunToolCallResponse] | Unset = UNSET warnings: list[str] | None | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) @@ -94,6 +99,12 @@ def to_dict(self) -> dict[str, Any]: attachments_item = attachments_item_data.to_dict() attachments.append(attachments_item) + decision: None | str | Unset + if isinstance(self.decision, Unset): + decision = UNSET + else: + decision = self.decision + tool_calls: list[dict[str, Any]] | Unset = UNSET if not isinstance(self.tool_calls, Unset): tool_calls = [] @@ -128,6 +139,8 @@ def to_dict(self) -> dict[str, Any]: ) if attachments is not UNSET: field_dict["attachments"] = attachments + if decision is not UNSET: + field_dict["decision"] = decision if tool_calls is not UNSET: field_dict["tool_calls"] = tool_calls if warnings is not UNSET: @@ -200,6 +213,15 @@ def _parse_started_at(data: object) -> None | str: attachments.append(attachments_item) + def _parse_decision(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + decision = _parse_decision(d.pop("decision", UNSET)) + _tool_calls = d.pop("tool_calls", UNSET) tool_calls: list[AgentRunToolCallResponse] | Unset = UNSET if _tool_calls is not UNSET: @@ -240,6 +262,7 @@ def _parse_warnings(data: object) -> list[str] | None | Unset: status=status, step_type=step_type, attachments=attachments, + decision=decision, tool_calls=tool_calls, warnings=warnings, ) diff --git a/seclai/_generated/models/agent_summary_response.py b/seclai/_generated/models/agent_summary_response.py index 52a6f0a..2d86b9b 100644 --- a/seclai/_generated/models/agent_summary_response.py +++ b/seclai/_generated/models/agent_summary_response.py @@ -9,6 +9,9 @@ from ..types import UNSET, Unset if TYPE_CHECKING: + from ..models.agent_summary_response_created_resources_type_0 import ( + AgentSummaryResponseCreatedResourcesType0, + ) from ..models.agent_summary_response_sampling_config_type_0 import ( AgentSummaryResponseSamplingConfigType0, ) @@ -27,6 +30,8 @@ class AgentSummaryResponse: id (str): Unique agent identifier. name (str): Agent name. updated_at (str): ISO 8601 last-updated timestamp. + created_resources (AgentSummaryResponseCreatedResourcesType0 | None | Unset): On a create from an + `agent_template`: {slot: resource_id} for each resource `create_missing_resources` created. default_evaluation_tier (None | str | Unset): Default evaluation tier: fast, balanced, or thorough. disabled (bool | Unset): Whether the agent is paused (disabled). Default: False. disabled_at (None | str | Unset): ISO 8601 timestamp the agent was paused. @@ -36,7 +41,12 @@ class AgentSummaryResponse: import_warnings (list[ImportSkipResponse] | None | Unset): One entry per item dropped or substituted during import. Present only on endpoints that accept agent_definition; null on non-import calls; [] when the import had no skips. + max_credits_per_period (float | None | Unset): Credit limit per billing period; null when none. + max_credits_per_run (float | None | Unset): Credit limit per run; null when none. max_retries (int | Unset): Max retries for eval_and_retry mode. Default: 3. + max_runs_per_day (int | None | Unset): Runs per day limit; null when none. + max_runs_per_hour (int | None | Unset): Runs per hour limit; null when none. + max_runs_total (int | None | Unset): Limit on runs in total; null when none. prompt_model_auto_rollback_enabled (bool | Unset): Whether automatic rollback is enabled for upgraded models. Default: False. prompt_model_auto_rollback_triggers (list[str] | None | Unset): Failure signals that trigger rollback. Defaults @@ -46,6 +56,8 @@ class AgentSummaryResponse: retry_on_failure (bool | Unset): Whether to retry on evaluation failure. Default: True. sampling_config (AgentSummaryResponseSamplingConfigType0 | None | Unset): Sampling configuration for sample_and_flag mode. + solution_id (None | str | Unset): On a create from an `agent_template` that created resources: the solution + grouping the agent with them. trigger_id (None | str | Unset): ID of the agent's trigger, for the `/agents/{agent_id}/triggers/{trigger_id}/…` endpoints such as `accepted-attachments` and `email-config`. trigger_type (None | str | Unset): Trigger type for the agent. @@ -56,23 +68,33 @@ class AgentSummaryResponse: id: str name: str updated_at: str + created_resources: AgentSummaryResponseCreatedResourcesType0 | None | Unset = UNSET default_evaluation_tier: None | str | Unset = UNSET disabled: bool | Unset = False disabled_at: None | str | Unset = UNSET disabled_reason: None | str | Unset = UNSET evaluation_mode: str | Unset = "eval_and_retry" import_warnings: list[ImportSkipResponse] | None | Unset = UNSET + max_credits_per_period: float | None | Unset = UNSET + max_credits_per_run: float | None | Unset = UNSET max_retries: int | Unset = 3 + max_runs_per_day: int | None | Unset = UNSET + max_runs_per_hour: int | None | Unset = UNSET + max_runs_total: int | None | Unset = UNSET prompt_model_auto_rollback_enabled: bool | Unset = False prompt_model_auto_rollback_triggers: list[str] | None | Unset = UNSET prompt_model_auto_upgrade_strategy: str | Unset = "none" retry_on_failure: bool | Unset = True sampling_config: AgentSummaryResponseSamplingConfigType0 | None | Unset = UNSET + solution_id: None | str | Unset = UNSET trigger_id: None | str | Unset = UNSET trigger_type: None | str | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: + from ..models.agent_summary_response_created_resources_type_0 import ( + AgentSummaryResponseCreatedResourcesType0, + ) from ..models.agent_summary_response_sampling_config_type_0 import ( AgentSummaryResponseSamplingConfigType0, ) @@ -88,6 +110,16 @@ def to_dict(self) -> dict[str, Any]: updated_at = self.updated_at + created_resources: dict[str, Any] | None | Unset + if isinstance(self.created_resources, Unset): + created_resources = UNSET + elif isinstance( + self.created_resources, AgentSummaryResponseCreatedResourcesType0 + ): + created_resources = self.created_resources.to_dict() + else: + created_resources = self.created_resources + default_evaluation_tier: None | str | Unset if isinstance(self.default_evaluation_tier, Unset): default_evaluation_tier = UNSET @@ -122,8 +154,38 @@ def to_dict(self) -> dict[str, Any]: else: import_warnings = self.import_warnings + max_credits_per_period: float | None | Unset + if isinstance(self.max_credits_per_period, Unset): + max_credits_per_period = UNSET + else: + max_credits_per_period = self.max_credits_per_period + + max_credits_per_run: float | None | Unset + if isinstance(self.max_credits_per_run, Unset): + max_credits_per_run = UNSET + else: + max_credits_per_run = self.max_credits_per_run + max_retries = self.max_retries + max_runs_per_day: int | None | Unset + if isinstance(self.max_runs_per_day, Unset): + max_runs_per_day = UNSET + else: + max_runs_per_day = self.max_runs_per_day + + max_runs_per_hour: int | None | Unset + if isinstance(self.max_runs_per_hour, Unset): + max_runs_per_hour = UNSET + else: + max_runs_per_hour = self.max_runs_per_hour + + max_runs_total: int | None | Unset + if isinstance(self.max_runs_total, Unset): + max_runs_total = UNSET + else: + max_runs_total = self.max_runs_total + prompt_model_auto_rollback_enabled = self.prompt_model_auto_rollback_enabled prompt_model_auto_rollback_triggers: list[str] | None | Unset @@ -151,6 +213,12 @@ def to_dict(self) -> dict[str, Any]: else: sampling_config = self.sampling_config + solution_id: None | str | Unset + if isinstance(self.solution_id, Unset): + solution_id = UNSET + else: + solution_id = self.solution_id + trigger_id: None | str | Unset if isinstance(self.trigger_id, Unset): trigger_id = UNSET @@ -174,6 +242,8 @@ def to_dict(self) -> dict[str, Any]: "updated_at": updated_at, } ) + if created_resources is not UNSET: + field_dict["created_resources"] = created_resources if default_evaluation_tier is not UNSET: field_dict["default_evaluation_tier"] = default_evaluation_tier if disabled is not UNSET: @@ -186,8 +256,18 @@ def to_dict(self) -> dict[str, Any]: field_dict["evaluation_mode"] = evaluation_mode if import_warnings is not UNSET: field_dict["import_warnings"] = import_warnings + if max_credits_per_period is not UNSET: + field_dict["max_credits_per_period"] = max_credits_per_period + if max_credits_per_run is not UNSET: + field_dict["max_credits_per_run"] = max_credits_per_run if max_retries is not UNSET: field_dict["max_retries"] = max_retries + if max_runs_per_day is not UNSET: + field_dict["max_runs_per_day"] = max_runs_per_day + if max_runs_per_hour is not UNSET: + field_dict["max_runs_per_hour"] = max_runs_per_hour + if max_runs_total is not UNSET: + field_dict["max_runs_total"] = max_runs_total if prompt_model_auto_rollback_enabled is not UNSET: field_dict["prompt_model_auto_rollback_enabled"] = ( prompt_model_auto_rollback_enabled @@ -204,6 +284,8 @@ def to_dict(self) -> dict[str, Any]: field_dict["retry_on_failure"] = retry_on_failure if sampling_config is not UNSET: field_dict["sampling_config"] = sampling_config + if solution_id is not UNSET: + field_dict["solution_id"] = solution_id if trigger_id is not UNSET: field_dict["trigger_id"] = trigger_id if trigger_type is not UNSET: @@ -213,6 +295,9 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.agent_summary_response_created_resources_type_0 import ( + AgentSummaryResponseCreatedResourcesType0, + ) from ..models.agent_summary_response_sampling_config_type_0 import ( AgentSummaryResponseSamplingConfigType0, ) @@ -234,6 +319,27 @@ def _parse_description(data: object) -> None | str: updated_at = d.pop("updated_at") + def _parse_created_resources( + data: object, + ) -> AgentSummaryResponseCreatedResourcesType0 | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, dict): + raise TypeError() + created_resources_type_0 = ( + AgentSummaryResponseCreatedResourcesType0.from_dict(data) + ) + + return created_resources_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(AgentSummaryResponseCreatedResourcesType0 | None | Unset, data) + + created_resources = _parse_created_resources(d.pop("created_resources", UNSET)) + def _parse_default_evaluation_tier(data: object) -> None | str | Unset: if data is None: return data @@ -293,8 +399,57 @@ def _parse_import_warnings( import_warnings = _parse_import_warnings(d.pop("import_warnings", UNSET)) + def _parse_max_credits_per_period(data: object) -> float | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(float | None | Unset, data) + + max_credits_per_period = _parse_max_credits_per_period( + d.pop("max_credits_per_period", UNSET) + ) + + def _parse_max_credits_per_run(data: object) -> float | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(float | None | Unset, data) + + max_credits_per_run = _parse_max_credits_per_run( + d.pop("max_credits_per_run", UNSET) + ) + max_retries = d.pop("max_retries", UNSET) + def _parse_max_runs_per_day(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_runs_per_day = _parse_max_runs_per_day(d.pop("max_runs_per_day", UNSET)) + + def _parse_max_runs_per_hour(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_runs_per_hour = _parse_max_runs_per_hour(d.pop("max_runs_per_hour", UNSET)) + + def _parse_max_runs_total(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_runs_total = _parse_max_runs_total(d.pop("max_runs_total", UNSET)) + prompt_model_auto_rollback_enabled = d.pop( "prompt_model_auto_rollback_enabled", UNSET ) @@ -349,6 +504,15 @@ def _parse_sampling_config( sampling_config = _parse_sampling_config(d.pop("sampling_config", UNSET)) + def _parse_solution_id(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + solution_id = _parse_solution_id(d.pop("solution_id", UNSET)) + def _parse_trigger_id(data: object) -> None | str | Unset: if data is None: return data @@ -373,18 +537,25 @@ def _parse_trigger_type(data: object) -> None | str | Unset: id=id, name=name, updated_at=updated_at, + created_resources=created_resources, default_evaluation_tier=default_evaluation_tier, disabled=disabled, disabled_at=disabled_at, disabled_reason=disabled_reason, evaluation_mode=evaluation_mode, import_warnings=import_warnings, + max_credits_per_period=max_credits_per_period, + max_credits_per_run=max_credits_per_run, max_retries=max_retries, + max_runs_per_day=max_runs_per_day, + max_runs_per_hour=max_runs_per_hour, + max_runs_total=max_runs_total, prompt_model_auto_rollback_enabled=prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers=prompt_model_auto_rollback_triggers, prompt_model_auto_upgrade_strategy=prompt_model_auto_upgrade_strategy, retry_on_failure=retry_on_failure, sampling_config=sampling_config, + solution_id=solution_id, trigger_id=trigger_id, trigger_type=trigger_type, ) diff --git a/seclai/_generated/models/agent_summary_response_created_resources_type_0.py b/seclai/_generated/models/agent_summary_response_created_resources_type_0.py new file mode 100644 index 0000000..a2dbc26 --- /dev/null +++ b/seclai/_generated/models/agent_summary_response_created_resources_type_0.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AgentSummaryResponseCreatedResourcesType0") + + +@_attrs_define +class AgentSummaryResponseCreatedResourcesType0: + """ """ + + additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + agent_summary_response_created_resources_type_0 = cls() + + agent_summary_response_created_resources_type_0.additional_properties = d + return agent_summary_response_created_resources_type_0 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> str: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: str) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/create_agent_request.py b/seclai/_generated/models/create_agent_request.py index a7635bb..6fcb359 100644 --- a/seclai/_generated/models/create_agent_request.py +++ b/seclai/_generated/models/create_agent_request.py @@ -16,6 +16,9 @@ from ..models.create_agent_request_entity_remap_type_0 import ( CreateAgentRequestEntityRemapType0, ) + from ..models.create_agent_request_resource_bindings_type_0 import ( + CreateAgentRequestResourceBindingsType0, + ) T = TypeVar("T", bound="CreateAgentRequest") @@ -34,24 +37,32 @@ class CreateAgentRequest: produced by GET /agents/{id}/export. When provided, replaces any template-derived workflow and pre-fills metadata/trigger fields the request does not specify explicitly. Validation errors include line/column references against a canonical pretty-printed echo of the supplied payload. - agent_template (None | str | Unset): Template to initialize the agent from. Values: blank, retrieval_example, - simple_qa, summarizer, json_extractor, content_change_notifier, scheduled_report, webhook_pipeline. + agent_template (None | str | Unset): Agent gallery entry to start from: a `key` from GET /agents/examples, or + `blank`. The keys retrieval_example and simple_qa remain accepted for their gallery entries. + create_missing_resources (bool | Unset): For an `agent_template`: create each creatable resource slot left out + of `resource_bindings`, and group the agent with them in a new solution. When false, an unbound slot the + template needs is an error. Default: False. description (None | str | Unset): Optional description. entity_remap (CreateAgentRequestEntityRemapType0 | None | Unset): Optional UUID-substitution map applied to the imported workflow before save. Each key is a source-account UUID (as returned by /agents/preview-import's ``unresolved_refs``); each value is the target-account UUID to substitute. Used to relink knowledge bases, memory banks, source connections, and sub-agents on cross-account imports. - trigger_type (str | Unset): Trigger type: dynamic_input, template_input, schedule, new_content, email_received. - Default: 'dynamic_input'. + resource_bindings (CreateAgentRequestResourceBindingsType0 | None | Unset): For an `agent_template`: the + existing resource to use for each of the template's resource slots, as {slot: resource_id}. GET /agents/examples + lists each template's slots. + trigger_type (None | str | Unset): Defaults to dynamic_input, or to the template's own trigger type for an + `agent_template` without `agent_definition`. """ name: str accepted_attachments: list[AcceptedAttachmentSlot] | None | Unset = UNSET agent_definition: CreateAgentRequestAgentDefinitionType0 | None | Unset = UNSET agent_template: None | str | Unset = UNSET + create_missing_resources: bool | Unset = False description: None | str | Unset = UNSET entity_remap: CreateAgentRequestEntityRemapType0 | None | Unset = UNSET - trigger_type: str | Unset = "dynamic_input" + resource_bindings: CreateAgentRequestResourceBindingsType0 | None | Unset = UNSET + trigger_type: None | str | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -61,6 +72,9 @@ def to_dict(self) -> dict[str, Any]: from ..models.create_agent_request_entity_remap_type_0 import ( CreateAgentRequestEntityRemapType0, ) + from ..models.create_agent_request_resource_bindings_type_0 import ( + CreateAgentRequestResourceBindingsType0, + ) name = self.name @@ -92,6 +106,8 @@ def to_dict(self) -> dict[str, Any]: else: agent_template = self.agent_template + create_missing_resources = self.create_missing_resources + description: None | str | Unset if isinstance(self.description, Unset): description = UNSET @@ -106,7 +122,21 @@ def to_dict(self) -> dict[str, Any]: else: entity_remap = self.entity_remap - trigger_type = self.trigger_type + resource_bindings: dict[str, Any] | None | Unset + if isinstance(self.resource_bindings, Unset): + resource_bindings = UNSET + elif isinstance( + self.resource_bindings, CreateAgentRequestResourceBindingsType0 + ): + resource_bindings = self.resource_bindings.to_dict() + else: + resource_bindings = self.resource_bindings + + trigger_type: None | str | Unset + if isinstance(self.trigger_type, Unset): + trigger_type = UNSET + else: + trigger_type = self.trigger_type field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) @@ -121,10 +151,14 @@ def to_dict(self) -> dict[str, Any]: field_dict["agent_definition"] = agent_definition if agent_template is not UNSET: field_dict["agent_template"] = agent_template + if create_missing_resources is not UNSET: + field_dict["create_missing_resources"] = create_missing_resources if description is not UNSET: field_dict["description"] = description if entity_remap is not UNSET: field_dict["entity_remap"] = entity_remap + if resource_bindings is not UNSET: + field_dict["resource_bindings"] = resource_bindings if trigger_type is not UNSET: field_dict["trigger_type"] = trigger_type @@ -139,6 +173,9 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: from ..models.create_agent_request_entity_remap_type_0 import ( CreateAgentRequestEntityRemapType0, ) + from ..models.create_agent_request_resource_bindings_type_0 import ( + CreateAgentRequestResourceBindingsType0, + ) d = dict(src_dict) name = d.pop("name") @@ -203,6 +240,8 @@ def _parse_agent_template(data: object) -> None | str | Unset: agent_template = _parse_agent_template(d.pop("agent_template", UNSET)) + create_missing_resources = d.pop("create_missing_resources", UNSET) + def _parse_description(data: object) -> None | str | Unset: if data is None: return data @@ -231,15 +270,45 @@ def _parse_entity_remap( entity_remap = _parse_entity_remap(d.pop("entity_remap", UNSET)) - trigger_type = d.pop("trigger_type", UNSET) + def _parse_resource_bindings( + data: object, + ) -> CreateAgentRequestResourceBindingsType0 | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, dict): + raise TypeError() + resource_bindings_type_0 = ( + CreateAgentRequestResourceBindingsType0.from_dict(data) + ) + + return resource_bindings_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(CreateAgentRequestResourceBindingsType0 | None | Unset, data) + + resource_bindings = _parse_resource_bindings(d.pop("resource_bindings", UNSET)) + + def _parse_trigger_type(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + trigger_type = _parse_trigger_type(d.pop("trigger_type", UNSET)) create_agent_request = cls( name=name, accepted_attachments=accepted_attachments, agent_definition=agent_definition, agent_template=agent_template, + create_missing_resources=create_missing_resources, description=description, entity_remap=entity_remap, + resource_bindings=resource_bindings, trigger_type=trigger_type, ) diff --git a/seclai/_generated/models/create_agent_request_resource_bindings_type_0.py b/seclai/_generated/models/create_agent_request_resource_bindings_type_0.py new file mode 100644 index 0000000..5f6a5d5 --- /dev/null +++ b/seclai/_generated/models/create_agent_request_resource_bindings_type_0.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="CreateAgentRequestResourceBindingsType0") + + +@_attrs_define +class CreateAgentRequestResourceBindingsType0: + """ """ + + additional_properties: dict[str, UUID] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + field_dict: dict[str, Any] = {} + for prop_name, prop in self.additional_properties.items(): + field_dict[prop_name] = str(prop) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + create_agent_request_resource_bindings_type_0 = cls() + + additional_properties = {} + for prop_name, prop_dict in d.items(): + additional_property = UUID(prop_dict) + + additional_properties[prop_name] = additional_property + + create_agent_request_resource_bindings_type_0.additional_properties = ( + additional_properties + ) + return create_agent_request_resource_bindings_type_0 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> UUID: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: UUID) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/email_source_rejection_response.py b/seclai/_generated/models/email_source_rejection_response.py index b786c14..d7def21 100644 --- a/seclai/_generated/models/email_source_rejection_response.py +++ b/seclai/_generated/models/email_source_rejection_response.py @@ -28,9 +28,9 @@ class EmailSourceRejectionResponse: created_at (str): When the mail was refused. id (str): Unique identifier of the refusal. reason (str): Why it was refused: sender_not_allowed, unauthenticated_sender, unreadable_from, sender_blocked, - spam, virus, unsafe_content, rate_limited, account_not_chargeable or empty_message; or, for a message the source - received before, what became of the earlier one: repeat_stored, repeat_held, repeat_deleted or - repeat_in_progress. + spam, virus, unsafe_content, rate_limited, account_not_chargeable, spend_limit_reached or empty_message; or, for + a message the source received before, what became of the earlier one: repeat_stored, repeat_held, repeat_deleted + or repeat_in_progress. recipient (str): The source address it was sent to. sender (str): The envelope sender. For bulk mail this is the delivery provider's bounce address, not the From address. diff --git a/seclai/_generated/models/set_accepted_attachments_request.py b/seclai/_generated/models/set_accepted_attachments_request.py index f968db2..6e69dd6 100644 --- a/seclai/_generated/models/set_accepted_attachments_request.py +++ b/seclai/_generated/models/set_accepted_attachments_request.py @@ -18,8 +18,8 @@ class SetAcceptedAttachmentsRequest: """ Attributes: accepted_attachments (list[AcceptedAttachmentSlot] | None): The input attachments the trigger accepts; ``null`` - accepts any files (one attachment named ``files``). Only ``dynamic_input`` and ``email_received`` triggers take - files. + accepts any files (one attachment named ``files``). Only ``dynamic_input``, ``email_received`` and + ``slack_command`` triggers take files. """ accepted_attachments: list[AcceptedAttachmentSlot] | None diff --git a/seclai/_generated/models/set_slack_trigger_config_api_request.py b/seclai/_generated/models/set_slack_trigger_config_api_request.py new file mode 100644 index 0000000..f44603c --- /dev/null +++ b/seclai/_generated/models/set_slack_trigger_config_api_request.py @@ -0,0 +1,435 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.slack_reply_visibility import SlackReplyVisibility +from ..models.slack_trigger_activation import SlackTriggerActivation +from ..models.slack_trigger_scope import SlackTriggerScope +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.set_slack_trigger_config_api_request_form_type_0_item import ( + SetSlackTriggerConfigApiRequestFormType0Item, + ) + + +T = TypeVar("T", bound="SetSlackTriggerConfigApiRequest") + + +@_attrs_define +class SetSlackTriggerConfigApiRequest: + """Omitted fields are left unchanged. + + Attributes: + activation (None | SlackTriggerActivation | Unset): `everywhere` in scope, or `channel_opt_in`. + allow_dms (bool | None | Unset): Runnable in the app's own DMs. + channel_ids (list[str] | None | Unset): + form (list[SetSlackTriggerConfigApiRequestFormType0Item] | None | Unset): Form fields `{key, label, type, + required, hint, choices, max_length}`. `type`: short_text, long_text, number, single_choice, multi_choice, + yes_no, date, slack_user or slack_channel. Each value reaches the run as `{{metadata.}}`. + include_invoker_email (bool | None | Unset): + input_ (None | str | Unset): The trigger's input template. Each `{{metadata.}}` in it must be a form field + key or a platform key; it is checked together with `form`. + max_turns (int | None | Unset): + mcp_client_id (None | Unset | UUID): The account's connected Slack (Bot) MCP client. + notify_failure_after_answer (bool | None | Unset): + scope (None | SlackTriggerScope | Unset): `selected_channels` (see `channel_ids`) or `bot_channels`. + start_without_form (bool | None | Unset): + turns_anyone (bool | None | Unset): + turns_enabled (bool | None | Unset): + visibility (None | SlackReplyVisibility | Unset): `channel`, or `private` (replies in the person's DM). + """ + + activation: None | SlackTriggerActivation | Unset = UNSET + allow_dms: bool | None | Unset = UNSET + channel_ids: list[str] | None | Unset = UNSET + form: list[SetSlackTriggerConfigApiRequestFormType0Item] | None | Unset = UNSET + include_invoker_email: bool | None | Unset = UNSET + input_: None | str | Unset = UNSET + max_turns: int | None | Unset = UNSET + mcp_client_id: None | Unset | UUID = UNSET + notify_failure_after_answer: bool | None | Unset = UNSET + scope: None | SlackTriggerScope | Unset = UNSET + start_without_form: bool | None | Unset = UNSET + turns_anyone: bool | None | Unset = UNSET + turns_enabled: bool | None | Unset = UNSET + visibility: None | SlackReplyVisibility | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + activation: None | str | Unset + if isinstance(self.activation, Unset): + activation = UNSET + elif isinstance(self.activation, SlackTriggerActivation): + activation = self.activation.value + else: + activation = self.activation + + allow_dms: bool | None | Unset + if isinstance(self.allow_dms, Unset): + allow_dms = UNSET + else: + allow_dms = self.allow_dms + + channel_ids: list[str] | None | Unset + if isinstance(self.channel_ids, Unset): + channel_ids = UNSET + elif isinstance(self.channel_ids, list): + channel_ids = self.channel_ids + + else: + channel_ids = self.channel_ids + + form: list[dict[str, Any]] | None | Unset + if isinstance(self.form, Unset): + form = UNSET + elif isinstance(self.form, list): + form = [] + for form_type_0_item_data in self.form: + form_type_0_item = form_type_0_item_data.to_dict() + form.append(form_type_0_item) + + else: + form = self.form + + include_invoker_email: bool | None | Unset + if isinstance(self.include_invoker_email, Unset): + include_invoker_email = UNSET + else: + include_invoker_email = self.include_invoker_email + + input_: None | str | Unset + if isinstance(self.input_, Unset): + input_ = UNSET + else: + input_ = self.input_ + + max_turns: int | None | Unset + if isinstance(self.max_turns, Unset): + max_turns = UNSET + else: + max_turns = self.max_turns + + mcp_client_id: None | str | Unset + if isinstance(self.mcp_client_id, Unset): + mcp_client_id = UNSET + elif isinstance(self.mcp_client_id, UUID): + mcp_client_id = str(self.mcp_client_id) + else: + mcp_client_id = self.mcp_client_id + + notify_failure_after_answer: bool | None | Unset + if isinstance(self.notify_failure_after_answer, Unset): + notify_failure_after_answer = UNSET + else: + notify_failure_after_answer = self.notify_failure_after_answer + + scope: None | str | Unset + if isinstance(self.scope, Unset): + scope = UNSET + elif isinstance(self.scope, SlackTriggerScope): + scope = self.scope.value + else: + scope = self.scope + + start_without_form: bool | None | Unset + if isinstance(self.start_without_form, Unset): + start_without_form = UNSET + else: + start_without_form = self.start_without_form + + turns_anyone: bool | None | Unset + if isinstance(self.turns_anyone, Unset): + turns_anyone = UNSET + else: + turns_anyone = self.turns_anyone + + turns_enabled: bool | None | Unset + if isinstance(self.turns_enabled, Unset): + turns_enabled = UNSET + else: + turns_enabled = self.turns_enabled + + visibility: None | str | Unset + if isinstance(self.visibility, Unset): + visibility = UNSET + elif isinstance(self.visibility, SlackReplyVisibility): + visibility = self.visibility.value + else: + visibility = self.visibility + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if activation is not UNSET: + field_dict["activation"] = activation + if allow_dms is not UNSET: + field_dict["allow_dms"] = allow_dms + if channel_ids is not UNSET: + field_dict["channel_ids"] = channel_ids + if form is not UNSET: + field_dict["form"] = form + if include_invoker_email is not UNSET: + field_dict["include_invoker_email"] = include_invoker_email + if input_ is not UNSET: + field_dict["input"] = input_ + if max_turns is not UNSET: + field_dict["max_turns"] = max_turns + if mcp_client_id is not UNSET: + field_dict["mcp_client_id"] = mcp_client_id + if notify_failure_after_answer is not UNSET: + field_dict["notify_failure_after_answer"] = notify_failure_after_answer + if scope is not UNSET: + field_dict["scope"] = scope + if start_without_form is not UNSET: + field_dict["start_without_form"] = start_without_form + if turns_anyone is not UNSET: + field_dict["turns_anyone"] = turns_anyone + if turns_enabled is not UNSET: + field_dict["turns_enabled"] = turns_enabled + if visibility is not UNSET: + field_dict["visibility"] = visibility + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.set_slack_trigger_config_api_request_form_type_0_item import ( + SetSlackTriggerConfigApiRequestFormType0Item, + ) + + d = dict(src_dict) + + def _parse_activation(data: object) -> None | SlackTriggerActivation | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + activation_type_0 = SlackTriggerActivation(data) + + return activation_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | SlackTriggerActivation | Unset, data) + + activation = _parse_activation(d.pop("activation", UNSET)) + + def _parse_allow_dms(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + allow_dms = _parse_allow_dms(d.pop("allow_dms", UNSET)) + + def _parse_channel_ids(data: object) -> list[str] | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, list): + raise TypeError() + channel_ids_type_0 = cast(list[str], data) + + return channel_ids_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(list[str] | None | Unset, data) + + channel_ids = _parse_channel_ids(d.pop("channel_ids", UNSET)) + + def _parse_form( + data: object, + ) -> list[SetSlackTriggerConfigApiRequestFormType0Item] | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, list): + raise TypeError() + form_type_0 = [] + _form_type_0 = data + for form_type_0_item_data in _form_type_0: + form_type_0_item = ( + SetSlackTriggerConfigApiRequestFormType0Item.from_dict( + form_type_0_item_data + ) + ) + + form_type_0.append(form_type_0_item) + + return form_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast( + list[SetSlackTriggerConfigApiRequestFormType0Item] | None | Unset, data + ) + + form = _parse_form(d.pop("form", UNSET)) + + def _parse_include_invoker_email(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + include_invoker_email = _parse_include_invoker_email( + d.pop("include_invoker_email", UNSET) + ) + + def _parse_input_(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + input_ = _parse_input_(d.pop("input", UNSET)) + + def _parse_max_turns(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_turns = _parse_max_turns(d.pop("max_turns", UNSET)) + + def _parse_mcp_client_id(data: object) -> None | Unset | UUID: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + mcp_client_id_type_0 = UUID(data) + + return mcp_client_id_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | Unset | UUID, data) + + mcp_client_id = _parse_mcp_client_id(d.pop("mcp_client_id", UNSET)) + + def _parse_notify_failure_after_answer(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + notify_failure_after_answer = _parse_notify_failure_after_answer( + d.pop("notify_failure_after_answer", UNSET) + ) + + def _parse_scope(data: object) -> None | SlackTriggerScope | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + scope_type_0 = SlackTriggerScope(data) + + return scope_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | SlackTriggerScope | Unset, data) + + scope = _parse_scope(d.pop("scope", UNSET)) + + def _parse_start_without_form(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + start_without_form = _parse_start_without_form( + d.pop("start_without_form", UNSET) + ) + + def _parse_turns_anyone(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + turns_anyone = _parse_turns_anyone(d.pop("turns_anyone", UNSET)) + + def _parse_turns_enabled(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + turns_enabled = _parse_turns_enabled(d.pop("turns_enabled", UNSET)) + + def _parse_visibility(data: object) -> None | SlackReplyVisibility | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + visibility_type_0 = SlackReplyVisibility(data) + + return visibility_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | SlackReplyVisibility | Unset, data) + + visibility = _parse_visibility(d.pop("visibility", UNSET)) + + set_slack_trigger_config_api_request = cls( + activation=activation, + allow_dms=allow_dms, + channel_ids=channel_ids, + form=form, + include_invoker_email=include_invoker_email, + input_=input_, + max_turns=max_turns, + mcp_client_id=mcp_client_id, + notify_failure_after_answer=notify_failure_after_answer, + scope=scope, + start_without_form=start_without_form, + turns_anyone=turns_anyone, + turns_enabled=turns_enabled, + visibility=visibility, + ) + + set_slack_trigger_config_api_request.additional_properties = d + return set_slack_trigger_config_api_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/set_slack_trigger_config_api_request_form_type_0_item.py b/seclai/_generated/models/set_slack_trigger_config_api_request_form_type_0_item.py new file mode 100644 index 0000000..13aa303 --- /dev/null +++ b/seclai/_generated/models/set_slack_trigger_config_api_request_form_type_0_item.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetSlackTriggerConfigApiRequestFormType0Item") + + +@_attrs_define +class SetSlackTriggerConfigApiRequestFormType0Item: + """ """ + + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + set_slack_trigger_config_api_request_form_type_0_item = cls() + + set_slack_trigger_config_api_request_form_type_0_item.additional_properties = d + return set_slack_trigger_config_api_request_form_type_0_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/slack_reply_visibility.py b/seclai/_generated/models/slack_reply_visibility.py new file mode 100644 index 0000000..c021ca8 --- /dev/null +++ b/seclai/_generated/models/slack_reply_visibility.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class SlackReplyVisibility(str, Enum): + CHANNEL = "channel" + PRIVATE = "private" + + def __str__(self) -> str: + return str(self.value) diff --git a/seclai/_generated/models/slack_trigger_activation.py b/seclai/_generated/models/slack_trigger_activation.py new file mode 100644 index 0000000..2990753 --- /dev/null +++ b/seclai/_generated/models/slack_trigger_activation.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class SlackTriggerActivation(str, Enum): + CHANNEL_OPT_IN = "channel_opt_in" + EVERYWHERE = "everywhere" + + def __str__(self) -> str: + return str(self.value) diff --git a/seclai/_generated/models/slack_trigger_config_api_response.py b/seclai/_generated/models/slack_trigger_config_api_response.py new file mode 100644 index 0000000..20e5704 --- /dev/null +++ b/seclai/_generated/models/slack_trigger_config_api_response.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.slack_trigger_config_api_response_form_item import ( + SlackTriggerConfigApiResponseFormItem, + ) + + +T = TypeVar("T", bound="SlackTriggerConfigApiResponse") + + +@_attrs_define +class SlackTriggerConfigApiResponse: + """ + Attributes: + activation (str): + agent_id (UUID): + allow_dms (bool): + channel_ids (list[str]): + form (list[SlackTriggerConfigApiResponseFormItem]): + include_invoker_email (bool): + max_turns (int | None): + mcp_client_id (None | UUID): + missing_scopes (list[str]): Scopes the Slack connection lacks for optional features. + notify_failure_after_answer (bool): + scope (str): + slack_team_id (None | str): + start_without_form (bool): + trigger_id (UUID): + turns_anyone (bool): + turns_enabled (bool): + visibility (str): + """ + + activation: str + agent_id: UUID + allow_dms: bool + channel_ids: list[str] + form: list[SlackTriggerConfigApiResponseFormItem] + include_invoker_email: bool + max_turns: int | None + mcp_client_id: None | UUID + missing_scopes: list[str] + notify_failure_after_answer: bool + scope: str + slack_team_id: None | str + start_without_form: bool + trigger_id: UUID + turns_anyone: bool + turns_enabled: bool + visibility: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + activation = self.activation + + agent_id = str(self.agent_id) + + allow_dms = self.allow_dms + + channel_ids = self.channel_ids + + form = [] + for form_item_data in self.form: + form_item = form_item_data.to_dict() + form.append(form_item) + + include_invoker_email = self.include_invoker_email + + max_turns: int | None + max_turns = self.max_turns + + mcp_client_id: None | str + if isinstance(self.mcp_client_id, UUID): + mcp_client_id = str(self.mcp_client_id) + else: + mcp_client_id = self.mcp_client_id + + missing_scopes = self.missing_scopes + + notify_failure_after_answer = self.notify_failure_after_answer + + scope = self.scope + + slack_team_id: None | str + slack_team_id = self.slack_team_id + + start_without_form = self.start_without_form + + trigger_id = str(self.trigger_id) + + turns_anyone = self.turns_anyone + + turns_enabled = self.turns_enabled + + visibility = self.visibility + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "activation": activation, + "agent_id": agent_id, + "allow_dms": allow_dms, + "channel_ids": channel_ids, + "form": form, + "include_invoker_email": include_invoker_email, + "max_turns": max_turns, + "mcp_client_id": mcp_client_id, + "missing_scopes": missing_scopes, + "notify_failure_after_answer": notify_failure_after_answer, + "scope": scope, + "slack_team_id": slack_team_id, + "start_without_form": start_without_form, + "trigger_id": trigger_id, + "turns_anyone": turns_anyone, + "turns_enabled": turns_enabled, + "visibility": visibility, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.slack_trigger_config_api_response_form_item import ( + SlackTriggerConfigApiResponseFormItem, + ) + + d = dict(src_dict) + activation = d.pop("activation") + + agent_id = UUID(d.pop("agent_id")) + + allow_dms = d.pop("allow_dms") + + channel_ids = cast(list[str], d.pop("channel_ids")) + + form = [] + _form = d.pop("form") + for form_item_data in _form: + form_item = SlackTriggerConfigApiResponseFormItem.from_dict(form_item_data) + + form.append(form_item) + + include_invoker_email = d.pop("include_invoker_email") + + def _parse_max_turns(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + max_turns = _parse_max_turns(d.pop("max_turns")) + + def _parse_mcp_client_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + mcp_client_id_type_0 = UUID(data) + + return mcp_client_id_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + mcp_client_id = _parse_mcp_client_id(d.pop("mcp_client_id")) + + missing_scopes = cast(list[str], d.pop("missing_scopes")) + + notify_failure_after_answer = d.pop("notify_failure_after_answer") + + scope = d.pop("scope") + + def _parse_slack_team_id(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + slack_team_id = _parse_slack_team_id(d.pop("slack_team_id")) + + start_without_form = d.pop("start_without_form") + + trigger_id = UUID(d.pop("trigger_id")) + + turns_anyone = d.pop("turns_anyone") + + turns_enabled = d.pop("turns_enabled") + + visibility = d.pop("visibility") + + slack_trigger_config_api_response = cls( + activation=activation, + agent_id=agent_id, + allow_dms=allow_dms, + channel_ids=channel_ids, + form=form, + include_invoker_email=include_invoker_email, + max_turns=max_turns, + mcp_client_id=mcp_client_id, + missing_scopes=missing_scopes, + notify_failure_after_answer=notify_failure_after_answer, + scope=scope, + slack_team_id=slack_team_id, + start_without_form=start_without_form, + trigger_id=trigger_id, + turns_anyone=turns_anyone, + turns_enabled=turns_enabled, + visibility=visibility, + ) + + slack_trigger_config_api_response.additional_properties = d + return slack_trigger_config_api_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/slack_trigger_config_api_response_form_item.py b/seclai/_generated/models/slack_trigger_config_api_response_form_item.py new file mode 100644 index 0000000..3234dd4 --- /dev/null +++ b/seclai/_generated/models/slack_trigger_config_api_response_form_item.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SlackTriggerConfigApiResponseFormItem") + + +@_attrs_define +class SlackTriggerConfigApiResponseFormItem: + """ """ + + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + slack_trigger_config_api_response_form_item = cls() + + slack_trigger_config_api_response_form_item.additional_properties = d + return slack_trigger_config_api_response_form_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/seclai/_generated/models/slack_trigger_scope.py b/seclai/_generated/models/slack_trigger_scope.py new file mode 100644 index 0000000..bc30b35 --- /dev/null +++ b/seclai/_generated/models/slack_trigger_scope.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class SlackTriggerScope(str, Enum): + BOT_CHANNELS = "bot_channels" + SELECTED_CHANNELS = "selected_channels" + + def __str__(self) -> str: + return str(self.value) diff --git a/seclai/_generated/models/source_content_status_response.py b/seclai/_generated/models/source_content_status_response.py index 891a3f8..b85e6b5 100644 --- a/seclai/_generated/models/source_content_status_response.py +++ b/seclai/_generated/models/source_content_status_response.py @@ -29,9 +29,8 @@ class SourceContentStatusResponse: mime_type (None | str): MIME type the item was ingested as, when known. published_at (None | str): Publication timestamp of the item, when known. pulled_at (str): Timestamp when the item was uploaded or pulled. - source_connection_content_version_id (None | str): ID to pass to `GET /contents/{id}`. `null` until the item has - finished indexing — an item that is still processing, or that failed, has no retrievable content and keeps this - `null`. + source_connection_content_version_id (None | str): ID to pass to `GET /contents/{id}`. `null` while the item has + no retrievable content. title (None | str): Title of the content item. awaiting_reindex (bool | Unset): True when the item is linked and reports completed but its content is not yet embedded under the index the source connection currently uses, because it still sits under the index that @@ -56,8 +55,11 @@ class SourceContentStatusResponse: extraction was not capped, or when it stopped because the container could not be read rather than because a bound fired. held_for_review (bool | Unset): An ENFORCE governance policy blocked this item at import. It is held for review - and is not retrievable: resolving its blocking evaluations releases it into the source, and it is purged when - the hold window ends. Default: False. + and is not retrievable: resolving its blocking evaluations releases it into the source; left unresolved, it is + purged when the hold window ends. Default: False. + release_waiting_reason (None | str | Unset): Set on a held item review approved whose release was refused: why + it waits, the account being unable to pay for it or the source's spend limit having no room for it. Its release + is retried; null until one is refused. """ content_status: str @@ -78,6 +80,7 @@ class SourceContentStatusResponse: extracted_media_count: int | None | Unset = UNSET extracted_media_limit: int | None | Unset = UNSET held_for_review: bool | Unset = False + release_waiting_reason: None | str | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -134,6 +137,12 @@ def to_dict(self) -> dict[str, Any]: held_for_review = self.held_for_review + release_waiting_reason: None | str | Unset + if isinstance(self.release_waiting_reason, Unset): + release_waiting_reason = UNSET + else: + release_waiting_reason = self.release_waiting_reason + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -163,6 +172,8 @@ def to_dict(self) -> dict[str, Any]: field_dict["extracted_media_limit"] = extracted_media_limit if held_for_review is not UNSET: field_dict["held_for_review"] = held_for_review + if release_waiting_reason is not UNSET: + field_dict["release_waiting_reason"] = release_waiting_reason return field_dict @@ -272,6 +283,17 @@ def _parse_extracted_media_limit(data: object) -> int | None | Unset: held_for_review = d.pop("held_for_review", UNSET) + def _parse_release_waiting_reason(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + release_waiting_reason = _parse_release_waiting_reason( + d.pop("release_waiting_reason", UNSET) + ) + source_content_status_response = cls( content_status=content_status, content_token_count=content_token_count, @@ -291,6 +313,7 @@ def _parse_extracted_media_limit(data: object) -> int | None | Unset: extracted_media_count=extracted_media_count, extracted_media_limit=extracted_media_limit, held_for_review=held_for_review, + release_waiting_reason=release_waiting_reason, ) source_content_status_response.additional_properties = d diff --git a/seclai/_generated/models/source_response.py b/seclai/_generated/models/source_response.py index adb4146..7b6fbcd 100644 --- a/seclai/_generated/models/source_response.py +++ b/seclai/_generated/models/source_response.py @@ -8,6 +8,8 @@ from attrs import field as _attrs_field from ..models.source_index_mode import SourceIndexMode +from ..models.spend_cap_action import SpendCapAction +from ..models.spend_cap_delete_order import SpendCapDeleteOrder from ..types import UNSET, Unset T = TypeVar("T", bound="SourceResponse") @@ -67,10 +69,16 @@ class SourceResponse: has_historical_data (bool | Unset): Indicates if the source connection has historical data. Default: False. index_mode (None | SourceIndexMode | Unset): Index mode for custom_index sources: fast_and_cheap, balanced, slow_and_thorough, or custom. + max_credits_per_period (float | None | Unset): The source's spend limit: credits it may commit per billing + period. Null when it has none. media_types (list[str] | Unset): Media kinds in a web page's main content that are attached to the page's item and indexed (subset of ['images', 'video']). On a website or RSS source 'images' also covers the images inside PDF, DOCX, PPTX and XLSX files. readonly (bool | Unset): Indicates if the source connection is read-only. Default: False. + spend_cap_action (SpendCapAction | Unset): + spend_cap_delete_order (SpendCapDeleteOrder | Unset): Which entries a DELETE cap removes first. + spend_cap_reached (bool | Unset): True while the spend limit refuses uploads and email to this source. Default: + False. system_managed (bool | Unset): Indicates if this source is automatically managed by the system (e.g., agent traces). Default: False. """ @@ -112,8 +120,12 @@ class SourceResponse: free_retention_days: int | None | Unset = UNSET has_historical_data: bool | Unset = False index_mode: None | SourceIndexMode | Unset = UNSET + max_credits_per_period: float | None | Unset = UNSET media_types: list[str] | Unset = UNSET readonly: bool | Unset = False + spend_cap_action: SpendCapAction | Unset = UNSET + spend_cap_delete_order: SpendCapDeleteOrder | Unset = UNSET + spend_cap_reached: bool | Unset = False system_managed: bool | Unset = False additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) @@ -282,12 +294,28 @@ def to_dict(self) -> dict[str, Any]: else: index_mode = self.index_mode + max_credits_per_period: float | None | Unset + if isinstance(self.max_credits_per_period, Unset): + max_credits_per_period = UNSET + else: + max_credits_per_period = self.max_credits_per_period + media_types: list[str] | Unset = UNSET if not isinstance(self.media_types, Unset): media_types = self.media_types readonly = self.readonly + spend_cap_action: str | Unset = UNSET + if not isinstance(self.spend_cap_action, Unset): + spend_cap_action = self.spend_cap_action.value + + spend_cap_delete_order: str | Unset = UNSET + if not isinstance(self.spend_cap_delete_order, Unset): + spend_cap_delete_order = self.spend_cap_delete_order.value + + spend_cap_reached = self.spend_cap_reached + system_managed = self.system_managed field_dict: dict[str, Any] = {} @@ -356,10 +384,18 @@ def to_dict(self) -> dict[str, Any]: field_dict["has_historical_data"] = has_historical_data if index_mode is not UNSET: field_dict["index_mode"] = index_mode + if max_credits_per_period is not UNSET: + field_dict["max_credits_per_period"] = max_credits_per_period if media_types is not UNSET: field_dict["media_types"] = media_types if readonly is not UNSET: field_dict["readonly"] = readonly + if spend_cap_action is not UNSET: + field_dict["spend_cap_action"] = spend_cap_action + if spend_cap_delete_order is not UNSET: + field_dict["spend_cap_delete_order"] = spend_cap_delete_order + if spend_cap_reached is not UNSET: + field_dict["spend_cap_reached"] = spend_cap_reached if system_managed is not UNSET: field_dict["system_managed"] = system_managed @@ -648,10 +684,37 @@ def _parse_index_mode(data: object) -> None | SourceIndexMode | Unset: index_mode = _parse_index_mode(d.pop("index_mode", UNSET)) + def _parse_max_credits_per_period(data: object) -> float | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(float | None | Unset, data) + + max_credits_per_period = _parse_max_credits_per_period( + d.pop("max_credits_per_period", UNSET) + ) + media_types = cast(list[str], d.pop("media_types", UNSET)) readonly = d.pop("readonly", UNSET) + _spend_cap_action = d.pop("spend_cap_action", UNSET) + spend_cap_action: SpendCapAction | Unset + if isinstance(_spend_cap_action, Unset): + spend_cap_action = UNSET + else: + spend_cap_action = SpendCapAction(_spend_cap_action) + + _spend_cap_delete_order = d.pop("spend_cap_delete_order", UNSET) + spend_cap_delete_order: SpendCapDeleteOrder | Unset + if isinstance(_spend_cap_delete_order, Unset): + spend_cap_delete_order = UNSET + else: + spend_cap_delete_order = SpendCapDeleteOrder(_spend_cap_delete_order) + + spend_cap_reached = d.pop("spend_cap_reached", UNSET) + system_managed = d.pop("system_managed", UNSET) source_response = cls( @@ -692,8 +755,12 @@ def _parse_index_mode(data: object) -> None | SourceIndexMode | Unset: free_retention_days=free_retention_days, has_historical_data=has_historical_data, index_mode=index_mode, + max_credits_per_period=max_credits_per_period, media_types=media_types, readonly=readonly, + spend_cap_action=spend_cap_action, + spend_cap_delete_order=spend_cap_delete_order, + spend_cap_reached=spend_cap_reached, system_managed=system_managed, ) diff --git a/seclai/_generated/models/spend_cap_action.py b/seclai/_generated/models/spend_cap_action.py new file mode 100644 index 0000000..1a7dda7 --- /dev/null +++ b/seclai/_generated/models/spend_cap_action.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class SpendCapAction(str, Enum): + DELETE = "delete" + STOP = "stop" + + def __str__(self) -> str: + return str(self.value) diff --git a/seclai/_generated/models/spend_cap_delete_order.py b/seclai/_generated/models/spend_cap_delete_order.py new file mode 100644 index 0000000..791bcdf --- /dev/null +++ b/seclai/_generated/models/spend_cap_delete_order.py @@ -0,0 +1,10 @@ +from enum import Enum + + +class SpendCapDeleteOrder(str, Enum): + LARGEST_FIRST = "largest_first" + OLDEST_ADDED = "oldest_added" + OLDEST_PUBLISHED = "oldest_published" + + def __str__(self) -> str: + return str(self.value) diff --git a/seclai/_generated/models/update_agent_request.py b/seclai/_generated/models/update_agent_request.py index ae34ee8..573a23c 100644 --- a/seclai/_generated/models/update_agent_request.py +++ b/seclai/_generated/models/update_agent_request.py @@ -33,13 +33,22 @@ class UpdateAgentRequest: are taken from the payload, and the agent's workflow is replaced from `agent.definition`. The previous version is preserved in history. Validation errors include line/column references against a canonical pretty-printed echo of the supplied payload. + apply_import_run_limits (bool | Unset): With `agent_definition`, also replace the agent's run limits with the + payload's (a null there removes a limit). Off by default: the agent keeps its limits. Default: False. default_evaluation_tier (None | str | Unset): Default evaluation tier: 'fast', 'balanced', or 'thorough'. description (None | str | Unset): New description for the agent. entity_remap (None | Unset | UpdateAgentRequestEntityRemapType0): Optional UUID-substitution map applied to the imported workflow before save (same shape as on POST /agents). evaluation_mode (None | str | Unset): Evaluation mode: 'output_expectation', 'eval_and_retry', or 'sample_and_flag'. + max_credits_per_period (float | None | Unset): Credit limit per billing period of the paying account: once + reached, runs stop at their next step and new runs are refused. + max_credits_per_run (float | None | Unset): Credit limit per run: a run that reaches it is stopped before its + next step. max_retries (int | None | Unset): Max retries for eval_and_retry mode (1-10). + max_runs_per_day (int | None | Unset): Runs per day; at most the plan's run quota. + max_runs_per_hour (int | None | Unset): Runs per hour; at most the plan's run quota. + max_runs_total (int | None | Unset): Runs in total; once reached, new runs are refused. name (None | str | Unset): New name for the agent. prompt_model_auto_rollback_enabled (bool | None | Unset): Enable or disable automatic rollback for upgraded models. @@ -52,6 +61,15 @@ class UpdateAgentRequest: sample_and_flag mode. Format: {combinator: 'and'|'or', rules: [...]}. set_default_evaluation_tier (bool | Unset): When true and default_evaluation_tier is omitted, clears the tier to null (system default). Default: False. + set_max_credits_per_period (bool | Unset): When true and max_credits_per_period is omitted, removes the limit. + Default: False. + set_max_credits_per_run (bool | Unset): When true and max_credits_per_run is omitted, removes the limit. + Default: False. + set_max_runs_per_day (bool | Unset): When true and max_runs_per_day is omitted, removes the limit. Default: + False. + set_max_runs_per_hour (bool | Unset): When true and max_runs_per_hour is omitted, removes the limit. Default: + False. + set_max_runs_total (bool | Unset): When true and max_runs_total is omitted, removes the limit. Default: False. set_prompt_model_auto_rollback_triggers (bool | Unset): When true and prompt_model_auto_rollback_triggers is omitted, clears the list to null (revert to system defaults). Default: False. set_sampling_config (bool | Unset): When true and sampling_config is omitted, clears the config to null. @@ -59,11 +77,17 @@ class UpdateAgentRequest: """ agent_definition: None | Unset | UpdateAgentRequestAgentDefinitionType0 = UNSET + apply_import_run_limits: bool | Unset = False default_evaluation_tier: None | str | Unset = UNSET description: None | str | Unset = UNSET entity_remap: None | Unset | UpdateAgentRequestEntityRemapType0 = UNSET evaluation_mode: None | str | Unset = UNSET + max_credits_per_period: float | None | Unset = UNSET + max_credits_per_run: float | None | Unset = UNSET max_retries: int | None | Unset = UNSET + max_runs_per_day: int | None | Unset = UNSET + max_runs_per_hour: int | None | Unset = UNSET + max_runs_total: int | None | Unset = UNSET name: None | str | Unset = UNSET prompt_model_auto_rollback_enabled: bool | None | Unset = UNSET prompt_model_auto_rollback_triggers: list[str] | None | Unset = UNSET @@ -73,6 +97,11 @@ class UpdateAgentRequest: retry_on_failure: bool | None | Unset = UNSET sampling_config: None | Unset | UpdateAgentRequestSamplingConfigType0 = UNSET set_default_evaluation_tier: bool | Unset = False + set_max_credits_per_period: bool | Unset = False + set_max_credits_per_run: bool | Unset = False + set_max_runs_per_day: bool | Unset = False + set_max_runs_per_hour: bool | Unset = False + set_max_runs_total: bool | Unset = False set_prompt_model_auto_rollback_triggers: bool | Unset = False set_sampling_config: bool | Unset = False additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) @@ -96,6 +125,8 @@ def to_dict(self) -> dict[str, Any]: else: agent_definition = self.agent_definition + apply_import_run_limits = self.apply_import_run_limits + default_evaluation_tier: None | str | Unset if isinstance(self.default_evaluation_tier, Unset): default_evaluation_tier = UNSET @@ -122,12 +153,42 @@ def to_dict(self) -> dict[str, Any]: else: evaluation_mode = self.evaluation_mode + max_credits_per_period: float | None | Unset + if isinstance(self.max_credits_per_period, Unset): + max_credits_per_period = UNSET + else: + max_credits_per_period = self.max_credits_per_period + + max_credits_per_run: float | None | Unset + if isinstance(self.max_credits_per_run, Unset): + max_credits_per_run = UNSET + else: + max_credits_per_run = self.max_credits_per_run + max_retries: int | None | Unset if isinstance(self.max_retries, Unset): max_retries = UNSET else: max_retries = self.max_retries + max_runs_per_day: int | None | Unset + if isinstance(self.max_runs_per_day, Unset): + max_runs_per_day = UNSET + else: + max_runs_per_day = self.max_runs_per_day + + max_runs_per_hour: int | None | Unset + if isinstance(self.max_runs_per_hour, Unset): + max_runs_per_hour = UNSET + else: + max_runs_per_hour = self.max_runs_per_hour + + max_runs_total: int | None | Unset + if isinstance(self.max_runs_total, Unset): + max_runs_total = UNSET + else: + max_runs_total = self.max_runs_total + name: None | str | Unset if isinstance(self.name, Unset): name = UNSET @@ -181,6 +242,16 @@ def to_dict(self) -> dict[str, Any]: set_default_evaluation_tier = self.set_default_evaluation_tier + set_max_credits_per_period = self.set_max_credits_per_period + + set_max_credits_per_run = self.set_max_credits_per_run + + set_max_runs_per_day = self.set_max_runs_per_day + + set_max_runs_per_hour = self.set_max_runs_per_hour + + set_max_runs_total = self.set_max_runs_total + set_prompt_model_auto_rollback_triggers = ( self.set_prompt_model_auto_rollback_triggers ) @@ -192,6 +263,8 @@ def to_dict(self) -> dict[str, Any]: field_dict.update({}) if agent_definition is not UNSET: field_dict["agent_definition"] = agent_definition + if apply_import_run_limits is not UNSET: + field_dict["apply_import_run_limits"] = apply_import_run_limits if default_evaluation_tier is not UNSET: field_dict["default_evaluation_tier"] = default_evaluation_tier if description is not UNSET: @@ -200,8 +273,18 @@ def to_dict(self) -> dict[str, Any]: field_dict["entity_remap"] = entity_remap if evaluation_mode is not UNSET: field_dict["evaluation_mode"] = evaluation_mode + if max_credits_per_period is not UNSET: + field_dict["max_credits_per_period"] = max_credits_per_period + if max_credits_per_run is not UNSET: + field_dict["max_credits_per_run"] = max_credits_per_run if max_retries is not UNSET: field_dict["max_retries"] = max_retries + if max_runs_per_day is not UNSET: + field_dict["max_runs_per_day"] = max_runs_per_day + if max_runs_per_hour is not UNSET: + field_dict["max_runs_per_hour"] = max_runs_per_hour + if max_runs_total is not UNSET: + field_dict["max_runs_total"] = max_runs_total if name is not UNSET: field_dict["name"] = name if prompt_model_auto_rollback_enabled is not UNSET: @@ -222,6 +305,16 @@ def to_dict(self) -> dict[str, Any]: field_dict["sampling_config"] = sampling_config if set_default_evaluation_tier is not UNSET: field_dict["set_default_evaluation_tier"] = set_default_evaluation_tier + if set_max_credits_per_period is not UNSET: + field_dict["set_max_credits_per_period"] = set_max_credits_per_period + if set_max_credits_per_run is not UNSET: + field_dict["set_max_credits_per_run"] = set_max_credits_per_run + if set_max_runs_per_day is not UNSET: + field_dict["set_max_runs_per_day"] = set_max_runs_per_day + if set_max_runs_per_hour is not UNSET: + field_dict["set_max_runs_per_hour"] = set_max_runs_per_hour + if set_max_runs_total is not UNSET: + field_dict["set_max_runs_total"] = set_max_runs_total if set_prompt_model_auto_rollback_triggers is not UNSET: field_dict["set_prompt_model_auto_rollback_triggers"] = ( set_prompt_model_auto_rollback_triggers @@ -266,6 +359,8 @@ def _parse_agent_definition( agent_definition = _parse_agent_definition(d.pop("agent_definition", UNSET)) + apply_import_run_limits = d.pop("apply_import_run_limits", UNSET) + def _parse_default_evaluation_tier(data: object) -> None | str | Unset: if data is None: return data @@ -314,6 +409,28 @@ def _parse_evaluation_mode(data: object) -> None | str | Unset: evaluation_mode = _parse_evaluation_mode(d.pop("evaluation_mode", UNSET)) + def _parse_max_credits_per_period(data: object) -> float | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(float | None | Unset, data) + + max_credits_per_period = _parse_max_credits_per_period( + d.pop("max_credits_per_period", UNSET) + ) + + def _parse_max_credits_per_run(data: object) -> float | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(float | None | Unset, data) + + max_credits_per_run = _parse_max_credits_per_run( + d.pop("max_credits_per_run", UNSET) + ) + def _parse_max_retries(data: object) -> int | None | Unset: if data is None: return data @@ -323,6 +440,33 @@ def _parse_max_retries(data: object) -> int | None | Unset: max_retries = _parse_max_retries(d.pop("max_retries", UNSET)) + def _parse_max_runs_per_day(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_runs_per_day = _parse_max_runs_per_day(d.pop("max_runs_per_day", UNSET)) + + def _parse_max_runs_per_hour(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_runs_per_hour = _parse_max_runs_per_hour(d.pop("max_runs_per_hour", UNSET)) + + def _parse_max_runs_total(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + max_runs_total = _parse_max_runs_total(d.pop("max_runs_total", UNSET)) + def _parse_name(data: object) -> None | str | Unset: if data is None: return data @@ -423,6 +567,16 @@ def _parse_sampling_config( set_default_evaluation_tier = d.pop("set_default_evaluation_tier", UNSET) + set_max_credits_per_period = d.pop("set_max_credits_per_period", UNSET) + + set_max_credits_per_run = d.pop("set_max_credits_per_run", UNSET) + + set_max_runs_per_day = d.pop("set_max_runs_per_day", UNSET) + + set_max_runs_per_hour = d.pop("set_max_runs_per_hour", UNSET) + + set_max_runs_total = d.pop("set_max_runs_total", UNSET) + set_prompt_model_auto_rollback_triggers = d.pop( "set_prompt_model_auto_rollback_triggers", UNSET ) @@ -431,11 +585,17 @@ def _parse_sampling_config( update_agent_request = cls( agent_definition=agent_definition, + apply_import_run_limits=apply_import_run_limits, default_evaluation_tier=default_evaluation_tier, description=description, entity_remap=entity_remap, evaluation_mode=evaluation_mode, + max_credits_per_period=max_credits_per_period, + max_credits_per_run=max_credits_per_run, max_retries=max_retries, + max_runs_per_day=max_runs_per_day, + max_runs_per_hour=max_runs_per_hour, + max_runs_total=max_runs_total, name=name, prompt_model_auto_rollback_enabled=prompt_model_auto_rollback_enabled, prompt_model_auto_rollback_triggers=prompt_model_auto_rollback_triggers, @@ -443,6 +603,11 @@ def _parse_sampling_config( retry_on_failure=retry_on_failure, sampling_config=sampling_config, set_default_evaluation_tier=set_default_evaluation_tier, + set_max_credits_per_period=set_max_credits_per_period, + set_max_credits_per_run=set_max_credits_per_run, + set_max_runs_per_day=set_max_runs_per_day, + set_max_runs_per_hour=set_max_runs_per_hour, + set_max_runs_total=set_max_runs_total, set_prompt_model_auto_rollback_triggers=set_prompt_model_auto_rollback_triggers, set_sampling_config=set_sampling_config, ) diff --git a/seclai/_generated/models/update_source_body.py b/seclai/_generated/models/update_source_body.py index 844e072..2c181a6 100644 --- a/seclai/_generated/models/update_source_body.py +++ b/seclai/_generated/models/update_source_body.py @@ -6,6 +6,8 @@ from attrs import define as _attrs_define from attrs import field as _attrs_field +from ..models.spend_cap_action import SpendCapAction +from ..models.spend_cap_delete_order import SpendCapDeleteOrder from ..types import UNSET, Unset T = TypeVar("T", bound="UpdateSourceBody") @@ -32,6 +34,9 @@ class UpdateSourceBody: feed_attachments (list[str] | None | Unset): Kinds of file listed beside a feed item's content to attach to the item and index, on an RSS source. Subset of ['enclosures', 'item_image', 'media_rss']; any other value is refused. [] attaches none. Applies to items added after it changes. Omit the field to leave it unchanged. + max_credits_per_period (float | None | Unset): Spend limit: the credits this source may commit per billing + period — what the account was charged for it this period plus the storage of what it holds until the period + ends. Send null to remove the limit; omit to leave it unchanged. media_types (list[str] | None | Unset): Media kinds in a web page's main content to attach to the page's item and index, on a website or RSS source. Subset of ['images', 'video']. From `Seclai-Version: 2026-10-13` any other value, and any kind on another source type, is refused with a 400; older versions drop an unknown value @@ -43,6 +48,11 @@ class UpdateSourceBody: retention_days (int | None | Unset): New retention period in days — content older than this is deleted permanently. Send null to clear the window: content is then kept indefinitely. Omit the field to leave it unchanged. + spend_cap_action (None | SpendCapAction | Unset): Once the limit is reached: `stop` refuses new content; + `delete` deletes entries, in `spend_cap_delete_order`, to make room, and refuses new content as `stop` does once + spend already fills the limit. Deleting does not return credits already spent. + spend_cap_delete_order (None | SpendCapDeleteOrder | Unset): Which entries `delete` removes first: + `oldest_added`, `oldest_published` or `largest_first`. """ cloud_drive_content_types: None | str | Unset = UNSET @@ -52,10 +62,13 @@ class UpdateSourceBody: document_images: bool | None | Unset = UNSET email_allowed_senders: list[str] | None | Unset = UNSET feed_attachments: list[str] | None | Unset = UNSET + max_credits_per_period: float | None | Unset = UNSET media_types: list[str] | None | Unset = UNSET name: None | str | Unset = UNSET polling: None | str | Unset = UNSET retention_days: int | None | Unset = UNSET + spend_cap_action: None | SpendCapAction | Unset = UNSET + spend_cap_delete_order: None | SpendCapDeleteOrder | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -107,6 +120,12 @@ def to_dict(self) -> dict[str, Any]: else: feed_attachments = self.feed_attachments + max_credits_per_period: float | None | Unset + if isinstance(self.max_credits_per_period, Unset): + max_credits_per_period = UNSET + else: + max_credits_per_period = self.max_credits_per_period + media_types: list[str] | None | Unset if isinstance(self.media_types, Unset): media_types = UNSET @@ -134,6 +153,22 @@ def to_dict(self) -> dict[str, Any]: else: retention_days = self.retention_days + spend_cap_action: None | str | Unset + if isinstance(self.spend_cap_action, Unset): + spend_cap_action = UNSET + elif isinstance(self.spend_cap_action, SpendCapAction): + spend_cap_action = self.spend_cap_action.value + else: + spend_cap_action = self.spend_cap_action + + spend_cap_delete_order: None | str | Unset + if isinstance(self.spend_cap_delete_order, Unset): + spend_cap_delete_order = UNSET + elif isinstance(self.spend_cap_delete_order, SpendCapDeleteOrder): + spend_cap_delete_order = self.spend_cap_delete_order.value + else: + spend_cap_delete_order = self.spend_cap_delete_order + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update({}) @@ -151,6 +186,8 @@ def to_dict(self) -> dict[str, Any]: field_dict["email_allowed_senders"] = email_allowed_senders if feed_attachments is not UNSET: field_dict["feed_attachments"] = feed_attachments + if max_credits_per_period is not UNSET: + field_dict["max_credits_per_period"] = max_credits_per_period if media_types is not UNSET: field_dict["media_types"] = media_types if name is not UNSET: @@ -159,6 +196,10 @@ def to_dict(self) -> dict[str, Any]: field_dict["polling"] = polling if retention_days is not UNSET: field_dict["retention_days"] = retention_days + if spend_cap_action is not UNSET: + field_dict["spend_cap_action"] = spend_cap_action + if spend_cap_delete_order is not UNSET: + field_dict["spend_cap_delete_order"] = spend_cap_delete_order return field_dict @@ -255,6 +296,17 @@ def _parse_feed_attachments(data: object) -> list[str] | None | Unset: feed_attachments = _parse_feed_attachments(d.pop("feed_attachments", UNSET)) + def _parse_max_credits_per_period(data: object) -> float | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(float | None | Unset, data) + + max_credits_per_period = _parse_max_credits_per_period( + d.pop("max_credits_per_period", UNSET) + ) + def _parse_media_types(data: object) -> list[str] | None | Unset: if data is None: return data @@ -299,6 +351,44 @@ def _parse_retention_days(data: object) -> int | None | Unset: retention_days = _parse_retention_days(d.pop("retention_days", UNSET)) + def _parse_spend_cap_action(data: object) -> None | SpendCapAction | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + spend_cap_action_type_0 = SpendCapAction(data) + + return spend_cap_action_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | SpendCapAction | Unset, data) + + spend_cap_action = _parse_spend_cap_action(d.pop("spend_cap_action", UNSET)) + + def _parse_spend_cap_delete_order( + data: object, + ) -> None | SpendCapDeleteOrder | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + spend_cap_delete_order_type_0 = SpendCapDeleteOrder(data) + + return spend_cap_delete_order_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | SpendCapDeleteOrder | Unset, data) + + spend_cap_delete_order = _parse_spend_cap_delete_order( + d.pop("spend_cap_delete_order", UNSET) + ) + update_source_body = cls( cloud_drive_content_types=cloud_drive_content_types, cloud_drive_folder_path=cloud_drive_folder_path, @@ -307,10 +397,13 @@ def _parse_retention_days(data: object) -> int | None | Unset: document_images=document_images, email_allowed_senders=email_allowed_senders, feed_attachments=feed_attachments, + max_credits_per_period=max_credits_per_period, media_types=media_types, name=name, polling=polling, retention_days=retention_days, + spend_cap_action=spend_cap_action, + spend_cap_delete_order=spend_cap_delete_order, ) update_source_body.additional_properties = d diff --git a/seclai/seclai.py b/seclai/seclai.py index 8688433..e2535ff 100644 --- a/seclai/seclai.py +++ b/seclai/seclai.py @@ -2251,14 +2251,55 @@ def list_agents(self, *, page: int = 1, limit: int = 50) -> dict[str, Any]: ), ) + def list_agent_examples( + self, + *, + query: str | None = None, + use_case: str | None = None, + page: int = 1, + limit: int = 20, + ) -> dict[str, Any]: + """List the agent gallery: example agents to start from. + + Pass an entry's ``key`` as ``agent_template`` to :meth:`create_agent`, + with ``resource_bindings`` for the resources it needs. + + Args: + query: Words every match must contain. + use_case: Only entries for this use case. + page: Page number (1-indexed). + limit: Items per page. + + Returns: + The page of examples under ``data`` with ``pagination``. + """ + return cast( + dict[str, Any], + self.request( + "GET", + "/agents/examples", + params=_strip_none( + {"query": query, "use_case": use_case, "page": page, "limit": limit} + ), + ), + ) + def create_agent(self, body: dict[str, Any]) -> dict[str, Any]: """Create a new agent. Args: - body: Agent creation payload (name, description, etc.). + body: Agent creation payload: ``name`` (required), ``description`` + and the other ``CreateAgentRequest`` fields. To start from a + gallery entry, pass its ``key`` from :meth:`list_agent_examples` + as ``agent_template``, with ``resource_bindings`` + (``{slot: resource_id}``) for the resources it needs. Set + ``create_missing_resources`` to ``True`` to create each unbound + slot instead of getting an error. Returns: - The created agent. + The created agent. On a create from ``agent_template`` that created + resources, ``created_resources`` maps each slot to the new resource + and ``solution_id`` names the solution grouping them with the agent. """ return cast(dict[str, Any], self.request("POST", "/agents", json=body)) @@ -2825,7 +2866,15 @@ def get_evaluation_criteria_summary(self, criteria_id: str) -> dict[str, Any]: ) def list_evaluation_results( - self, criteria_id: str, *, page: int = 1, limit: int = 50 + self, + criteria_id: str, + *, + page: int = 1, + limit: int = 50, + status: str | None = None, + flagged_only: bool | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> dict[str, Any]: """List evaluation results for criteria. @@ -2833,6 +2882,10 @@ def list_evaluation_results( criteria_id: Evaluation criteria identifier. page: Page number (1-indexed). limit: Items per page. + status: Only results with this status. + flagged_only: Only flagged results. + time_from: Only results at or after this time (ISO 8601). + time_to: Only results at or before this time (ISO 8601). Returns: The page of results under ``data`` with ``total``, ``page`` and @@ -2844,7 +2897,16 @@ def list_evaluation_results( self.request( "GET", f"/agents/evaluation-criteria/{criteria_id}/results", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "flagged_only": flagged_only, + "time_from": time_from, + "time_to": time_to, + } + ), ), "data", _PAGE_COUNTERS, @@ -2872,7 +2934,12 @@ def create_evaluation_result( ) def list_compatible_runs( - self, criteria_id: str, *, page: int = 1, limit: int = 50 + self, + criteria_id: str, + *, + page: int = 1, + limit: int = 50, + started_after: str | None = None, ) -> dict[str, Any]: """List agent runs compatible with evaluation criteria. @@ -2880,6 +2947,7 @@ def list_compatible_runs( criteria_id: Evaluation criteria identifier. page: Page number (1-indexed). limit: Items per page. + started_after: Only runs started after this time (ISO 8601). Returns: The page of compatible runs under ``data`` with ``total``, ``page`` and @@ -2891,7 +2959,9 @@ def list_compatible_runs( self.request( "GET", f"/agents/evaluation-criteria/{criteria_id}/compatible-runs", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + {"page": page, "limit": limit, "started_after": started_after} + ), ), "data", _PAGE_COUNTERS, @@ -2921,7 +2991,16 @@ def test_draft_evaluation( ) def list_agent_evaluation_results( - self, agent_id: str, *, page: int = 1, limit: int = 50 + self, + agent_id: str, + *, + page: int = 1, + limit: int = 50, + status: str | None = None, + step: str | None = None, + flagged_only: bool | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> dict[str, Any]: """List all evaluation results for an agent. @@ -2929,6 +3008,11 @@ def list_agent_evaluation_results( agent_id: Agent identifier. page: Page number (1-indexed). limit: Items per page. + status: Only results with this status. + step: Only results for this agent step. + flagged_only: Only flagged results. + time_from: Only results at or after this time (ISO 8601). + time_to: Only results at or before this time (ISO 8601). Returns: The page of results with their criteria under ``data`` with ``total``, @@ -2940,7 +3024,17 @@ def list_agent_evaluation_results( self.request( "GET", f"/agents/{agent_id}/evaluation-results", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "step": step, + "flagged_only": flagged_only, + "time_from": time_from, + "time_to": time_to, + } + ), ), "data", _PAGE_COUNTERS, @@ -2993,7 +3087,15 @@ def list_run_evaluation_results_page( return _keyed_list(result, "data") def list_evaluation_runs( - self, agent_id: str, *, page: int = 1, limit: int = 50 + self, + agent_id: str, + *, + page: int = 1, + limit: int = 50, + status: str | None = None, + step: str | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> dict[str, Any]: """List evaluation run summaries for an agent. @@ -3001,6 +3103,10 @@ def list_evaluation_runs( agent_id: Agent identifier. page: Page number (1-indexed). limit: Items per page. + status: Only runs with this status. + step: Only runs for this agent step. + time_from: Only runs at or after this time (ISO 8601). + time_to: Only runs at or before this time (ISO 8601). Returns: The page of run summaries under ``data`` with ``total``, ``page`` and @@ -3012,21 +3118,42 @@ def list_evaluation_runs( self.request( "GET", f"/agents/{agent_id}/evaluation-runs", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "step": step, + "time_from": time_from, + "time_to": time_to, + } + ), ), "data", _PAGE_COUNTERS, ) - def get_non_manual_evaluation_summary(self, agent_id: str) -> dict[str, Any]: + def get_non_manual_evaluation_summary( + self, + agent_id: str | None = None, + *, + days: int | None = None, + start_date: str | None = None, + end_date: str | None = None, + ) -> dict[str, Any]: """Get the non-manual evaluation summary, scoped to an agent when opted in. Args: - agent_id: Agent identifier. Scoping is part of the ``2026-07-27`` - changeset: on the legacy baseline the API **ignores** it and - always returns the account-wide rollup, so set - ``api_version="2026-07-27"`` (or pin the account) to get - per-agent numbers. + agent_id: Agent identifier; omit it for the account-wide summary. + Scoping is part of the ``2026-07-27`` changeset: on the legacy + baseline the API **ignores** it and always returns the + account-wide rollup, so set ``api_version="2026-07-27"`` (or + pin the account) to get per-agent numbers. + days: Report the last this many days (the API defaults to 30). + start_date: First day to report (YYYY-MM-DD). When given it + overrides ``days``, and the range runs to ``end_date`` or today. + end_date: Last day to report (YYYY-MM-DD). Ignored without + ``start_date``. Returns: Summary of automated evaluation results — for ``agent_id`` when the @@ -3040,7 +3167,14 @@ def get_non_manual_evaluation_summary(self, agent_id: str) -> dict[str, Any]: self.request( "GET", "/agents/evaluation-results/non-manual-summary", - params={"agent_id": agent_id}, + params=_strip_none( + { + "agent_id": agent_id, + "days": days, + "start_date": start_date, + "end_date": end_date, + } + ), ), ) @@ -3244,6 +3378,37 @@ def set_email_trigger_config( ), ) + def set_slack_trigger_config( + self, + agent_id: str, + trigger_id: str, + body: dict[str, Any], + ) -> dict[str, Any]: + """Configure an agent's SLACK_COMMAND trigger. + + People run the agent from Slack with ``/seclai`` or the message shortcut. + + Args: + agent_id: Agent identifier. + trigger_id: Trigger identifier. + body: Fields to set (mcp_client_id, form, scope, channel_ids, + allow_dms, activation, visibility, start_without_form, input, + turns_enabled, turns_anyone, max_turns, include_invoker_email, + notify_failure_after_answer). Omitted fields are unchanged. + + Returns: + The trigger's Slack config, with ``missing_scopes`` listing what the + Slack connection lacks for optional features. + """ + return cast( + dict[str, Any], + self.request( + "PUT", + f"/agents/{agent_id}/triggers/{trigger_id}/slack-config", + json=body, + ), + ) + def set_accepted_attachments( self, agent_id: str, @@ -3254,8 +3419,8 @@ def set_accepted_attachments( Replaces the trigger's declaration. A run's files are each assigned to one declared attachment before any step runs, and steps reference one as - ``{{agent.attachments.}}``. Only ``dynamic_input`` and - ``email_received`` triggers take files. The API answers 400 when the + ``{{agent.attachments.}}``. Only ``dynamic_input``, + ``email_received`` and ``slack_command`` triggers take files. The API answers 400 when the agent references an attachment the new declaration leaves out. Args: @@ -3385,6 +3550,8 @@ def list_memory_banks( limit: int = 50, sort: str = "created_at", order: str = "desc", + # Named for the wire param; shadows the builtin, so don't call type() here. + type: str | None = None, ) -> dict[str, Any]: """List memory banks. @@ -3393,6 +3560,7 @@ def list_memory_banks( limit: Items per page. sort: Sort field. order: Sort order (``"asc"`` or ``"desc"``). + type: Only banks of this type (``"conversation"`` or ``"general"``). Returns: The page of memory banks under ``memory_banks`` with ``total``, ``page`` @@ -3405,7 +3573,13 @@ def list_memory_banks( "GET", "/memory_banks", params=_strip_none( - {"page": page, "limit": limit, "sort": sort, "order": order} + { + "page": page, + "limit": limit, + "sort": sort, + "order": order, + "type": type, + } ), ), "memory_banks", @@ -3483,16 +3657,34 @@ def get_agents_using_memory_bank(self, memory_bank_id: str) -> JSONValue: unwrap_items(self.request("GET", f"/memory_banks/{memory_bank_id}/agents")), ) - def get_memory_bank_stats(self, memory_bank_id: str) -> JSONValue: + def get_memory_bank_stats( + self, + memory_bank_id: str, + *, + days: int | None = None, + start_date: str | None = None, + end_date: str | None = None, + ) -> JSONValue: """Get statistics for a memory bank. Args: memory_bank_id: Memory bank identifier. + days: Report the last this many days (the API defaults to 30). + start_date: First day to report (YYYY-MM-DD). Only with + ``end_date``, when the two override ``days``; either alone is + ignored. + end_date: Last day to report (YYYY-MM-DD). Only with ``start_date``. Returns: Memory bank statistics. """ - return self.request("GET", f"/memory_banks/{memory_bank_id}/stats") + return self.request( + "GET", + f"/memory_banks/{memory_bank_id}/stats", + params=_strip_none( + {"days": days, "start_date": start_date, "end_date": end_date} + ), + ) def compact_memory_bank(self, memory_bank_id: str) -> None: """Trigger compaction of a memory bank. @@ -3577,9 +3769,15 @@ def generate_memory_bank_config(self, body: dict[str, Any]) -> dict[str, Any]: ), ) - def get_memory_bank_ai_last_conversation(self) -> dict[str, Any]: + def get_memory_bank_ai_last_conversation( + self, *, limit: int | None = None, offset: int | None = None + ) -> dict[str, Any]: """Get the last AI assistant conversation for memory banks. + Args: + limit: Most turns to return (the API defaults to 5). + offset: Number of most recent turns to skip. + Returns: Last conversation with the memory bank AI assistant. """ @@ -3588,6 +3786,7 @@ def get_memory_bank_ai_last_conversation(self) -> dict[str, Any]: self.request( "GET", "/memory_banks/ai-assistant/last-conversation", + params=_strip_none({"limit": limit, "offset": offset}), ), ) @@ -4009,6 +4208,7 @@ def list_solutions( limit: int = 50, sort: str = "created_at", order: str = "desc", + search: str | None = None, ) -> dict[str, Any]: """List solutions. @@ -4017,6 +4217,7 @@ def list_solutions( limit: Items per page. sort: Sort field. order: Sort order (``"asc"`` or ``"desc"``). + search: Only solutions whose name contains this text, ignoring case. Returns: Paginated list of solutions. @@ -4027,7 +4228,13 @@ def list_solutions( "GET", "/solutions", params=_strip_none( - {"page": page, "limit": limit, "sort": sort, "order": order} + { + "page": page, + "limit": limit, + "sort": sort, + "order": order, + "search": search, + } ), ), ) @@ -4377,9 +4584,14 @@ def generate_governance_ai_plan(self, body: dict[str, Any]) -> dict[str, Any]: ), ) - def list_governance_ai_conversations(self) -> list[dict[str, Any]]: + def list_governance_ai_conversations( + self, *, limit: int | None = None + ) -> list[dict[str, Any]]: """List governance AI assistant conversations. + Args: + limit: Most conversations to return (the API defaults to 20). + Returns: The governance conversations, as a list on every API version. """ @@ -4387,6 +4599,7 @@ def list_governance_ai_conversations(self) -> list[dict[str, Any]]: self.request( "GET", "/governance/ai-assistant/conversations", + params=_strip_none({"limit": limit}), ) ) @@ -4427,6 +4640,10 @@ def list_alerts( limit: int = 50, status: str | None = None, severity: str | None = None, + agent_id: str | None = None, + source_connection_id: str | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> JSONValue: """List alerts. @@ -4438,6 +4655,10 @@ def list_alerts( on this endpoint, so it never filtered anything, and sending it is a 422 once ``api_version`` is ``2026-07-27`` or later. It is accepted and dropped so existing call sites keep working. + agent_id: Only alerts for this agent. + source_connection_id: Only alerts for this source. + time_from: Only alerts at or after this time (ISO 8601). + time_to: Only alerts at or before this time (ISO 8601). Returns: Paginated list of alerts. @@ -4445,7 +4666,17 @@ def list_alerts( return self.request( "GET", "/alerts", - params=_strip_none({"page": page, "limit": limit, "status": status}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "agent_id": agent_id, + "source_connection_id": source_connection_id, + "time_from": time_from, + "time_to": time_to, + } + ), ) def get_alert(self, alert_id: str) -> JSONValue: @@ -4507,7 +4738,15 @@ def unsubscribe_from_alert(self, alert_id: str) -> JSONValue: # ── Alert Configs ───────────────────────────────────────────────────────── - def list_alert_configs(self, *, page: int = 1, limit: int = 50) -> JSONValue: + def list_alert_configs( + self, + *, + page: int = 1, + limit: int = 50, + agent_id: str | None = None, + source_connection_id: str | None = None, + scope: str | None = None, + ) -> JSONValue: """List alert configurations. Args: @@ -4515,6 +4754,10 @@ def list_alert_configs(self, *, page: int = 1, limit: int = 50) -> JSONValue: with ``api_version="2026-07-27"`` or later — by default the response is unpaginated and always contains every configuration. limit: Items per page. Ignored by default, as above. + agent_id: Only configurations for this agent. + source_connection_id: Only configurations for this source. + scope: ``"source"`` lists the account-level source alert + configurations. Returns: The configurations under ``configs`` with ``total``, on every API @@ -4526,7 +4769,15 @@ def list_alert_configs(self, *, page: int = 1, limit: int = 50) -> JSONValue: self.request( "GET", "/alerts/configs", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "agent_id": agent_id, + "source_connection_id": source_connection_id, + "scope": scope, + } + ), ), "configs", ("total",), @@ -4576,9 +4827,19 @@ def delete_alert_config(self, config_id: str) -> None: # ── Alert Preferences ───────────────────────────────────────────────────── - def list_organization_alert_preferences(self) -> dict[str, Any]: + def list_organization_alert_preferences( + self, + *, + organization_id: str | None = None, + include_defaults: bool | None = None, + ) -> dict[str, Any]: """List organization alert preferences. + Args: + organization_id: Only preferences for this organization. + include_defaults: Also return the effective subscribed state for + every alert type, not only explicit overrides. + Returns: The preferences under ``preferences`` with ``total``, on every API version. Once the client opts in with ``api_version="2026-07-27"`` or @@ -4588,6 +4849,12 @@ def list_organization_alert_preferences(self) -> dict[str, Any]: self.request( "GET", "/alerts/organization-preferences/list", + params=_strip_none( + { + "organization_id": organization_id, + "include_defaults": include_defaults, + } + ), ), "preferences", ("total",), @@ -4614,7 +4881,14 @@ def update_organization_alert_preference( # ── Model Alerts ────────────────────────────────────────────────────────── - def list_model_alerts(self, *, page: int = 1, limit: int = 50) -> JSONValue: + def list_model_alerts( + self, + *, + page: int = 1, + limit: int = 50, + agent_id: str | None = None, + unread_only: bool | None = None, + ) -> JSONValue: """List model alerts. Args: @@ -4622,6 +4896,8 @@ def list_model_alerts(self, *, page: int = 1, limit: int = 50) -> JSONValue: endpoint actually declares; it does not accept ``page``, so every page but the first previously returned page 1. limit: Items per page. + agent_id: Only alerts for this agent. + unread_only: Only unread alerts. Returns: The alerts under ``alerts`` with ``total``, on every API version. Once @@ -4635,7 +4911,14 @@ def list_model_alerts(self, *, page: int = 1, limit: int = 50) -> JSONValue: self.request( "GET", "/models/alerts", - params=_strip_none({"offset": offset, "limit": limit}), + params=_strip_none( + { + "offset": offset, + "limit": limit, + "agent_id": agent_id, + "unread_only": unread_only, + } + ), ), "alerts", ("total",), @@ -4663,16 +4946,43 @@ def mark_model_alert_read(self, alert_id: str) -> None: # ── Models ──────────────────────────────────────────────────────────────── - def get_model_recommendations(self, model_id: str) -> JSONValue: + def get_model_recommendations( + self, + model_id: str, + *, + require_tool_use: bool | None = None, + require_structured_output: bool | None = None, + require_thinking: bool | None = None, + min_context_tokens: int | None = None, + min_output_tokens: int | None = None, + ) -> JSONValue: """Get recommendations for a model. Args: model_id: Model identifier. + require_tool_use: Only recommend models that support tool use. + require_structured_output: Only recommend models that support + structured output. + require_thinking: Only recommend models that support thinking. + min_context_tokens: Smallest context window to accept, in tokens. + min_output_tokens: Smallest output token limit to accept. Returns: Model recommendations. """ - return self.request("GET", f"/models/{model_id}/recommendations") + return self.request( + "GET", + f"/models/{model_id}/recommendations", + params=_strip_none( + { + "require_tool_use": require_tool_use, + "require_structured_output": require_structured_output, + "require_thinking": require_thinking, + "min_context_tokens": min_context_tokens, + "min_output_tokens": min_output_tokens, + } + ), + ) def list_models( self, @@ -4680,6 +4990,8 @@ def list_models( provider: str | None = None, supports_tool_use: bool | None = None, supports_thinking: bool | None = None, + supports_input_media: str | None = None, + supports_output_media: str | None = None, ) -> JSONValue: """List all enabled LLM models grouped by provider. @@ -4687,6 +4999,10 @@ def list_models( provider: Filter by provider name. supports_tool_use: Filter to models that support tool use. supports_thinking: Filter to models that support extended thinking. + supports_input_media: Filter to models that accept this input: a + kind (``image``, ``audio``, ``video``, ``pdf``) or a full MIME type. + supports_output_media: Filter to models that produce this output: a + kind (``image``, ``audio``, ``video``) or a full MIME type. Returns: The provider groups with their models, as a list on every API version. @@ -4702,6 +5018,8 @@ def list_models( "provider": provider, "supports_tool_use": supports_tool_use, "supports_thinking": supports_thinking, + "supports_input_media": supports_input_media, + "supports_output_media": supports_output_media, } ), ) @@ -5218,9 +5536,15 @@ def ai_assistant_memory_bank(self, body: dict[str, Any]) -> dict[str, Any]: ), ) - def get_ai_assistant_memory_bank_history(self) -> dict[str, Any]: + def get_ai_assistant_memory_bank_history( + self, *, limit: int | None = None, offset: int | None = None + ) -> dict[str, Any]: """Get the last AI assistant memory bank conversation. + Args: + limit: Most turns to return (the API defaults to 5). + offset: Number of most recent turns to skip. + Returns: Last conversation. """ @@ -5229,6 +5553,7 @@ def get_ai_assistant_memory_bank_history(self) -> dict[str, Any]: self.request( "GET", "/ai-assistant/memory-bank/last-conversation", + params=_strip_none({"limit": limit, "offset": offset}), ), ) @@ -6782,14 +7107,55 @@ async def list_agents(self, *, page: int = 1, limit: int = 50) -> dict[str, Any] ), ) + async def list_agent_examples( + self, + *, + query: str | None = None, + use_case: str | None = None, + page: int = 1, + limit: int = 20, + ) -> dict[str, Any]: + """List the agent gallery: example agents to start from. + + Pass an entry's ``key`` as ``agent_template`` to :meth:`create_agent`, + with ``resource_bindings`` for the resources it needs. + + Args: + query: Words every match must contain. + use_case: Only entries for this use case. + page: Page number (1-indexed). + limit: Items per page. + + Returns: + The page of examples under ``data`` with ``pagination``. + """ + return cast( + dict[str, Any], + await self.request( + "GET", + "/agents/examples", + params=_strip_none( + {"query": query, "use_case": use_case, "page": page, "limit": limit} + ), + ), + ) + async def create_agent(self, body: dict[str, Any]) -> dict[str, Any]: """Create a new agent. Args: - body: Agent creation payload (name, description, etc.). + body: Agent creation payload: ``name`` (required), ``description`` + and the other ``CreateAgentRequest`` fields. To start from a + gallery entry, pass its ``key`` from :meth:`list_agent_examples` + as ``agent_template``, with ``resource_bindings`` + (``{slot: resource_id}``) for the resources it needs. Set + ``create_missing_resources`` to ``True`` to create each unbound + slot instead of getting an error. Returns: - The created agent. + The created agent. On a create from ``agent_template`` that created + resources, ``created_resources`` maps each slot to the new resource + and ``solution_id`` names the solution grouping them with the agent. """ return cast(dict[str, Any], await self.request("POST", "/agents", json=body)) @@ -7371,7 +7737,15 @@ async def get_evaluation_criteria_summary(self, criteria_id: str) -> dict[str, A ) async def list_evaluation_results( - self, criteria_id: str, *, page: int = 1, limit: int = 50 + self, + criteria_id: str, + *, + page: int = 1, + limit: int = 50, + status: str | None = None, + flagged_only: bool | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> dict[str, Any]: """List evaluation results for criteria. @@ -7379,6 +7753,10 @@ async def list_evaluation_results( criteria_id: Evaluation criteria identifier. page: Page number (1-indexed). limit: Items per page. + status: Only results with this status. + flagged_only: Only flagged results. + time_from: Only results at or after this time (ISO 8601). + time_to: Only results at or before this time (ISO 8601). Returns: The page of results under ``data`` with ``total``, ``page`` and @@ -7390,7 +7768,16 @@ async def list_evaluation_results( await self.request( "GET", f"/agents/evaluation-criteria/{criteria_id}/results", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "flagged_only": flagged_only, + "time_from": time_from, + "time_to": time_to, + } + ), ), "data", _PAGE_COUNTERS, @@ -7418,7 +7805,12 @@ async def create_evaluation_result( ) async def list_compatible_runs( - self, criteria_id: str, *, page: int = 1, limit: int = 50 + self, + criteria_id: str, + *, + page: int = 1, + limit: int = 50, + started_after: str | None = None, ) -> dict[str, Any]: """List agent runs compatible with evaluation criteria. @@ -7426,6 +7818,7 @@ async def list_compatible_runs( criteria_id: Evaluation criteria identifier. page: Page number (1-indexed). limit: Items per page. + started_after: Only runs started after this time (ISO 8601). Returns: The page of compatible runs under ``data`` with ``total``, ``page`` and @@ -7437,7 +7830,9 @@ async def list_compatible_runs( await self.request( "GET", f"/agents/evaluation-criteria/{criteria_id}/compatible-runs", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + {"page": page, "limit": limit, "started_after": started_after} + ), ), "data", _PAGE_COUNTERS, @@ -7467,7 +7862,16 @@ async def test_draft_evaluation( ) async def list_agent_evaluation_results( - self, agent_id: str, *, page: int = 1, limit: int = 50 + self, + agent_id: str, + *, + page: int = 1, + limit: int = 50, + status: str | None = None, + step: str | None = None, + flagged_only: bool | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> dict[str, Any]: """List all evaluation results for an agent. @@ -7475,6 +7879,11 @@ async def list_agent_evaluation_results( agent_id: Agent identifier. page: Page number (1-indexed). limit: Items per page. + status: Only results with this status. + step: Only results for this agent step. + flagged_only: Only flagged results. + time_from: Only results at or after this time (ISO 8601). + time_to: Only results at or before this time (ISO 8601). Returns: The page of results with their criteria under ``data`` with ``total``, @@ -7486,7 +7895,17 @@ async def list_agent_evaluation_results( await self.request( "GET", f"/agents/{agent_id}/evaluation-results", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "step": step, + "flagged_only": flagged_only, + "time_from": time_from, + "time_to": time_to, + } + ), ), "data", _PAGE_COUNTERS, @@ -7539,7 +7958,15 @@ async def list_run_evaluation_results_page( return _keyed_list(result, "data") async def list_evaluation_runs( - self, agent_id: str, *, page: int = 1, limit: int = 50 + self, + agent_id: str, + *, + page: int = 1, + limit: int = 50, + status: str | None = None, + step: str | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> dict[str, Any]: """List evaluation run summaries for an agent. @@ -7547,6 +7974,10 @@ async def list_evaluation_runs( agent_id: Agent identifier. page: Page number (1-indexed). limit: Items per page. + status: Only runs with this status. + step: Only runs for this agent step. + time_from: Only runs at or after this time (ISO 8601). + time_to: Only runs at or before this time (ISO 8601). Returns: The page of run summaries under ``data`` with ``total``, ``page`` and @@ -7558,21 +7989,42 @@ async def list_evaluation_runs( await self.request( "GET", f"/agents/{agent_id}/evaluation-runs", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "step": step, + "time_from": time_from, + "time_to": time_to, + } + ), ), "data", _PAGE_COUNTERS, ) - async def get_non_manual_evaluation_summary(self, agent_id: str) -> dict[str, Any]: + async def get_non_manual_evaluation_summary( + self, + agent_id: str | None = None, + *, + days: int | None = None, + start_date: str | None = None, + end_date: str | None = None, + ) -> dict[str, Any]: """Get the non-manual evaluation summary, scoped to an agent when opted in. Args: - agent_id: Agent identifier. Scoping is part of the ``2026-07-27`` - changeset: on the legacy baseline the API **ignores** it and - always returns the account-wide rollup, so set - ``api_version="2026-07-27"`` (or pin the account) to get - per-agent numbers. + agent_id: Agent identifier; omit it for the account-wide summary. + Scoping is part of the ``2026-07-27`` changeset: on the legacy + baseline the API **ignores** it and always returns the + account-wide rollup, so set ``api_version="2026-07-27"`` (or + pin the account) to get per-agent numbers. + days: Report the last this many days (the API defaults to 30). + start_date: First day to report (YYYY-MM-DD). When given it + overrides ``days``, and the range runs to ``end_date`` or today. + end_date: Last day to report (YYYY-MM-DD). Ignored without + ``start_date``. Returns: Summary of automated evaluation results — for ``agent_id`` when the @@ -7586,7 +8038,14 @@ async def get_non_manual_evaluation_summary(self, agent_id: str) -> dict[str, An await self.request( "GET", "/agents/evaluation-results/non-manual-summary", - params={"agent_id": agent_id}, + params=_strip_none( + { + "agent_id": agent_id, + "days": days, + "start_date": start_date, + "end_date": end_date, + } + ), ), ) @@ -7793,6 +8252,37 @@ async def set_email_trigger_config( ), ) + async def set_slack_trigger_config( + self, + agent_id: str, + trigger_id: str, + body: dict[str, Any], + ) -> dict[str, Any]: + """Configure an agent's SLACK_COMMAND trigger. + + People run the agent from Slack with ``/seclai`` or the message shortcut. + + Args: + agent_id: Agent identifier. + trigger_id: Trigger identifier. + body: Fields to set (mcp_client_id, form, scope, channel_ids, + allow_dms, activation, visibility, start_without_form, input, + turns_enabled, turns_anyone, max_turns, include_invoker_email, + notify_failure_after_answer). Omitted fields are unchanged. + + Returns: + The trigger's Slack config, with ``missing_scopes`` listing what the + Slack connection lacks for optional features. + """ + return cast( + dict[str, Any], + await self.request( + "PUT", + f"/agents/{agent_id}/triggers/{trigger_id}/slack-config", + json=body, + ), + ) + async def set_accepted_attachments( self, agent_id: str, @@ -7803,8 +8293,8 @@ async def set_accepted_attachments( Replaces the trigger's declaration. A run's files are each assigned to one declared attachment before any step runs, and steps reference one as - ``{{agent.attachments.}}``. Only ``dynamic_input`` and - ``email_received`` triggers take files. The API answers 400 when the + ``{{agent.attachments.}}``. Only ``dynamic_input``, + ``email_received`` and ``slack_command`` triggers take files. The API answers 400 when the agent references an attachment the new declaration leaves out. Args: @@ -7936,6 +8426,8 @@ async def list_memory_banks( limit: int = 50, sort: str = "created_at", order: str = "desc", + # Named for the wire param; shadows the builtin, so don't call type() here. + type: str | None = None, ) -> dict[str, Any]: """List memory banks. @@ -7944,6 +8436,7 @@ async def list_memory_banks( limit: Items per page. sort: Sort field. order: Sort order (``"asc"`` or ``"desc"``). + type: Only banks of this type (``"conversation"`` or ``"general"``). Returns: The page of memory banks under ``memory_banks`` with ``total``, ``page`` @@ -7956,7 +8449,13 @@ async def list_memory_banks( "GET", "/memory_banks", params=_strip_none( - {"page": page, "limit": limit, "sort": sort, "order": order} + { + "page": page, + "limit": limit, + "sort": sort, + "order": order, + "type": type, + } ), ), "memory_banks", @@ -8038,16 +8537,34 @@ async def get_agents_using_memory_bank(self, memory_bank_id: str) -> JSONValue: ), ) - async def get_memory_bank_stats(self, memory_bank_id: str) -> JSONValue: + async def get_memory_bank_stats( + self, + memory_bank_id: str, + *, + days: int | None = None, + start_date: str | None = None, + end_date: str | None = None, + ) -> JSONValue: """Get statistics for a memory bank. Args: memory_bank_id: Memory bank identifier. + days: Report the last this many days (the API defaults to 30). + start_date: First day to report (YYYY-MM-DD). Only with + ``end_date``, when the two override ``days``; either alone is + ignored. + end_date: Last day to report (YYYY-MM-DD). Only with ``start_date``. Returns: Memory bank statistics. """ - return await self.request("GET", f"/memory_banks/{memory_bank_id}/stats") + return await self.request( + "GET", + f"/memory_banks/{memory_bank_id}/stats", + params=_strip_none( + {"days": days, "start_date": start_date, "end_date": end_date} + ), + ) async def compact_memory_bank(self, memory_bank_id: str) -> None: """Trigger compaction of a memory bank. @@ -8135,9 +8652,15 @@ async def generate_memory_bank_config(self, body: dict[str, Any]) -> dict[str, A ), ) - async def get_memory_bank_ai_last_conversation(self) -> dict[str, Any]: + async def get_memory_bank_ai_last_conversation( + self, *, limit: int | None = None, offset: int | None = None + ) -> dict[str, Any]: """Get the last AI assistant conversation for memory banks. + Args: + limit: Most turns to return (the API defaults to 5). + offset: Number of most recent turns to skip. + Returns: Last conversation with the memory bank AI assistant. """ @@ -8146,6 +8669,7 @@ async def get_memory_bank_ai_last_conversation(self) -> dict[str, Any]: await self.request( "GET", "/memory_banks/ai-assistant/last-conversation", + params=_strip_none({"limit": limit, "offset": offset}), ), ) @@ -8577,6 +9101,7 @@ async def list_solutions( limit: int = 50, sort: str = "created_at", order: str = "desc", + search: str | None = None, ) -> dict[str, Any]: """List solutions. @@ -8585,6 +9110,7 @@ async def list_solutions( limit: Items per page. sort: Sort field. order: Sort order (``"asc"`` or ``"desc"``). + search: Only solutions whose name contains this text, ignoring case. Returns: Paginated list of solutions. @@ -8595,7 +9121,13 @@ async def list_solutions( "GET", "/solutions", params=_strip_none( - {"page": page, "limit": limit, "sort": sort, "order": order} + { + "page": page, + "limit": limit, + "sort": sort, + "order": order, + "search": search, + } ), ), ) @@ -8953,9 +9485,14 @@ async def generate_governance_ai_plan(self, body: dict[str, Any]) -> dict[str, A ), ) - async def list_governance_ai_conversations(self) -> list[dict[str, Any]]: + async def list_governance_ai_conversations( + self, *, limit: int | None = None + ) -> list[dict[str, Any]]: """List governance AI assistant conversations. + Args: + limit: Most conversations to return (the API defaults to 20). + Returns: The governance conversations, as a list on every API version. """ @@ -8963,6 +9500,7 @@ async def list_governance_ai_conversations(self) -> list[dict[str, Any]]: await self.request( "GET", "/governance/ai-assistant/conversations", + params=_strip_none({"limit": limit}), ) ) @@ -9003,6 +9541,10 @@ async def list_alerts( limit: int = 50, status: str | None = None, severity: str | None = None, + agent_id: str | None = None, + source_connection_id: str | None = None, + time_from: str | None = None, + time_to: str | None = None, ) -> JSONValue: """List alerts. @@ -9014,6 +9556,10 @@ async def list_alerts( on this endpoint, so it never filtered anything, and sending it is a 422 once ``api_version`` is ``2026-07-27`` or later. It is accepted and dropped so existing call sites keep working. + agent_id: Only alerts for this agent. + source_connection_id: Only alerts for this source. + time_from: Only alerts at or after this time (ISO 8601). + time_to: Only alerts at or before this time (ISO 8601). Returns: Paginated list of alerts. @@ -9021,7 +9567,17 @@ async def list_alerts( return await self.request( "GET", "/alerts", - params=_strip_none({"page": page, "limit": limit, "status": status}), + params=_strip_none( + { + "page": page, + "limit": limit, + "status": status, + "agent_id": agent_id, + "source_connection_id": source_connection_id, + "time_from": time_from, + "time_to": time_to, + } + ), ) async def get_alert(self, alert_id: str) -> JSONValue: @@ -9085,7 +9641,15 @@ async def unsubscribe_from_alert(self, alert_id: str) -> JSONValue: # ── Alert Configs ───────────────────────────────────────────────────────── - async def list_alert_configs(self, *, page: int = 1, limit: int = 50) -> JSONValue: + async def list_alert_configs( + self, + *, + page: int = 1, + limit: int = 50, + agent_id: str | None = None, + source_connection_id: str | None = None, + scope: str | None = None, + ) -> JSONValue: """List alert configurations. Args: @@ -9093,6 +9657,10 @@ async def list_alert_configs(self, *, page: int = 1, limit: int = 50) -> JSONVal with ``api_version="2026-07-27"`` or later — by default the response is unpaginated and always contains every configuration. limit: Items per page. Ignored by default, as above. + agent_id: Only configurations for this agent. + source_connection_id: Only configurations for this source. + scope: ``"source"`` lists the account-level source alert + configurations. Returns: The configurations under ``configs`` with ``total``, on every API @@ -9104,7 +9672,15 @@ async def list_alert_configs(self, *, page: int = 1, limit: int = 50) -> JSONVal await self.request( "GET", "/alerts/configs", - params=_strip_none({"page": page, "limit": limit}), + params=_strip_none( + { + "page": page, + "limit": limit, + "agent_id": agent_id, + "source_connection_id": source_connection_id, + "scope": scope, + } + ), ), "configs", ("total",), @@ -9156,9 +9732,19 @@ async def delete_alert_config(self, config_id: str) -> None: # ── Alert Preferences ───────────────────────────────────────────────────── - async def list_organization_alert_preferences(self) -> dict[str, Any]: + async def list_organization_alert_preferences( + self, + *, + organization_id: str | None = None, + include_defaults: bool | None = None, + ) -> dict[str, Any]: """List organization alert preferences. + Args: + organization_id: Only preferences for this organization. + include_defaults: Also return the effective subscribed state for + every alert type, not only explicit overrides. + Returns: The preferences under ``preferences`` with ``total``, on every API version. Once the client opts in with ``api_version="2026-07-27"`` or @@ -9168,6 +9754,12 @@ async def list_organization_alert_preferences(self) -> dict[str, Any]: await self.request( "GET", "/alerts/organization-preferences/list", + params=_strip_none( + { + "organization_id": organization_id, + "include_defaults": include_defaults, + } + ), ), "preferences", ("total",), @@ -9194,7 +9786,14 @@ async def update_organization_alert_preference( # ── Model Alerts ────────────────────────────────────────────────────────── - async def list_model_alerts(self, *, page: int = 1, limit: int = 50) -> JSONValue: + async def list_model_alerts( + self, + *, + page: int = 1, + limit: int = 50, + agent_id: str | None = None, + unread_only: bool | None = None, + ) -> JSONValue: """List model alerts. Args: @@ -9202,6 +9801,8 @@ async def list_model_alerts(self, *, page: int = 1, limit: int = 50) -> JSONValu endpoint actually declares; it does not accept ``page``, so every page but the first previously returned page 1. limit: Items per page. + agent_id: Only alerts for this agent. + unread_only: Only unread alerts. Returns: The alerts under ``alerts`` with ``total``, on every API version. Once @@ -9215,7 +9816,14 @@ async def list_model_alerts(self, *, page: int = 1, limit: int = 50) -> JSONValu await self.request( "GET", "/models/alerts", - params=_strip_none({"offset": offset, "limit": limit}), + params=_strip_none( + { + "offset": offset, + "limit": limit, + "agent_id": agent_id, + "unread_only": unread_only, + } + ), ), "alerts", ("total",), @@ -9243,16 +9851,43 @@ async def mark_model_alert_read(self, alert_id: str) -> None: # ── Models ──────────────────────────────────────────────────────────────── - async def get_model_recommendations(self, model_id: str) -> JSONValue: + async def get_model_recommendations( + self, + model_id: str, + *, + require_tool_use: bool | None = None, + require_structured_output: bool | None = None, + require_thinking: bool | None = None, + min_context_tokens: int | None = None, + min_output_tokens: int | None = None, + ) -> JSONValue: """Get recommendations for a model. Args: model_id: Model identifier. + require_tool_use: Only recommend models that support tool use. + require_structured_output: Only recommend models that support + structured output. + require_thinking: Only recommend models that support thinking. + min_context_tokens: Smallest context window to accept, in tokens. + min_output_tokens: Smallest output token limit to accept. Returns: Model recommendations. """ - return await self.request("GET", f"/models/{model_id}/recommendations") + return await self.request( + "GET", + f"/models/{model_id}/recommendations", + params=_strip_none( + { + "require_tool_use": require_tool_use, + "require_structured_output": require_structured_output, + "require_thinking": require_thinking, + "min_context_tokens": min_context_tokens, + "min_output_tokens": min_output_tokens, + } + ), + ) async def list_models( self, @@ -9260,6 +9895,8 @@ async def list_models( provider: str | None = None, supports_tool_use: bool | None = None, supports_thinking: bool | None = None, + supports_input_media: str | None = None, + supports_output_media: str | None = None, ) -> JSONValue: """List all enabled LLM models grouped by provider. @@ -9267,6 +9904,10 @@ async def list_models( provider: Filter by provider name. supports_tool_use: Filter to models that support tool use. supports_thinking: Filter to models that support extended thinking. + supports_input_media: Filter to models that accept this input: a + kind (``image``, ``audio``, ``video``, ``pdf``) or a full MIME type. + supports_output_media: Filter to models that produce this output: a + kind (``image``, ``audio``, ``video``) or a full MIME type. Returns: The provider groups with their models, as a list on every API version. @@ -9282,6 +9923,8 @@ async def list_models( "provider": provider, "supports_tool_use": supports_tool_use, "supports_thinking": supports_thinking, + "supports_input_media": supports_input_media, + "supports_output_media": supports_output_media, } ), ) @@ -9809,9 +10452,15 @@ async def ai_assistant_memory_bank(self, body: dict[str, Any]) -> dict[str, Any] ), ) - async def get_ai_assistant_memory_bank_history(self) -> dict[str, Any]: + async def get_ai_assistant_memory_bank_history( + self, *, limit: int | None = None, offset: int | None = None + ) -> dict[str, Any]: """Get the last AI assistant memory bank conversation. + Args: + limit: Most turns to return (the API defaults to 5). + offset: Number of most recent turns to skip. + Returns: Last conversation. """ @@ -9820,6 +10469,7 @@ async def get_ai_assistant_memory_bank_history(self) -> dict[str, Any]: await self.request( "GET", "/ai-assistant/memory-bank/last-conversation", + params=_strip_none({"limit": limit, "offset": offset}), ), ) diff --git a/seclai/versions.py b/seclai/versions.py index e839dfb..0714fee 100644 --- a/seclai/versions.py +++ b/seclai/versions.py @@ -31,13 +31,14 @@ class ApiVersion(StrEnum): V2026_10_18 = "2026-10-18" V2026_10_19 = "2026-10-19" V2026_10_21 = "2026-10-21" + V2026_10_28 = "2026-10-28" #: Baseline applied to an unpinned, header-less caller. DEFAULT_API_VERSION = ApiVersion.V2026_07_01 #: Newest version known to this SDK release. May lag the server. -LATEST_API_VERSION = ApiVersion.V2026_10_21 +LATEST_API_VERSION = ApiVersion.V2026_10_28 def validate_api_version(version: str | None, *, allow_unknown: bool) -> str | None: diff --git a/tests/test_new_methods.py b/tests/test_new_methods.py index 1b8349a..f19eb0b 100644 --- a/tests/test_new_methods.py +++ b/tests/test_new_methods.py @@ -8,6 +8,7 @@ import json import pathlib +from collections.abc import Callable from typing import Any import httpx @@ -4840,10 +4841,10 @@ def test_null_metadata_is_accepted(self) -> None: } -class TestLatestApiVersion20261021: - def test_latest_is_2026_10_21(self) -> None: +class TestLatestApiVersion20261028: + def test_latest_is_2026_10_28(self) -> None: assert ( - seclai_versions.LATEST_API_VERSION is seclai_versions.ApiVersion.V2026_10_21 + seclai_versions.LATEST_API_VERSION is seclai_versions.ApiVersion.V2026_10_28 ) def test_latest_is_sent_as_the_header(self) -> None: @@ -4855,7 +4856,7 @@ def handler(req: httpx.Request) -> httpx.Response: client = _sync_client(handler, api_version=seclai_versions.LATEST_API_VERSION) client.list_agents() - assert seen["version"] == "2026-10-21" + assert seen["version"] == "2026-10-28" class TestInsufficientCredits402: @@ -4912,3 +4913,444 @@ def test_generated_model_reads_error_counts(self) -> None: parsed = NonManualEvaluationSummaryResponse.from_dict(_NON_MANUAL_SUMMARY) assert parsed.error == 2 assert parsed.by_mode[0].error == 2 + + +# --------------------------------------------------------------------------- +# 2026-10-31 sync: agent examples, Slack triggers, declared query filters +# --------------------------------------------------------------------------- + + +class TestAgentExamples: + """The agent gallery.""" + + def test_list_agent_examples(self) -> None: + seen: dict[str, Any] = {} + + def handler(req: httpx.Request) -> httpx.Response: + seen["method"] = req.method + seen["path"] = req.url.path + seen["params"] = dict(req.url.params) + return _json_response({"data": [{"key": "triage"}], "pagination": {}}) + + client = _sync_client(handler) + result = client.list_agent_examples( + query="support inbox", use_case="support", page=2, limit=10 + ) + assert seen["method"] == "GET" + assert seen["path"] == "/agents/examples" + assert seen["params"] == { + "query": "support inbox", + "use_case": "support", + "page": "2", + "limit": "10", + } + assert result["data"] == [{"key": "triage"}] + + def test_list_agent_examples_omits_unset_filters(self) -> None: + seen: dict[str, Any] = {} + + def handler(req: httpx.Request) -> httpx.Response: + seen["params"] = dict(req.url.params) + return _json_response({"data": [], "pagination": {}}) + + _sync_client(handler).list_agent_examples() + assert seen["params"] == {"page": "1", "limit": "20"} + + @pytest.mark.asyncio + async def test_async_list_agent_examples(self) -> None: + seen: dict[str, Any] = {} + + async def handler(req: httpx.Request) -> httpx.Response: + seen["method"] = req.method + seen["path"] = req.url.path + seen["params"] = dict(req.url.params) + return _json_response({"data": [{"key": "triage"}], "pagination": {}}) + + client = _async_client(handler) + result = await client.list_agent_examples(query="support", use_case="support") + assert seen["method"] == "GET" + assert seen["path"] == "/agents/examples" + assert seen["params"] == { + "query": "support", + "use_case": "support", + "page": "1", + "limit": "20", + } + assert result["data"] == [{"key": "triage"}] + + +_SLACK_CONFIG = { + "trigger_id": "t1", + "agent_id": "a1", + "mcp_client_id": "m1", + "slack_team_id": "T1", + "form": [], + "scope": "selected_channels", + "allow_dms": False, + "activation": "channel_opt_in", + "visibility": "private", + "start_without_form": False, + "turns_enabled": True, + "turns_anyone": False, + "max_turns": 5, + "include_invoker_email": False, + "notify_failure_after_answer": True, + "channel_ids": ["C1"], + "missing_scopes": [], +} + + +class TestAgentSlackTriggers: + """Agent Slack triggers.""" + + def test_set_slack_trigger_config(self) -> None: + seen: dict[str, Any] = {} + + def handler(req: httpx.Request) -> httpx.Response: + seen["method"] = req.method + seen["path"] = req.url.path + seen["body"] = json.loads(req.content) + return _json_response(_SLACK_CONFIG) + + client = _sync_client(handler) + body = {"channel_ids": ["C1"], "visibility": "private", "max_turns": 5} + result = client.set_slack_trigger_config("a1", "t1", body) + assert seen["method"] == "PUT" + assert seen["path"] == "/agents/a1/triggers/t1/slack-config" + assert seen["body"] == body + assert result == _SLACK_CONFIG + + @pytest.mark.asyncio + async def test_async_set_slack_trigger_config(self) -> None: + seen: dict[str, Any] = {} + + async def handler(req: httpx.Request) -> httpx.Response: + seen["method"] = req.method + seen["path"] = req.url.path + seen["body"] = json.loads(req.content) + return _json_response(_SLACK_CONFIG) + + client = _async_client(handler) + result = await client.set_slack_trigger_config("a1", "t1", {"allow_dms": True}) + assert seen["method"] == "PUT" + assert seen["path"] == "/agents/a1/triggers/t1/slack-config" + assert seen["body"] == {"allow_dms": True} + assert result == _SLACK_CONFIG + + +# Each declared query filter: (method, positional args, kwargs, path, the query +# the kwargs add, and the query the call sends when none of them is passed). +_QUERY_FILTERS: list[ + tuple[str, tuple[str, ...], dict[str, Any], str, dict[str, str], dict[str, str]] +] = [ + ( + "list_evaluation_results", + ("c1",), + { + "status": "failed", + "flagged_only": True, + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + "/agents/evaluation-criteria/c1/results", + { + "status": "failed", + "flagged_only": "true", + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + {"page": "1", "limit": "50"}, + ), + ( + "list_compatible_runs", + ("c1",), + {"started_after": "2026-10-01T00:00:00Z"}, + "/agents/evaluation-criteria/c1/compatible-runs", + {"started_after": "2026-10-01T00:00:00Z"}, + {"page": "1", "limit": "50"}, + ), + ( + "list_agent_evaluation_results", + ("a1",), + { + "status": "passed", + "step": "s1", + "flagged_only": False, + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + "/agents/a1/evaluation-results", + { + "status": "passed", + "step": "s1", + "flagged_only": "false", + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + {"page": "1", "limit": "50"}, + ), + ( + "list_evaluation_runs", + ("a1",), + { + "status": "completed", + "step": "s1", + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + "/agents/a1/evaluation-runs", + { + "status": "completed", + "step": "s1", + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + {"page": "1", "limit": "50"}, + ), + ( + "get_non_manual_evaluation_summary", + ("a1",), + {"days": 7, "start_date": "2026-10-01", "end_date": "2026-10-07"}, + "/agents/evaluation-results/non-manual-summary", + {"days": "7", "start_date": "2026-10-01", "end_date": "2026-10-07"}, + {"agent_id": "a1"}, + ), + ( + "get_ai_assistant_memory_bank_history", + (), + {"limit": 10, "offset": 5}, + "/ai-assistant/memory-bank/last-conversation", + {"limit": "10", "offset": "5"}, + {}, + ), + ( + "get_memory_bank_ai_last_conversation", + (), + {"limit": 10, "offset": 5}, + "/memory_banks/ai-assistant/last-conversation", + {"limit": "10", "offset": "5"}, + {}, + ), + ( + "list_governance_ai_conversations", + (), + {"limit": 3}, + "/governance/ai-assistant/conversations", + {"limit": "3"}, + {}, + ), + ( + "list_alerts", + (), + { + "agent_id": "a1", + "source_connection_id": "s1", + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + "/alerts", + { + "agent_id": "a1", + "source_connection_id": "s1", + "time_from": "2026-10-01T00:00:00Z", + "time_to": "2026-10-31T00:00:00Z", + }, + {"page": "1", "limit": "50"}, + ), + ( + "list_alert_configs", + (), + {"agent_id": "a1", "source_connection_id": "s1", "scope": "source"}, + "/alerts/configs", + {"agent_id": "a1", "source_connection_id": "s1", "scope": "source"}, + {"page": "1", "limit": "50"}, + ), + ( + "list_organization_alert_preferences", + (), + {"organization_id": "o1", "include_defaults": True}, + "/alerts/organization-preferences/list", + {"organization_id": "o1", "include_defaults": "true"}, + {}, + ), + ( + "list_model_alerts", + (), + {"agent_id": "a1", "unread_only": True}, + "/models/alerts", + {"agent_id": "a1", "unread_only": "true"}, + {"offset": "0", "limit": "50"}, + ), + ( + "list_memory_banks", + (), + {"type": "conversation"}, + "/memory_banks", + {"type": "conversation"}, + {"page": "1", "limit": "50", "sort": "created_at", "order": "desc"}, + ), + ( + "get_memory_bank_stats", + ("mb1",), + {"days": 14, "start_date": "2026-10-01", "end_date": "2026-10-14"}, + "/memory_banks/mb1/stats", + {"days": "14", "start_date": "2026-10-01", "end_date": "2026-10-14"}, + {}, + ), + ( + "get_model_recommendations", + ("m1",), + { + "require_tool_use": True, + "require_structured_output": False, + "require_thinking": True, + "min_context_tokens": 100000, + "min_output_tokens": 8000, + }, + "/models/m1/recommendations", + { + "require_tool_use": "true", + "require_structured_output": "false", + "require_thinking": "true", + "min_context_tokens": "100000", + "min_output_tokens": "8000", + }, + {}, + ), + ( + "list_models", + (), + {"supports_input_media": "image", "supports_output_media": "audio/mpeg"}, + "/models", + {"supports_input_media": "image", "supports_output_media": "audio/mpeg"}, + {}, + ), + ( + "list_solutions", + (), + {"search": "billing"}, + "/solutions", + {"search": "billing"}, + {"page": "1", "limit": "50", "sort": "created_at", "order": "desc"}, + ), +] + +_FILTER_IDS = [case[0] for case in _QUERY_FILTERS] + + +class TestDeclaredQueryFilters: + """Every query param the spec declares on these endpoints is sent as given.""" + + @pytest.mark.parametrize( + "name,args,kwargs,path,added,default", _QUERY_FILTERS, ids=_FILTER_IDS + ) + def test_sends_filters( + self, + name: str, + args: tuple[str, ...], + kwargs: dict[str, Any], + path: str, + added: dict[str, str], + default: dict[str, str], + ) -> None: + seen: dict[str, Any] = {} + client = _sync_client(_recording_handler(seen, {"data": []})) + getattr(client, name)(*args, **kwargs) + assert seen["method"] == "GET" + assert seen["path"] == path + assert dict(seen["query"]) == {**default, **added} + + @pytest.mark.parametrize( + "name,args,kwargs,path,added,default", _QUERY_FILTERS, ids=_FILTER_IDS + ) + def test_unset_filters_leave_the_request_unchanged( + self, + name: str, + args: tuple[str, ...], + kwargs: dict[str, Any], + path: str, + added: dict[str, str], + default: dict[str, str], + ) -> None: + seen: dict[str, Any] = {} + client = _sync_client(_recording_handler(seen, {"data": []})) + getattr(client, name)(*args) + assert seen["path"] == path + assert dict(seen["query"]) == default + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "name,args,kwargs,path,added,default", _QUERY_FILTERS, ids=_FILTER_IDS + ) + async def test_async_sends_filters( + self, + name: str, + args: tuple[str, ...], + kwargs: dict[str, Any], + path: str, + added: dict[str, str], + default: dict[str, str], + ) -> None: + seen: dict[str, Any] = {} + sync_handler: Callable[[httpx.Request], httpx.Response] = _recording_handler( + seen, {"data": []} + ) + + async def handler(req: httpx.Request) -> httpx.Response: + return sync_handler(req) + + client = _async_client(handler) + await getattr(client, name)(*args, **kwargs) + assert seen["method"] == "GET" + assert seen["path"] == path + assert dict(seen["query"]) == {**default, **added} + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "name,args,kwargs,path,added,default", _QUERY_FILTERS, ids=_FILTER_IDS + ) + async def test_async_unset_filters_leave_the_request_unchanged( + self, + name: str, + args: tuple[str, ...], + kwargs: dict[str, Any], + path: str, + added: dict[str, str], + default: dict[str, str], + ) -> None: + seen: dict[str, Any] = {} + sync_handler: Callable[[httpx.Request], httpx.Response] = _recording_handler( + seen, {"data": []} + ) + + async def handler(req: httpx.Request) -> httpx.Response: + return sync_handler(req) + + client = _async_client(handler) + await getattr(client, name)(*args) + assert seen["path"] == path + assert dict(seen["query"]) == default + + def test_non_manual_summary_without_agent_is_account_wide(self) -> None: + seen: dict[str, Any] = {} + client = _sync_client(_recording_handler(seen, {})) + client.get_non_manual_evaluation_summary(days=7) + assert seen["path"] == "/agents/evaluation-results/non-manual-summary" + assert dict(seen["query"]) == {"days": "7"} + + @pytest.mark.asyncio + async def test_async_non_manual_summary_without_agent_is_account_wide( + self, + ) -> None: + seen: dict[str, Any] = {} + sync_handler: Callable[[httpx.Request], httpx.Response] = _recording_handler( + seen, {} + ) + + async def handler(req: httpx.Request) -> httpx.Response: + return sync_handler(req) + + client = _async_client(handler) + await client.get_non_manual_evaluation_summary() + assert seen["path"] == "/agents/evaluation-results/non-manual-summary" + assert dict(seen["query"]) == {}