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/.gitignore b/.gitignore index c68891c..fb167d7 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ build .DS_Store .version-backup.json .README.md.bak +__pycache__ diff --git a/CHANGELOG.md b/CHANGELOG.md index 8358b0f..4476bc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## [1.8.0] - 2026-10-31 + +### Changed + +- Sync the bundled OpenAPI spec and regenerate the types. Existing responses gain properties: `decision` on `AgentRunStepResponse`, `created_resources`, `solution_id` and the run and credit limits `max_runs_total`, `max_runs_per_day`, `max_runs_per_hour`, `max_credits_per_run` and `max_credits_per_period` on `AgentSummaryResponse`, `max_credits_per_period`, `spend_cap_action`, `spend_cap_delete_order` and `spend_cap_reached` on `SourceResponse`, and `release_waiting_reason` on `SourceContentStatusResponse` +- Move `SeclaiApiVersion.Latest` to `2026-10-28`. Nothing is sent unless `apiVersion` is set, so a client that passes `SeclaiApiVersion.Latest` now opts into `2026-10-28`: an `if_else` or `switch` step's `output` is the result of the arm it took, where it was a `{"branch": ...}` marker naming the arm. Read the arm from the step's new `decision`, which is set on every version +- Mark `severity` on `listAlerts()` deprecated. It has never been sent, because `GET /alerts` has no severity filter + +### Added + +- Add `listAgentExamples()` for the agent gallery, searchable with `query` and filterable by `useCase`, returning typed `AgentExample` entries with the `resources` each needs, and accept `agent_template` entries from it on `createAgent()` with `resource_bindings` and `create_missing_resources` +- Add `setSlackTriggerConfig()` to configure an agent's `SLACK_COMMAND` trigger: its Slack connection, form, channels, activation, reply visibility and conversation settings +- Accept the run and credit limits on `updateAgent()`: `max_runs_total`, `max_runs_per_day`, `max_runs_per_hour`, `max_credits_per_run` and `max_credits_per_period`, a `set_max_*` flag for each to remove it, and `apply_import_run_limits` +- Accept a spend limit on `updateSource()`: `max_credits_per_period`, `spend_cap_action` and `spend_cap_delete_order` +- Accept the query filters the API declares and no method sent: `status`, `flaggedOnly`, `timeFrom` and `timeTo` on `listEvaluationResults()` and `listAgentEvaluationResults()`, which also takes `step`; `status`, `step`, `timeFrom` and `timeTo` on `listEvaluationRuns()`; `startedAfter` on `listCompatibleRuns()`; `days`, `startDate` and `endDate` on `getNonManualEvaluationSummary()` and `getMemoryBankStats()` (each method documents how the dates combine with `days`); `limit` and `offset` on `getMemoryBankAiLastConversation()` and `getAiAssistantMemoryBankHistory()`; `agentId`, `sourceConnectionId`, `timeFrom` and `timeTo` on `listAlerts()`; `agentId`, `sourceConnectionId` and `scope` on `listAlertConfigs()`; `organizationId` and `includeDefaults` on `listOrganizationAlertPreferences()`; `limit` on `listGovernanceAiConversations()`; `type` on `listMemoryBanks()`; `agentId` and `unreadOnly` on `listModelAlerts()`; `requireToolUse`, `requireStructuredOutput`, `requireThinking`, `minContextTokens` and `minOutputTokens` on `getModelRecommendations()`; and `search` on `listSolutions()` +- Let `getNonManualEvaluationSummary()` omit `agentId` for the account-wide summary +- Add the `SeclaiApiVersion.V2026_10_28` constant, so that version is accepted as `apiVersion` +- Add the type exports `AgentExampleListResponse`, `AgentExample`, `AgentExampleResource`, `SetSlackTriggerConfigRequest`, `SlackTriggerConfigResponse`, `SlackTriggerActivation`, `SlackTriggerScope`, `SlackReplyVisibility`, `SpendCapAction` and `SpendCapDeleteOrder`, and the option types `ListAgentExamplesOptions`, `ListEvaluationResultsOptions`, `ListAgentEvaluationResultsOptions`, `ListEvaluationRunsOptions`, `ListCompatibleRunsOptions`, `DateRangeOptions`, `OffsetPageOptions`, `ListAlertsOptions`, `ListAlertConfigsOptions`, `ListOrganizationAlertPreferencesOptions`, `ListMemoryBanksOptions`, `ListModelAlertsOptions`, `ModelRecommendationsOptions` and `ListSolutionsOptions` + +### Fixed + +- Make every field of `UpdateAgentRequest` optional. `updateAgent()` required `set_default_evaluation_tier`, `set_prompt_model_auto_rollback_triggers` and `set_sampling_config`, which the server defaults to `false`, so `updateAgent(id, { name })` did not compile +- Make server-defaulted fields optional on the request types that required them, so a call can leave them to the server: `description` on `CreateSolutionRequest` (`createSolution({ name })` did not compile), `priority` on `AgentRunRequest`, `enabled` and `distribution_type` on `CreateAlertConfigRequest`, `mode`, `type` and `strip_quoted_reply_chains` on `CreateMemoryBankBody`, `enabled` and `pass_threshold` on `CreateEvaluationCriteriaRequest`, `flagged`, `retry_count` and `retry_triggered` on `CreateEvaluationResultRequest`, `content_type` on `InlineTextUploadRequest` and `InlineTextReplaceRequest`, `entry_count` on `TestCompactionRequest`, `entry_count` and `bank_type` on `StandaloneTestCompactionRequest`, `match_type` on `BlockEmailSenderRequest`, `delegated` on `AddEmailDomainRequest`, `mode` on `GenerateAgentStepsRequest`, `pass_threshold` on `TestDraftEvaluationRequest`, `top_n` on `AgentTraceSearchRequest`, `confirm_deletions` on `AiAssistantAcceptRequest`, and the playground settings on `PlaygroundCreateRequest`. Response types are unchanged + ## [1.7.0] - 2026-10-21 ### Changed @@ -246,6 +270,7 @@ _Stable release. No functional changes since 0.0.1._ _Initial release._ +[1.8.0]: https://github.com/seclai/seclai-javascript/releases/tag/1.8.0 [1.7.0]: https://github.com/seclai/seclai-javascript/releases/tag/1.7.0 [1.6.1]: https://github.com/seclai/seclai-javascript/releases/tag/1.6.1 [1.6.0]: https://github.com/seclai/seclai-javascript/releases/tag/1.6.0 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4d144a0 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,6 @@ +# seclai-javascript + +## 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 183a515..66ed44f 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ Leave `apiVersion` unset and the header is omitted, so the account's pinned baseline applies and responses keep their current shapes. Upgrading this package alone never changes the wire contract. -Known versions are on `SeclaiApiVersion` (`V2026_07_01` through `V2026_10_21`, +Known versions are on `SeclaiApiVersion` (`V2026_07_01` through `V2026_10_28`, plus `Default` and `Latest`), imported from `@seclai/sdk`. A version this release was **not** built against throws at construction: a newer version can reshape responses, and this client would decode them incorrectly rather than reject them. @@ -188,6 +188,8 @@ a request that used to succeed, or (from `2026-10-21`) which fields can be - `2026-10-21` changes evaluation numbers you may be reading: an `error` result no longer counts as `failed` or toward the rates, and `testDraftEvaluation()` returns `null` `score` and `passed` for one. +- `2026-10-28` changes what an `if_else` or `switch` step's `output` contains. + Read the arm it took from the step's `decision`, which is set on every version. | Version | What it changes | | --- | --- | @@ -202,6 +204,7 @@ a request that used to succeed, or (from `2026-10-21`) which fields can be | `2026-10-18` | A source's `document_images` defaults to `true` on every embedder. Below it it defaults to `false` on a text-only embedder | | `2026-10-19` | `createSource()` rejects `polling_max_items` on any source type but an RSS feed with a 400. Below it the value is stored | | `2026-10-21` | An evaluation result whose evaluator returned no verdict (`error`) is left out of `failed` and of `pass_rate` / `failure_rate` in `getNonManualEvaluationSummary()`, and `getEvaluationCriteriaSummary()` averages `average_score` over passed and failed results only. `testDraftEvaluation()` returns `score` and `passed` as `null` for an `error` result. Below it the summary counts `error` results in `failed` and the rates, `average_score` includes their stored scores, and the test draft returns `score` 0.5 and `passed: false`. The summary's `error` count is returned on every version | +| `2026-10-28` | An `if_else` or `switch` step's `output` is the result of the arm it took, or its input when that arm is empty or it took none. Below it the `output` is a `{"branch": ...}` marker naming the arm, with no `attachments`. The step's `decision` names the arm on every version | **`Latest` moves with the SDK.** `SeclaiApiVersion.Latest` is the newest version the installed release knows, so upgrading the package can opt a client that @@ -209,7 +212,8 @@ passes it into every version added since — `1.6.0` moved it from `2026-07-27` `2026-10-03`, across the `2026-09-30` output change, and `1.7.0` moves it to `2026-10-21`, across the `2026-10-05` status change, the `2026-10-13` and `2026-10-19` source-setting rejections, the `2026-10-16` input change and the -`2026-10-21` evaluation change. Pass a +`2026-10-21` evaluation change, and `1.8.0` moves it to `2026-10-28`, +across the `if_else` / `switch` step-output change. Pass a dated constant such as `SeclaiApiVersion.V2026_07_27` to keep behaviour fixed across upgrades. @@ -270,6 +274,10 @@ const fetched = await client.getAgent("agent_id"); const updated = await client.updateAgent("agent_id", { name: "Renamed" }); await client.deleteAgent("agent_id"); +// Run and credit limits. To remove one, send its set_max_* flag and omit the value. +await client.updateAgent("agent_id", { max_runs_per_hour: 60, max_credits_per_period: 500 }); +await client.updateAgent("agent_id", { set_max_runs_per_hour: true }); + // Pause / resume — a disabled agent stops firing from every trigger path const callers = await client.getAgentCallers("agent_id"); // live agents calling this one await client.disableAgent("agent_id"); // 409 if any caller above is still live @@ -299,6 +307,31 @@ const imported = await client.createAgent({ // `imported.import_warnings` lists any items that couldn't be applied. ``` +### Agent examples + +The agent gallery lists example agents to start from. Pass an entry's `key` as +`agent_template` to `createAgent()`. Bind each resource the template needs with +`resource_bindings`, or set `create_missing_resources` to have the API create the +ones you leave out; `created_resources` reports what it made. + + +```ts +const examples = await client.listAgentExamples({ query: "support", useCase: "customer_support", limit: 10 }); +const example = examples.data[0]; +console.log(example.key, example.title, examples.pagination.total); +for (const slot of example.resources) { + console.log(slot.slot, slot.kind, slot.creatable); // what resource_bindings can bind +} + +const agent = await client.createAgent({ + name: "Support triage", + agent_template: example.key, + resource_bindings: { [example.resources[0].slot]: "kb_id" }, + create_missing_resources: true, +}); +console.log(agent.created_resources); // { slot: resource_id } for each resource it created +``` + ### Agent runs ```ts @@ -429,6 +462,28 @@ Set `run_on_attachment_mismatch: true` to run an email whose attachments do not fit what the agent accepts: files it cannot take are left out and the problems are listed in the run's `email_attachment_issues` metadata. By default the run fails. +### Agent Slack triggers + +Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack with +`/seclai` or the message shortcut. Omitted fields are left unchanged. + + +```ts +const slack = await client.setSlackTriggerConfig("agent_id", "trigger_id", { + scope: "selected_channels", // or "bot_channels" + channel_ids: ["C0123456789"], + activation: "everywhere", // or "channel_opt_in" + visibility: "private", // or "channel" + allow_dms: true, + turns_enabled: true, // let people keep the conversation going + max_turns: 5, + form: [{ key: "ticket", label: "Ticket ID", type: "short_text", required: true }], +}); +console.log(slack.missing_scopes); // Slack scopes the connection lacks for optional features +``` + +Each form value reaches the run as `{{metadata.}}`. + ### Accepted attachments Declare the input attachments a trigger accepts. A run's files are each assigned @@ -503,18 +558,21 @@ const draft = await client.testDraftEvaluation("agent_id", { step_output: "...", if (draft.status !== "error") console.log(draft.score, draft.passed); // Results by criteria -const results = await client.listEvaluationResults("criteria_id"); +const results = await client.listEvaluationResults("criteria_id", { flaggedOnly: true, timeFrom: "2026-10-01T00:00:00Z" }); const summary = await client.getEvaluationCriteriaSummary("criteria_id"); await client.createEvaluationResult("criteria_id", { ... }); // Results by run const runResults = await client.listRunEvaluationResults("agent_id", "run_id"); +const agentResults = await client.listAgentEvaluationResults("agent_id", { status: "failed", step: "step_id" }); +const evalRuns = await client.listEvaluationRuns("agent_id", { timeFrom: "2026-10-01T00:00:00Z" }); -// Non-manual evaluation summary -const nonManual = await client.getNonManualEvaluationSummary("agent_id"); +// Non-manual evaluation summary, for one agent or the whole account +const nonManual = await client.getNonManualEvaluationSummary("agent_id", { days: 7 }); +const accountWide = await client.getNonManualEvaluationSummary(undefined, { startDate: "2026-10-01", endDate: "2026-10-31" }); // Compatible runs for a criteria -const compatible = await client.listCompatibleRuns("criteria_id"); +const compatible = await client.listCompatibleRuns("criteria_id", { startedAfter: "2026-10-01T00:00:00Z" }); ``` ### Knowledge bases @@ -530,14 +588,14 @@ await client.deleteKnowledgeBase("kb_id"); ### Memory banks ```ts -const banks = await client.listMemoryBanks(); +const banks = await client.listMemoryBanks({ type: "conversation" }); const bank = await client.createMemoryBank({ name: "Chat Memory", type: "conversation" }); const fetched = await client.getMemoryBank("mb_id"); await client.updateMemoryBank("mb_id", { name: "Renamed" }); await client.deleteMemoryBank("mb_id"); // Stats & compaction -const stats = await client.getMemoryBankStats("mb_id"); +const stats = await client.getMemoryBankStats("mb_id", { startDate: "2026-10-01", endDate: "2026-10-31" }); await client.compactMemoryBank("mb_id"); // Test compaction @@ -550,7 +608,7 @@ const agents = await client.getAgentsUsingMemoryBank("mb_id"); // AI assistant const suggestion = await client.generateMemoryBankConfig({ user_input: "..." }); -const history = await client.getMemoryBankAiLastConversation(); +const history = await client.getMemoryBankAiLastConversation({ limit: 5 }); await client.acceptMemoryBankAiSuggestion("conv_id", { ... }); // Source management @@ -567,6 +625,21 @@ await client.updateSource("source_id", { name: "Renamed" }); await client.deleteSource("source_id"); ``` +A spend limit caps the credits a source may commit per billing period. When it is +reached, `stop` refuses new uploads and email, and `delete` removes entries in +`spend_cap_delete_order` to make room. Send `null` to remove the limit. + + +```ts +const capped = await client.updateSource("source_id", { + max_credits_per_period: 1000, + spend_cap_action: "delete", + spend_cap_delete_order: "oldest_published", +}); +console.log(capped.spend_cap_reached); +await client.updateSource("source_id", { max_credits_per_period: null }); +``` + Indexing status of a source's content, keyed by the `content_version_id` the upload methods return: @@ -728,7 +801,7 @@ const bytes = new Uint8Array(await file.arrayBuffer()); ### Solutions ```ts -const solutions = await client.listSolutions(); +const solutions = await client.listSolutions({ search: "billing" }); const sol = await client.createSolution({ name: "My Solution" }); const fetched = await client.getSolution("solution_id"); await client.updateSolution("solution_id", { name: "Renamed" }); @@ -761,7 +834,7 @@ await client.markSolutionConversationTurn("solution_id", "conversation_id", { .. ```ts const plan = await client.generateGovernanceAiPlan({ user_input: "Add a toxicity policy" }); -const convs = await client.listGovernanceAiConversations(); +const convs = await client.listGovernanceAiConversations({ limit: 10 }); await client.acceptGovernanceAiPlan("conversation_id"); await client.declineGovernanceAiPlan("conversation_id"); ``` @@ -769,7 +842,7 @@ await client.declineGovernanceAiPlan("conversation_id"); ### Alerts ```ts -const alerts = await client.listAlerts({ status: "active" }); +const alerts = await client.listAlerts({ status: "active", agentId: "agent_id", timeFrom: "2026-10-01T00:00:00Z" }); const alert = await client.getAlert("alert_id"); await client.changeAlertStatus("alert_id", { status: "resolved" }); await client.addAlertComment("alert_id", { text: "Investigating" }); @@ -779,14 +852,14 @@ await client.subscribeToAlert("alert_id"); await client.unsubscribeFromAlert("alert_id"); // Alert configs -const configs = await client.listAlertConfigs(); +const configs = await client.listAlertConfigs({ agentId: "agent_id" }); await client.createAlertConfig({ ... }); await client.getAlertConfig("config_id"); await client.updateAlertConfig("config_id", { ... }); await client.deleteAlertConfig("config_id"); // Organization preferences -const prefs = await client.listOrganizationAlertPreferences(); +const prefs = await client.listOrganizationAlertPreferences({ includeDefaults: true }); await client.updateOrganizationAlertPreference("org_id", "alert_type", { ... }); ``` @@ -807,11 +880,11 @@ const embedders = await client.listEmbeddingModels({ supportsInputMedia: "image" const rerankers = await client.listRerankerModels(); console.log(embedders.models, embedders.default_model_type, rerankers.models); -const alerts = await client.listModelAlerts(); +const alerts = await client.listModelAlerts({ unreadOnly: true }); await client.markModelAlertRead("alert_id"); await client.markAllModelAlertsRead(); const unread = await client.getUnreadModelAlertCount(); -const recs = await client.getModelRecommendations("model_id"); +const recs = await client.getModelRecommendations("model_id", { requireToolUse: true, minContextTokens: 100_000 }); // Model playground experiments const experiment = await client.createExperiment({ 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/src/client.ts b/src/client.ts index 038541c..51cb2d2 100644 --- a/src/client.ts +++ b/src/client.ts @@ -178,6 +178,23 @@ import type { UpdateSolutionRequest, UpdateSourceBody, UploadAgentInputApiResponse, + AgentExampleListResponse, + ListAgentExamplesOptions, + SetSlackTriggerConfigRequest, + SlackTriggerConfigResponse, + ListSolutionsOptions, + ListMemoryBanksOptions, + ListEvaluationResultsOptions, + ListAgentEvaluationResultsOptions, + ListEvaluationRunsOptions, + ListCompatibleRunsOptions, + DateRangeOptions, + OffsetPageOptions, + ListAlertsOptions, + ListAlertConfigsOptions, + ListOrganizationAlertPreferencesOptions, + ListModelAlertsOptions, + ModelRecommendationsOptions, } from "./types"; /** Default API base URL (can be overridden with `baseUrl` or `SECLAI_API_URL`). */ @@ -917,6 +934,21 @@ export class Seclai { })) as AgentListResponse; } + /** + * List the agent gallery: example agents to start from. + * + * Pass an entry's `key` as `agent_template` to {@link createAgent}, with + * `resource_bindings` for the resources it needs. + * + * @param opts - Text search, use-case filter and pagination. + * @returns A page of gallery entries. + */ + async listAgentExamples(opts: ListAgentExamplesOptions = {}): Promise { + return (await this.request("GET", "/agents/examples", { + query: { query: opts.query, use_case: opts.useCase, page: opts.page, limit: opts.limit }, + })) as AgentExampleListResponse; + } + /** * Create a new agent. * @@ -1735,12 +1767,22 @@ export class Seclai { * List evaluation results for a specific criteria. * * @param criteriaId - Criteria identifier. - * @param opts - Pagination options. + * @param opts - Pagination, status, flag and time-range filters. */ - async listEvaluationResults(criteriaId: string, opts: ListOptions = {}): Promise { + async listEvaluationResults( + criteriaId: string, + opts: ListEvaluationResultsOptions = {}, + ): Promise { return keyedList( await this.request("GET", `/agents/evaluation-criteria/${criteriaId}/results`, { - query: { page: opts.page, limit: opts.limit }, + query: { + page: opts.page, + limit: opts.limit, + status: opts.status, + flagged_only: opts.flaggedOnly, + time_from: opts.timeFrom, + time_to: opts.timeTo, + }, }), "data", PAGE_COUNTERS, @@ -1762,12 +1804,12 @@ export class Seclai { * List runs compatible with a specific evaluation criteria. * * @param criteriaId - Criteria identifier. - * @param opts - Pagination options. + * @param opts - Pagination and a `startedAfter` filter. */ - async listCompatibleRuns(criteriaId: string, opts: ListOptions = {}): Promise { + async listCompatibleRuns(criteriaId: string, opts: ListCompatibleRunsOptions = {}): Promise { return keyedList( await this.request("GET", `/agents/evaluation-criteria/${criteriaId}/compatible-runs`, { - query: { page: opts.page, limit: opts.limit }, + query: { page: opts.page, limit: opts.limit, started_after: opts.startedAfter }, }), "data", PAGE_COUNTERS, @@ -1789,12 +1831,23 @@ export class Seclai { * List all evaluation results for an agent. * * @param agentId - Agent identifier. - * @param opts - Pagination options. + * @param opts - Pagination, status, step, flag and time-range filters. */ - async listAgentEvaluationResults(agentId: string, opts: ListOptions = {}): Promise { + async listAgentEvaluationResults( + agentId: string, + opts: ListAgentEvaluationResultsOptions = {}, + ): Promise { return keyedList( await this.request("GET", `/agents/${agentId}/evaluation-results`, { - query: { page: opts.page, limit: opts.limit }, + query: { + page: opts.page, + limit: opts.limit, + status: opts.status, + step: opts.step, + flagged_only: opts.flaggedOnly, + time_from: opts.timeFrom, + time_to: opts.timeTo, + }, }), "data", PAGE_COUNTERS, @@ -1805,12 +1858,19 @@ export class Seclai { * List evaluation run summaries for an agent. * * @param agentId - Agent identifier. - * @param opts - Pagination options. + * @param opts - Pagination, status, step and time-range filters. */ - async listEvaluationRuns(agentId: string, opts: ListOptions = {}): Promise { + async listEvaluationRuns(agentId: string, opts: ListEvaluationRunsOptions = {}): Promise { return keyedList( await this.request("GET", `/agents/${agentId}/evaluation-runs`, { - query: { page: opts.page, limit: opts.limit }, + query: { + page: opts.page, + limit: opts.limit, + status: opts.status, + step: opts.step, + time_from: opts.timeFrom, + time_to: opts.timeTo, + }, }), "data", PAGE_COUNTERS, @@ -1818,13 +1878,19 @@ export class Seclai { } /** - * Get a summary of non-manual evaluations across an agent's runs. + * Get a summary of non-manual evaluations, for one agent or the whole account. * - * @param agentId - Agent identifier. + * @param agentId - Agent identifier. Omit (pass `undefined`) for the account-wide summary. + * @param opts - Date range. `startDate` and `endDate` together set the range; + * `startDate` alone runs from it through today; otherwise the last `days` + * days apply (server default 30), and an `endDate` without `startDate` is ignored. */ - async getNonManualEvaluationSummary(agentId: string): Promise { + async getNonManualEvaluationSummary( + agentId?: string, + opts: DateRangeOptions = {}, + ): Promise { return (await this.request("GET", "/agents/evaluation-results/non-manual-summary", { - query: { agent_id: agentId }, + query: { agent_id: agentId, days: opts.days, start_date: opts.startDate, end_date: opts.endDate }, })) as NonManualEvaluationSummaryResponse; } @@ -1855,6 +1921,32 @@ export class Seclai { })) as EmailTriggerConfigResponse; } + // ═══════════════════════════════════════════════════════════════════════════ + // Agent Slack Triggers + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack + * with `/seclai` or the message shortcut. + * + * Sets the Slack connection, form, channels, reply visibility and conversation + * settings. Omitted fields are left unchanged. + * + * @param agentId - Agent identifier. + * @param triggerId - Trigger identifier. + * @param body - The fields to set. + * @returns The trigger's full Slack config, including any `missing_scopes`. + */ + async setSlackTriggerConfig( + agentId: string, + triggerId: string, + body: SetSlackTriggerConfigRequest, + ): Promise { + return (await this.request("PUT", `/agents/${agentId}/triggers/${triggerId}/slack-config`, { + json: body, + })) as SlackTriggerConfigResponse; + } + /** * Replace the input attachments a trigger accepts. * @@ -1921,7 +2013,7 @@ export class Seclai { * @param opts.offset - Rows to skip (default 0). */ async listBlockedEmailSenders( - opts: { limit?: number; offset?: number } = {}, + opts: OffsetPageOptions = {}, ): Promise { return keyedList( await this.request("GET", "/agents/blocked-email-senders", { @@ -2092,13 +2184,13 @@ export class Seclai { /** * List memory banks. * - * @param opts - Pagination and sorting options. + * @param opts - Pagination, sorting and a `type` filter. * @returns Paginated list of memory banks. */ - async listMemoryBanks(opts: SortableListOptions = {}): Promise { + async listMemoryBanks(opts: ListMemoryBanksOptions = {}): Promise { return keyedList( await this.request("GET", "/memory_banks", { - query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order }, + query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order, type: opts.type }, }), "memory_banks", PAGE_COUNTERS, @@ -2161,9 +2253,13 @@ export class Seclai { * Get stats for a memory bank. * * @param memoryBankId - Memory bank identifier. + * @param opts - Date range. Only `startDate` and `endDate` together replace + * `days`; either one alone is ignored and the last `days` days apply (server default 30). */ - async getMemoryBankStats(memoryBankId: string): Promise { - return await this.request("GET", `/memory_banks/${memoryBankId}/stats`); + async getMemoryBankStats(memoryBankId: string, opts: DateRangeOptions = {}): Promise { + return await this.request("GET", `/memory_banks/${memoryBankId}/stats`, { + query: { days: opts.days, start_date: opts.startDate, end_date: opts.endDate }, + }); } /** @@ -2224,9 +2320,13 @@ export class Seclai { /** * Get the last AI conversation for memory banks. + * + * @param opts - Turns to return (server default 5) and most-recent turns to skip (default 0). */ - async getMemoryBankAiLastConversation(): Promise { - return (await this.request("GET", "/memory_banks/ai-assistant/last-conversation")) as MemoryBankLastConversationResponse; + async getMemoryBankAiLastConversation(opts: OffsetPageOptions = {}): Promise { + return (await this.request("GET", "/memory_banks/ai-assistant/last-conversation", { + query: { limit: opts.limit, offset: opts.offset }, + })) as MemoryBankLastConversationResponse; } /** @@ -2710,12 +2810,12 @@ export class Seclai { /** * List solutions. * - * @param opts - Pagination and sorting options. + * @param opts - Pagination, sorting and a name `search`. * @returns Paginated list of solutions. */ - async listSolutions(opts: SortableListOptions = {}): Promise { + async listSolutions(opts: ListSolutionsOptions = {}): Promise { return (await this.request("GET", "/solutions", { - query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order }, + query: { page: opts.page, limit: opts.limit, sort: opts.sort, order: opts.order, search: opts.search }, })) as SolutionListResponse; } @@ -2936,10 +3036,12 @@ export class Seclai { /** * List governance AI conversations. + * + * @param opts - `limit`: how many conversations (the server defaults to 20). */ - async listGovernanceAiConversations(): Promise { + async listGovernanceAiConversations(opts: { limit?: number } = {}): Promise { return listItems( - await this.request("GET", "/governance/ai-assistant/conversations"), + await this.request("GET", "/governance/ai-assistant/conversations", { query: { limit: opts.limit } }), ); } @@ -2972,13 +3074,21 @@ export class Seclai { * @param opts - Pagination and filter options. * @returns Paginated list of alerts. */ - async listAlerts(opts: ListOptions & { status?: string; severity?: string } = {}): Promise { + async listAlerts(opts: ListAlertsOptions = {}): Promise { // `severity` is deliberately not forwarded: GET /alerts declares no such // filter, so it never filtered anything, and sending it is a 422 once // `apiVersion` is 2026-07-27 or later. Accepted and dropped so existing // call sites keep working. return (await this.request("GET", "/alerts", { - query: { page: opts.page, limit: opts.limit, status: opts.status }, + query: { + page: opts.page, + limit: opts.limit, + status: opts.status, + agent_id: opts.agentId, + source_connection_id: opts.sourceConnectionId, + time_from: opts.timeFrom, + time_to: opts.timeTo, + }, })) as AlertListResponse; } @@ -3042,9 +3152,17 @@ export class Seclai { * `configs` and `total` are populated on every API version; `data` and * `pagination` are also present once `apiVersion` is 2026-07-27 or later. */ - async listAlertConfigs(opts: ListOptions = {}): Promise { + async listAlertConfigs(opts: ListAlertConfigsOptions = {}): Promise { return keyedList( - await this.request("GET", "/alerts/configs", { query: { page: opts.page, limit: opts.limit } }), + await this.request("GET", "/alerts/configs", { + query: { + page: opts.page, + limit: opts.limit, + agent_id: opts.agentId, + source_connection_id: opts.sourceConnectionId, + scope: opts.scope, + }, + }), "configs", ["total"], ); @@ -3094,10 +3212,16 @@ export class Seclai { /** * List organization alert preferences. + * + * @param opts - Organization filter, and whether to include default subscriptions. */ - async listOrganizationAlertPreferences(): Promise { + async listOrganizationAlertPreferences( + opts: ListOrganizationAlertPreferencesOptions = {}, + ): Promise { return keyedList( - await this.request("GET", "/alerts/organization-preferences/list"), + await this.request("GET", "/alerts/organization-preferences/list", { + query: { organization_id: opts.organizationId, include_defaults: opts.includeDefaults }, + }), "preferences", ["total"], ); @@ -3129,15 +3253,17 @@ export class Seclai { /** * List model alerts. * - * @param opts - Pagination options. + * @param opts - Pagination, an agent filter and `unreadOnly`. */ - async listModelAlerts(opts: ListOptions = {}): Promise { + async listModelAlerts(opts: ListModelAlertsOptions = {}): Promise { // The endpoint declares limit/offset, not page, so `page` was ignored and // every page after the first returned page 1. const limit = opts.limit ?? 50; const offset = opts.page && opts.page > 1 ? (opts.page - 1) * limit : undefined; return keyedList( - await this.request("GET", "/models/alerts", { query: { offset, limit: opts.limit } }), + await this.request("GET", "/models/alerts", { + query: { offset, limit: opts.limit, agent_id: opts.agentId, unread_only: opts.unreadOnly }, + }), "alerts", ["total"], ); @@ -3170,9 +3296,21 @@ export class Seclai { * Get model recommendations. * * @param modelId - Model identifier. + * @param opts - Capabilities and limits a recommended model must have. */ - async getModelRecommendations(modelId: string): Promise { - return (await this.request("GET", `/models/${modelId}/recommendations`)) as ModelRecommendationsResponse; + async getModelRecommendations( + modelId: string, + opts: ModelRecommendationsOptions = {}, + ): Promise { + return (await this.request("GET", `/models/${modelId}/recommendations`, { + query: { + require_tool_use: opts.requireToolUse, + require_structured_output: opts.requireStructuredOutput, + require_thinking: opts.requireThinking, + min_context_tokens: opts.minContextTokens, + min_output_tokens: opts.minOutputTokens, + }, + })) as ModelRecommendationsResponse; } /** @@ -3259,9 +3397,11 @@ export class Seclai { /** * List model playground experiments. * - * @param opts - Optional filters and pagination. + * @param opts - Date range and offset paging. Only `startDate` and `endDate` + * together replace `days`; either one alone is ignored and the last `days` + * days apply (server default 30). */ - async listExperiments(opts: { days?: number; startDate?: string; endDate?: string; limit?: number; offset?: number } = {}): Promise { + async listExperiments(opts: DateRangeOptions & OffsetPageOptions = {}): Promise { return keyedList( await this.request("GET", "/models/playground/experiments", { query: { days: opts.days, start_date: opts.startDate, end_date: opts.endDate, limit: opts.limit, offset: opts.offset }, @@ -3628,9 +3768,13 @@ export class Seclai { /** * Get AI assistant memory bank conversation history. + * + * @param opts - Turns to return (server default 5) and most-recent turns to skip (default 0). */ - async getAiAssistantMemoryBankHistory(): Promise { - return (await this.request("GET", "/ai-assistant/memory-bank/last-conversation")) as MemoryBankLastConversationResponse; + async getAiAssistantMemoryBankHistory(opts: OffsetPageOptions = {}): Promise { + return (await this.request("GET", "/ai-assistant/memory-bank/last-conversation", { + query: { limit: opts.limit, offset: opts.offset }, + })) as MemoryBankLastConversationResponse; } /** diff --git a/src/index.ts b/src/index.ts index e8ae7ea..5d0a673 100644 --- a/src/index.ts +++ b/src/index.ts @@ -72,6 +72,20 @@ export type { PaginationResponse, ListOptions, SortableListOptions, + ListAgentExamplesOptions, + ListSolutionsOptions, + ListMemoryBanksOptions, + ListEvaluationResultsOptions, + ListAgentEvaluationResultsOptions, + ListEvaluationRunsOptions, + ListCompatibleRunsOptions, + DateRangeOptions, + OffsetPageOptions, + ListAlertsOptions, + ListAlertConfigsOptions, + ListOrganizationAlertPreferencesOptions, + ListModelAlertsOptions, + ModelRecommendationsOptions, // Identity MeResponse, @@ -79,6 +93,9 @@ export type { // Agents AgentListResponse, + AgentExampleListResponse, + AgentExample, + AgentExampleResource, AgentDefinitionResponse, AgentExportResponse, AgentSummaryResponse, @@ -97,6 +114,13 @@ export type { SetEmailTriggerConfigRequest, EmailTriggerConfigResponse, + // Agent Slack Triggers + SetSlackTriggerConfigRequest, + SlackTriggerConfigResponse, + SlackTriggerActivation, + SlackTriggerScope, + SlackReplyVisibility, + // Agent Email Governance AgentEmailOptOutResponse, AgentEmailOptOutListResponse, @@ -216,6 +240,8 @@ export type { SourceConnectionResponse, CreateSourceBody, UpdateSourceBody, + SpendCapAction, + SpendCapDeleteOrder, FileUploadResponse, InlineTextUploadRequest, InlineTextReplaceRequest, diff --git a/src/openapi.ts b/src/openapi.ts index b08e65c..4e4835e 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -27,11 +27,11 @@ export interface paths { * 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 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. @@ -314,6 +314,26 @@ export interface paths { patch?: never; trace?: never; }; + "/agents/examples": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List agent gallery examples + * @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. + */ + get: operations["list_agent_examples_api_agents_examples_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/agents/inbound-email-rejections": { parameters: { query?: never; @@ -508,12 +528,14 @@ export interface paths { get: operations["get_agent_metadata_api_agents__agent_id__get"]; /** * Update agent metadata - * @description Update an agent's name, description, evaluation settings, and model lifecycle settings. + * @description 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`, `sampling_config`. * * Model 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'). * + * 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, 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). * - `entity_remap: {source_uuid: target_uuid}` substitutes workflow entity refs before save (same shape as `POST /agents`). @@ -1143,6 +1165,28 @@ export interface paths { patch?: never; trace?: never; }; + "/agents/{agent_id}/triggers/{trigger_id}/slack-config": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Configure a SLACK_COMMAND trigger + * @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. + * + * Auth & scoping: requires `X-API-Key` header or OAuth Bearer token; the trigger must belong to an agent in the key's account. + */ + put: operations["set_slack_trigger_config_api_api_agents__agent_id__triggers__trigger_id__slack_config_put"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/agents/{agent_id}/upload-input": { parameters: { query?: never; @@ -1430,7 +1474,7 @@ export interface paths { * @description Create a new alert configuration. * * Agent 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. - * 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. * @@ -3481,6 +3525,8 @@ export interface paths { * @description Update a content source's configuration. Only provided fields are changed; omitted fields are left unchanged. * * 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. */ put: operations["update_source_api_sources__source_connection_id__put"]; /** @@ -4160,6 +4206,12 @@ export interface components { * @enum {string} */ AgentEvaluationTier: "fast" | "balanced" | "thorough"; + /** AgentExampleListResponse */ + AgentExampleListResponse: { + /** Data */ + data: unknown[]; + pagination: components["schemas"]["PaginationResponse"]; + }; /** * AgentExportResponse * @description Portable JSON snapshot of an agent definition. @@ -4167,7 +4219,7 @@ export interface components { AgentExportResponse: { /** * Agent - * @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. */ agent: { [key: string]: unknown; @@ -4437,6 +4489,11 @@ export interface components { * @description Credits consumed by this step across every attempt it made. Some charges made outside any step, such as governance screening of the run's input, count toward the run's total but no step's. The timestamps above and the tool calls below describe the latest attempt only. */ credits_used: number; + /** + * Decision + * @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. + */ + decision?: string | null; /** * Duration Seconds * @description Duration of the step attempt in seconds. @@ -4454,7 +4511,7 @@ export interface components { input: string | null; /** * Output - * @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`. */ output: string | null; /** @@ -4598,6 +4655,13 @@ export interface components { * @description ISO 8601 creation timestamp. */ created_at: string; + /** + * Created Resources + * @description On a create from an `agent_template`: {slot: resource_id} for each resource `create_missing_resources` created. + */ + created_resources?: { + [key: string]: string; + } | null; /** * Default Evaluation Tier * @description Default evaluation tier: fast, balanced, or thorough. @@ -4640,12 +4704,37 @@ export interface components { * @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. */ import_warnings?: components["schemas"]["ImportSkipResponse"][] | null; + /** + * Max Credits Per Period + * @description Credit limit per billing period; null when none. + */ + max_credits_per_period?: number | null; + /** + * Max Credits Per Run + * @description Credit limit per run; null when none. + */ + max_credits_per_run?: number | null; /** * Max Retries * @description Max retries for eval_and_retry mode. * @default 3 */ max_retries: number; + /** + * Max Runs Per Day + * @description Runs per day limit; null when none. + */ + max_runs_per_day?: number | null; + /** + * Max Runs Per Hour + * @description Runs per hour limit; null when none. + */ + max_runs_per_hour?: number | null; + /** + * Max Runs Total + * @description Limit on runs in total; null when none. + */ + max_runs_total?: number | null; /** * Name * @description Agent name. @@ -4681,6 +4770,11 @@ export interface components { sampling_config?: { [key: string]: unknown; } | null; + /** + * Solution Id + * @description On a create from an `agent_template` that created resources: the solution grouping the agent with them. + */ + solution_id?: string | null; /** * Trigger Id * @description ID of the agent's trigger, for the `/agents/{agent_id}/triggers/{trigger_id}/…` endpoints such as `accepted-attachments` and `email-config`. @@ -6164,7 +6258,7 @@ export interface components { id: 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. */ reason: string; /** @@ -7873,7 +7967,7 @@ export interface components { SetAcceptedAttachmentsRequest: { /** * Accepted Attachments - * @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. */ accepted_attachments: components["schemas"]["AcceptedAttachmentSlot"][] | null; }; @@ -7885,6 +7979,54 @@ export interface components { /** Mode */ mode: string; }; + /** + * SetSlackTriggerConfigApiRequest + * @description Omitted fields are left unchanged. + */ + SetSlackTriggerConfigApiRequest: { + /** @description `everywhere` in scope, or `channel_opt_in`. */ + activation?: components["schemas"]["SlackTriggerActivation"] | null; + /** + * Allow Dms + * @description Runnable in the app's own DMs. + */ + allow_dms?: boolean | null; + /** Channel Ids */ + channel_ids?: string[] | null; + /** + * Form + * @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.}}`. + */ + form?: { + [key: string]: unknown; + }[] | null; + /** Include Invoker Email */ + include_invoker_email?: boolean | null; + /** + * Input + * @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`. + */ + input?: string | null; + /** Max Turns */ + max_turns?: number | null; + /** + * Mcp Client Id + * @description The account's connected Slack (Bot) MCP client. + */ + mcp_client_id?: string | null; + /** Notify Failure After Answer */ + notify_failure_after_answer?: boolean | null; + /** @description `selected_channels` (see `channel_ids`) or `bot_channels`. */ + scope?: components["schemas"]["SlackTriggerScope"] | null; + /** Start Without Form */ + start_without_form?: boolean | null; + /** Turns Anyone */ + turns_anyone?: boolean | null; + /** Turns Enabled */ + turns_enabled?: boolean | null; + /** @description `channel`, or `private` (replies in the person's DM). */ + visibility?: components["schemas"]["SlackReplyVisibility"] | null; + }; /** * SkippedAttachmentReason * @enum {string} @@ -7913,6 +8055,69 @@ export interface components { */ size_bytes: number | null; }; + /** + * SlackReplyVisibility + * @enum {string} + */ + SlackReplyVisibility: "channel" | "private"; + /** + * SlackTriggerActivation + * @enum {string} + */ + SlackTriggerActivation: "everywhere" | "channel_opt_in"; + /** SlackTriggerConfigApiResponse */ + SlackTriggerConfigApiResponse: { + /** Activation */ + activation: string; + /** + * Agent Id + * Format: uuid + */ + agent_id: string; + /** Allow Dms */ + allow_dms: boolean; + /** Channel Ids */ + channel_ids: string[]; + /** Form */ + form: { + [key: string]: unknown; + }[]; + /** Include Invoker Email */ + include_invoker_email: boolean; + /** Max Turns */ + max_turns: number | null; + /** Mcp Client Id */ + mcp_client_id: string | null; + /** + * Missing Scopes + * @description Scopes the Slack connection lacks for optional features. + */ + missing_scopes: string[]; + /** Notify Failure After Answer */ + notify_failure_after_answer: boolean; + /** Scope */ + scope: string; + /** Slack Team Id */ + slack_team_id: string | null; + /** Start Without Form */ + start_without_form: boolean; + /** + * Trigger Id + * Format: uuid + */ + trigger_id: string; + /** Turns Anyone */ + turns_anyone: boolean; + /** Turns Enabled */ + turns_enabled: boolean; + /** Visibility */ + visibility: string; + }; + /** + * SlackTriggerScope + * @enum {string} + */ + SlackTriggerScope: "selected_channels" | "bot_channels"; /** SolutionSourceConnectionResponse */ SolutionSourceConnectionResponse: { /** @@ -8079,7 +8284,7 @@ export interface components { extracted_media_limit?: number | null; /** * Held For Review - * @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. * @default false */ held_for_review: boolean; @@ -8103,9 +8308,14 @@ export interface components { * @description Timestamp when the item was uploaded or pulled. */ pulled_at: string; + /** + * Release Waiting Reason + * @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. + */ + release_waiting_reason?: string | null; /** * Source Connection Content Version Id - * @description 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`. + * @description ID to pass to `GET /contents/{id}`. `null` while the item has no retrievable content. */ source_connection_content_version_id: string | null; /** @@ -8313,6 +8523,11 @@ export interface components { id: string; /** @description Index mode for custom_index sources: fast_and_cheap, balanced, slow_and_thorough, or custom. */ index_mode?: components["schemas"]["SourceIndexMode"] | null; + /** + * Max Credits Per Period + * @description The source's spend limit: credits it may commit per billing period. Null when it has none. + */ + max_credits_per_period?: number | null; /** * 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. @@ -8364,6 +8579,22 @@ export interface components { * @description Type of the source connection. */ source_type: string; + /** + * @description What the source does once it reaches its spend limit. + * @default stop + */ + spend_cap_action: components["schemas"]["SpendCapAction"]; + /** + * @description Which entries a `delete` spend limit removes first. + * @default oldest_added + */ + spend_cap_delete_order: components["schemas"]["SpendCapDeleteOrder"]; + /** + * Spend Cap Reached + * @description True while the spend limit refuses uploads and email to this source. + * @default false + */ + spend_cap_reached: boolean; /** * System Managed * @description Indicates if this source is automatically managed by the system (e.g., agent traces). @@ -8381,6 +8612,17 @@ export interface components { */ url: string | null; }; + /** + * SpendCapAction + * @enum {string} + */ + SpendCapAction: "stop" | "delete"; + /** + * SpendCapDeleteOrder + * @description Which entries a DELETE cap removes first. + * @enum {string} + */ + SpendCapDeleteOrder: "oldest_added" | "oldest_published" | "largest_first"; /** * StandaloneTestCompactionRequest * @description Request body for testing a compaction prompt *without* an existing bank. @@ -8793,6 +9035,11 @@ export interface components { * @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. */ feed_attachments?: string[] | null; + /** + * Max Credits Per Period + * @description 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. + */ + max_credits_per_period?: number | null; /** * Media Types * @description 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 and store the rest. A kind the source's embedder cannot index is stored and not indexed (see `supported_input_media` on GET /models/embedders). [] attaches no media from web pages. 'images' also covers the images inside PDF, DOCX, PPTX and XLSX files. Applies to pages and documents added after it changes. @@ -8813,6 +9060,10 @@ export interface components { * @description 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. */ retention_days?: number | 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_action?: components["schemas"]["SpendCapAction"] | null; + /** @description Which entries `delete` removes first: `oldest_added`, `oldest_published` or `largest_first`. */ + spend_cap_delete_order?: components["schemas"]["SpendCapDeleteOrder"] | null; }; /** UploadAgentInputApiResponse */ UploadAgentInputApiResponse: { @@ -9072,9 +9323,15 @@ export interface components { } | null; /** * Agent Template - * @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. */ agent_template?: string | null; + /** + * Create Missing Resources + * @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. + * @default false + */ + create_missing_resources: boolean; /** * Description * @description Optional description. @@ -9092,12 +9349,18 @@ export interface components { * @description Name for the new agent. */ name: string; + /** + * Resource Bindings + * @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. + */ + resource_bindings?: { + [key: string]: string; + } | null; /** * Trigger Type - * @description Trigger type: dynamic_input, template_input, schedule, new_content, email_received. - * @default dynamic_input + * @description Defaults to dynamic_input, or to the template's own trigger type for an `agent_template` without `agent_definition`. */ - trigger_type: string; + trigger_type?: string | null; }; /** * GovernancePolicyRefResponse @@ -9163,6 +9426,12 @@ export interface components { agent_definition?: { [key: string]: unknown; } | null; + /** + * Apply Import Run Limits + * @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. + * @default false + */ + apply_import_run_limits: boolean; /** * Default Evaluation Tier * @description Default evaluation tier: 'fast', 'balanced', or 'thorough'. @@ -9185,11 +9454,36 @@ export interface components { * @description Evaluation mode: 'output_expectation', 'eval_and_retry', or 'sample_and_flag'. */ evaluation_mode?: string | null; + /** + * Max Credits Per Period + * @description 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_period?: number | null; + /** + * Max Credits Per Run + * @description Credit limit per run: a run that reaches it is stopped before its next step. + */ + max_credits_per_run?: number | null; /** * Max Retries * @description Max retries for eval_and_retry mode (1-10). */ max_retries?: number | null; + /** + * Max Runs Per Day + * @description Runs per day; at most the plan's run quota. + */ + max_runs_per_day?: number | null; + /** + * Max Runs Per Hour + * @description Runs per hour; at most the plan's run quota. + */ + max_runs_per_hour?: number | null; + /** + * Max Runs Total + * @description Runs in total; once reached, new runs are refused. + */ + max_runs_total?: number | null; /** * Name * @description New name for the agent. @@ -9225,6 +9519,36 @@ export interface components { * @default false */ set_default_evaluation_tier: boolean; + /** + * Set Max Credits Per Period + * @description When true and max_credits_per_period is omitted, removes the limit. + * @default false + */ + set_max_credits_per_period: boolean; + /** + * Set Max Credits Per Run + * @description When true and max_credits_per_run is omitted, removes the limit. + * @default false + */ + set_max_credits_per_run: boolean; + /** + * Set Max Runs Per Day + * @description When true and max_runs_per_day is omitted, removes the limit. + * @default false + */ + set_max_runs_per_day: boolean; + /** + * Set Max Runs Per Hour + * @description When true and max_runs_per_hour is omitted, removes the limit. + * @default false + */ + set_max_runs_per_hour: boolean; + /** + * Set Max Runs Total + * @description When true and max_runs_total is omitted, removes the limit. + * @default false + */ + set_max_runs_total: boolean; /** * Set Prompt Model Auto Rollback Triggers * @description When true and prompt_model_auto_rollback_triggers is omitted, clears the list to null (revert to system defaults). @@ -11368,6 +11692,60 @@ export interface operations { }; }; }; + list_agent_examples_api_agents_examples_get: { + parameters: { + query?: { + /** @description Words every match must contain. */ + query?: string | null; + /** @description Only entries for this use case. */ + use_case?: string | null; + /** @description Page number */ + page?: number; + /** @description Items per page */ + limit?: number; + }; + header?: { + /** @description Target a different organization account (OAuth only). When omitted, the user's default account is used. Ignored for API key authentication — the key's account is always used. */ + "X-Account-Id"?: components["parameters"]["X-Account-Id"]; + /** @description Opt into dated, backward-incompatible API changes (format YYYY-MM-DD). When omitted, the account's pinned baseline version is used and responses keep their legacy shapes. Send a date on or after a change's release to adopt it — e.g. `2026-07-27` enables rejection of undeclared query parameters (422) and the canonical `{data, pagination}` envelope (pagination = `{page, limit, total, pages, has_next, has_prev}`) on every list endpoint that previously returned a bare array, a flat `{data, total, page, limit}`, a `{configs, total}`, or another per-resource key. */ + "Seclai-Version"?: components["parameters"]["Seclai-Version"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AgentExampleListResponse"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + /** @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. */ + 503: { + headers: { + /** @description Seconds to wait before retrying. Sent only with `database_unavailable`. */ + "Retry-After"?: number; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ServiceUnavailableError"]; + }; + }; + }; + }; list_inbound_email_rejections_api_api_agents_inbound_email_rejections_get: { parameters: { query?: { @@ -13065,6 +13443,58 @@ export interface operations { }; }; }; + set_slack_trigger_config_api_api_agents__agent_id__triggers__trigger_id__slack_config_put: { + parameters: { + query?: never; + header?: { + /** @description Target a different organization account (OAuth only). When omitted, the user's default account is used. Ignored for API key authentication — the key's account is always used. */ + "X-Account-Id"?: components["parameters"]["X-Account-Id"]; + /** @description Opt into dated, backward-incompatible API changes (format YYYY-MM-DD). When omitted, the account's pinned baseline version is used and responses keep their legacy shapes. Send a date on or after a change's release to adopt it — e.g. `2026-07-27` enables rejection of undeclared query parameters (422) and the canonical `{data, pagination}` envelope (pagination = `{page, limit, total, pages, has_next, has_prev}`) on every list endpoint that previously returned a bare array, a flat `{data, total, page, limit}`, a `{configs, total}`, or another per-resource key. */ + "Seclai-Version"?: components["parameters"]["Seclai-Version"]; + }; + path: { + agent_id: string; + trigger_id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["SetSlackTriggerConfigApiRequest"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["SlackTriggerConfigApiResponse"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + /** @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. */ + 503: { + headers: { + /** @description Seconds to wait before retrying. Sent only with `database_unavailable`. */ + "Retry-After"?: number; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ServiceUnavailableError"]; + }; + }; + }; + }; api_upload_agent_input_api_agents__agent_id__upload_input_post: { parameters: { query?: never; diff --git a/src/types.ts b/src/types.ts index 2f6bbc4..c520e8c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -9,6 +9,15 @@ */ import type { components } from "./openapi"; +/** + * `T` with the keys `K` optional. openapi-typescript marks every property that + * declares a `default` as required, which is right for a response (the server + * always sends it) and wrong for a request body (the server fills it in). Apply + * this to a request type's server-defaulted keys only; the test + * "request types leave server-defaulted fields optional" lists them from the spec. + */ +type WithServerDefaults = Omit & Partial>; + // ─── General ───────────────────────────────────────────────────────────────── /** JSON-serializable values accepted/returned by the SDK's low-level `request()` method. */ @@ -49,6 +58,73 @@ export type OrganizationInfoResponse = components["schemas"]["OrganizationInfoRe /** Paginated list of agents. */ export type AgentListResponse = components["schemas"]["routers__api__agents__AgentListResponse"]; +/** + * A page of the agent gallery. Each entry's `key` goes in `agent_template` on + * {@link CreateAgentRequest}, with `resource_bindings` for the resources it needs. + */ +export type AgentExampleListResponse = Omit & { + data: AgentExample[]; +}; + +/** + * A resource an {@link AgentExample} needs: bind it in `resource_bindings` under + * `slot`, or let `create_missing_resources` create it when `creatable`. + */ +export interface AgentExampleResource { + /** Slot name, the key in `resource_bindings`. */ + slot: string; + /** Resource kind: knowledge_base, memory_bank, source_connection, mcp_client or cloud_drive_connection. */ + kind: string; + /** Display name of the slot. */ + label: string; + /** What the slot is used for. */ + description: string; + /** The id that stands for this resource in `definition`. */ + placeholder: string; + /** Whether `create_missing_resources` can create it. When false it must be bound to an existing resource. */ + creatable: boolean; + /** For a memory_bank slot, the bank type a bound bank must have. */ + memory_bank_type: string | null; + /** Whether the steps in `definition` name this slot. */ + named_in_definition: boolean; + /** Whether the entry's trigger names this slot; it applies only when the agent keeps the entry's trigger type. */ + named_in_trigger: boolean; + /** Slots whose creation uses this one. */ + named_in_create_of: string[]; +} + +/** + * One agent gallery entry from {@link Seclai.listAgentExamples}. Pass `key` as + * `agent_template` on {@link CreateAgentRequest}. + * + * Typed by hand: the spec declares the list's items without a schema. + */ +export interface AgentExample { + /** Pass as `agent_template` when creating an agent. */ + key: string; + title: string; + summary: string; + use_cases: string[]; + tags: string[]; + /** Other `agent_template` values that create this entry. */ + aliases: string[]; + /** A request to the AI assistant that describes this agent. */ + prompt: string; + /** The trigger type the entry is built for. */ + trigger_type: string; + /** The date the entry was added to the gallery, `YYYY-MM-DD`. */ + created_at: string; + /** The template_input trigger's input, when the entry sets one. */ + trigger_input: string | null; + /** The template_input trigger's schedules, applied on create when the trigger type is the entry's own. */ + schedules: Record[]; + /** The trigger's declared attachment slots. Empty when the entry declares none. */ + accepted_attachments: Record[]; + resources: AgentExampleResource[]; + /** The agent definition, naming each resource by its placeholder. */ + definition: Record; +} + /** Full agent configuration including definition and metadata. */ export type AgentDefinitionResponse = components["schemas"]["AgentDefinitionResponse"]; @@ -65,12 +141,21 @@ export type AgentSummaryResponse = components["schemas"]["AgentSummaryResponse"] * server-defaulted `min` can be omitted. */ export type CreateAgentRequest = Omit< - components["schemas"]["routers__api__agents__CreateAgentRequest"], + WithServerDefaults, "accepted_attachments" -> & { accepted_attachments?: AcceptedAttachmentSlotInput[] | null }; +> & { + accepted_attachments?: AcceptedAttachmentSlotInput[] | null; +}; -/** Request body for updating an agent. */ -export type UpdateAgentRequest = components["schemas"]["routers__api__agents__UpdateAgentRequest"]; +/** + * Request body for updating an agent. Every field is optional. + * + * To remove a run or credit limit, send its `set_max_*` flag as `true` and omit + * the matching `max_*` field. The `set_*` flags and `apply_import_run_limits` + * default to `false` on the server; the generated schema marks them required + * only because they declare a default. + */ +export type UpdateAgentRequest = Partial; /** * Request body for updating an agent definition (steps, model, etc.). @@ -151,6 +236,27 @@ export type SetEmailTriggerConfigRequest = components["schemas"]["routers__api__ /** An `EMAIL_RECEIVED` trigger's resolved email address(es) and inbound-handling config. */ export type EmailTriggerConfigResponse = components["schemas"]["EmailTriggerConfigResponse"]; +// ─── Agent Slack Triggers ──────────────────────────────────────────────────── + +/** + * Request body for configuring a `SLACK_COMMAND` trigger. + * + * Every field is optional, and an omitted field is left unchanged. + */ +export type SetSlackTriggerConfigRequest = components["schemas"]["SetSlackTriggerConfigApiRequest"]; + +/** A `SLACK_COMMAND` trigger's Slack connection, form, channels and conversation settings. */ +export type SlackTriggerConfigResponse = components["schemas"]["SlackTriggerConfigApiResponse"]; + +/** Where a Slack trigger runs within its scope: `everywhere` or `channel_opt_in`. */ +export type SlackTriggerActivation = components["schemas"]["SlackTriggerActivation"]; + +/** Which channels a Slack trigger covers: `selected_channels` or `bot_channels`. */ +export type SlackTriggerScope = components["schemas"]["SlackTriggerScope"]; + +/** Who sees a Slack trigger's reply: `channel` or `private`. */ +export type SlackReplyVisibility = components["schemas"]["SlackReplyVisibility"]; + // ─── Agent Email Governance ────────────────────────────────────────────────── /** A recipient's opt-out from an account's agent emails (one agent, or account-wide). */ @@ -160,7 +266,7 @@ export type AgentEmailOptOutResponse = components["schemas"]["AgentEmailOptOutRe export type AgentEmailOptOutListResponse = VersionedList; /** Request body for blocking an inbound email sender or domain. */ -export type BlockEmailSenderRequest = components["schemas"]["BlockEmailSenderRequest"]; +export type BlockEmailSenderRequest = WithServerDefaults; /** A single blocked inbound email sender. */ export type BlockedEmailSenderResponse = components["schemas"]["BlockedEmailSenderResponse"]; @@ -192,16 +298,10 @@ export type ResumeInboundResponse = components["schemas"]["ResumeInboundResponse // ─── Agent Runs ────────────────────────────────────────────────────────────── /** Request body for starting an agent run. */ -export type AgentRunRequest = components["schemas"]["AgentRunRequest"]; +export type AgentRunRequest = WithServerDefaults; -/** - * Request body for starting an agent run in streaming mode (SSE). - * - * `include_reasoning` has a server-side default of `false` and stays optional — - * the generated type marks it required only because the schema declares a default. - */ -export type AgentRunStreamRequest = Omit & - Partial>; +/** Request body for starting an agent run in streaming mode (SSE). `include_reasoning` defaults to `false`. */ +export type AgentRunStreamRequest = WithServerDefaults; /** Response body describing an agent run. */ export type AgentRunResponse = components["schemas"]["AgentRunResponse"]; @@ -222,7 +322,7 @@ export type AgentRunFileResponse = components["schemas"]["AgentRunFileResponse"] export type AgentRunToolCallResponse = components["schemas"]["AgentRunToolCallResponse"]; /** Search request for agent runs (traces). */ -export type AgentTraceSearchRequest = components["schemas"]["routers__api__agents__AgentTraceSearchRequest"]; +export type AgentTraceSearchRequest = WithServerDefaults; /** Search response containing matching agent runs. */ export type AgentTraceSearchResponse = components["schemas"]["AgentTraceSearchResponse"]; @@ -247,7 +347,7 @@ export type AttachmentRefsSourceApiSummary = components["schemas"]["AttachmentRe // ─── Agent Steps AI Assistant ──────────────────────────────────────────────── /** Request body for generating agent workflow steps via AI. */ -export type GenerateAgentStepsRequest = components["schemas"]["GenerateAgentStepsRequest"]; +export type GenerateAgentStepsRequest = WithServerDefaults; /** Response containing AI-generated agent workflow steps. */ export type GenerateAgentStepsResponse = components["schemas"]["GenerateAgentStepsResponse"]; @@ -375,7 +475,7 @@ export type EvaluationCriteriaListResponse = { }; /** Request body for creating evaluation criteria. */ -export type CreateEvaluationCriteriaRequest = components["schemas"]["CreateEvaluationCriteriaRequest"]; +export type CreateEvaluationCriteriaRequest = WithServerDefaults; /** Request body for updating evaluation criteria. */ export type UpdateEvaluationCriteriaRequest = components["schemas"]["UpdateEvaluationCriteriaRequest"]; @@ -387,7 +487,7 @@ export type EvaluationResultResponse = components["schemas"]["EvaluationResultRe export type EvaluationResultListResponse = VersionedList; /** Request body for creating a manual evaluation result. */ -export type CreateEvaluationResultRequest = components["schemas"]["CreateEvaluationResultRequest"]; +export type CreateEvaluationResultRequest = WithServerDefaults; /** Summary of evaluation results for a criteria. */ export type EvaluationResultSummaryResponse = components["schemas"]["EvaluationResultSummaryResponse"]; @@ -435,7 +535,7 @@ export type NonManualEvaluationSummaryResponse = components["schemas"]["schemas_ export type NonManualEvaluationModeStatResponse = components["schemas"]["schemas__v1__agent_evaluations__NonManualEvaluationModeStatResponse"]; /** Request for testing a draft evaluation. */ -export type TestDraftEvaluationRequest = components["schemas"]["TestDraftEvaluationRequest"]; +export type TestDraftEvaluationRequest = WithServerDefaults; /** * Response from testing a draft evaluation. When `status` is `error` (no @@ -480,7 +580,7 @@ export type MemoryBankListResponse = VersionedList; /** Request body for updating a memory bank. */ export type UpdateMemoryBankBody = components["schemas"]["UpdateMemoryBankBody"]; @@ -504,13 +604,13 @@ export type MemoryBankLastConversationResponse = components["schemas"]["routers_ export type MemoryBankConversationTurnResponse = components["schemas"]["routers__api__memory_banks__MemoryBankConversationTurnResponse"]; /** Compaction test request for memory banks. */ -export type TestCompactionRequest = components["schemas"]["TestCompactionRequest"]; +export type TestCompactionRequest = WithServerDefaults; /** Compaction test response. */ export type CompactionTestResponse = components["schemas"]["CompactionTestResponseModel"]; /** Standalone compaction test request. */ -export type StandaloneTestCompactionRequest = components["schemas"]["StandaloneTestCompactionRequest"]; +export type StandaloneTestCompactionRequest = WithServerDefaults; /** Compaction evaluation model result. */ export type CompactionEvaluationModel = components["schemas"]["CompactionEvaluationModel"]; @@ -532,14 +632,23 @@ export type CreateSourceBody = components["schemas"]["CreateSourceBody"]; /** Request body for updating a source. */ export type UpdateSourceBody = components["schemas"]["UpdateSourceBody"]; +/** What a source does when it reaches `max_credits_per_period`: `stop` or `delete`. */ +export type SpendCapAction = components["schemas"]["SpendCapAction"]; + +/** + * Which entries a `delete` spend cap removes first: `oldest_added`, + * `oldest_published` or `largest_first`. + */ +export type SpendCapDeleteOrder = components["schemas"]["SpendCapDeleteOrder"]; + /** Upload response for file uploads to a source. */ export type FileUploadResponse = components["schemas"]["routers__api__sources__FileUploadResponse"]; /** Request body for uploading inline text to a source. */ -export type InlineTextUploadRequest = components["schemas"]["InlineTextUploadRequest"]; +export type InlineTextUploadRequest = WithServerDefaults; /** Request body for replacing content with inline text. */ -export type InlineTextReplaceRequest = components["schemas"]["InlineTextReplaceRequest"]; +export type InlineTextReplaceRequest = WithServerDefaults; /** One content item's indexing status within a source. */ export type SourceContentStatusResponse = components["schemas"]["SourceContentStatusResponse"]; @@ -651,7 +760,7 @@ export type SolutionResponse = components["schemas"]["routers__api__solutions__S export type SolutionSummaryResponse = components["schemas"]["SolutionSummaryResponse"]; /** Request body for creating a solution. */ -export type CreateSolutionRequest = components["schemas"]["CreateSolutionRequest"]; +export type CreateSolutionRequest = WithServerDefaults; /** Request body for updating a solution. */ export type UpdateSolutionRequest = components["schemas"]["UpdateSolutionRequest"]; @@ -681,7 +790,7 @@ export type AiAssistantGenerateRequest = components["schemas"]["routers__api__so export type AiAssistantGenerateResponse = components["schemas"]["AiAssistantGenerateResponse"]; /** AI assistant accept request for solutions. */ -export type AiAssistantAcceptRequest = components["schemas"]["routers__api__solutions__AiAssistantAcceptRequest"]; +export type AiAssistantAcceptRequest = WithServerDefaults; /** AI assistant accept response for solutions. */ export type AiAssistantAcceptResponse = components["schemas"]["AiAssistantAcceptResponse"]; @@ -723,7 +832,7 @@ export type GovernanceAppliedActionResponse = components["schemas"]["AppliedActi // ─── Alerts ────────────────────────────────────────────────────────────────── /** Request body for creating an alert config. */ -export type CreateAlertConfigRequest = components["schemas"]["CreateAlertConfigRequest"]; +export type CreateAlertConfigRequest = WithServerDefaults; /** Request body for updating an alert config. */ export type UpdateAlertConfigRequest = components["schemas"]["UpdateAlertConfigRequest"]; @@ -796,7 +905,7 @@ export type VariantCategoryResponse = components["schemas"]["VariantCategoryResp export type VariantOptionResponse = components["schemas"]["VariantOptionResponse"]; /** Request body for creating a model playground experiment. */ -export type PlaygroundCreateRequest = components["schemas"]["PlaygroundCreateRequest"]; +export type PlaygroundCreateRequest = WithServerDefaults; /** * Input type for {@link SeclaiClient.createExperiment}. @@ -810,7 +919,7 @@ export type CreateExperimentInput = Pick; /** * Input type for {@link Seclai.addEmailDomain}. @@ -891,3 +1000,133 @@ export interface SortableListOptions extends ListOptions { /** Sort order. */ order?: "asc" | "desc"; } + +/** Filters for {@link Seclai.listAgentExamples}. */ +export interface ListAgentExamplesOptions extends ListOptions { + /** Words every matching example must contain. */ + query?: string; + /** Only examples for this use case. */ + useCase?: string; +} + +/** Filters for {@link Seclai.listSolutions}. */ +export interface ListSolutionsOptions extends SortableListOptions { + /** Keep solutions whose name contains this text (case-insensitive). */ + search?: string; +} + +/** Filters for {@link Seclai.listMemoryBanks}. */ +export interface ListMemoryBanksOptions extends SortableListOptions { + /** Keep only one bank type. */ + type?: "conversation" | "general" | (string & {}); +} + +/** Filters for {@link Seclai.listEvaluationResults}. */ +export interface ListEvaluationResultsOptions extends ListOptions { + /** Keep only one result status. */ + status?: string; + /** Keep only flagged results. Defaults to `false`. */ + flaggedOnly?: boolean; + /** Earliest result time, ISO 8601. */ + timeFrom?: string; + /** Latest result time, ISO 8601. */ + timeTo?: string; +} + +/** Filters for {@link Seclai.listAgentEvaluationResults}. */ +export interface ListAgentEvaluationResultsOptions extends ListEvaluationResultsOptions { + /** Keep only results for this agent step. */ + step?: string; +} + +/** Filters for {@link Seclai.listEvaluationRuns}: those of {@link ListAgentEvaluationResultsOptions} except `flaggedOnly`. */ +export type ListEvaluationRunsOptions = Omit; + +/** Filters for {@link Seclai.listCompatibleRuns}. */ +export interface ListCompatibleRunsOptions extends ListOptions { + /** Only runs started after this time, ISO 8601. */ + startedAfter?: string; +} + +/** + * Date range for {@link Seclai.getNonManualEvaluationSummary}, + * {@link Seclai.getMemoryBankStats} and {@link Seclai.listExperiments}. Each + * endpoint combines the dates with `days` its own way; see the method. + */ +export interface DateRangeOptions { + /** Days back from today. The server defaults to 30. */ + days?: number; + /** First day, `YYYY-MM-DD`. */ + startDate?: string; + /** Last day, `YYYY-MM-DD`. */ + endDate?: string; +} + +/** Offset paging. Each method documents its server defaults and bounds. */ +export interface OffsetPageOptions { + /** Most items to return. */ + limit?: number; + /** Items to skip. */ + offset?: number; +} + +/** Filters for {@link Seclai.listAlerts}. */ +export interface ListAlertsOptions extends ListOptions { + /** Keep only one alert status. */ + status?: string; + /** + * Accepted for compatibility and never sent: `GET /alerts` has no severity + * filter. + * + * @deprecated The API has no severity filter; this never filtered anything. + */ + severity?: string; + /** Keep only alerts for this agent. */ + agentId?: string; + /** Keep only alerts for this source connection. */ + sourceConnectionId?: string; + /** Earliest alert time, ISO 8601. */ + timeFrom?: string; + /** Latest alert time, ISO 8601. */ + timeTo?: string; +} + +/** Filters for {@link Seclai.listAlertConfigs}. */ +export interface ListAlertConfigsOptions extends ListOptions { + /** Keep only configs for this agent. */ + agentId?: string; + /** Keep only configs for this source connection. */ + sourceConnectionId?: string; + /** `source` lists the account-level source alert configs. */ + scope?: "source" | (string & {}); +} + +/** Filters for {@link Seclai.listOrganizationAlertPreferences}. */ +export interface ListOrganizationAlertPreferencesOptions { + /** Keep only one organization's preferences. */ + organizationId?: string; + /** Also list the default subscription for every alert type. Defaults to `false`. */ + includeDefaults?: boolean; +} + +/** Filters for {@link Seclai.listModelAlerts}. */ +export interface ListModelAlertsOptions extends ListOptions { + /** Keep only alerts for this agent. */ + agentId?: string; + /** Keep only unread alerts. Defaults to `false`. */ + unreadOnly?: boolean; +} + +/** Requirements for {@link Seclai.getModelRecommendations}. */ +export interface ModelRecommendationsOptions { + /** Only models that support tool use. */ + requireToolUse?: boolean; + /** Only models that support structured output. */ + requireStructuredOutput?: boolean; + /** Only models that support thinking. */ + requireThinking?: boolean; + /** Smallest acceptable context window, in tokens. */ + minContextTokens?: number; + /** Smallest acceptable output limit, in tokens. */ + minOutputTokens?: number; +} diff --git a/src/versions.ts b/src/versions.ts index e24e4d4..bbde5d8 100644 --- a/src/versions.ts +++ b/src/versions.ts @@ -22,10 +22,11 @@ export const SeclaiApiVersion = { 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: "2026-07-01", /** Newest version known to this SDK release. May lag the server. */ - Latest: "2026-10-21", + Latest: "2026-10-28", } as const; /** diff --git a/tests/client.test.ts b/tests/client.test.ts index 55d9e67..28c84ba 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -1951,6 +1951,17 @@ describe("Agent Evaluations — extended", () => { }); await client.getNonManualEvaluationSummary("ag_1"); }); + + test("getNonManualEvaluationSummary without agentId asks for the account-wide summary", async () => { + const client = makeClient((req) => { + const u = new URL(req.url); + expect(u.pathname).toBe("/agents/evaluation-results/non-manual-summary"); + expect(u.searchParams.has("agent_id")).toBe(false); + expect(u.searchParams.get("start_date")).toBe("2026-10-01"); + return jsonResponse({ by_mode: [] }); + }); + await client.getNonManualEvaluationSummary(undefined, { startDate: "2026-10-01" }); + }); }); // ───────────────────────────────────────────────────────────────────────────── @@ -2460,6 +2471,96 @@ describe("Agent Email Triggers", () => { }); }); +describe("Agent Slack Triggers", () => { + test("setSlackTriggerConfig sends PUT /agents/:id/triggers/:tid/slack-config", async () => { + const client = makeClient((req) => { + const u = new URL(req.url); + expect(req.method).toBe("PUT"); + expect(u.pathname).toBe("/agents/ag_1/triggers/tr_1/slack-config"); + expect(u.search).toBe(""); + expect(JSON.parse(req.bodyText!)).toEqual({ + scope: "selected_channels", + channel_ids: ["C1", "C2"], + visibility: "private", + turns_enabled: true, + max_turns: 5, + }); + return jsonResponse({ + trigger_id: "tr_1", + agent_id: "ag_1", + mcp_client_id: null, + slack_team_id: "T1", + form: [], + scope: "selected_channels", + allow_dms: false, + activation: "everywhere", + visibility: "private", + start_without_form: false, + turns_enabled: true, + turns_anyone: false, + max_turns: 5, + include_invoker_email: false, + notify_failure_after_answer: false, + channel_ids: ["C1", "C2"], + missing_scopes: ["users:read.email"], + }); + }); + const config = await client.setSlackTriggerConfig("ag_1", "tr_1", { + scope: "selected_channels", + channel_ids: ["C1", "C2"], + visibility: "private", + turns_enabled: true, + max_turns: 5, + }); + expect(config.channel_ids).toEqual(["C1", "C2"]); + expect(config.missing_scopes).toEqual(["users:read.email"]); + }); + + test("setSlackTriggerConfig sends only the fields given", async () => { + const client = makeClient((req) => { + expect(JSON.parse(req.bodyText!)).toEqual({ allow_dms: true }); + return jsonResponse({ trigger_id: "tr_1", allow_dms: true }); + }); + await client.setSlackTriggerConfig("ag_1", "tr_1", { allow_dms: true }); + }); +}); + +describe("Agent Examples", () => { + test("listAgentExamples sends GET /agents/examples with its filters", async () => { + const client = makeClient((req) => { + const u = new URL(req.url); + expect(req.method).toBe("GET"); + expect(u.pathname).toBe("/agents/examples"); + expect(Object.fromEntries(u.searchParams)).toEqual({ + query: "support inbox", + use_case: "customer_support", + page: "2", + limit: "10", + }); + return jsonResponse({ + data: [{ key: "support-triage" }], + pagination: { page: 2, limit: 10, total: 11, pages: 2, has_next: false, has_prev: true }, + }); + }); + const res = await client.listAgentExamples({ + query: "support inbox", + useCase: "customer_support", + page: 2, + limit: 10, + }); + expect(res.data).toEqual([{ key: "support-triage" }]); + expect(res.pagination.total).toBe(11); + }); + + test("listAgentExamples sends no query without options", async () => { + const client = makeClient((req) => { + expect(new URL(req.url).search).toBe(""); + return jsonResponse({ data: [], pagination: { page: 1, limit: 20, total: 0, pages: 0, has_next: false, has_prev: false } }); + }); + await client.listAgentExamples(); + }); +}); + // ───────────────────────────────────────────────────────────────────────────── // Agent Email Governance // ───────────────────────────────────────────────────────────────────────────── @@ -3058,7 +3159,7 @@ describe("API version constants", () => { test("a constant reaches the wire", async () => { const client = makeClient( (req) => { - expect(req.headers["seclai-version"]).toBe("2026-10-21"); + expect(req.headers["seclai-version"]).toBe("2026-10-28"); return jsonResponse({ data: [] }); }, { apiVersion: SeclaiApiVersion.Latest }, @@ -3765,3 +3866,200 @@ describe("Header edge cases from untyped callers", () => { ).toThrow("defaultHeaders['seclai-version']"); }); }); + + +describe("Query filters", () => { + type Row = [string, string, (c: Seclai) => Promise, Record]; + const rows: Row[] = [ + [ + "listEvaluationResults", + "/agents/evaluation-criteria/c1/results", + (c) => + c.listEvaluationResults("c1", { + status: "completed", + flaggedOnly: true, + timeFrom: "2026-10-01T00:00:00Z", + timeTo: "2026-10-31T00:00:00Z", + }), + { status: "completed", flagged_only: "true", time_from: "2026-10-01T00:00:00Z", time_to: "2026-10-31T00:00:00Z" }, + ], + [ + "listCompatibleRuns", + "/agents/evaluation-criteria/c1/compatible-runs", + (c) => c.listCompatibleRuns("c1", { startedAfter: "2026-10-01T00:00:00Z" }), + { started_after: "2026-10-01T00:00:00Z" }, + ], + [ + "listAgentEvaluationResults", + "/agents/a1/evaluation-results", + (c) => + c.listAgentEvaluationResults("a1", { + status: "failed", + step: "s1", + flaggedOnly: false, + timeFrom: "2026-10-01", + timeTo: "2026-10-02", + }), + { status: "failed", step: "s1", flagged_only: "false", time_from: "2026-10-01", time_to: "2026-10-02" }, + ], + [ + "listEvaluationRuns", + "/agents/a1/evaluation-runs", + (c) => c.listEvaluationRuns("a1", { status: "completed", step: "s1", timeFrom: "2026-10-01", timeTo: "2026-10-02" }), + { status: "completed", step: "s1", time_from: "2026-10-01", time_to: "2026-10-02" }, + ], + [ + "getNonManualEvaluationSummary", + "/agents/evaluation-results/non-manual-summary", + (c) => c.getNonManualEvaluationSummary("a1", { days: 7, startDate: "2026-10-01", endDate: "2026-10-07" }), + { agent_id: "a1", days: "7", start_date: "2026-10-01", end_date: "2026-10-07" }, + ], + [ + "getAiAssistantMemoryBankHistory", + "/ai-assistant/memory-bank/last-conversation", + (c) => c.getAiAssistantMemoryBankHistory({ limit: 3, offset: 2 }), + { limit: "3", offset: "2" }, + ], + [ + "listAlerts", + "/alerts", + (c) => + c.listAlerts({ + agentId: "a1", + sourceConnectionId: "s1", + timeFrom: "2026-10-01T00:00:00Z", + timeTo: "2026-10-02T00:00:00Z", + }), + { agent_id: "a1", source_connection_id: "s1", time_from: "2026-10-01T00:00:00Z", time_to: "2026-10-02T00:00:00Z" }, + ], + [ + "listAlertConfigs", + "/alerts/configs", + (c) => c.listAlertConfigs({ agentId: "a1", sourceConnectionId: "s1", scope: "source" }), + { agent_id: "a1", source_connection_id: "s1", scope: "source" }, + ], + [ + "listOrganizationAlertPreferences", + "/alerts/organization-preferences/list", + (c) => c.listOrganizationAlertPreferences({ organizationId: "o1", includeDefaults: true }), + { organization_id: "o1", include_defaults: "true" }, + ], + [ + "listGovernanceAiConversations", + "/governance/ai-assistant/conversations", + (c) => c.listGovernanceAiConversations({ limit: 5 }), + { limit: "5" }, + ], + ["listMemoryBanks", "/memory_banks", (c) => c.listMemoryBanks({ type: "general" }), { type: "general" }], + [ + "getMemoryBankAiLastConversation", + "/memory_banks/ai-assistant/last-conversation", + (c) => c.getMemoryBankAiLastConversation({ limit: 4, offset: 1 }), + { limit: "4", offset: "1" }, + ], + [ + "getMemoryBankStats", + "/memory_banks/mb1/stats", + (c) => c.getMemoryBankStats("mb1", { days: 14, startDate: "2026-10-01", endDate: "2026-10-14" }), + { days: "14", start_date: "2026-10-01", end_date: "2026-10-14" }, + ], + [ + "listModelAlerts", + "/models/alerts", + (c) => c.listModelAlerts({ agentId: "a1", unreadOnly: true }), + { agent_id: "a1", unread_only: "true" }, + ], + [ + "getModelRecommendations", + "/models/m1/recommendations", + (c) => + c.getModelRecommendations("m1", { + requireToolUse: true, + requireStructuredOutput: false, + requireThinking: true, + minContextTokens: 100000, + minOutputTokens: 8000, + }), + { + require_tool_use: "true", + require_structured_output: "false", + require_thinking: "true", + min_context_tokens: "100000", + min_output_tokens: "8000", + }, + ], + ["listSolutions", "/solutions", (c) => c.listSolutions({ search: "billing" }), { search: "billing" }], + ]; + + test.each(rows)("%s sends its filters as snake_case query keys", async (_name, path, call, query) => { + const client = makeClient((req) => { + const u = new URL(req.url); + expect(req.method).toBe("GET"); + expect(u.pathname).toBe(path); + expect(Object.fromEntries(u.searchParams)).toEqual(query); + return jsonResponse({ data: [], pagination: { page: 1, limit: 20, total: 0, pages: 0, has_next: false, has_prev: false } }); + }); + await call(client); + }); +}); + +describe("Request types", () => { + // openapi-typescript marks a property that declares a `default` as required. + // For a schema only ever sent as a request body that is wrong, so src/types.ts + // wraps each such alias in WithServerDefaults<…, "key" | …>. This lists the + // keys from the spec, so a new server default fails here rather than shipping + // a request type that forces callers to send it. + test("request types leave server-defaulted fields optional", () => { + const spec = JSON.parse( + readFileSync(new URL("../openapi/seclai.openapi.json", import.meta.url), "utf8"), + ); + const types = readFileSync(new URL("../src/types.ts", import.meta.url), "utf8"); + const schemas: Record = spec.components.schemas; + + const reach = (node: unknown, into: Set): void => { + if (Array.isArray(node)) return node.forEach((n) => reach(n, into)); + if (!node || typeof node !== "object") return; + const ref = (node as { $ref?: string }).$ref; + if (ref?.startsWith("#/components/schemas/")) { + const name = ref.slice("#/components/schemas/".length); + if (!into.has(name)) { + into.add(name); + reach(schemas[name], into); + } + } + Object.values(node).forEach((n) => reach(n, into)); + }; + const requests = new Set(); + const responses = new Set(); + for (const ops of Object.values(spec.paths)) { + for (const op of Object.values(ops)) { + if (!op || typeof op !== "object") continue; + reach(op.requestBody, requests); + for (const [code, r] of Object.entries(op.responses ?? {})) { + if (code.startsWith("2")) reach(r, responses); + } + } + } + + const missing: string[] = []; + for (const name of requests) { + if (responses.has(name)) continue; + const schema = schemas[name]; + const required = new Set(schema.required ?? []); + const defaulted = Object.entries(schema.properties ?? {}) + .filter(([k, v]) => "default" in v && !required.has(k)) + .map(([k]) => k); + if (defaulted.length === 0) continue; + const ref = `components["schemas"]["${name}"]`; + if (!types.includes(ref)) continue; // not exported as a request type + if (types.includes(`Partial<${ref}>`)) continue; + const wrapped = types.match( + new RegExp(`WithServerDefaults<${ref.replace(/[[\]"]/g, "\\$&")},\\s*([^>]+)>`), + ); + for (const key of defaulted) { + if (!wrapped || !wrapped[1].includes(`"${key}"`)) missing.push(`${name}.${key}`); + } + } + expect(missing).toEqual([]); + }); +});