@devries-cameron20 / composio Mirror · read-only / commits / cc1248370
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 12:15 UTC

fix(typesafe): block null-leaf container swaps and tighten gate option checks

- Treat dict/list as their own leaf kind when asserting a redactor masks only, so a redactor cannot replace a JSON null leaf with an object or array while the gate would approve the altered call (Python now matches the TS scalarTypeOf behavior). - Reject non-number gate thresholds ('', '0.9', true) at construction on the TS side, matching the strict Python check. - Omit the gate state context key when getContext returns null, matching Python and decide's context handling. - Pin all three with regression tests on both SDKs, and assert the context key is absent from the sent state when no getContext is given.

jkomyno committed Sep 17, 2026 at 19:03 UTC cc1248370b746d9f1db479140307198feb256ab9
4 files changed +78 -3
python/providers/typesafe/composio_typesafe/companion.py
+5
@@ -135,6 +135,11 @@ def _leaf_kind(value: t.Any) -> str:
135 return "number"
136 if isinstance(value, str):
137 return "string"
138 + if isinstance(value, (dict, list)):
139 + # Containers are compared structurally by the recursion, never by kind, so a
140 + # container at a scalar position (e.g. a redactor replacing a JSON null with
141 + # an object) cannot pass as a null-to-null mask.
142 + return "container"
143 return "null"
144
145
python/tests/test_typesafe_provider.py
+24
@@ -1488,6 +1488,8 @@ class TestConfidenceGate:
1488 },
1489 },
1490 )
1491 + # A context-less gate sends no context key at all, not an empty one.
1492 + assert "context" not in client.sent()["state"]
1493 # The proposed call travels in state, never inside the question text.
1494 assert "ada@example.com" not in json.dumps(client.sent()["questions"])
1495
@@ -1525,6 +1527,15 @@ class TestConfidenceGate:
1527 },
1528 {},
1529 ),
1530 + (
1531 + {
1532 + "redact_arguments": lambda _slug, arguments: {
1533 + **arguments,
1534 + "flag": {"controlled": "data"},
1535 + }
1536 + },
1537 + {"flag": None},
1538 + ),
1539 (
1540 {
1541 "redact_arguments": lambda _slug, arguments: {
@@ -1550,6 +1561,7 @@ class TestConfidenceGate:
1561 "redactor returns no dict",
1562 "redactor deletes a key",
1563 "redactor retypes a value",
1564 + "redactor replaces a null leaf with an object",
1565 "redactor shortens an array",
1566 "redactor deletes a nested key",
1567 "arguments not JSON",
@@ -1586,6 +1598,18 @@ class TestConfidenceGate:
1598 "password": "•" * len("hunter2-SENTINEL-4"),
1599 }
1600
1601 + def test_a_null_leaf_may_be_masked_to_null(self) -> None:
1602 + arguments = {**PARAMS["arguments"], "flag": None}
1603 +
1604 + def redact(_slug: str, to_mask: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
1605 + return {**to_mask, "flag": None}
1606 +
1607 + gate, client = gate_with(0.9, redact_arguments=redact)
1608 + call_params = {**PARAMS, "arguments": arguments}
1609 + assert run_gate(gate, call_params) is call_params
1610 + sent_state = client.sent()["state"]
1611 + assert sent_state["proposed_call"]["arguments"] == arguments
1612 +
1613 @pytest.mark.parametrize("value", ["alow", "ALLOW", 1, None])
1614 def test_an_invalid_on_unavailable_raises_at_construction(
1615 self, value: t.Any
ts/packages/providers/typesafe/src/companion.ts
+9 -3
@@ -143,7 +143,12 @@ const isUnavailable = (
143 export function confidenceGate(options: TypesafeGateOptions, ask: Ask): beforeExecuteModifier {
144 const threshold = options.threshold ?? 0.7;
145 const maxVetoes = options.maxVetoes ?? 3;
146 - if (!(threshold >= 0 && threshold <= 1)) {
146 + if (
147 + typeof threshold !== 'number' ||
148 + !Number.isFinite(threshold) ||
149 + threshold < 0 ||
150 + threshold > 1
151 + ) {
152 throw new TypesafeInvalidOptionsError('The gate threshold must be a number from 0 to 1.');
153 }
154 if (!Number.isInteger(maxVetoes) || maxVetoes < 1) {
@@ -189,10 +194,11 @@ export function confidenceGate(options: TypesafeGateOptions, ask: Ask): beforeEx
194 }
195 // Only the slug and the arguments are copied out of the execution parameters.
196 // `userId`, `connectedAccountId`, and the custom auth fields never leave. The `context`
192 - // key exists only when there is one, so a context-less state stays context-less.
197 + // key exists only when there is one (`null` counts as none), so a context-less
198 + // state stays context-less.
199 const state = jsonOrBlock({
200 request,
195 - ...(gateContext === undefined ? {} : { context: gateContext }),
201 + ...(gateContext === undefined || gateContext === null ? {} : { context: gateContext }),
202 proposed_call: {
203 tool: tool.slug,
204 description: tool.description ?? tool.name,
ts/packages/providers/typesafe/test/companion.test.ts
+40
@@ -135,6 +135,12 @@ describe('confidenceGate', () => {
135 expect(sent(systemOne).state).toMatchObject({ context: { thread: 't1' } });
136 });
137
138 + it('sends no context key when getContext returns null', async () => {
139 + const { gate, systemOne } = gateWith(0.9, { getContext: () => null });
140 + await gate(context);
141 + expect(sent(systemOne).state).not.toHaveProperty('context');
142 + });
143 +
144 it('hands redactArguments a copy, so redacting in place leaves the executed call alone', async () => {
145 const before = structuredClone(params.arguments);
146 const { gate, systemOne } = gateWith(0.9, {
@@ -171,6 +177,20 @@ describe('confidenceGate', () => {
177 });
178 });
179
180 + it('lets a redactor mask a null leaf to null and keeps the executed call original', async () => {
181 + const callArguments = { ...params.arguments, flag: null };
182 + const executedParams = { ...params, arguments: callArguments };
183 + const { gate, systemOne } = gateWith(0.9, {
184 + redactArguments: (_slug, args) => ({ ...args, flag: null }),
185 + });
186 + const executed = await gate({ ...context, params: executedParams });
187 + expect(executed).toBe(executedParams);
188 + const call = sent(systemOne).state as {
189 + proposed_call: { arguments: Record<string, unknown> };
190 + };
191 + expect(call.proposed_call.arguments).toEqual(callArguments);
192 + });
193 +
194 it.each<[string, Partial<TypesafeGateOptions>, Record<string, unknown>]>([
195 ['a redactor that returns no object', { redactArguments: () => 'secret' as never }, {}],
196 [
@@ -186,6 +206,11 @@ describe('confidenceGate', () => {
206 { redactArguments: (_slug, args) => ({ ...args, password: 42 }) },
207 {},
208 ],
209 + [
210 + 'a redactor that replaces a null leaf with an object',
211 + { redactArguments: (_slug, args) => ({ ...args, flag: { controlled: 'data' } }) },
212 + { flag: null },
213 + ],
214 [
215 'a redactor that shortens an array',
216 { redactArguments: (_slug, args) => ({ ...args, to: (args.to as string[]).slice(1) }) },
@@ -230,6 +255,21 @@ describe('confidenceGate', () => {
255 }
256 );
257
258 + it.each<[string, unknown]>([
259 + ['an empty string', ''],
260 + ['a numeric string', '0.9'],
261 + ['a boolean', true],
262 + ['NaN', Number.NaN],
263 + ])('rejects a threshold of %s when the gate is built, not at check time', (_label, value) => {
264 + expect(() =>
265 + new TypesafeProvider({ client: mockClient(() => undefined).client }).confidenceGate({
266 + tools,
267 + getRequest: () => 'email ada',
268 + threshold: value as never,
269 + })
270 + ).toThrow(TypesafeInvalidOptionsError);
271 + });
272 +
273 const unavailable = Object.assign(new Error('down'), {
274 name: 'InternalServerError',
275 status: 503,