@elevasis/sdk 1.42.0 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -300,217 +300,6 @@ interface IExecutionLogger {
300
300
  error(message: string, context?: LogContext): void;
301
301
  }
302
302
 
303
- /**
304
- * Serialized Registry Types
305
- *
306
- * Pre-computed JSON-safe types for API responses and Command View.
307
- * Serialization happens once at API startup, enabling instant response times.
308
- */
309
-
310
- /**
311
- * Serialized agent definition (JSON-safe)
312
- * Result of serializeDefinition(AgentDefinition)
313
- */
314
- interface SerializedAgentDefinition {
315
- config: {
316
- resourceId: string;
317
- name: string;
318
- description: string;
319
- version: string;
320
- type: 'agent';
321
- kind: 'orchestrator' | 'specialist' | 'utility' | 'system';
322
- status: 'dev' | 'prod';
323
- links?: ResourceLink[];
324
- category?: ResourceCategory;
325
- /** Whether this resource is archived and should be excluded from registration and deployment */
326
- archived?: boolean;
327
- systemPrompt: string;
328
- constraints?: {
329
- maxIterations?: number;
330
- timeout?: number;
331
- maxSessionMemoryKeys?: number;
332
- maxMemoryTokens?: number;
333
- };
334
- sessionCapable?: boolean;
335
- memoryPreferences?: string;
336
- };
337
- modelConfig: {
338
- provider: string;
339
- model: string;
340
- apiKey: string;
341
- temperature: number;
342
- maxOutputTokens: number;
343
- topP?: number;
344
- modelOptions?: Record<string, unknown>;
345
- };
346
- contract: {
347
- inputSchema: object;
348
- outputSchema?: object;
349
- };
350
- tools: Array<{
351
- name: string;
352
- description: string;
353
- inputSchema?: object;
354
- outputSchema?: object;
355
- }>;
356
- knowledgeMap?: {
357
- nodeCount: number;
358
- nodes: Array<{
359
- id: string;
360
- description: string;
361
- loaded: boolean;
362
- hasPrompt: boolean;
363
- }>;
364
- };
365
- metricsConfig?: object;
366
- }
367
- /**
368
- * Serialized workflow definition (JSON-safe)
369
- * Result of serializeDefinition(WorkflowDefinition)
370
- */
371
- interface SerializedWorkflowDefinition {
372
- config: {
373
- resourceId: string;
374
- name: string;
375
- description: string;
376
- version: string;
377
- type: 'workflow';
378
- status: 'dev' | 'prod';
379
- links?: ResourceLink[];
380
- category?: ResourceCategory;
381
- /** Whether this resource is archived and should be excluded from registration and deployment */
382
- archived?: boolean;
383
- };
384
- entryPoint: string;
385
- steps: Array<{
386
- id: string;
387
- name: string;
388
- description: string;
389
- inputSchema?: object;
390
- outputSchema?: object;
391
- next: {
392
- type: 'linear' | 'conditional';
393
- target?: string;
394
- routes?: Array<{
395
- target: string;
396
- }>;
397
- default?: string;
398
- } | null;
399
- }>;
400
- contract: {
401
- inputSchema: object;
402
- outputSchema?: object;
403
- };
404
- metricsConfig?: object;
405
- }
406
-
407
- /**
408
- * Model Configuration
409
- * Centralized model information, configuration, options, constraints, and validation
410
- * Single source of truth for all model-related definitions
411
- * Update manually when pricing changes or new models are added
412
- */
413
-
414
- /**
415
- * Supported Open AI models (direct SDK access)
416
- */
417
- type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano';
418
- /**
419
- * Supported OpenRouter models (explicit union for type safety)
420
- */
421
- type OpenRouterModel = 'openrouter/z-ai/glm-5';
422
- /**
423
- * Supported Google models (direct SDK access)
424
- */
425
- type GoogleModel = 'gemini-3-flash-preview' | 'gemini-3.1-flash-lite-preview';
426
- /**
427
- * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
428
- */
429
- type AnthropicModel = 'claude-opus-5' | 'claude-sonnet-5' | 'claude-haiku-4-5-20251001' | 'claude-haiku-4-5';
430
- /** Supported LLM models */
431
- type LLMModel = OpenAIModel | OpenRouterModel | GoogleModel | AnthropicModel | 'mock';
432
- /**
433
- * GPT-5 model options schema
434
- */
435
- declare const GPT5OptionsSchema: z.ZodObject<{
436
- reasoning_effort: z.ZodOptional<z.ZodEnum<{
437
- minimal: "minimal";
438
- low: "low";
439
- medium: "medium";
440
- high: "high";
441
- }>>;
442
- verbosity: z.ZodOptional<z.ZodEnum<{
443
- low: "low";
444
- medium: "medium";
445
- high: "high";
446
- }>>;
447
- }, z.core.$strip>;
448
- /**
449
- * OpenRouter model options schema
450
- * OpenRouter-specific options for routing and transforms
451
- */
452
- declare const OpenRouterOptionsSchema: z.ZodObject<{
453
- transforms: z.ZodOptional<z.ZodArray<z.ZodString>>;
454
- route: z.ZodOptional<z.ZodEnum<{
455
- fallback: "fallback";
456
- }>>;
457
- }, z.core.$strip>;
458
- /**
459
- * Google model options schema
460
- * Gemini 3 specific options for thinking depth control
461
- */
462
- declare const GoogleOptionsSchema: z.ZodObject<{
463
- thinkingLevel: z.ZodOptional<z.ZodEnum<{
464
- minimal: "minimal";
465
- low: "low";
466
- medium: "medium";
467
- high: "high";
468
- }>>;
469
- }, z.core.$strip>;
470
- /**
471
- * Anthropic model options schema
472
- * Currently empty - future options must be added per supported model family
473
- */
474
- declare const AnthropicOptionsSchema: z.ZodObject<{}, z.core.$strict>;
475
- /**
476
- * Infer TypeScript types from schemas
477
- */
478
- type GPT5Options = z.infer<typeof GPT5OptionsSchema>;
479
- type MockOptions = Record<string, never>;
480
- type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>;
481
- type GoogleOptions = z.infer<typeof GoogleOptionsSchema>;
482
- type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>;
483
- type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | GoogleOptions | AnthropicOptions;
484
- /**
485
- * Model configuration for LLM execution
486
- * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
487
- */
488
- interface ModelConfig {
489
- model: LLMModel;
490
- provider: 'openai' | 'anthropic' | 'openrouter' | 'google' | 'mock';
491
- apiKey: string;
492
- temperature?: number;
493
- /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
494
- maxOutputTokens?: number;
495
- topP?: number;
496
- /**
497
- * Model-specific options (flat structure)
498
- * Options are model-specific, not vendor-specific
499
- * Available options defined in MODEL_INFO per model
500
- * Validated at build time via validateModelOptions()
501
- */
502
- modelOptions?: ModelSpecificOptions;
503
- }
504
-
505
- /**
506
- * What happened to `strict` on a request, recorded per call rather than inferred.
507
- *
508
- * `applied` and `notAttempted` are the two states that a refusal-only field cannot tell apart —
509
- * both leave `strictRefusalReasons` empty. Recording the verdict positively is what makes "was
510
- * this agent's output actually enforced?" answerable from an `ai_calls` row.
511
- */
512
- type StrictStatus = 'applied' | 'refused' | 'compileRejected' | 'notAttempted';
513
-
514
303
  declare const ResourceGovernanceStatusSchema: z.ZodEnum<{
515
304
  active: "active";
516
305
  deprecated: "deprecated";
@@ -873,165 +662,194 @@ type AgentResourceEntry = z.infer<typeof AgentResourceEntrySchema$1>;
873
662
  type ResourceEntry$1 = z.infer<typeof ResourceEntrySchema$1>;
874
663
 
875
664
  /**
876
- * Shared form field types for dynamic form generation
877
- * Used by: Command Queue, Execution Runner UI, future form-based features
878
- */
879
- /**
880
- * Supported form field types for action payloads
881
- * Maps to Mantine form components
665
+ * Memory type definitions
666
+ * Types for agent memory management with semantic entry types
882
667
  */
883
- type FormFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'radio' | 'richtext';
884
668
  /**
885
- * Form field definition
669
+ * Semantic memory entry types
670
+ * Use-case agnostic types that describe the purpose of each entry
671
+ * Memory types mirror action types for clarity and filtering
886
672
  */
887
- interface FormField {
888
- /** Field key in payload object */
889
- name: string;
890
- /** Field label for UI */
891
- label: string;
892
- /** Field type (determines UI component) */
893
- type: FormFieldType;
894
- /** Default value */
895
- defaultValue?: unknown;
896
- /** Required field */
897
- required?: boolean;
898
- /** Placeholder text */
899
- placeholder?: string;
900
- /** Help text */
901
- description?: string;
902
- /** Options for select/radio */
903
- options?: Array<{
904
- label: string;
905
- value: string | number;
906
- }>;
907
- /** Min/max for number */
908
- min?: number;
909
- max?: number;
910
- /** Path to context value for pre-filling (dot notation, e.g., 'proposal.summary') */
911
- defaultValueFromContext?: string;
912
- }
673
+ type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'error';
913
674
  /**
914
- * Form schema for action payload collection
675
+ * Who authored an entry's content.
676
+ *
677
+ * This is what lets the assembled prompt tell framework-authored text apart from text that
678
+ * originated outside the trust boundary. `'framework'` content is ours; the other three are not
679
+ * and are rendered inside the JSON data envelope (see `MemoryManager.toContextParts`).
915
680
  */
916
- interface FormSchema {
917
- /** Form title */
918
- title?: string;
919
- /** Form description */
920
- description?: string;
921
- /** Form fields */
922
- fields: FormField[];
923
- }
924
-
681
+ type MemoryEntrySource = 'framework' | 'user' | 'tool' | 'model';
925
682
  /**
926
- * Execution interface configuration
927
- * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
928
- * Applies to both agents and workflows
683
+ * Memory entry - represents a single entry in agent memory
684
+ * Stored in agent memory, translated by adapters to vendor-specific formats
929
685
  */
930
- interface ExecutionInterface {
931
- /** Form configuration for execution inputs */
932
- form: ExecutionFormSchema;
933
- /** Optional: Schedule configuration */
934
- schedule?: ScheduleConfig;
935
- /** Optional: Webhook trigger configuration */
936
- webhook?: WebhookConfig;
686
+ interface MemoryEntry {
687
+ type: MemoryEntryType;
688
+ content: string;
689
+ timestamp: number;
690
+ turnNumber: number | null;
691
+ iterationNumber: number | null;
692
+ /**
693
+ * Provenance. **Optional on purpose** — `undefined` means unknown, which is what every
694
+ * pre-existing snapshot and every not-yet-redeployed tenant bundle produces. Read sites MUST
695
+ * test `== null`, never `=== undefined`: the `inTurnScope` predicate in `manager.ts` is the
696
+ * cautionary precedent, where a `=== undefined` check silently dropped every `null`-stamped
697
+ * entry. `isMemoryEntry` is deliberately NOT tightened to require this field; doing so would
698
+ * make every stored snapshot fail validation, and `restoreSessionMemory` fails open by
699
+ * starting the agent with empty memory rather than throwing.
700
+ */
701
+ source?: MemoryEntrySource;
702
+ /**
703
+ * Which tool produced this entry. Set on `tool-result` entries so the model can tell N parallel
704
+ * results apart -- the framework instructs batching independent tool calls in one iteration, and
705
+ * an anonymous result is unattributable the moment two land in the same iteration. `addToolError`
706
+ * already carries this (folded into its `content` JSON); this is the same fact for the success
707
+ * path, carried as a real field instead of prose the caller has to parse back out.
708
+ */
709
+ toolName?: string;
710
+ /**
711
+ * Present when `truncateContent` cut this entry's `content` to fit its token budget. A sibling
712
+ * field, never text appended into `content` -- the notice used to be spliced into the string
713
+ * itself, which could (and did) land inside a JSON string literal `truncateContent` had just cut
714
+ * open, breaking `JSON.parse` on the far end. Absent means never truncated.
715
+ */
716
+ truncated?: {
717
+ omittedTokens: number;
718
+ };
719
+ /**
720
+ * Prompt-injection warning types found in `content`, screened once here -- when the entry is
721
+ * written -- instead of by re-scanning the whole accumulated envelope on every iteration it gets
722
+ * re-sent for (`screenRequest`'s `data-envelope` slot used to do exactly that). Empty array means
723
+ * screened and clean; `undefined` means never screened (entries that bypass `addToHistory`/`set`,
724
+ * or pre-existing snapshots from before this field existed).
725
+ */
726
+ warnings?: string[];
937
727
  }
938
728
  /**
939
- * Execution form schema
940
- * Extends FormSchema with execution-specific fields
729
+ * Agent memory - Self-orchestrated memory with session + working storage
730
+ * Agent has full control over what persists, framework handles auto-compaction
941
731
  */
942
- interface ExecutionFormSchema extends FormSchema {
732
+ interface AgentMemory {
943
733
  /**
944
- * Field mappings to resource input schema
945
- * Maps form field names to contract input paths
946
- * If omitted, field names must match contract input keys exactly
734
+ * Session memory - Persists for session/conversation duration
735
+ * Never auto-trimmed by framework
736
+ * Agent-managed key-value store for critical information
737
+ * Agent provides strings, framework wraps in MemoryEntry
947
738
  */
948
- fieldMappings?: Record<string, string>;
739
+ sessionMemory: Record<string, MemoryEntry>;
949
740
  /**
950
- * Submit button configuration
951
- * Default: { label: 'Run', loadingLabel: 'Running...' }
741
+ * Working memory - Execution history
742
+ * Automatically compacted by framework when needed
743
+ * Agent doesn't control compaction
952
744
  */
953
- submitButton?: {
954
- label?: string;
955
- loadingLabel?: string;
956
- confirmMessage?: string;
957
- };
745
+ history: MemoryEntry[];
958
746
  }
959
747
  /**
960
- * Schedule configuration for automated execution
748
+ * Memory status for agent awareness
961
749
  */
962
- interface ScheduleConfig {
963
- /** Whether scheduling is enabled for this resource */
964
- enabled: boolean;
965
- /** Default schedule (cron expression) */
966
- defaultSchedule?: string;
967
- /** Allowed schedule patterns (if restricted) */
968
- allowedPatterns?: string[];
750
+ interface MemoryStatus {
751
+ sessionMemoryKeys: number;
752
+ sessionMemoryLimit: number;
753
+ sessionMemoryTokens: number;
754
+ sessionMemoryTokenLimit: number;
755
+ /**
756
+ * History tokens as a percentage of `historyBudget` — history ALONE, not history plus session
757
+ * memory. It previously reported the combined total under this name, so session memory growth
758
+ * read as history pressure and triggered history compaction that could not relieve it.
759
+ */
760
+ historyPercent: number;
761
+ /**
762
+ * Tokens the history entries **in scope for the requested turn** occupy — the same set
763
+ * `toContextParts` puts in the envelope. Equal to `storedHistoryTokens` when `getStatus` is
764
+ * called without a turn.
765
+ *
766
+ * This is the number the model is shown, and it is scoped because the model is handed a scoped
767
+ * set. Counting the whole cross-turn array here meant the framing quoted the size of a store
768
+ * while the envelope beside it carried one turn's worth of it.
769
+ */
770
+ historyTokens: number;
771
+ /**
772
+ * Tokens the **entire** history array occupies, across every turn the session snapshot restored.
773
+ *
774
+ * This is what compaction measures, because compaction trims that array. Scoping it to a turn
775
+ * would let the store grow without bound whenever the current turn happened to be small.
776
+ */
777
+ storedHistoryTokens: number;
778
+ /** `storedHistoryTokens` as a percentage of `historyBudget`. The auto-compaction trigger. */
779
+ storedHistoryPercent: number;
780
+ historyBudget: number;
969
781
  }
970
782
  /**
971
- * Webhook configuration for external triggers
783
+ * Memory constraints (optional limits)
972
784
  */
973
- interface WebhookConfig {
974
- /** Whether webhook trigger is enabled */
975
- enabled: boolean;
976
- /** Expected payload schema (for documentation) */
977
- payloadSchema?: unknown;
785
+ interface MemoryConstraints {
786
+ maxSessionMemoryKeys?: number;
787
+ maxMemoryTokens?: number;
978
788
  }
979
789
 
980
- interface WorkflowConfig extends ResourceDefinition {
981
- type: 'workflow';
982
- /** OM descriptor backing canonical identity and governance metadata. */
983
- resource?: WorkflowResourceEntry;
984
- }
985
- interface WorkflowStepDefinition {
986
- id: string;
987
- name: string;
988
- description: string;
989
- }
990
- type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>;
991
- interface LinearNext {
992
- type: 'linear';
993
- target: string;
994
- }
995
- interface ConditionalNext {
996
- type: 'conditional';
997
- routes: Array<{
998
- condition: (data: unknown) => boolean;
999
- target: string;
1000
- }>;
1001
- default: string;
1002
- }
1003
- type NextConfig = LinearNext | ConditionalNext | null;
1004
- interface WorkflowStep extends WorkflowStepDefinition {
1005
- handler: StepHandler;
1006
- inputSchema: z.ZodSchema;
1007
- outputSchema: z.ZodSchema;
1008
- next: NextConfig;
1009
- }
1010
- interface WorkflowDefinition {
1011
- config: WorkflowConfig;
1012
- contract: Contract;
1013
- steps: Record<string, WorkflowStep>;
1014
- entryPoint: string;
1015
- /**
1016
- * Metrics configuration for ROI calculations
1017
- * Optional: Only needed if tracking automation savings
1018
- */
1019
- metricsConfig?: ResourceMetricsConfig;
790
+ /**
791
+ * Types for the schema compiler. `compile.ts` walks a `JsonSchema` once, driven entirely by a
792
+ * `ProviderDialect`, and every server adapter compiles through it.
793
+ */
794
+ /**
795
+ * What happened to `strict` on a request, recorded per call rather than inferred.
796
+ *
797
+ * `applied` and `notAttempted` are the two states that a refusal-only field cannot tell apart --
798
+ * both leave `strictRefusalReasons` empty. Recording the verdict positively is what makes "was
799
+ * this agent's output actually enforced?" answerable from an `ai_calls` row.
800
+ */
801
+ type StrictStatus = 'applied' | 'refused' | 'compileRejected' | 'notAttempted';
802
+ /**
803
+ * A JSON Schema node, typed enough to be useful without pretending to validate the spec.
804
+ *
805
+ * The compiler has to accept schemas that arrive OUTSIDE the strict subset (that is the whole
806
+ * point of a dialect that can refuse or rewrite them) as well as the `$ref`/`$defs`/`const`/
807
+ * `$schema` shapes the strict subset has no vocabulary for at all. The index signature exists
808
+ * because tenant schemas carry keywords (`minLength`, `pattern`, `minimum`, ...) this compiler
809
+ * drops or refuses on, and they still need somewhere to type-check while they pass through
810
+ * `Object.entries`.
811
+ */
812
+ interface JsonSchema {
813
+ type?: string | string[];
1020
814
  /**
1021
- * Execution interface configuration (optional)
1022
- * If provided, workflow appears in Execution Runner UI
815
+ * The value is `JsonSchema | undefined`, not `JsonSchema`, because a property really can be
816
+ * declared with nothing describing it. `buildIterationResponseSchema` emits one per tool as
817
+ * `input: tool.inputSchema`, and `ToolDefinition.inputSchema` is typed `unknown` -- a tool
818
+ * deployed without one puts `undefined` under a key that exists.
819
+ *
820
+ * Both readers already handle it: `compileSchema` passes each value through `convertNode`, which
821
+ * takes `unknown`, and `collectErrors` opens with `if (!schema || typeof schema !== 'object')`
822
+ * above a comment naming this exact case. Declaring the value non-optional only hid that they
823
+ * were right to.
1023
824
  */
1024
- interface?: ExecutionInterface;
825
+ properties?: Record<string, JsonSchema | undefined>;
826
+ items?: JsonSchema;
827
+ anyOf?: JsonSchema[];
828
+ oneOf?: JsonSchema[];
829
+ allOf?: JsonSchema[];
830
+ required?: string[];
831
+ additionalProperties?: boolean | JsonSchema;
832
+ minItems?: number;
833
+ maxItems?: number;
834
+ format?: string;
835
+ enum?: unknown[];
836
+ const?: unknown;
837
+ description?: string;
838
+ default?: unknown;
839
+ $ref?: string;
840
+ $defs?: Record<string, JsonSchema>;
841
+ definitions?: Record<string, JsonSchema>;
842
+ $schema?: string;
843
+ $id?: string;
844
+ $anchor?: string;
1025
845
  /**
1026
- * Lead-gen processing stage this workflow implements (optional).
1027
- * Must match a key in the platform lead-gen stage catalog.
1028
- * Used by org-os graph derivation to surface workflow→stage edges and
1029
- * by pipeline_config validation to confirm each catalog stage has an
1030
- * implementing workflow before a list is activated.
1031
- *
1032
- * Example: stageImplemented: 'verified' on the email-verification workflow.
846
+ * OpenAPI's nullability spelling, which is not JSON Schema's. It is declared because
847
+ * `response-schema-validator.ts` READS it (`schemaPermitsNull`) -- Google's schema dialect is
848
+ * OpenAPI-derived, so a schema that reaches the validator can carry it. No dialect in `compile.ts`
849
+ * writes or rewrites it; the canonical spelling this compiler emits is `type: ['x', 'null']`.
1033
850
  */
1034
- stageImplemented?: string;
851
+ nullable?: boolean;
852
+ [key: string]: unknown;
1035
853
  }
1036
854
 
1037
855
  /**
@@ -1046,6 +864,31 @@ interface WorkflowDefinition {
1046
864
  interface LLMMessage {
1047
865
  role: 'system' | 'user' | 'assistant';
1048
866
  content: string;
867
+ /**
868
+ * Marks this message as the end of a byte-stable prefix worth an Anthropic cache breakpoint,
869
+ * beyond the one the system prompt already gets. Anthropic's rule is "everything up to and
870
+ * including the marked block is cached", so this only ever needs to sit on ONE message -- the
871
+ * last one before content that changes.
872
+ *
873
+ * `buildAgentMessages` sets it on the last replayed prior-turn message: conversation history is
874
+ * fixed for the whole turn (only the framing/envelope after it grow per iteration), so it is the
875
+ * only part of a session agent's messages, besides the system prompt, that is ever byte-identical
876
+ * call to call. A hint rather than a mechanism deliberately -- an adapter that does not read it
877
+ * (OpenAI, OpenRouter, any test stub) just ignores the extra property; only the Anthropic adapter
878
+ * turns it into a wire `cache_control` block.
879
+ */
880
+ cacheBreakpoint?: boolean;
881
+ /**
882
+ * Prompt-injection warning types already found in this message's content, when the caller has
883
+ * already screened it and wants `screenRequest` to use that verdict instead of re-scanning.
884
+ *
885
+ * Set only on the data-envelope message by `buildAgentMessages`, sourced from
886
+ * `MemoryContextParts.envelopeWarnings` -- itself an aggregate of `MemoryEntry.warnings` stamped
887
+ * once per fragment when it entered memory. `undefined` means "not pre-screened"; `screenRequest`
888
+ * falls back to scanning the content directly, which is what every other message role/slot still
889
+ * does and what a hand-built message (tests, other callers) gets by default.
890
+ */
891
+ envelopeWarnings?: string[];
1049
892
  }
1050
893
  /**
1051
894
  * Generic LLM generation request
@@ -1053,16 +896,86 @@ interface LLMMessage {
1053
896
  */
1054
897
  interface LLMGenerateRequest {
1055
898
  messages: LLMMessage[];
1056
- responseSchema: unknown;
899
+ /**
900
+ * JSON Schema for structured output. Omit it for an unstructured call.
901
+ *
902
+ * Absence is what turns validation off: `runGeneratePipeline` skips `validateResponseSchema`
903
+ * entirely when this is missing, whatever `validationSchema` holds.
904
+ *
905
+ * This was declared `responseSchema: unknown` -- required, and typed as nothing. `unknown` admits
906
+ * `undefined`, so "required" only ever forced the KEY to be written, and `createLLMCallTool`
907
+ * writes it as `undefined` on every call where the model supplies no usable schema. There was no
908
+ * type error available for that, and three separate layers re-derived the same nullability at
909
+ * runtime under three different rules -- truthiness in the pipeline, an object check in the
910
+ * validator, and a `'type'`-key check in the tool. Because the pipeline's was truthiness, `null`,
911
+ * `0` and `''` all quietly meant "no structured output" while the type insisted a schema was
912
+ * mandatory. Optional-and-typed is what those three were compensating for.
913
+ */
914
+ responseSchema?: JsonSchema;
1057
915
  /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
1058
916
  maxOutputTokens?: number;
1059
917
  temperature?: number;
1060
918
  topP?: number;
1061
919
  signal?: AbortSignal;
920
+ /**
921
+ * Caller-supplied acceptance step (Wave D2b / decision A15). A pipeline-aware adapter
922
+ * (`UniversalLLMAdapter`, via `runGeneratePipeline`) runs this once per retry attempt, right
923
+ * after the response has passed `responseSchema` validation. Throw to reject the attempt --
924
+ * rejection is classified exactly like a thrown `LLMResponseParseError` from
925
+ * `validateResponseSchema`: retryable, no circuit-breaker verdict, and the attempt is recorded as
926
+ * a failure (`ai_calls` validation-failure row) rather than a clean success. Returning normally
927
+ * (including `undefined`) accepts the response.
928
+ *
929
+ * Optional, and a HINT rather than a dependency -- an adapter that does not read this field
930
+ * simply ignores it, so a caller must not assume it ran:
931
+ * - A bare test-stub `LLMAdapter` (many exist in this codebase) does not invoke it.
932
+ * - `PostMessageLLMAdapter` (`packages/sdk/src/worker/llm-adapter.ts`) cannot forward it at all --
933
+ * functions cannot be structured-cloned across the worker `postMessage` boundary, so its
934
+ * `params` object is built from an explicit allowlist that omits `accept`. The field is dropped
935
+ * before `postMessage` is ever called (no `DataCloneError`), and the parent-side handler that
936
+ * fulfils the call (`tool-dispatcher.ts`'s `case 'llm'`) rebuilds its own `LLMGenerateRequest`
937
+ * from that allowlisted payload, so there is nothing to forward even in principle. This is the
938
+ * path every deployed org-bundle agent and the `command-center-assistant` static module run
939
+ * through today -- `accept` does not reach their retry loop.
940
+ *
941
+ * This is not a validation mechanism on its own: it does not decide whether output is acceptable,
942
+ * the caller's function does, by throwing or not. `callLLMForAgentIteration`
943
+ * (`execution/engine/agent/reasoning/adapters/agent-adapter-helpers.ts`) passes its Zod parse of
944
+ * the iteration response as this field, so a malformed-but-schema-valid iteration is re-sampled
945
+ * inside the retry loop instead of losing the turn -- for the in-process callers that can see it.
946
+ */
947
+ accept?: (output: unknown) => void;
948
+ /**
949
+ * The schema the RESPONSE is validated against, when that must differ from the schema the
950
+ * provider was asked to sample against. Defaults to `responseSchema` when omitted.
951
+ *
952
+ * **This does not affect what is sent to the provider.** `responseSchema` remains the only schema
953
+ * an adapter puts on the wire; this one is read solely by `runGeneratePipeline`'s validation step.
954
+ * Whether validation happens at all is still decided by `responseSchema` -- a request with no
955
+ * `responseSchema` is unstructured and stays unvalidated, whatever this field holds.
956
+ *
957
+ * A caller may legitimately ACCEPT A SUPERSET of what it ASKS FOR -- a document that validates a
958
+ * response more leniently than the one the provider was asked to sample against. No caller in this
959
+ * codebase supplies one today (agent iterations validate with a single Zod parse instead, see
960
+ * `agent-adapter-helpers.ts`), but the mechanism stays: `validateResponseSchema` does not descend
961
+ * into `anyOf`/`oneOf` regardless of which document is supplied here, so this field only ever
962
+ * changes which top-level/required/type keywords are checked, never which acceptance contract a
963
+ * union is read as.
964
+ *
965
+ * Unlike `accept` above, this is DATA. It is structured-cloneable, so it survives the worker
966
+ * `postMessage` boundary that drops `accept`: `PostMessageLLMAdapter` forwards it in its params
967
+ * allowlist and `tool-dispatcher.ts`'s `case 'llm'` puts it back on the `LLMGenerateRequest` it
968
+ * rebuilds parent-side. That is why a divergence expressible as a schema belongs here rather than
969
+ * in a callback -- deployed org-bundle agents run on the far side of that boundary.
970
+ */
971
+ validationSchema?: JsonSchema;
1062
972
  }
1063
973
  /**
1064
974
  * Generic LLM generation response
1065
- * Usage field is internal-only (stripped by UniversalLLMAdapter wrapper)
975
+ * `usage`, `cost`, `strictStatus` and `strictRefusalReasons` are observability fields. They are
976
+ * **read** by `UniversalLLMAdapter` and lifted onto the `ai_calls` row; they are **not removed**.
977
+ * The wrapper returns the base adapter's response object as-is, so a caller can observe all four.
978
+ * Earlier revisions of this file claimed they were stripped — they never were.
1066
979
  */
1067
980
  interface LLMGenerateResponse<T = unknown> {
1068
981
  output: T;
@@ -1070,35 +983,53 @@ interface LLMGenerateResponse<T = unknown> {
1070
983
  inputTokens: number;
1071
984
  outputTokens: number;
1072
985
  totalTokens: number;
986
+ /**
987
+ * Anthropic-only: input tokens served from the prompt cache (`cache_read_input_tokens`), billed
988
+ * at 0.1x the base input rate. Optional so OpenAI/OpenRouter usage objects, which never report
989
+ * this, stay valid -- absent means "this provider doesn't report it," not "zero were read."
990
+ */
991
+ cacheReadInputTokens?: number;
992
+ /**
993
+ * Anthropic-only: input tokens written to the prompt cache this call
994
+ * (`cache_creation_input_tokens`), billed at 1.25x the base input rate. Same optionality
995
+ * rationale as `cacheReadInputTokens`.
996
+ */
997
+ cacheCreationInputTokens?: number;
1073
998
  };
1074
999
  cost?: number;
1075
1000
  /**
1076
- * What actually happened to `strict` on the request that produced this response. Every server
1077
- * adapter sets it on every call, so the value is a statement rather than an inference:
1001
+ * What actually happened to `strict` on the request that produced this response.
1078
1002
  *
1079
1003
  * - `applied` — the request carried `strict: true` and the grammar was in effect
1080
- * - `refused` — `toStrictSchema` could not express the schema, so the request went out unstrict
1081
- * - `compileRejected` — the schema passed `toStrictSchema` but the provider's grammar compiler
1004
+ * - `refused` — `compileSchema` could not express the schema, so the request went out unstrict
1005
+ * - `compileRejected` — the schema passed `compileSchema` but the provider's grammar compiler
1082
1006
  * rejected it at request time, and the call was retried unstrict
1083
- * - `notAttempted` — this adapter does not send strict at all (OpenAI, Google, OpenRouter)
1007
+ * - `notAttempted` — the adapter did not send `strict` on this call
1084
1008
  *
1085
1009
  * This exists because `strictRefusalReasons` alone cannot answer the question. Its absence means
1086
1010
  * "strict held" OR "nothing ever tried", and a prod run that recorded zero refusals while
1087
1011
  * returning an array-typed field as a string is exactly the case where the difference matters.
1088
1012
  *
1089
- * Internal-only, like `usage` `UniversalLLMAdapter` lifts it onto the `ai_calls` row and
1090
- * strips it before the response reaches callers.
1013
+ * **Do not read this as "provider X never sends strict."** It describes one call, not an adapter.
1014
+ * A previous revision of this comment enumerated OpenAI, Google and OpenRouter as adapters that
1015
+ * never send `strict`, which was false for OpenRouter — it sends `strict: true` whenever the
1016
+ * schema compiles, and separately reports `notAttempted`. That producer bug is still live; the
1017
+ * fix is to make the value a return of schema compilation rather than a per-adapter literal.
1018
+ * `MockAdapter` sets no value at all, so absence does not imply `notAttempted` either.
1019
+ *
1020
+ * Observability only — `UniversalLLMAdapter` lifts it onto the `ai_calls` row. It is not removed
1021
+ * from the response.
1091
1022
  */
1092
1023
  strictStatus?: StrictStatus;
1093
1024
  /**
1094
1025
  * Why this call went out WITHOUT `strict`, on an adapter that tried to send it with one.
1095
1026
  *
1096
1027
  * The detail behind a `refused` / `compileRejected` `strictStatus` — the short, stable reason
1097
- * strings `toStrictSchema` computes. Read `strictStatus` to answer "was it enforced"; read this
1028
+ * strings `compileSchema` computes. Read `strictStatus` to answer "was it enforced"; read this
1098
1029
  * to answer "why not".
1099
1030
  *
1100
- * Internal-only, like `usage` — `UniversalLLMAdapter` lifts it onto the `ai_calls` row and
1101
- * strips it before the response reaches callers.
1031
+ * Observability only — `UniversalLLMAdapter` lifts it onto the `ai_calls` row. It is not removed
1032
+ * from the response.
1102
1033
  */
1103
1034
  strictRefusalReasons?: string[];
1104
1035
  }
@@ -1123,89 +1054,84 @@ interface LLMAdapter {
1123
1054
  }
1124
1055
 
1125
1056
  /**
1126
- * Memory type definitions
1127
- * Types for agent memory management with semantic entry types
1057
+ * Model Configuration
1058
+ * Centralized model information, configuration, options, constraints, and validation
1059
+ * Single source of truth for all model-related definitions
1060
+ * Update manually when pricing changes or new models are added
1128
1061
  */
1062
+
1129
1063
  /**
1130
- * Semantic memory entry types
1131
- * Use-case agnostic types that describe the purpose of each entry
1132
- * Memory types mirror action types for clarity and filtering
1064
+ * Supported Open AI models (direct SDK access)
1133
1065
  */
1134
- type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'delegation-result' | 'error';
1066
+ type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano';
1135
1067
  /**
1136
- * Who authored an entry's content.
1137
- *
1138
- * This is what lets the assembled prompt tell framework-authored text apart from text that
1139
- * originated outside the trust boundary. `'framework'` content is ours; the other three are not
1140
- * and are rendered inside the JSON data envelope (see `MemoryManager.toContextParts`).
1068
+ * Supported OpenRouter models (explicit union for type safety)
1141
1069
  */
1142
- type MemoryEntrySource = 'framework' | 'user' | 'tool' | 'model';
1070
+ type OpenRouterModel = 'openrouter/z-ai/glm-5';
1143
1071
  /**
1144
- * Memory entry - represents a single entry in agent memory
1145
- * Stored in agent memory, translated by adapters to vendor-specific formats
1072
+ * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
1146
1073
  */
1147
- interface MemoryEntry {
1148
- type: MemoryEntryType;
1149
- content: string;
1150
- timestamp: number;
1151
- turnNumber: number | null;
1152
- iterationNumber: number | null;
1153
- /**
1154
- * Provenance. **Optional on purpose** — `undefined` means unknown, which is what every
1155
- * pre-existing snapshot and every not-yet-redeployed tenant bundle produces. Read sites MUST
1156
- * test `== null`, never `=== undefined`: the `inTurnScope` predicate in `manager.ts` is the
1157
- * cautionary precedent, where a `=== undefined` check silently dropped every `null`-stamped
1158
- * entry. `isMemoryEntry` is deliberately NOT tightened to require this field; doing so would
1159
- * make every stored snapshot fail validation, and `restoreSessionMemory` fails open by
1160
- * starting the agent with empty memory rather than throwing.
1161
- */
1162
- source?: MemoryEntrySource;
1163
- }
1074
+ type AnthropicModel = 'claude-opus-5' | 'claude-sonnet-5' | 'claude-haiku-4-5-20251001' | 'claude-haiku-4-5';
1075
+ /** Supported LLM models */
1076
+ type LLMModel = OpenAIModel | OpenRouterModel | AnthropicModel | 'mock';
1164
1077
  /**
1165
- * Agent memory - Self-orchestrated memory with session + working storage
1166
- * Agent has full control over what persists, framework handles auto-compaction
1078
+ * GPT-5 model options schema
1167
1079
  */
1168
- interface AgentMemory {
1169
- /**
1170
- * Session memory - Persists for session/conversation duration
1171
- * Never auto-trimmed by framework
1172
- * Agent-managed key-value store for critical information
1173
- * Agent provides strings, framework wraps in MemoryEntry
1174
- */
1175
- sessionMemory: Record<string, MemoryEntry>;
1176
- /**
1177
- * Working memory - Execution history
1178
- * Automatically compacted by framework when needed
1179
- * Agent doesn't control compaction
1180
- */
1181
- history: MemoryEntry[];
1182
- }
1080
+ declare const GPT5OptionsSchema: z.ZodObject<{
1081
+ reasoning_effort: z.ZodOptional<z.ZodEnum<{
1082
+ minimal: "minimal";
1083
+ low: "low";
1084
+ medium: "medium";
1085
+ high: "high";
1086
+ }>>;
1087
+ verbosity: z.ZodOptional<z.ZodEnum<{
1088
+ low: "low";
1089
+ medium: "medium";
1090
+ high: "high";
1091
+ }>>;
1092
+ }, z.core.$strip>;
1183
1093
  /**
1184
- * Memory status for agent awareness
1094
+ * OpenRouter model options schema
1095
+ * OpenRouter-specific options for routing and transforms
1185
1096
  */
1186
- interface MemoryStatus {
1187
- sessionMemoryKeys: number;
1188
- sessionMemoryLimit: number;
1189
- currentKeys: string[];
1190
- sessionMemoryTokens: number;
1191
- sessionMemoryTokenLimit: number;
1192
- /**
1193
- * History tokens as a percentage of `historyBudget` — history ALONE, not history plus session
1194
- * memory. It previously reported the combined total under this name, so session memory growth
1195
- * read as history pressure and triggered history compaction that could not relieve it.
1196
- */
1197
- historyPercent: number;
1198
- historyTokens: number;
1199
- historyBudget: number;
1200
- totalTokens: number;
1201
- tokenBudget: number;
1202
- }
1097
+ declare const OpenRouterOptionsSchema: z.ZodObject<{
1098
+ transforms: z.ZodOptional<z.ZodArray<z.ZodString>>;
1099
+ route: z.ZodOptional<z.ZodEnum<{
1100
+ fallback: "fallback";
1101
+ }>>;
1102
+ }, z.core.$strip>;
1203
1103
  /**
1204
- * Memory constraints (optional limits)
1104
+ * Anthropic model options schema
1105
+ * Currently empty - future options must be added per supported model family
1205
1106
  */
1206
- interface MemoryConstraints {
1207
- maxSessionMemoryKeys?: number;
1208
- maxMemoryTokens?: number;
1107
+ declare const AnthropicOptionsSchema: z.ZodObject<{}, z.core.$strict>;
1108
+ /**
1109
+ * Infer TypeScript types from schemas
1110
+ */
1111
+ type GPT5Options = z.infer<typeof GPT5OptionsSchema>;
1112
+ type MockOptions = Record<string, never>;
1113
+ type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>;
1114
+ type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>;
1115
+ type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | AnthropicOptions;
1116
+ /**
1117
+ * Model configuration for LLM execution
1118
+ * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
1119
+ */
1120
+ interface ModelConfig {
1121
+ model: LLMModel;
1122
+ provider: 'openai' | 'anthropic' | 'openrouter' | 'mock';
1123
+ apiKey: string;
1124
+ temperature?: number;
1125
+ /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
1126
+ maxOutputTokens?: number;
1127
+ topP?: number;
1128
+ /**
1129
+ * Model-specific options (flat structure)
1130
+ * Options are model-specific, not vendor-specific
1131
+ * Available options defined in MODEL_INFO per model
1132
+ * Validated at build time via validateModelOptions()
1133
+ */
1134
+ modelOptions?: ModelSpecificOptions;
1209
1135
  }
1210
1136
 
1211
1137
  /**
@@ -1225,8 +1151,27 @@ interface MemoryConstraints {
1225
1151
  interface MemoryContextParts {
1226
1152
  /** Framework-authored. Memory status and a description of the envelope. Carries NO stored content. */
1227
1153
  framing: string;
1228
- /** Every stored fragment, JSON-encoded and source-tagged. Untrusted. */
1154
+ /** Every stored fragment, JSON-encoded. Untrusted. */
1229
1155
  dataEnvelope: string;
1156
+ /**
1157
+ * Union of prompt-injection warning types already found across every fragment `dataEnvelope`
1158
+ * actually carries this call, aggregated from verdicts stamped once when each fragment entered
1159
+ * memory (see `MemoryEntry.warnings`) rather than by re-scanning `dataEnvelope`'s text on every
1160
+ * iteration it gets rebuilt for. Elided fragments (see `ENVELOPE_FULL_RESULT_WINDOW`) contribute
1161
+ * nothing here — their original content isn't what gets sent once they're stubbed.
1162
+ *
1163
+ * This is metadata about the envelope, not part of it: folding a detector's own finding into the
1164
+ * model-visible JSON would hand a would-be attacker — plausibly the same person on the other end
1165
+ * of a session conversation — direct feedback on which pattern tripped. A caller wiring this up
1166
+ * (`screenRequest`'s `data-envelope` slot is the one that currently re-scans instead of reading
1167
+ * this) should treat it exactly the way `screenRequest` already treats cross-turn history: it
1168
+ * warns, but whether it blocks is that caller's decision to make, not this one's.
1169
+ *
1170
+ * Optional (not just possibly-empty): the fixture literals in `agent/reasoning/**` tests build
1171
+ * `MemoryContextParts` by hand without it, and requiring it would make this signature's landing
1172
+ * a forced edit across files this change does not otherwise touch.
1173
+ */
1174
+ envelopeWarnings?: string[];
1230
1175
  }
1231
1176
  /**
1232
1177
  * Memory Manager - Agent memory orchestration
@@ -1238,7 +1183,41 @@ declare class MemoryManager {
1238
1183
  private constraints;
1239
1184
  private logger?;
1240
1185
  private cachedSnapshot?;
1186
+ /**
1187
+ * Rolling correction for `estimateTokens`'s bias, learned from real provider usage.
1188
+ * `undefined` until the first `recordActualUsage` call -- the cold-start state, where
1189
+ * `estimate()` returns the raw `estimateTokens` output unscaled. See `recordActualUsage`.
1190
+ */
1191
+ private tokenCorrectionFactor?;
1241
1192
  constructor(memory: AgentMemory, constraints?: MemoryConstraints, logger?: AgentScopedLogger | undefined);
1193
+ /**
1194
+ * Record how far `estimateTokens` was from reality on a real provider call, and roll it into a
1195
+ * correction applied to every estimate this instance makes from here on -- `getStatus`'s three
1196
+ * token fields and `enforceSessionMemoryTokenLimit`'s eviction check, which is what
1197
+ * `autoCompact`/`enforceHardLimits` actually decide compaction from (C3 / Wave M3).
1198
+ *
1199
+ * `estimateTokens` is `chars / 3.5` -- a constant-ratio guess with no knowledge of JSON escaping,
1200
+ * key overhead, or real tokenizer behaviour. Every provider call already returns an EXACT count
1201
+ * (`usage.inputTokens`) that reaches `ai_calls` and is then dropped; this is where it stops being
1202
+ * dropped, without replacing the estimator outright -- a cold session still needs SOME number
1203
+ * before its first real call completes, so the estimator stays the prior and this only corrects
1204
+ * it once real data exists.
1205
+ *
1206
+ * `estimatedRequestTokens` must be `estimateTokens` applied to the SAME text `actualInputTokens`
1207
+ * was billed for -- the whole assembled request (system prompt, tools, conversation history, the
1208
+ * envelope, everything), not just what this class itself emits. `estimateTokens`'s bias is a
1209
+ * property of the heuristic, not of which slice of the request it is pointed at, so measuring it
1210
+ * against the full request (visible to the caller, not to this class) and applying the result to
1211
+ * this class's own estimates (which can only ever see its own slice) is a fair trade -- one ratio,
1212
+ * calibrated on real data, standing in for a per-segment breakdown nothing needs.
1213
+ *
1214
+ * Exponential moving average, not a straight replace: a single call's ratio is noisy, and a
1215
+ * straight replace lets one outlier swing every compaction decision made afterward. Each new
1216
+ * observation gets 30% weight, converging within a handful of calls without chasing one spike.
1217
+ */
1218
+ recordActualUsage(estimatedRequestTokens: number, actualInputTokens: number): void;
1219
+ /** `estimateTokens`, scaled by the learned correction once one exists. See `recordActualUsage`. */
1220
+ private estimate;
1242
1221
  /**
1243
1222
  * Set session memory entry (agent provides string, framework wraps it)
1244
1223
  * @param key - Session memory key
@@ -1280,6 +1259,14 @@ declare class MemoryManager {
1280
1259
  * are not. Eviction is oldest-first by timestamp, matching the key-count path, and always
1281
1260
  * leaves at least one entry so a single oversized key degrades to "one key" rather than to
1282
1261
  * "memory silently emptied".
1262
+ *
1263
+ * The running total is **recomputed** from the survivors rather than decremented per entry.
1264
+ * `getStatus` estimates the pool as a ceiling of the joined sum, and a per-entry decrement is a
1265
+ * sum of ceilings — the larger of the two by up to one token per key. The running total therefore
1266
+ * fell faster than the pool did, and the loop could exit reporting a fit while the very next
1267
+ * `getStatus` still read over the limit. Recomputing makes the loop's exit condition and the
1268
+ * number it is judged by the same expression. The pool is capped at `MAX_SESSION_MEMORY_KEYS`
1269
+ * entries, so the extra passes are bounded and cheap.
1283
1270
  */
1284
1271
  private enforceSessionMemoryTokenLimit;
1285
1272
  /**
@@ -1289,9 +1276,13 @@ declare class MemoryManager {
1289
1276
  getHistoryLength(): number;
1290
1277
  /**
1291
1278
  * Get memory status for agent awareness
1279
+ *
1280
+ * @param currentTurn - Turn to scope `historyTokens` / `historyPercent` to. Omit to measure the
1281
+ * whole store, which is what the compaction paths want. Callers building something the model
1282
+ * reads should pass it, so the count describes the set the model is actually handed.
1292
1283
  * @returns Memory status with token usage and key counts
1293
1284
  */
1294
- getStatus(): MemoryStatus;
1285
+ getStatus(currentTurn?: number): MemoryStatus;
1295
1286
  /**
1296
1287
  * Create memory snapshot for persistence
1297
1288
  * Caches snapshot internally for later retrieval
@@ -1322,184 +1313,162 @@ declare class MemoryManager {
1322
1313
  * treat "everything in this block" as data was also being handed the live question inside that
1323
1314
  * block.
1324
1315
  *
1325
- * Shows current iteration entries FIRST (reverse chronological) for LLM attention.
1316
+ * History entries stay chronological. They used to be split into a "current iteration" slot
1317
+ * (reverse chronological, for LLM positional bias) and an "earlier" slot -- but the LLM call
1318
+ * always happens BEFORE `addToHistory` writes that iteration's own entries, so the
1319
+ * current-iteration slot held nothing on any call that mattered. One chronological list replaces
1320
+ * both.
1321
+ *
1322
+ * Tool results (and tool errors) older than `ENVELOPE_FULL_RESULT_WINDOW` iterations are carried
1323
+ * as a short stub instead of their full content -- see `ENVELOPE_FULL_RESULT_WINDOW`. The STORE
1324
+ * (`this.memory.history`) is untouched; only what this call carries is capped.
1326
1325
  *
1327
1326
  * @param currentIteration - Current iteration number (0 = pre-iteration)
1328
1327
  * @param currentTurn - Current turn number (optional, for session context filtering)
1329
1328
  */
1330
1329
  toContextParts(currentIteration: number, currentTurn?: number): MemoryContextParts;
1331
1330
  }
1332
-
1331
+
1332
+ /**
1333
+ * Shared form field types for dynamic form generation
1334
+ * Used by: Command Queue, Execution Runner UI, future form-based features
1335
+ */
1336
+ /**
1337
+ * Supported form field types for action payloads
1338
+ * Maps to Mantine form components
1339
+ */
1340
+ type FormFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'radio' | 'richtext';
1341
+ /**
1342
+ * Form field definition
1343
+ */
1344
+ interface FormField {
1345
+ /** Field key in payload object */
1346
+ name: string;
1347
+ /** Field label for UI */
1348
+ label: string;
1349
+ /** Field type (determines UI component) */
1350
+ type: FormFieldType;
1351
+ /** Default value */
1352
+ defaultValue?: unknown;
1353
+ /** Required field */
1354
+ required?: boolean;
1355
+ /** Placeholder text */
1356
+ placeholder?: string;
1357
+ /** Help text */
1358
+ description?: string;
1359
+ /** Options for select/radio */
1360
+ options?: Array<{
1361
+ label: string;
1362
+ value: string | number;
1363
+ }>;
1364
+ /** Min/max for number */
1365
+ min?: number;
1366
+ max?: number;
1367
+ /** Path to context value for pre-filling (dot notation, e.g., 'proposal.summary') */
1368
+ defaultValueFromContext?: string;
1369
+ }
1333
1370
  /**
1334
- * Knowledge Map Types
1335
- *
1336
- * Enables agents to navigate organizational knowledge through a lightweight
1337
- * graph that lazy-loads capabilities on-demand.
1338
- *
1339
- * @module agent/knowledge-map
1371
+ * Form schema for action payload collection
1340
1372
  */
1373
+ interface FormSchema {
1374
+ /** Form title */
1375
+ title?: string;
1376
+ /** Form description */
1377
+ description?: string;
1378
+ /** Form fields */
1379
+ fields: FormField[];
1380
+ }
1341
1381
 
1342
1382
  /**
1343
- * Lightweight knowledge map (passed as agent property)
1344
- *
1345
- * Contains metadata about available knowledge nodes without loading
1346
- * the full content upfront. Total size: ~300-500 tokens.
1347
- *
1348
- * Multi-tenancy is enforced via:
1349
- * - File-scoped maps (organizations/{org-name}/knowledge/)
1350
- * - ExecutionContext.organizationId passed to node.load()
1383
+ * Execution interface configuration
1384
+ * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
1385
+ * Applies to both agents and workflows
1351
1386
  */
1352
- interface KnowledgeMap {
1353
- /** Available knowledge nodes indexed by ID */
1354
- nodes: Record<string, KnowledgeNode>;
1387
+ interface ExecutionInterface {
1388
+ /** Form configuration for execution inputs */
1389
+ form: ExecutionFormSchema;
1390
+ /** Optional: Schedule configuration */
1391
+ schedule?: ScheduleConfig;
1392
+ /** Optional: Webhook trigger configuration */
1393
+ webhook?: WebhookConfig;
1355
1394
  }
1356
1395
  /**
1357
- * Single knowledge source
1358
- *
1359
- * Represents a domain knowledge area (CRM, brand guidelines, Excel tools)
1360
- * that can be lazy-loaded to provide instructions and tools to agents.
1396
+ * Execution form schema
1397
+ * Extends FormSchema with execution-specific fields
1361
1398
  */
1362
- interface KnowledgeNode {
1363
- /** Unique identifier for this node (e.g., "crm", "brand-guidelines") */
1364
- id: string;
1365
- /**
1366
- * Description of when to use this knowledge
1367
- * Used for semantic matching against user intent
1368
- */
1369
- description: string;
1370
- /**
1371
- * Load knowledge content on-demand
1372
- *
1373
- * @param context - Execution context with organizationId for multi-tenancy
1374
- * @returns Promise resolving to knowledge content (prompt + optional tools)
1375
- */
1376
- load(context: ExecutionContext): Promise<KnowledgeContent>;
1399
+ interface ExecutionFormSchema extends FormSchema {
1377
1400
  /**
1378
- * Loaded state flag
1379
- * Set to true after load() is called
1401
+ * Field mappings to resource input schema
1402
+ * Maps form field names to contract input paths
1403
+ * If omitted, field names must match contract input keys exactly
1380
1404
  */
1381
- loaded?: boolean;
1405
+ fieldMappings?: Record<string, string>;
1382
1406
  /**
1383
- * Cached prompt (for system prompt serialization)
1384
- * Only the prompt is cached - tools go to toolRegistry, children flattened to nodes
1407
+ * Submit button configuration
1408
+ * Default: { label: 'Run', loadingLabel: 'Running...' }
1385
1409
  */
1386
- prompt?: string;
1410
+ submitButton?: {
1411
+ label?: string;
1412
+ loadingLabel?: string;
1413
+ confirmMessage?: string;
1414
+ };
1387
1415
  }
1388
1416
  /**
1389
- * Content returned by knowledge node
1390
- *
1391
- * Separates instructions (prompt) from capabilities (tools).
1392
- * Tools are optional - some nodes only provide context.
1393
- *
1394
- * Supports recursive navigation - nodes can contain child nodes
1395
- * that are discovered when the parent node is loaded.
1396
- */
1397
- interface KnowledgeContent {
1398
- /** Instructions and context (markdown format) */
1399
- prompt: string;
1400
- /** Tool implementations (optional) */
1401
- tools?: Tool[];
1402
- /**
1403
- * Child knowledge nodes (optional, recursive)
1404
- *
1405
- * Enables hierarchical navigation: base → specialized → deep expertise.
1406
- * Child nodes are flattened into the main knowledge map when parent loads,
1407
- * making them available for subsequent navigate-knowledge actions.
1408
- *
1409
- * Example: CRM base node returns crm-customers and crm-deals as children
1410
- */
1411
- nodes?: Record<string, KnowledgeNode>;
1417
+ * Schedule configuration for automated execution
1418
+ */
1419
+ interface ScheduleConfig {
1420
+ /** Whether scheduling is enabled for this resource */
1421
+ enabled: boolean;
1422
+ /** Default schedule (cron expression) */
1423
+ defaultSchedule?: string;
1424
+ /** Allowed schedule patterns (if restricted) */
1425
+ allowedPatterns?: string[];
1412
1426
  }
1413
-
1414
1427
  /**
1415
- * Agent-specific type definitions
1416
- * Types for autonomous agents with tools, memory, and constraints
1428
+ * Webhook configuration for external triggers
1417
1429
  */
1430
+ interface WebhookConfig {
1431
+ /** Whether webhook trigger is enabled */
1432
+ enabled: boolean;
1433
+ /** Expected payload schema (for documentation) */
1434
+ payloadSchema?: unknown;
1435
+ }
1418
1436
 
1419
- /**
1420
- * Factory function for creating LLM adapters.
1421
- * Injected into the Agent class to decouple the engine from server-only provider SDKs.
1422
- * - API process: provides createLLMAdapter (real SDKs + process.env API keys)
1423
- * - SDK worker: provides PostMessageLLMAdapter (proxies via platform.call)
1424
- *
1425
- * Uses `any` for optional params so both the real createLLMAdapter (with typed
1426
- * AIUsageCollector/AICallContext) and the worker proxy (which ignores them) satisfy the type.
1427
- */
1428
- type LLMAdapterFactory = (config: ModelConfig, ...args: any[]) => LLMAdapter;
1429
- type AgentKind = 'orchestrator' | 'specialist' | 'utility' | 'platform';
1430
- interface AgentConfig extends ResourceDefinition {
1431
- type: 'agent';
1437
+ interface WorkflowConfig extends ResourceDefinition {
1438
+ type: 'workflow';
1432
1439
  /** OM descriptor backing canonical identity and governance metadata. */
1433
- resource?: AgentResourceEntry;
1434
- kind: AgentKind;
1435
- systemPrompt: string;
1436
- constraints?: AgentConstraints;
1437
- /**
1438
- * Session capability declaration (opt-in)
1439
- * If true, agent is designed for multi-turn session interactions
1440
- * Controls whether agent can use message action and appears in Sessions UI
1441
- *
1442
- * Use for:
1443
- * - Conversational agents with multi-turn interactions
1444
- * - Agents requiring persistent context across turns
1445
- * - Agents that need human-in-the-loop communication
1446
- */
1447
- sessionCapable?: boolean;
1448
- /**
1449
- * Security level for system prompt hardening (auto-derived if omitted)
1450
- *
1451
- * - 'standard': Lightweight defense (3 rules) - default for non-session agents
1452
- * - 'hardened': Comprehensive defense (5 rules) - default for session-capable agents
1453
- * - 'none': No security prompt - for pure internal agents with no external input
1454
- *
1455
- * If omitted, derived from sessionCapable:
1456
- * sessionCapable: true -> 'hardened'
1457
- * sessionCapable: false -> 'standard'
1458
- */
1459
- securityLevel?: 'standard' | 'hardened' | 'none';
1460
- /**
1461
- * Memory management preferences (opt-in)
1462
- * If provided, agent can use memoryOps to manage session memory
1463
- * If omitted, agent has no memory management capabilities
1464
- *
1465
- * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
1466
- * This guidance is injected into the system prompt when memory management is enabled.
1467
- *
1468
- * Use for:
1469
- * - Conversational agents needing cross-turn context
1470
- * - Agents managing complex user preferences
1471
- * - Agents tracking decisions over multiple iterations
1472
- */
1473
- memoryPreferences?: string;
1440
+ resource?: WorkflowResourceEntry;
1474
1441
  }
1475
- interface AgentConstraints {
1476
- maxIterations?: number;
1477
- timeout?: number;
1478
- maxSessionMemoryKeys?: number;
1479
- maxMemoryTokens?: number;
1442
+ interface WorkflowStepDefinition {
1443
+ id: string;
1444
+ name: string;
1445
+ description: string;
1480
1446
  }
1481
- interface AgentDefinition {
1482
- config: AgentConfig;
1447
+ type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>;
1448
+ interface LinearNext {
1449
+ type: 'linear';
1450
+ target: string;
1451
+ }
1452
+ interface ConditionalNext {
1453
+ type: 'conditional';
1454
+ routes: Array<{
1455
+ condition: (data: unknown) => boolean;
1456
+ target: string;
1457
+ }>;
1458
+ default: string;
1459
+ }
1460
+ type NextConfig = LinearNext | ConditionalNext | null;
1461
+ interface WorkflowStep extends WorkflowStepDefinition {
1462
+ handler: StepHandler;
1463
+ inputSchema: z.ZodSchema;
1464
+ outputSchema: z.ZodSchema;
1465
+ next: NextConfig;
1466
+ }
1467
+ interface WorkflowDefinition {
1468
+ config: WorkflowConfig;
1483
1469
  contract: Contract;
1484
- tools: Tool[];
1485
- /**
1486
- * Model configuration for LLM execution
1487
- * Specifies provider, API key, and model-specific options
1488
- */
1489
- modelConfig: ModelConfig;
1490
- /**
1491
- * Optional knowledge map for lazy-loading capabilities
1492
- * Enables agents to navigate organizational knowledge on-demand
1493
- */
1494
- knowledgeMap?: KnowledgeMap;
1495
- /**
1496
- * Preload memory before execution starts
1497
- * Handles BOTH context loading AND session restoration
1498
- *
1499
- * @param context - Execution context (includes sessionId if session turn)
1500
- * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
1501
- */
1502
- preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory;
1470
+ steps: Record<string, WorkflowStep>;
1471
+ entryPoint: string;
1503
1472
  /**
1504
1473
  * Metrics configuration for ROI calculations
1505
1474
  * Optional: Only needed if tracking automation savings
@@ -1507,31 +1476,19 @@ interface AgentDefinition {
1507
1476
  metricsConfig?: ResourceMetricsConfig;
1508
1477
  /**
1509
1478
  * Execution interface configuration (optional)
1510
- * If provided, agent appears in Execution Runner UI
1479
+ * If provided, workflow appears in Execution Runner UI
1511
1480
  */
1512
1481
  interface?: ExecutionInterface;
1513
- }
1514
- /**
1515
- * Agent execution context
1516
- * Groups all state needed for agent execution phases
1517
- */
1518
- interface IterationContext {
1519
- config: AgentConfig;
1520
- contract: Contract;
1521
- toolRegistry: Map<string, Tool>;
1522
- memoryManager: MemoryManager;
1523
- executionContext: ExecutionContext;
1524
- iteration: number;
1525
- logger: AgentScopedLogger;
1526
- modelConfig: ModelConfig;
1527
- adapterFactory: LLMAdapterFactory;
1528
- knowledgeMap?: KnowledgeMap;
1529
1482
  /**
1530
- * The validated input for this execution, serialized. It travels here because the model gets
1531
- * it as its own `role:'user'` message; nothing else in this context carried it, so the input
1532
- * had to be read back out of memory history and shipped inside the memory block.
1483
+ * Lead-gen processing stage this workflow implements (optional).
1484
+ * Must match a key in the platform lead-gen stage catalog.
1485
+ * Used by org-os graph derivation to surface workflow→stage edges and
1486
+ * by pipeline_config validation to confirm each catalog stage has an
1487
+ * implementing workflow before a list is activated.
1488
+ *
1489
+ * Example: stageImplemented: 'verified' on the email-verification workflow.
1533
1490
  */
1534
- currentInput: string;
1491
+ stageImplemented?: string;
1535
1492
  }
1536
1493
 
1537
1494
  type Json = string | number | boolean | null | {
@@ -8260,6 +8217,32 @@ type StorageDownloadOutput = z.infer<typeof StorageDownloadOutputSchema>;
8260
8217
  type StorageDeleteOutput = z.infer<typeof StorageDeleteOutputSchema>;
8261
8218
  type StorageListOutput = z.infer<typeof StorageListOutputSchema>;
8262
8219
 
8220
+ /**
8221
+ * AIUsageCollector
8222
+ * Centralized token tracking that aggregates usage across all LLM calls in an execution
8223
+ */
8224
+ declare class AIUsageCollector {
8225
+ private model;
8226
+ private calls;
8227
+ private callSequence;
8228
+ /**
8229
+ * Record a single AI call with usage metrics
8230
+ *
8231
+ * @param usage - Token usage and latency data from LLM adapter
8232
+ * @param callType - Type discriminator (agent-reasoning, tool, etc.)
8233
+ * @param context - Optional typed context specific to callType
8234
+ */
8235
+ record(usage: LLMUsageData, callType?: BaseAICall['callType'], context?: AICallContext): void;
8236
+ /**
8237
+ * Get aggregated summary of all AI calls
8238
+ */
8239
+ getSummary(): AIUsageSummary;
8240
+ /**
8241
+ * Check if any usage has been recorded
8242
+ */
8243
+ hasUsage(): boolean;
8244
+ }
8245
+
8263
8246
  /**
8264
8247
  * Create record parameters
8265
8248
  */
@@ -9864,9 +9847,9 @@ declare const ProjectSchemas: {
9864
9847
  CreateProjectRequest: z.ZodObject<{
9865
9848
  name: z.ZodString;
9866
9849
  kind: z.ZodEnum<{
9867
- internal: "internal";
9868
9850
  other: "other";
9869
9851
  client_engagement: "client_engagement";
9852
+ internal: "internal";
9870
9853
  research: "research";
9871
9854
  }>;
9872
9855
  status: z.ZodOptional<z.ZodEnum<{
@@ -9889,9 +9872,9 @@ declare const ProjectSchemas: {
9889
9872
  UpdateProjectRequest: z.ZodObject<{
9890
9873
  name: z.ZodOptional<z.ZodString>;
9891
9874
  kind: z.ZodOptional<z.ZodEnum<{
9892
- internal: "internal";
9893
9875
  other: "other";
9894
9876
  client_engagement: "client_engagement";
9877
+ internal: "internal";
9895
9878
  research: "research";
9896
9879
  }>>;
9897
9880
  status: z.ZodOptional<z.ZodEnum<{
@@ -9914,9 +9897,9 @@ declare const ProjectSchemas: {
9914
9897
  }, z.core.$strict>;
9915
9898
  GetProjectsQuery: z.ZodObject<{
9916
9899
  kind: z.ZodOptional<z.ZodEnum<{
9917
- internal: "internal";
9918
9900
  other: "other";
9919
9901
  client_engagement: "client_engagement";
9902
+ internal: "internal";
9920
9903
  research: "research";
9921
9904
  }>>;
9922
9905
  status: z.ZodOptional<z.ZodEnum<{
@@ -10004,12 +9987,12 @@ declare const ProjectSchemas: {
10004
9987
  status: z.ZodOptional<z.ZodEnum<{
10005
9988
  completed: "completed";
10006
9989
  cancelled: "cancelled";
9990
+ rejected: "rejected";
10007
9991
  blocked: "blocked";
10008
9992
  in_progress: "in_progress";
10009
9993
  planned: "planned";
10010
9994
  submitted: "submitted";
10011
9995
  approved: "approved";
10012
- rejected: "rejected";
10013
9996
  revision_requested: "revision_requested";
10014
9997
  }>>;
10015
9998
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -10040,12 +10023,12 @@ declare const ProjectSchemas: {
10040
10023
  status: z.ZodOptional<z.ZodEnum<{
10041
10024
  completed: "completed";
10042
10025
  cancelled: "cancelled";
10026
+ rejected: "rejected";
10043
10027
  blocked: "blocked";
10044
10028
  in_progress: "in_progress";
10045
10029
  planned: "planned";
10046
10030
  submitted: "submitted";
10047
10031
  approved: "approved";
10048
- rejected: "rejected";
10049
10032
  revision_requested: "revision_requested";
10050
10033
  }>>;
10051
10034
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -10067,12 +10050,12 @@ declare const ProjectSchemas: {
10067
10050
  status: z.ZodOptional<z.ZodEnum<{
10068
10051
  completed: "completed";
10069
10052
  cancelled: "cancelled";
10053
+ rejected: "rejected";
10070
10054
  blocked: "blocked";
10071
10055
  in_progress: "in_progress";
10072
10056
  planned: "planned";
10073
10057
  submitted: "submitted";
10074
10058
  approved: "approved";
10075
- rejected: "rejected";
10076
10059
  revision_requested: "revision_requested";
10077
10060
  }>>;
10078
10061
  milestone_id: z.ZodOptional<z.ZodString>;
@@ -11230,6 +11213,17 @@ interface BaseAICall {
11230
11213
  costUsd: number;
11231
11214
  latencyMs: number;
11232
11215
  context?: AICallContext;
11216
+ /**
11217
+ * Anthropic-only: input tokens served from the prompt cache this call (`cache_read_input_tokens`),
11218
+ * billed at 0.1x the base input rate. Already folded into `inputTokens`/`totalInputTokens` so
11219
+ * aggregate totals reflect real usage -- present here as the raw breakdown, not additive on top.
11220
+ */
11221
+ cacheReadInputTokens?: number;
11222
+ /**
11223
+ * Anthropic-only: input tokens written to the prompt cache this call (`cache_creation_input_tokens`),
11224
+ * billed at 1.25x the base input rate. Same folding rationale as `cacheReadInputTokens`.
11225
+ */
11226
+ cacheCreationInputTokens?: number;
11233
11227
  /**
11234
11228
  * Distinct prompt-injection pattern types detected in the request's user-role messages.
11235
11229
  * Present only when the input sanitizer matched something. Non-blocking matches ride along on
@@ -11295,6 +11289,41 @@ interface BaseAICall {
11295
11289
  * Existing readers that only look at the fields above are unaffected.
11296
11290
  */
11297
11291
  strictRefusalReasons?: string[];
11292
+ /**
11293
+ * Time spent in the base adapter's `generate()` call alone, excluding `responseSchema`
11294
+ * validation. On a success or validation-failure row, `providerMs + validateMs === latencyMs`
11295
+ * (modulo rounding) -- `latencyMs` keeps its existing meaning unchanged; this and `validateMs`
11296
+ * are the same window split into its two components.
11297
+ *
11298
+ * Present on success and validation-failure rows. Absent on a blocked row (no provider call was
11299
+ * made) and on rows written before this field existed.
11300
+ */
11301
+ providerMs?: number;
11302
+ /**
11303
+ * Time spent in `validateResponseSchema` alone. Omitted when the call carried no `responseSchema`
11304
+ * (nothing to validate); `0` is a legitimate value meaning a schema was supplied and validation
11305
+ * was effectively instant. See `providerMs` for how the two relate to `latencyMs`.
11306
+ *
11307
+ * Present on success and validation-failure rows that supplied a `responseSchema`. Absent on a
11308
+ * blocked row and on rows written before this field existed.
11309
+ */
11310
+ validateMs?: number;
11311
+ /**
11312
+ * Total elapsed time for the WHOLE `generate()` call -- every retry attempt plus every backoff
11313
+ * sleep between them. Unlike `latencyMs` (which is per-attempt and never includes backoff, by
11314
+ * design -- see `runWithRetry`), this is the one number that answers "how long did the caller
11315
+ * actually wait". On a call that never retried, `wallClockMs === latencyMs`. On a retried call,
11316
+ * `wallClockMs` is strictly greater than any individual row's `latencyMs` from that same call, by
11317
+ * at least the backoff time actually slept.
11318
+ *
11319
+ * The same value is attached to every row produced by one `generate()` call (a validation-failure
11320
+ * row from an earlier attempt included), because it describes the call, not the attempt.
11321
+ *
11322
+ * Present on success and validation-failure rows. Absent on a blocked row -- a blocked call never
11323
+ * reaches the retry loop, so `wallClockMs` would just restate `latencyMs` (0). Absent on rows
11324
+ * written before this field existed.
11325
+ */
11326
+ wallClockMs?: number;
11298
11327
  }
11299
11328
  type AICallContext = AgentReasoningContext | AgentCompletionContext | WorkflowStepContext | ToolCallContext | OtherCallContext;
11300
11329
  interface AgentReasoningContext {
@@ -11340,6 +11369,16 @@ interface LLMUsageData {
11340
11369
  latencyMs: number;
11341
11370
  /** Actual cost from provider in USD (when available, e.g., OpenRouter) */
11342
11371
  cost?: number;
11372
+ /**
11373
+ * Anthropic-only: input tokens served from the prompt cache (`cache_read_input_tokens`), billed at
11374
+ * 0.1x the base input rate. Absent for providers that never report it (OpenAI, OpenRouter).
11375
+ */
11376
+ cacheReadInputTokens?: number;
11377
+ /**
11378
+ * Anthropic-only: input tokens written to the prompt cache this call
11379
+ * (`cache_creation_input_tokens`), billed at 1.25x the base input rate. Same absence rationale.
11380
+ */
11381
+ cacheCreationInputTokens?: number;
11343
11382
  /** Distinct prompt-injection pattern types detected in the request's user-role messages */
11344
11383
  inputWarnings?: string[];
11345
11384
  /** Additive per-source breakdown of `inputWarnings` — see `SourcedInputWarnings` */
@@ -11354,6 +11393,12 @@ interface LLMUsageData {
11354
11393
  strictStatus?: StrictStatus;
11355
11394
  /** Why the call went out unstrict, when a strict-capable adapter refused the schema */
11356
11395
  strictRefusalReasons?: string[];
11396
+ /** Time in the base adapter's `generate()` alone, excluding `responseSchema` validation. See `BaseAICall.providerMs`. */
11397
+ providerMs?: number;
11398
+ /** Time in `validateResponseSchema` alone. Omitted when no `responseSchema` was supplied. See `BaseAICall.validateMs`. */
11399
+ validateMs?: number;
11400
+ /** Total elapsed for the whole `generate()` call, including every retry and every backoff sleep. See `BaseAICall.wallClockMs`. */
11401
+ wallClockMs?: number;
11357
11402
  }
11358
11403
  interface AIUsageSummary {
11359
11404
  model: LLMModel;
@@ -11376,29 +11421,255 @@ interface ResourceMetricsConfig {
11376
11421
  }
11377
11422
 
11378
11423
  /**
11379
- * AIUsageCollector
11380
- * Centralized token tracking that aggregates usage across all LLM calls in an execution
11424
+ * Agent-specific type definitions
11425
+ * Types for autonomous agents with tools, memory, and constraints
11381
11426
  */
11382
- declare class AIUsageCollector {
11383
- private model;
11384
- private calls;
11385
- private callSequence;
11427
+
11428
+ /**
11429
+ * Factory function for creating LLM adapters.
11430
+ * Injected into the Agent class to decouple the engine from server-only provider SDKs.
11431
+ * - API process: provides createLLMAdapter (real SDKs + process.env API keys)
11432
+ * - SDK worker: provides PostMessageLLMAdapter (proxies via platform.call)
11433
+ *
11434
+ * Uses `any` for optional params so both the real createLLMAdapter (with typed
11435
+ * AIUsageCollector/AICallContext) and the worker proxy (which ignores them) satisfy the type.
11436
+ */
11437
+ type LLMAdapterFactory = (config: ModelConfig, ...args: any[]) => LLMAdapter;
11438
+ type AgentKind = 'orchestrator' | 'specialist' | 'utility' | 'platform';
11439
+ interface AgentConfig extends ResourceDefinition {
11440
+ type: 'agent';
11441
+ /** OM descriptor backing canonical identity and governance metadata. */
11442
+ resource?: AgentResourceEntry;
11443
+ kind: AgentKind;
11444
+ systemPrompt: string;
11445
+ constraints?: AgentConstraints;
11386
11446
  /**
11387
- * Record a single AI call with usage metrics
11447
+ * Session capability declaration (opt-in)
11448
+ * If true, agent is designed for multi-turn session interactions
11449
+ * Controls whether agent can use message action and appears in Sessions UI
11388
11450
  *
11389
- * @param usage - Token usage and latency data from LLM adapter
11390
- * @param callType - Type discriminator (agent-reasoning, tool, etc.)
11391
- * @param context - Optional typed context specific to callType
11451
+ * Use for:
11452
+ * - Conversational agents with multi-turn interactions
11453
+ * - Agents requiring persistent context across turns
11454
+ * - Agents that need human-in-the-loop communication
11392
11455
  */
11393
- record(usage: LLMUsageData, callType?: BaseAICall['callType'], context?: AICallContext): void;
11456
+ sessionCapable?: boolean;
11394
11457
  /**
11395
- * Get aggregated summary of all AI calls
11458
+ * Overrides the default `message` requiredness for a session-capable agent (ignored for
11459
+ * non-session agents, which always get `AgentCapabilities.message: 'off'`). Defaults to
11460
+ * `'required'` -- see `AgentCapabilities.message`'s doc comment for why. Set `'optional'` only
11461
+ * when the agent legitimately needs tool-only turns with no reply, and the deploy target can
11462
+ * tolerate the blind-retry risk `validateResponseSchema` carries on any path where the schema is
11463
+ * not compiled into a sampling grammar.
11396
11464
  */
11397
- getSummary(): AIUsageSummary;
11465
+ messagePolicy?: 'optional' | 'required';
11398
11466
  /**
11399
- * Check if any usage has been recorded
11467
+ * Explicit opt-in to skip the iteration loop and produce `contract.outputSchema`-shaped output in
11468
+ * a single LLM call (round 3 decision B6: explicit opt-in, never inferred from `kind`,
11469
+ * `sessionCapable`, or tool count -- so no existing agent changes shape by default). Structurally
11470
+ * the normal path pays two calls minimum: `iterate()` always runs at least one, and `complete()`
11471
+ * runs a second whose prompt re-derives the answer from history rather than reading what the
11472
+ * iteration already decided. A single-shot classifier -- one input in, one structured output out,
11473
+ * no multi-step reasoning needed -- does not need that second derivation; `complete()` already
11474
+ * makes exactly the one call it needs, from `currentInput` directly.
11475
+ *
11476
+ * Requires `sessionCapable` to be falsy and `contract.outputSchema` to be present. `Agent`
11477
+ * validates both during initialization and throws `AgentInitializationError` if either is missing,
11478
+ * rather than silently falling back to the normal two-call path on a misconfigured opt-in. Tools
11479
+ * registered on the agent are never invoked in this path -- there is no iteration loop to call
11480
+ * them from, so an agent that needs tool calls before it can answer is not eligible regardless of
11481
+ * this flag.
11400
11482
  */
11401
- hasUsage(): boolean;
11483
+ singleShot?: boolean;
11484
+ /**
11485
+ * Security level for system prompt hardening (auto-derived if omitted)
11486
+ *
11487
+ * - 'standard': Lightweight defense (3 rules) - default for non-session agents
11488
+ * - 'hardened': Comprehensive defense (5 rules) - default for session-capable agents
11489
+ * - 'none': No security prompt - for pure internal agents with no external input
11490
+ *
11491
+ * If omitted, derived from sessionCapable:
11492
+ * sessionCapable: true -> 'hardened'
11493
+ * sessionCapable: false -> 'standard'
11494
+ */
11495
+ securityLevel?: 'standard' | 'hardened' | 'none';
11496
+ /**
11497
+ * Memory management preferences (opt-in)
11498
+ * If provided, agent can use memoryOps to manage session memory
11499
+ * If omitted, agent has no memory management capabilities
11500
+ *
11501
+ * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
11502
+ * This guidance is injected into the system prompt when memory management is enabled.
11503
+ *
11504
+ * Use for:
11505
+ * - Conversational agents needing cross-turn context
11506
+ * - Agents managing complex user preferences
11507
+ * - Agents tracking decisions over multiple iterations
11508
+ */
11509
+ memoryPreferences?: string;
11510
+ }
11511
+ interface AgentConstraints {
11512
+ maxIterations?: number;
11513
+ timeout?: number;
11514
+ maxSessionMemoryKeys?: number;
11515
+ maxMemoryTokens?: number;
11516
+ }
11517
+ interface AgentDefinition {
11518
+ config: AgentConfig;
11519
+ contract: Contract;
11520
+ tools: Tool[];
11521
+ /**
11522
+ * Model configuration for LLM execution
11523
+ * Specifies provider, API key, and model-specific options
11524
+ */
11525
+ modelConfig: ModelConfig;
11526
+ /**
11527
+ * Preload memory before execution starts
11528
+ * Handles BOTH context loading AND session restoration
11529
+ *
11530
+ * @param context - Execution context (includes sessionId if session turn)
11531
+ * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
11532
+ */
11533
+ preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory;
11534
+ /**
11535
+ * Metrics configuration for ROI calculations
11536
+ * Optional: Only needed if tracking automation savings
11537
+ */
11538
+ metricsConfig?: ResourceMetricsConfig;
11539
+ /**
11540
+ * Execution interface configuration (optional)
11541
+ * If provided, agent appears in Execution Runner UI
11542
+ */
11543
+ interface?: ExecutionInterface;
11544
+ }
11545
+ /**
11546
+ * Agent execution context
11547
+ * Groups all state needed for agent execution phases
11548
+ */
11549
+ interface IterationContext {
11550
+ config: AgentConfig;
11551
+ contract: Contract;
11552
+ toolRegistry: Map<string, Tool>;
11553
+ memoryManager: MemoryManager;
11554
+ executionContext: ExecutionContext;
11555
+ iteration: number;
11556
+ logger: AgentScopedLogger;
11557
+ modelConfig: ModelConfig;
11558
+ adapterFactory: LLMAdapterFactory;
11559
+ /**
11560
+ * The validated input for this execution, serialized. It travels here because the model gets
11561
+ * it as its own `role:'user'` message; nothing else in this context carried it, so the input
11562
+ * had to be read back out of memory history and shipped inside the memory block.
11563
+ */
11564
+ currentInput: string;
11565
+ }
11566
+
11567
+ /**
11568
+ * Serialized Registry Types
11569
+ *
11570
+ * Pre-computed JSON-safe types for API responses and Command View.
11571
+ * Serialization happens once at API startup, enabling instant response times.
11572
+ */
11573
+
11574
+ /**
11575
+ * Serialized agent definition (JSON-safe)
11576
+ * Result of serializeDefinition(AgentDefinition)
11577
+ */
11578
+ interface SerializedAgentDefinition {
11579
+ config: {
11580
+ resourceId: string;
11581
+ name: string;
11582
+ description: string;
11583
+ version: string;
11584
+ type: 'agent';
11585
+ /**
11586
+ * Imported from the runtime type instead of hand-copied. It used to be a hand-written literal
11587
+ * union that said `'system'` where `AgentKind`'s fourth member is `'platform'` -- undetected
11588
+ * because `serializeDefinition` returns `any` and every call site casts the result to this
11589
+ * interface, so the literal union was never actually checked against real data. Deriving from
11590
+ * the source of truth makes that class of drift a type error instead of a silent typo.
11591
+ */
11592
+ kind: AgentKind;
11593
+ status: 'dev' | 'prod';
11594
+ links?: ResourceLink[];
11595
+ category?: ResourceCategory;
11596
+ /** Whether this resource is archived and should be excluded from registration and deployment */
11597
+ archived?: boolean;
11598
+ systemPrompt: string;
11599
+ constraints?: {
11600
+ maxIterations?: number;
11601
+ timeout?: number;
11602
+ maxSessionMemoryKeys?: number;
11603
+ maxMemoryTokens?: number;
11604
+ };
11605
+ sessionCapable?: boolean;
11606
+ memoryPreferences?: string;
11607
+ };
11608
+ modelConfig: {
11609
+ provider: string;
11610
+ model: string;
11611
+ apiKey: string;
11612
+ /**
11613
+ * Optional here, matching `ModelConfig` -- this used to be required even though neither real
11614
+ * agent literal in the monorepo (`local-test-agent`, the `createPlatformToolAgent` test fixture)
11615
+ * sets it, and nothing caught the mismatch for the same `serializeDefinition`-returns-`any`
11616
+ * reason `kind` drifted above.
11617
+ */
11618
+ temperature?: number;
11619
+ maxOutputTokens?: number;
11620
+ topP?: number;
11621
+ modelOptions?: Record<string, unknown>;
11622
+ };
11623
+ contract: {
11624
+ inputSchema: object;
11625
+ outputSchema?: object;
11626
+ };
11627
+ tools: Array<{
11628
+ name: string;
11629
+ description: string;
11630
+ inputSchema?: object;
11631
+ outputSchema?: object;
11632
+ }>;
11633
+ metricsConfig?: object;
11634
+ }
11635
+ /**
11636
+ * Serialized workflow definition (JSON-safe)
11637
+ * Result of serializeDefinition(WorkflowDefinition)
11638
+ */
11639
+ interface SerializedWorkflowDefinition {
11640
+ config: {
11641
+ resourceId: string;
11642
+ name: string;
11643
+ description: string;
11644
+ version: string;
11645
+ type: 'workflow';
11646
+ status: 'dev' | 'prod';
11647
+ links?: ResourceLink[];
11648
+ category?: ResourceCategory;
11649
+ /** Whether this resource is archived and should be excluded from registration and deployment */
11650
+ archived?: boolean;
11651
+ };
11652
+ entryPoint: string;
11653
+ steps: Array<{
11654
+ id: string;
11655
+ name: string;
11656
+ description: string;
11657
+ inputSchema?: object;
11658
+ outputSchema?: object;
11659
+ next: {
11660
+ type: 'linear' | 'conditional';
11661
+ target?: string;
11662
+ routes?: Array<{
11663
+ target: string;
11664
+ }>;
11665
+ default?: string;
11666
+ } | null;
11667
+ }>;
11668
+ contract: {
11669
+ inputSchema: object;
11670
+ outputSchema?: object;
11671
+ };
11672
+ metricsConfig?: object;
11402
11673
  }
11403
11674
 
11404
11675
  /**
@@ -11546,12 +11817,31 @@ interface Tool {
11546
11817
  outputSchema: z.ZodSchema;
11547
11818
  execute: (options: ToolExecutionOptions) => Promise<unknown>;
11548
11819
  timeout?: number;
11820
+ /**
11821
+ * Optional per-tool output size bound, in approximate tokens. Today the ONLY size bound on tool
11822
+ * output is a 4,000-token truncation applied post-hoc at memory insert -- after the payload is
11823
+ * already fully materialized, validated against `outputSchema`, emitted as a session message, and
11824
+ * logged. This field exists so a tool can declare its own bound up front instead.
11825
+ *
11826
+ * Enforcement is NOT here. `executor.ts:executeToolCall` is the single call site that produces the
11827
+ * value handed to all four sinks (memory, the `agent:tool_result` event, the session message, and
11828
+ * the log line) -- enforcing there, before that value is emitted, is what makes the four sinks agree
11829
+ * instead of three of them seeing the untruncated payload. See that file's own comment for the
11830
+ * exact insertion point.
11831
+ */
11832
+ maxOutputTokens?: number;
11549
11833
  }
11550
11834
  /**
11551
11835
  * Tooling error types
11552
11836
  * Used across platform tools and integration tools
11553
11837
  */
11554
- type ToolingErrorType = 'service_unavailable' | 'permission_denied' | 'platform_internal' | 'adapter_not_found' | 'method_not_found' | 'tool_not_found' | 'credentials_missing' | 'credentials_invalid' | 'rate_limit_exceeded' | 'server_unavailable' | 'auth_error' | 'api_error' | 'validation_error' | 'network_error' | 'timeout_error' | 'unknown_error';
11838
+ type ToolingErrorType = 'service_unavailable' | 'permission_denied' | 'platform_internal' | 'adapter_not_found' | 'method_not_found' | 'tool_not_found' | 'credentials_missing' | 'credentials_invalid' | 'rate_limit_exceeded' | 'server_unavailable' | 'auth_error' | 'api_error' | 'validation_error' | 'network_error' | 'timeout_error'
11839
+ /** Tool was cut off by an external abort (reaper/stall detection, user cancellation, a parent
11840
+ * execution's own timeout reaching this tool through the composed signal) rather than exhausting
11841
+ * its OWN per-call budget -- that case stays `timeout_error`. D1 (agent-framework-round-3.mdx):
11842
+ * before this existed, `executor.ts`'s cancellation branch threw a plain `Error`, so a cancelled
11843
+ * tool's memory entry had the right message text but no `errorType`/`severity`/`isRetryable`. */
11844
+ | 'cancelled' | 'unknown_error';
11555
11845
 
11556
11846
  /**
11557
11847
  * Supported integration types
@@ -11908,7 +12198,6 @@ interface CommandViewAgent extends ResourceDefinition {
11908
12198
  modelProvider: string;
11909
12199
  modelId: string;
11910
12200
  toolCount: number;
11911
- hasKnowledgeMap: boolean;
11912
12201
  hasMemory: boolean;
11913
12202
  sessionCapable: boolean;
11914
12203
  }
@@ -12399,19 +12688,17 @@ declare function validateDeclaredSystemInterfaceReadiness(orgName: string, organ
12399
12688
  * Types are shared with the server-side LLM engine and inlined for SDK consumers.
12400
12689
  */
12401
12690
 
12402
- type LLMProvider = 'openai' | 'anthropic' | 'openrouter' | 'google';
12691
+ type LLMProvider = 'openai' | 'anthropic' | 'openrouter';
12403
12692
  /**
12404
12693
  * SDK LLM generate params.
12405
12694
  * Extends LLMGenerateRequest with required provider/model for worker→platform dispatch.
12406
12695
  * Provider and model must always be specified explicitly — no implicit fallback.
12407
12696
  */
12408
- interface SDKLLMGenerateParams extends Omit<LLMGenerateRequest, 'signal' | 'responseSchema'> {
12697
+ interface SDKLLMGenerateParams extends Omit<LLMGenerateRequest, 'signal'> {
12409
12698
  /** LLM provider */
12410
12699
  provider: LLMProvider;
12411
12700
  /** Model identifier — must be a supported LLMModel */
12412
12701
  model: LLMModel;
12413
- /** JSON Schema for structured output (optional — omit for unstructured text) */
12414
- responseSchema?: unknown;
12415
12702
  }
12416
12703
 
12417
12704
  type ResourceStatus = 'dev' | 'prod';
@@ -12972,4 +13259,4 @@ declare const ListBuilderStageKeySchema: z.ZodString;
12972
13259
  type ListBuilderStageKey = z.infer<typeof ListBuilderStageKeySchema>;
12973
13260
 
12974
13261
  export { ActivityEventSchema, BuildPlanSnapshotStepSchema, ProspectingBuildTemplateSchema as BuildTemplateSchema, ContractRefResolutionError, CrmStageKeySchema, CrmStateKeySchema, EmailSchema, ExecutionError, ListBuilderStageKeySchema, ProcessingStageStatusSchema, RegistryValidationError, ResourceRegistry, StepType, ToolingError, bindResourceDescriptor, compileBusinessOntologyValidationIndex, concurrentPool, createLeadGenStageValidators, defineContract, defineResource, defineResourceOntology, defineResources, defineStep, defineTopology, defineTopologyRelationship, defineWorkflow, defineWorkflowConfig, deriveActions, diagnosticOutput, integrationInput, isBuiltInReadinessProfile, isZodType, lookupReadinessProfile, parseTopologyNodeRef, profileForInterface, projectDeploymentSpec, projectTopologyRelationships, registerReadinessProfile, resolveContractRef, runDiagnostic, splitName, toSdkResourceDescriptor, topologyRef, topologyRelationship, validateDeclaredSystemInterfaceReadiness, validateResourceGovernance, withPlatformAgentResourceDescriptor, withPlatformAgentResourceDescriptors, withPlatformIntegrationResourceDescriptor, withPlatformIntegrationResourceDescriptors, withPlatformResourceDescriptor, withPlatformResourceDescriptors };
12975
- export type { AbsoluteScheduleConfig, AcqCompany, AcqContact, AcqDeal, AcqDealRow, AcqList, Action$1 as Action, ActionDef, ActivityEvent, AddToCampaignLead, AddToCampaignParams, AddToCampaignResult, AgentConfig, AgentConstraints, AgentDefinition, AgentMemory, AgentResourceDescriptorResolver, FindCompanyEmailParams as AnymailfinderFindCompanyEmailParams, FindCompanyEmailResult as AnymailfinderFindCompanyEmailResult, FindDecisionMakerEmailParams as AnymailfinderFindDecisionMakerEmailParams, FindDecisionMakerEmailResult as AnymailfinderFindDecisionMakerEmailResult, FindPersonEmailParams as AnymailfinderFindPersonEmailParams, FindPersonEmailResult as AnymailfinderFindPersonEmailResult, AnymailfinderToolMap, VerifyEmailParams as AnymailfinderVerifyEmailParams, VerifyEmailResult as AnymailfinderVerifyEmailResult, ApifyToolMap, ApifyWebhookConfig, AppendRowsParams, AppendRowsResult, ApprovalToolMap, AttioToolMap, BatchUpdateParams, BatchUpdateResult, BuildPlanSnapshotStep, BulkDeleteLeadsParams, BulkDeleteLeadsResult, BulkImportParams, BulkImportResult, BusinessOntologyValidationIndex, CancelHitlByDealIdParams, CancelSchedulesAndHitlByEmailParams, ClearDealFieldsParams, ClearRangeParams, ClearRangeResult, ClickUpToolMap, CompanyFilters, ConcurrentPoolOptions, ConcurrentPoolResult, ConditionalNext, ContactFilters, Contract, ContractRefResolutionErrorCode, ContractRegistry, CreateAttributeParams, CreateAttributeResult, CreateAutoPaymentLinkParams, CreateAutoPaymentLinkResult, CreateCheckoutSessionParams, CreateCheckoutSessionResult, CreateCompanyParams, CreateContactParams, CreateEnvelopeParams, CreateEnvelopeResult, CreateFolderParams, CreateFolderResult, CreateListParams, CreateNoteParams, CreateNoteResult, CreatePaymentLinkParams, CreatePaymentLinkResult, CreateRecordParams, CreateRecordResult, CreateScheduleInput, CrmStageKey, CrmStateKey, CrmToolMap, DeleteDealParams, DeleteNoteParams, DeleteNoteResult, DeleteRecordParams, DeleteRecordResult, DeleteRowByValueParams, DeleteRowByValueResult, DeploymentSpec, DiagnosticOutput, DownloadDocumentParams, DownloadDocumentResult, DropboxToolMap, ElevasConfig, EmailToolMap, EnvelopeDocument, EventTriggerConfig, ExecutionContext, ExecutionInterface, ExecutionMetadata, ExecutionToolMap, FilterExpression, FilterRowsParams, FilterRowsResult, FormField, FormFieldType, FormSchema, GetDailyCampaignAnalyticsParams, GetDailyCampaignAnalyticsResult, GetEmailsParams, GetEmailsResult, GetEnvelopeParams, GetEnvelopeResult, GetHeadersParams, GetHeadersResult, GetLastRowParams, GetLastRowResult, GetPaymentLinkParams, GetPaymentLinkResult, GetRecordParams, GetRecordResult, GetRowByValueParams, GetRowByValueResult, GetSpreadsheetMetadataParams, GetSpreadsheetMetadataResult, GmailSendEmailParams, GmailSendEmailResult, GmailToolMap, GoogleSheetsToolMap, HumanCheckpointDefinition, InstantlyToolMap, IntegrationDefinition, IntegrationResourceDescriptorResolver, LLMAdapterFactory, LLMGenerateRequest, LLMGenerateResponse, LLMMessage, LLMModel, LeadGenStageValidators, LeadToolMap, LinearNext, ListAttributesParams, ListAttributesResult, ListBuilderStageKey, ListBuilderStep, ListLeadsParams, ListLeadsResult, ListNotesParams, ListNotesResult, ListObjectsResult, ListPaymentLinksParams, ListPaymentLinksResult, ListToolMap, MarkProposalReviewedParams, MarkProposalSentParams, MethodEntry, MillionVerifierToolMap, ModelConfig, NextConfig, NotificationSDKInput, NotificationToolMap, OrganizationModelAgentResourceEntry, OrganizationModelIntegrationResourceEntry, OrganizationModelResourceEntry, OrganizationModelResourceOntologyBinding, OrganizationModelTopology, OrganizationModelTopologyNodeRef, OrganizationModelTopologyRelationship, OrganizationModelWorkflowResourceEntry, PaginatedResult, PaginationParams, PdfToolMap, ProcessingStageStatus, ProjectDeploymentSpecOptions, ProjectsToolMap, QueryRecordsParams, QueryRecordsResult, ReadSheetParams, ReadSheetResult, ReadinessProfileEntry, ReadinessProfileKind, Recipient, RecurringScheduleConfig, RelationshipDeclaration, RelativeScheduleConfig, RemoveFromSubsequenceParams, RemoveFromSubsequenceResult, ResendGetEmailParams, ResendGetEmailResult, ResendSendEmailParams, ResendSendEmailResult, ResendToolMap, ResolvedContractRef, ResourceCategory, ResourceDefinition, ResourceLink, ResourceMetricsConfig, ResourceOntologyBindingResolver, ResourceRelationships, ResourceStatus$1 as ResourceStatus, ResourceType, RunActorParams, RunActorResult, SDKLLMGenerateParams, ScheduleOriginTracking, ScheduleTarget, ScheduleTriggerConfig, SchedulerToolMap, SendReplyParams, SendReplyResult, SetContactNurtureParams, SheetInfo, SignatureApiFieldType, SignatureApiToolMap, SigningPlace, SortCriteria, StartActorParams, StartActorResult, StepHandler, StorageDeleteInput, StorageDeleteOutput, StorageDownloadInput, StorageDownloadOutput, StorageListInput, StorageListOutput, StorageSignedUrlInput, StorageSignedUrlOutput, StorageToolMap, StorageUploadInput, StorageUploadOutput, StripeToolMap, SystemApiInterfaceReadinessContract, TaskSchedule, TaskScheduleConfig, TombaToolMap, Tool, ToolExecutionOptions, ToolMethodMap, ToolingErrorType, TransitionItemParams, TriggerConfig, TriggerDefinition, UpdateAttributeParams, UpdateAttributeResult, UpdateCloseLostReasonParams, UpdateCompanyParams, UpdateContactParams, UpdateDiscoveryDataParams, UpdateFeesParams, UpdateInterestStatusParams, UpdateInterestStatusResult, UpdateListParams, UpdatePaymentLinkParams, UpdatePaymentLinkResult, UpdateProposalDataParams, UpdateRecordParams, UpdateRecordResult, UpdateRowByValueParams, UpdateRowByValueResult, UploadFileParams, UploadFileResult, UpsertCompanyParams, UpsertContactParams, UpsertDealParams, UpsertRowParams, UpsertRowResult, VoidEnvelopeParams, VoidEnvelopeResult, WebhookProviderType, WebhookTriggerConfig, WorkflowConfig, WorkflowConfigActionRegistry, WorkflowDefinition, WorkflowLogger, WorkflowResourceDescriptorMap, WorkflowResourceDescriptorResolver, WorkflowStep, WriteSheetParams, WriteSheetResult };
13262
+ export type { AbsoluteScheduleConfig, AcqCompany, AcqContact, AcqDeal, AcqDealRow, AcqList, Action$1 as Action, ActionDef, ActivityEvent, AddToCampaignLead, AddToCampaignParams, AddToCampaignResult, AgentConfig, AgentConstraints, AgentDefinition, AgentMemory, AgentResourceDescriptorResolver, FindCompanyEmailParams as AnymailfinderFindCompanyEmailParams, FindCompanyEmailResult as AnymailfinderFindCompanyEmailResult, FindDecisionMakerEmailParams as AnymailfinderFindDecisionMakerEmailParams, FindDecisionMakerEmailResult as AnymailfinderFindDecisionMakerEmailResult, FindPersonEmailParams as AnymailfinderFindPersonEmailParams, FindPersonEmailResult as AnymailfinderFindPersonEmailResult, AnymailfinderToolMap, VerifyEmailParams as AnymailfinderVerifyEmailParams, VerifyEmailResult as AnymailfinderVerifyEmailResult, ApifyToolMap, ApifyWebhookConfig, AppendRowsParams, AppendRowsResult, ApprovalToolMap, AttioToolMap, BatchUpdateParams, BatchUpdateResult, BuildPlanSnapshotStep, BulkDeleteLeadsParams, BulkDeleteLeadsResult, BulkImportParams, BulkImportResult, BusinessOntologyValidationIndex, CancelHitlByDealIdParams, CancelSchedulesAndHitlByEmailParams, ClearDealFieldsParams, ClearRangeParams, ClearRangeResult, ClickUpToolMap, CompanyFilters, ConcurrentPoolOptions, ConcurrentPoolResult, ConditionalNext, ContactFilters, Contract, ContractRefResolutionErrorCode, ContractRegistry, CreateAttributeParams, CreateAttributeResult, CreateAutoPaymentLinkParams, CreateAutoPaymentLinkResult, CreateCheckoutSessionParams, CreateCheckoutSessionResult, CreateCompanyParams, CreateContactParams, CreateEnvelopeParams, CreateEnvelopeResult, CreateFolderParams, CreateFolderResult, CreateListParams, CreateNoteParams, CreateNoteResult, CreatePaymentLinkParams, CreatePaymentLinkResult, CreateRecordParams, CreateRecordResult, CreateScheduleInput, CrmStageKey, CrmStateKey, CrmToolMap, DeleteDealParams, DeleteNoteParams, DeleteNoteResult, DeleteRecordParams, DeleteRecordResult, DeleteRowByValueParams, DeleteRowByValueResult, DeploymentSpec, DiagnosticOutput, DownloadDocumentParams, DownloadDocumentResult, DropboxToolMap, ElevasConfig, EmailToolMap, EnvelopeDocument, EventTriggerConfig, ExecutionContext, ExecutionInterface, ExecutionMetadata, ExecutionToolMap, FilterExpression, FilterRowsParams, FilterRowsResult, FormField, FormFieldType, FormSchema, GetDailyCampaignAnalyticsParams, GetDailyCampaignAnalyticsResult, GetEmailsParams, GetEmailsResult, GetEnvelopeParams, GetEnvelopeResult, GetHeadersParams, GetHeadersResult, GetLastRowParams, GetLastRowResult, GetPaymentLinkParams, GetPaymentLinkResult, GetRecordParams, GetRecordResult, GetRowByValueParams, GetRowByValueResult, GetSpreadsheetMetadataParams, GetSpreadsheetMetadataResult, GmailSendEmailParams, GmailSendEmailResult, GmailToolMap, GoogleSheetsToolMap, HumanCheckpointDefinition, InstantlyToolMap, IntegrationDefinition, IntegrationResourceDescriptorResolver, JsonSchema, LLMAdapterFactory, LLMGenerateRequest, LLMGenerateResponse, LLMMessage, LLMModel, LeadGenStageValidators, LeadToolMap, LinearNext, ListAttributesParams, ListAttributesResult, ListBuilderStageKey, ListBuilderStep, ListLeadsParams, ListLeadsResult, ListNotesParams, ListNotesResult, ListObjectsResult, ListPaymentLinksParams, ListPaymentLinksResult, ListToolMap, MarkProposalReviewedParams, MarkProposalSentParams, MethodEntry, MillionVerifierToolMap, ModelConfig, NextConfig, NotificationSDKInput, NotificationToolMap, OrganizationModelAgentResourceEntry, OrganizationModelIntegrationResourceEntry, OrganizationModelResourceEntry, OrganizationModelResourceOntologyBinding, OrganizationModelTopology, OrganizationModelTopologyNodeRef, OrganizationModelTopologyRelationship, OrganizationModelWorkflowResourceEntry, PaginatedResult, PaginationParams, PdfToolMap, ProcessingStageStatus, ProjectDeploymentSpecOptions, ProjectsToolMap, QueryRecordsParams, QueryRecordsResult, ReadSheetParams, ReadSheetResult, ReadinessProfileEntry, ReadinessProfileKind, Recipient, RecurringScheduleConfig, RelationshipDeclaration, RelativeScheduleConfig, RemoveFromSubsequenceParams, RemoveFromSubsequenceResult, ResendGetEmailParams, ResendGetEmailResult, ResendSendEmailParams, ResendSendEmailResult, ResendToolMap, ResolvedContractRef, ResourceCategory, ResourceDefinition, ResourceLink, ResourceMetricsConfig, ResourceOntologyBindingResolver, ResourceRelationships, ResourceStatus$1 as ResourceStatus, ResourceType, RunActorParams, RunActorResult, SDKLLMGenerateParams, ScheduleOriginTracking, ScheduleTarget, ScheduleTriggerConfig, SchedulerToolMap, SendReplyParams, SendReplyResult, SetContactNurtureParams, SheetInfo, SignatureApiFieldType, SignatureApiToolMap, SigningPlace, SortCriteria, StartActorParams, StartActorResult, StepHandler, StorageDeleteInput, StorageDeleteOutput, StorageDownloadInput, StorageDownloadOutput, StorageListInput, StorageListOutput, StorageSignedUrlInput, StorageSignedUrlOutput, StorageToolMap, StorageUploadInput, StorageUploadOutput, StripeToolMap, SystemApiInterfaceReadinessContract, TaskSchedule, TaskScheduleConfig, TombaToolMap, Tool, ToolExecutionOptions, ToolMethodMap, ToolingErrorType, TransitionItemParams, TriggerConfig, TriggerDefinition, UpdateAttributeParams, UpdateAttributeResult, UpdateCloseLostReasonParams, UpdateCompanyParams, UpdateContactParams, UpdateDiscoveryDataParams, UpdateFeesParams, UpdateInterestStatusParams, UpdateInterestStatusResult, UpdateListParams, UpdatePaymentLinkParams, UpdatePaymentLinkResult, UpdateProposalDataParams, UpdateRecordParams, UpdateRecordResult, UpdateRowByValueParams, UpdateRowByValueResult, UploadFileParams, UploadFileResult, UpsertCompanyParams, UpsertContactParams, UpsertDealParams, UpsertRowParams, UpsertRowResult, VoidEnvelopeParams, VoidEnvelopeResult, WebhookProviderType, WebhookTriggerConfig, WorkflowConfig, WorkflowConfigActionRegistry, WorkflowDefinition, WorkflowLogger, WorkflowResourceDescriptorMap, WorkflowResourceDescriptorResolver, WorkflowStep, WriteSheetParams, WriteSheetResult };