Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(agent-platform): trim spec-schema tool token spend (ref reuse + sections) (#64835)

Ben Whitea2169c4cb7f9
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts
index 54be17fc2d15..bd35bb0b1c42 100644
--- a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.test.ts
@@ -5,15 +5,18 @@ import type { ToolContext } from '@posthog/agent-shared'
import { getNativeTool } from '../registry'
import { posthogAgentApplicationsSpecSchemaV1 } from './posthog-spec-schema.v1'
+const run = (args: { section?: string } = {}): ReturnType<typeof posthogAgentApplicationsSpecSchemaV1.run> =>
+ posthogAgentApplicationsSpecSchemaV1.run(args as never, {} as ToolContext)
+
describe('@posthog/agent-applications-spec-schema', () => {
it('is registered and resolvable by id', () => {
expect(getNativeTool('@posthog/agent-applications-spec-schema')).toBe(posthogAgentApplicationsSpecSchemaV1)
})
- it('returns the spec JSON Schema generated from the canonical AgentSpecSchema', async () => {
- const result = await posthogAgentApplicationsSpecSchemaV1.run({}, {} as ToolContext)
+ it('returns the full spec JSON Schema when no section is given', async () => {
+ const result = await run()
+ expect(result.section).toBeNull()
const schema = result.spec_json_schema as Record<string, unknown>
- // `model` is the only always-required field; everything else has a default.
expect(schema.type).toBe('object')
expect((schema.required as string[]) ?? []).toContain('model')
expect(schema.properties).toHaveProperty('triggers')
@@ -21,21 +24,51 @@ describe('@posthog/agent-applications-spec-schema', () => {
expect(schema.properties).toHaveProperty('secrets')
})
+ it('dedupes repeated subschemas into $defs to keep the payload small', async () => {
+ const { spec_json_schema } = await run()
+ // `reused: 'ref'` hoists the auth-mode union / approval policy into
+ // $defs instead of inlining a copy per trigger/tool — the whole point
+ // of the token-spend fix. Assert the $ref machinery is actually used.
+ expect(spec_json_schema.$defs).not.toBeUndefined()
+ expect(JSON.stringify(spec_json_schema)).toContain('$ref')
+ })
+
it('encodes the exact constructs that trip up authoring', async () => {
- const { spec_json_schema } = await posthogAgentApplicationsSpecSchemaV1.run({}, {} as ToolContext)
- // One serialized blob is the simplest way to assert the union/enum shapes
- // survive the JSON-Schema conversion (chat-trigger auth, reasoning enum,
- // the secrets string|object union with required allowed_hosts).
- const blob = JSON.stringify(spec_json_schema)
+ const blob = JSON.stringify((await run()).spec_json_schema)
expect(blob).toContain('acknowledge_public_exposure')
expect(blob).toContain('allowed_hosts')
expect(blob).toContain('xhigh')
expect(blob).toContain('trusted_workspaces')
})
- it('returns orientation notes', async () => {
- const { notes } = await posthogAgentApplicationsSpecSchemaV1.run({}, {} as ToolContext)
- expect(notes.length).toBeGreaterThan(0)
- expect(notes.every((n) => typeof n === 'string' && n.length > 0)).toBe(true)
+ it('returns only the requested slice for a section (much cheaper than the whole spec)', async () => {
+ const full = JSON.stringify((await run()).spec_json_schema)
+ const triggers = await run({ section: 'triggers' })
+ expect(triggers.section).toBe('triggers')
+ const triggersBlob = JSON.stringify(triggers.spec_json_schema)
+ // The triggers slice carries trigger constructs but not, say, the spec's
+ // limits field, and is meaningfully smaller than the full schema.
+ expect(triggersBlob).toContain('trusted_workspaces')
+ expect(triggersBlob.length).toBeLessThan(full.length)
+
+ const limits = await run({ section: 'limits' })
+ expect(limits.section).toBe('limits')
+ const limitsBlob = JSON.stringify(limits.spec_json_schema)
+ expect(limitsBlob).toContain('max_wall_seconds')
+ expect(limitsBlob.length).toBeLessThan(triggersBlob.length)
+ })
+
+ it('scopes notes to the requested section', async () => {
+ const triggers = await run({ section: 'triggers' })
+ expect(triggers.notes.length).toBeGreaterThan(0)
+ expect(triggers.notes.join(' ')).toMatch(/discriminated union on `type`/i)
+ // A section fetch must not be padded with notes about other sections.
+ expect(triggers.notes.join(' ')).not.toContain('allowed_hosts')
+ })
+
+ it('falls back to the full schema for an unknown section', async () => {
+ const result = await run({ section: 'nonsense' })
+ expect(result.section).toBeNull()
+ expect(result.spec_json_schema.properties).toHaveProperty('triggers')
})
})
diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts
index 70f44f81671c..527dea994291 100644
--- a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts
@@ -10,46 +10,126 @@
* `AgentSpecSchema` (the same schema the runner parses and the Django write
* path mirrors), so it cannot drift from what the API actually validates.
*
- * Defined as a static, no-arg, no-auth read — like the catalog tool, it
- * computes its result in-process with no API round-trip.
+ * Two things keep the result cheap. `reused: 'ref'` hoists repeated
+ * subschemas (the auth-mode union, the approval policy) into `$defs` instead
+ * of inlining each copy — the union alone is otherwise emitted once per
+ * chat/mcp/webhook trigger. And an optional `section` returns just one slice
+ * of the spec (`triggers` is ~half the whole thing), so the common
+ * "edit one part" path pays for that part only. Defined as a static, no-auth
+ * read: computed in-process with no API round-trip.
*/
import { z } from 'zod'
-import { AgentSpecSchema, defineNativeTool, Type } from '@posthog/agent-shared'
+import {
+ AgentSpecSchema,
+ AuthConfigSchema,
+ defineNativeTool,
+ FrameworkPromptConfigSchema,
+ McpRefSchema,
+ ReasoningEffortSchema,
+ ResumeConfigSchema,
+ SecretRefSchema,
+ SkillRefSchema,
+ SpecLimitsSchema,
+ ToolRefSchema,
+ TriggerSchema,
+ Type,
+} from '@posthog/agent-shared'
+
+// One spec slice each. `triggers`/`tools`/`secrets` are the element schemas
+// (the spec field is an array of these); the rest are the field schema itself.
+const SECTION_SCHEMAS = {
+ triggers: TriggerSchema,
+ tools: ToolRefSchema,
+ mcps: McpRefSchema,
+ secrets: SecretRefSchema,
+ skills: SkillRefSchema,
+ limits: SpecLimitsSchema,
+ auth: AuthConfigSchema,
+ reasoning: ReasoningEffortSchema,
+ framework_prompt: FrameworkPromptConfigSchema,
+ resume: ResumeConfigSchema,
+} as const
+
+type Section = keyof typeof SECTION_SCHEMAS
+const SECTION_IDS = Object.keys(SECTION_SCHEMAS) as Section[]
+
+// Pure derivations from the canonical schema — compute once at module load.
+// `reused: 'ref'` dedupes shared subschemas into `$defs`.
+const toJson = (schema: z.ZodType): Record<string, unknown> =>
+ z.toJSONSchema(schema, { reused: 'ref' }) as Record<string, unknown>
+const FULL_SCHEMA = toJson(AgentSpecSchema)
+const SECTION_JSON: Record<string, Record<string, unknown>> = Object.fromEntries(
+ SECTION_IDS.map((id) => [id, toJson(SECTION_SCHEMAS[id])])
+)
/**
* Orientation the bare JSON Schema doesn't make obvious. Kept short on purpose
- * — the schema is authoritative; these only point at the surrounding tools and
- * the two discriminated unions that are the usual source of validation errors.
+ * — the schema is authoritative; these point at the surrounding tools and the
+ * discriminated unions that are the usual source of validation errors. Scoped
+ * per section so a one-slice fetch isn't padded with notes about the rest.
*/
-const SPEC_NOTES: readonly string[] = [
- 'This is the canonical agent `spec` schema, generated from the source the API validates writes against. Pass a spec matching this shape to `agent-applications-revisions-create` / `-partial-update`.',
- 'Fields that carry a JSON Schema `default` are optional on write — omit them to take the default. `model` is the only always-required field.',
- '`triggers[]` is a discriminated union on `type`. `chat`, `mcp`, and `webhook` carry an `auth` block; `slack` and `cron` do not (they authenticate via their own protocol).',
- '`tools[]` is a discriminated union on `kind` (`native` | `custom` | `client`). For valid `native` tool ids call `@posthog/agent-applications-native-tools-list` — the validator rejects unknown ids.',
- '`secrets[]` entries are either a bare string (resolvable, no network-egress authority) or `{ name, allowed_hosts }` (required to let `@posthog/http-request` send the secret to those hosts).',
- 'Skill and custom-tool *content* (SKILL.md bodies, tool source/schema) is uploaded via the bundle file tools (`-skills-update` / `-tools-update`), not inline in the spec.',
+const SHARED_NOTE =
+ 'Canonical agent `spec` schema, generated from the source the API validates writes against — match it exactly. Fields with a JSON Schema `default` are optional on write.'
+const SECTION_NOTES: Record<string, string[]> = {
+ triggers: [
+ '`triggers[]` is a discriminated union on `type`. `chat`, `mcp`, and `webhook` carry an `auth` block; `slack` and `cron` authenticate via their own protocol and have none.',
+ 'Trigger-required secrets (`SLACK_SIGNING_SECRET`, `SLACK_BOT_TOKEN` for `slack`) are NOT in `spec.secrets[]` — they come from the platform `TRIGGER_REQUIRED_SECRETS` registry and live in `encrypted_env`.',
+ ],
+ tools: [
+ '`tools[]` is a discriminated union on `kind` (`native` | `custom` | `client`). For valid `native` ids call `@posthog/agent-applications-native-tools-list` — the validator rejects unknown ids.',
+ 'Skill and custom-tool *content* is uploaded via the bundle file tools (`-skills-update` / `-tools-update`), not inline in the spec.',
+ ],
+ secrets: [
+ '`secrets[]` entries are a bare string (resolvable, no egress authority) or `{ name, allowed_hosts }` (required to let `@posthog/http-request` send the secret to those hosts).',
+ ],
+}
+const FULL_NOTES = [
+ SHARED_NOTE,
+ '`model` is the only always-required field.',
+ ...(SECTION_NOTES.triggers ?? []),
+ ...(SECTION_NOTES.tools ?? []),
+ ...(SECTION_NOTES.secrets ?? []),
]
-// Pure derivation from the canonical schema — compute once at module load.
-const SPEC_JSON_SCHEMA = z.toJSONSchema(AgentSpecSchema) as Record<string, unknown>
-
export const posthogAgentApplicationsSpecSchemaV1 = defineNativeTool({
id: '@posthog/agent-applications-spec-schema',
description: [
'Return the JSON Schema for an agent `spec` — every field, type, enum, default, and the',
'discriminated unions for `triggers[]` / `tools[]` / `secrets[]`. Call this BEFORE writing or',
- 'editing a spec (create / partial-update a revision) instead of guessing the shape or copying',
- 'another agent. Generated from the canonical schema the API validates against, so it never drifts.',
+ 'editing a spec instead of guessing the shape or copying another agent. Generated from the',
+ 'canonical schema the API validates against, so it never drifts. Pass `section` (e.g. `triggers`,',
+ '`tools`, `limits`) to fetch just that slice when you are only editing one part — much cheaper',
+ 'than the whole spec. Omit `section` for the full schema.',
].join(' '),
- args: Type.Object({}),
+ args: Type.Object({
+ section: Type.Optional(
+ Type.Union(
+ SECTION_IDS.map((id) => Type.Literal(id)),
+ {
+ description:
+ 'Return only this part of the spec to save tokens. Omit for the whole spec. `triggers` alone is ~half the full schema.',
+ }
+ )
+ ),
+ }),
returns: Type.Object({
+ section: Type.Union([Type.String(), Type.Null()]),
spec_json_schema: Type.Record(Type.String(), Type.Unknown()),
notes: Type.Array(Type.String()),
}),
cost_hint: 'cheap',
- async run() {
- return { spec_json_schema: SPEC_JSON_SCHEMA, notes: [...SPEC_NOTES] }
+ async run(args) {
+ const section = args.section ?? null
+ if (section && SECTION_JSON[section]) {
+ const extra = SECTION_NOTES[section]
+ return {
+ section,
+ spec_json_schema: SECTION_JSON[section],
+ notes: extra ? [SHARED_NOTE, ...extra] : [SHARED_NOTE],
+ }
+ }
+ return { section: null, spec_json_schema: FULL_SCHEMA, notes: [...FULL_NOTES] }
},
})