@elevasis/sdk 1.43.0 → 1.44.1

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.
@@ -237,152 +237,6 @@ interface IExecutionLogger {
237
237
  error(message: string, context?: LogContext): void;
238
238
  }
239
239
 
240
- /**
241
- * Model Configuration
242
- * Centralized model information, configuration, options, constraints, and validation
243
- * Single source of truth for all model-related definitions
244
- * Update manually when pricing changes or new models are added
245
- */
246
-
247
- /**
248
- * Supported Open AI models (direct SDK access)
249
- */
250
- type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano';
251
- /**
252
- * Supported OpenRouter models (explicit union for type safety)
253
- */
254
- type OpenRouterModel = 'openrouter/z-ai/glm-5';
255
- /**
256
- * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
257
- */
258
- type AnthropicModel = 'claude-opus-5' | 'claude-sonnet-5' | 'claude-haiku-4-5-20251001' | 'claude-haiku-4-5';
259
- /** Supported LLM models */
260
- type LLMModel = OpenAIModel | OpenRouterModel | AnthropicModel | 'mock';
261
- /**
262
- * GPT-5 model options schema
263
- */
264
- declare const GPT5OptionsSchema: z.ZodObject<{
265
- reasoning_effort: z.ZodOptional<z.ZodEnum<{
266
- minimal: "minimal";
267
- low: "low";
268
- medium: "medium";
269
- high: "high";
270
- }>>;
271
- verbosity: z.ZodOptional<z.ZodEnum<{
272
- low: "low";
273
- medium: "medium";
274
- high: "high";
275
- }>>;
276
- }, z.core.$strip>;
277
- /**
278
- * OpenRouter model options schema
279
- * OpenRouter-specific options for routing and transforms
280
- */
281
- declare const OpenRouterOptionsSchema: z.ZodObject<{
282
- transforms: z.ZodOptional<z.ZodArray<z.ZodString>>;
283
- route: z.ZodOptional<z.ZodEnum<{
284
- fallback: "fallback";
285
- }>>;
286
- }, z.core.$strip>;
287
- /**
288
- * Anthropic model options schema
289
- * Currently empty - future options must be added per supported model family
290
- */
291
- declare const AnthropicOptionsSchema: z.ZodObject<{}, z.core.$strict>;
292
- /**
293
- * Infer TypeScript types from schemas
294
- */
295
- type GPT5Options = z.infer<typeof GPT5OptionsSchema>;
296
- type MockOptions = Record<string, never>;
297
- type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>;
298
- type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>;
299
- type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | AnthropicOptions;
300
- /**
301
- * Model configuration for LLM execution
302
- * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
303
- */
304
- interface ModelConfig {
305
- model: LLMModel;
306
- provider: 'openai' | 'anthropic' | 'openrouter' | 'mock';
307
- apiKey: string;
308
- temperature?: number;
309
- /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
310
- maxOutputTokens?: number;
311
- topP?: number;
312
- /**
313
- * Model-specific options (flat structure)
314
- * Options are model-specific, not vendor-specific
315
- * Available options defined in MODEL_INFO per model
316
- * Validated at build time via validateModelOptions()
317
- */
318
- modelOptions?: ModelSpecificOptions;
319
- }
320
-
321
- /**
322
- * Types for the schema compiler. `compile.ts` walks a `JsonSchema` once, driven entirely by a
323
- * `ProviderDialect`, and every server adapter compiles through it.
324
- */
325
- /**
326
- * What happened to `strict` on a request, recorded per call rather than inferred.
327
- *
328
- * `applied` and `notAttempted` are the two states that a refusal-only field cannot tell apart --
329
- * both leave `strictRefusalReasons` empty. Recording the verdict positively is what makes "was
330
- * this agent's output actually enforced?" answerable from an `ai_calls` row.
331
- */
332
- type StrictStatus = 'applied' | 'refused' | 'compileRejected' | 'notAttempted';
333
- /**
334
- * A JSON Schema node, typed enough to be useful without pretending to validate the spec.
335
- *
336
- * The compiler has to accept schemas that arrive OUTSIDE the strict subset (that is the whole
337
- * point of a dialect that can refuse or rewrite them) as well as the `$ref`/`$defs`/`const`/
338
- * `$schema` shapes the strict subset has no vocabulary for at all. The index signature exists
339
- * because tenant schemas carry keywords (`minLength`, `pattern`, `minimum`, ...) this compiler
340
- * drops or refuses on, and they still need somewhere to type-check while they pass through
341
- * `Object.entries`.
342
- */
343
- interface JsonSchema {
344
- type?: string | string[];
345
- /**
346
- * The value is `JsonSchema | undefined`, not `JsonSchema`, because a property really can be
347
- * declared with nothing describing it. `buildIterationResponseSchema` emits one per tool as
348
- * `input: tool.inputSchema`, and `ToolDefinition.inputSchema` is typed `unknown` -- a tool
349
- * deployed without one puts `undefined` under a key that exists.
350
- *
351
- * Both readers already handle it: `compileSchema` passes each value through `convertNode`, which
352
- * takes `unknown`, and `collectErrors` opens with `if (!schema || typeof schema !== 'object')`
353
- * above a comment naming this exact case. Declaring the value non-optional only hid that they
354
- * were right to.
355
- */
356
- properties?: Record<string, JsonSchema | undefined>;
357
- items?: JsonSchema;
358
- anyOf?: JsonSchema[];
359
- oneOf?: JsonSchema[];
360
- allOf?: JsonSchema[];
361
- required?: string[];
362
- additionalProperties?: boolean | JsonSchema;
363
- minItems?: number;
364
- maxItems?: number;
365
- format?: string;
366
- enum?: unknown[];
367
- const?: unknown;
368
- description?: string;
369
- default?: unknown;
370
- $ref?: string;
371
- $defs?: Record<string, JsonSchema>;
372
- definitions?: Record<string, JsonSchema>;
373
- $schema?: string;
374
- $id?: string;
375
- $anchor?: string;
376
- /**
377
- * OpenAPI's nullability spelling, which is not JSON Schema's. It is declared because
378
- * `response-schema-validator.ts` READS it (`schemaPermitsNull`) -- Google's schema dialect is
379
- * OpenAPI-derived, so a schema that reaches the validator can carry it. No dialect in `compile.ts`
380
- * writes or rewrites it; the canonical spelling this compiler emits is `type: ['x', 'null']`.
381
- */
382
- nullable?: boolean;
383
- [key: string]: unknown;
384
- }
385
-
386
240
  declare const ResourceGovernanceStatusSchema: z.ZodEnum<{
387
241
  active: "active";
388
242
  deprecated: "deprecated";
@@ -745,165 +599,194 @@ type AgentResourceEntry = z.infer<typeof AgentResourceEntrySchema>;
745
599
  type ResourceEntry = z.infer<typeof ResourceEntrySchema>;
746
600
 
747
601
  /**
748
- * Shared form field types for dynamic form generation
749
- * Used by: Command Queue, Execution Runner UI, future form-based features
750
- */
751
- /**
752
- * Supported form field types for action payloads
753
- * Maps to Mantine form components
754
- */
755
- type FormFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'radio' | 'richtext';
756
- /**
757
- * Form field definition
602
+ * Memory type definitions
603
+ * Types for agent memory management with semantic entry types
758
604
  */
759
- interface FormField {
760
- /** Field key in payload object */
761
- name: string;
762
- /** Field label for UI */
763
- label: string;
764
- /** Field type (determines UI component) */
765
- type: FormFieldType;
766
- /** Default value */
767
- defaultValue?: unknown;
768
- /** Required field */
769
- required?: boolean;
770
- /** Placeholder text */
771
- placeholder?: string;
772
- /** Help text */
773
- description?: string;
774
- /** Options for select/radio */
775
- options?: Array<{
776
- label: string;
777
- value: string | number;
778
- }>;
779
- /** Min/max for number */
780
- min?: number;
781
- max?: number;
782
- /** Path to context value for pre-filling (dot notation, e.g., 'proposal.summary') */
783
- defaultValueFromContext?: string;
784
- }
785
605
  /**
786
- * Form schema for action payload collection
606
+ * Semantic memory entry types
607
+ * Use-case agnostic types that describe the purpose of each entry
608
+ * Memory types mirror action types for clarity and filtering
787
609
  */
788
- interface FormSchema {
789
- /** Form title */
790
- title?: string;
791
- /** Form description */
792
- description?: string;
793
- /** Form fields */
794
- fields: FormField[];
795
- }
796
-
610
+ type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'error';
797
611
  /**
798
- * Execution interface configuration
799
- * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
800
- * Applies to both agents and workflows
612
+ * Who authored an entry's content.
613
+ *
614
+ * This is what lets the assembled prompt tell framework-authored text apart from text that
615
+ * originated outside the trust boundary. `'framework'` content is ours; the other three are not
616
+ * and are rendered inside the JSON data envelope (see `MemoryManager.toContextParts`).
801
617
  */
802
- interface ExecutionInterface {
803
- /** Form configuration for execution inputs */
804
- form: ExecutionFormSchema;
805
- /** Optional: Schedule configuration */
806
- schedule?: ScheduleConfig;
807
- /** Optional: Webhook trigger configuration */
808
- webhook?: WebhookConfig;
809
- }
618
+ type MemoryEntrySource = 'framework' | 'user' | 'tool' | 'model';
810
619
  /**
811
- * Execution form schema
812
- * Extends FormSchema with execution-specific fields
620
+ * Memory entry - represents a single entry in agent memory
621
+ * Stored in agent memory, translated by adapters to vendor-specific formats
813
622
  */
814
- interface ExecutionFormSchema extends FormSchema {
623
+ interface MemoryEntry {
624
+ type: MemoryEntryType;
625
+ content: string;
626
+ timestamp: number;
627
+ turnNumber: number | null;
628
+ iterationNumber: number | null;
815
629
  /**
816
- * Field mappings to resource input schema
817
- * Maps form field names to contract input paths
818
- * If omitted, field names must match contract input keys exactly
630
+ * Provenance. **Optional on purpose** `undefined` means unknown, which is what every
631
+ * pre-existing snapshot and every not-yet-redeployed tenant bundle produces. Read sites MUST
632
+ * test `== null`, never `=== undefined`: the `inTurnScope` predicate in `manager.ts` is the
633
+ * cautionary precedent, where a `=== undefined` check silently dropped every `null`-stamped
634
+ * entry. `isMemoryEntry` is deliberately NOT tightened to require this field; doing so would
635
+ * make every stored snapshot fail validation, and `restoreSessionMemory` fails open by
636
+ * starting the agent with empty memory rather than throwing.
819
637
  */
820
- fieldMappings?: Record<string, string>;
638
+ source?: MemoryEntrySource;
821
639
  /**
822
- * Submit button configuration
823
- * Default: { label: 'Run', loadingLabel: 'Running...' }
640
+ * Which tool produced this entry. Set on `tool-result` entries so the model can tell N parallel
641
+ * results apart -- the framework instructs batching independent tool calls in one iteration, and
642
+ * an anonymous result is unattributable the moment two land in the same iteration. `addToolError`
643
+ * already carries this (folded into its `content` JSON); this is the same fact for the success
644
+ * path, carried as a real field instead of prose the caller has to parse back out.
824
645
  */
825
- submitButton?: {
826
- label?: string;
827
- loadingLabel?: string;
828
- confirmMessage?: string;
646
+ toolName?: string;
647
+ /**
648
+ * Present when `truncateContent` cut this entry's `content` to fit its token budget. A sibling
649
+ * field, never text appended into `content` -- the notice used to be spliced into the string
650
+ * itself, which could (and did) land inside a JSON string literal `truncateContent` had just cut
651
+ * open, breaking `JSON.parse` on the far end. Absent means never truncated.
652
+ */
653
+ truncated?: {
654
+ omittedTokens: number;
829
655
  };
656
+ /**
657
+ * Prompt-injection warning types found in `content`, screened once here -- when the entry is
658
+ * written -- instead of by re-scanning the whole accumulated envelope on every iteration it gets
659
+ * re-sent for (`screenRequest`'s `data-envelope` slot used to do exactly that). Empty array means
660
+ * screened and clean; `undefined` means never screened (entries that bypass `addToHistory`/`set`,
661
+ * or pre-existing snapshots from before this field existed).
662
+ */
663
+ warnings?: string[];
830
664
  }
831
665
  /**
832
- * Schedule configuration for automated execution
833
- */
834
- interface ScheduleConfig {
835
- /** Whether scheduling is enabled for this resource */
836
- enabled: boolean;
837
- /** Default schedule (cron expression) */
838
- defaultSchedule?: string;
839
- /** Allowed schedule patterns (if restricted) */
840
- allowedPatterns?: string[];
666
+ * Agent memory - Self-orchestrated memory with session + working storage
667
+ * Agent has full control over what persists, framework handles auto-compaction
668
+ */
669
+ interface AgentMemory {
670
+ /**
671
+ * Session memory - Persists for session/conversation duration
672
+ * Never auto-trimmed by framework
673
+ * Agent-managed key-value store for critical information
674
+ * Agent provides strings, framework wraps in MemoryEntry
675
+ */
676
+ sessionMemory: Record<string, MemoryEntry>;
677
+ /**
678
+ * Working memory - Execution history
679
+ * Automatically compacted by framework when needed
680
+ * Agent doesn't control compaction
681
+ */
682
+ history: MemoryEntry[];
841
683
  }
842
684
  /**
843
- * Webhook configuration for external triggers
685
+ * Memory status for agent awareness
844
686
  */
845
- interface WebhookConfig {
846
- /** Whether webhook trigger is enabled */
847
- enabled: boolean;
848
- /** Expected payload schema (for documentation) */
849
- payloadSchema?: unknown;
850
- }
851
-
852
- interface WorkflowConfig extends ResourceDefinition {
853
- type: 'workflow';
854
- /** OM descriptor backing canonical identity and governance metadata. */
855
- resource?: WorkflowResourceEntry;
856
- }
857
- interface WorkflowStepDefinition {
858
- id: string;
859
- name: string;
860
- description: string;
861
- }
862
- type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>;
863
- interface LinearNext {
864
- type: 'linear';
865
- target: string;
866
- }
867
- interface ConditionalNext {
868
- type: 'conditional';
869
- routes: Array<{
870
- condition: (data: unknown) => boolean;
871
- target: string;
872
- }>;
873
- default: string;
874
- }
875
- type NextConfig = LinearNext | ConditionalNext | null;
876
- interface WorkflowStep extends WorkflowStepDefinition {
877
- handler: StepHandler;
878
- inputSchema: z.ZodSchema;
879
- outputSchema: z.ZodSchema;
880
- next: NextConfig;
881
- }
882
- interface WorkflowDefinition {
883
- config: WorkflowConfig;
884
- contract: Contract;
885
- steps: Record<string, WorkflowStep>;
886
- entryPoint: string;
687
+ interface MemoryStatus {
688
+ sessionMemoryKeys: number;
689
+ sessionMemoryLimit: number;
690
+ sessionMemoryTokens: number;
691
+ sessionMemoryTokenLimit: number;
887
692
  /**
888
- * Metrics configuration for ROI calculations
889
- * Optional: Only needed if tracking automation savings
693
+ * History tokens as a percentage of `historyBudget` — history ALONE, not history plus session
694
+ * memory. It previously reported the combined total under this name, so session memory growth
695
+ * read as history pressure and triggered history compaction that could not relieve it.
890
696
  */
891
- metricsConfig?: ResourceMetricsConfig;
697
+ historyPercent: number;
892
698
  /**
893
- * Execution interface configuration (optional)
894
- * If provided, workflow appears in Execution Runner UI
699
+ * Tokens the history entries **in scope for the requested turn** occupy — the same set
700
+ * `toContextParts` puts in the envelope. Equal to `storedHistoryTokens` when `getStatus` is
701
+ * called without a turn.
702
+ *
703
+ * This is the number the model is shown, and it is scoped because the model is handed a scoped
704
+ * set. Counting the whole cross-turn array here meant the framing quoted the size of a store
705
+ * while the envelope beside it carried one turn's worth of it.
895
706
  */
896
- interface?: ExecutionInterface;
707
+ historyTokens: number;
897
708
  /**
898
- * Lead-gen processing stage this workflow implements (optional).
899
- * Must match a key in the platform lead-gen stage catalog.
900
- * Used by org-os graph derivation to surface workflow→stage edges and
901
- * by pipeline_config validation to confirm each catalog stage has an
902
- * implementing workflow before a list is activated.
709
+ * Tokens the **entire** history array occupies, across every turn the session snapshot restored.
903
710
  *
904
- * Example: stageImplemented: 'verified' on the email-verification workflow.
711
+ * This is what compaction measures, because compaction trims that array. Scoping it to a turn
712
+ * would let the store grow without bound whenever the current turn happened to be small.
905
713
  */
906
- stageImplemented?: string;
714
+ storedHistoryTokens: number;
715
+ /** `storedHistoryTokens` as a percentage of `historyBudget`. The auto-compaction trigger. */
716
+ storedHistoryPercent: number;
717
+ historyBudget: number;
718
+ }
719
+ /**
720
+ * Memory constraints (optional limits)
721
+ */
722
+ interface MemoryConstraints {
723
+ maxSessionMemoryKeys?: number;
724
+ maxMemoryTokens?: number;
725
+ }
726
+
727
+ /**
728
+ * Types for the schema compiler. `compile.ts` walks a `JsonSchema` once, driven entirely by a
729
+ * `ProviderDialect`, and every server adapter compiles through it.
730
+ */
731
+ /**
732
+ * What happened to `strict` on a request, recorded per call rather than inferred.
733
+ *
734
+ * `applied` and `notAttempted` are the two states that a refusal-only field cannot tell apart --
735
+ * both leave `strictRefusalReasons` empty. Recording the verdict positively is what makes "was
736
+ * this agent's output actually enforced?" answerable from an `ai_calls` row.
737
+ */
738
+ type StrictStatus = 'applied' | 'refused' | 'compileRejected' | 'notAttempted';
739
+ /**
740
+ * A JSON Schema node, typed enough to be useful without pretending to validate the spec.
741
+ *
742
+ * The compiler has to accept schemas that arrive OUTSIDE the strict subset (that is the whole
743
+ * point of a dialect that can refuse or rewrite them) as well as the `$ref`/`$defs`/`const`/
744
+ * `$schema` shapes the strict subset has no vocabulary for at all. The index signature exists
745
+ * because tenant schemas carry keywords (`minLength`, `pattern`, `minimum`, ...) this compiler
746
+ * drops or refuses on, and they still need somewhere to type-check while they pass through
747
+ * `Object.entries`.
748
+ */
749
+ interface JsonSchema {
750
+ type?: string | string[];
751
+ /**
752
+ * The value is `JsonSchema | undefined`, not `JsonSchema`, because a property really can be
753
+ * declared with nothing describing it. `buildIterationResponseSchema` emits one per tool as
754
+ * `input: tool.inputSchema`, and `ToolDefinition.inputSchema` is typed `unknown` -- a tool
755
+ * deployed without one puts `undefined` under a key that exists.
756
+ *
757
+ * Both readers already handle it: `compileSchema` passes each value through `convertNode`, which
758
+ * takes `unknown`, and `collectErrors` opens with `if (!schema || typeof schema !== 'object')`
759
+ * above a comment naming this exact case. Declaring the value non-optional only hid that they
760
+ * were right to.
761
+ */
762
+ properties?: Record<string, JsonSchema | undefined>;
763
+ items?: JsonSchema;
764
+ anyOf?: JsonSchema[];
765
+ oneOf?: JsonSchema[];
766
+ allOf?: JsonSchema[];
767
+ required?: string[];
768
+ additionalProperties?: boolean | JsonSchema;
769
+ minItems?: number;
770
+ maxItems?: number;
771
+ format?: string;
772
+ enum?: unknown[];
773
+ const?: unknown;
774
+ description?: string;
775
+ default?: unknown;
776
+ $ref?: string;
777
+ $defs?: Record<string, JsonSchema>;
778
+ definitions?: Record<string, JsonSchema>;
779
+ $schema?: string;
780
+ $id?: string;
781
+ $anchor?: string;
782
+ /**
783
+ * OpenAPI's nullability spelling, which is not JSON Schema's. It is declared because
784
+ * `response-schema-validator.ts` READS it (`schemaPermitsNull`) -- Google's schema dialect is
785
+ * OpenAPI-derived, so a schema that reaches the validator can carry it. No dialect in `compile.ts`
786
+ * writes or rewrites it; the canonical spelling this compiler emits is `type: ['x', 'null']`.
787
+ */
788
+ nullable?: boolean;
789
+ [key: string]: unknown;
907
790
  }
908
791
 
909
792
  /**
@@ -918,6 +801,31 @@ interface WorkflowDefinition {
918
801
  interface LLMMessage {
919
802
  role: 'system' | 'user' | 'assistant';
920
803
  content: string;
804
+ /**
805
+ * Marks this message as the end of a byte-stable prefix worth an Anthropic cache breakpoint,
806
+ * beyond the one the system prompt already gets. Anthropic's rule is "everything up to and
807
+ * including the marked block is cached", so this only ever needs to sit on ONE message -- the
808
+ * last one before content that changes.
809
+ *
810
+ * `buildAgentMessages` sets it on the last replayed prior-turn message: conversation history is
811
+ * fixed for the whole turn (only the framing/envelope after it grow per iteration), so it is the
812
+ * only part of a session agent's messages, besides the system prompt, that is ever byte-identical
813
+ * call to call. A hint rather than a mechanism deliberately -- an adapter that does not read it
814
+ * (OpenAI, OpenRouter, any test stub) just ignores the extra property; only the Anthropic adapter
815
+ * turns it into a wire `cache_control` block.
816
+ */
817
+ cacheBreakpoint?: boolean;
818
+ /**
819
+ * Prompt-injection warning types already found in this message's content, when the caller has
820
+ * already screened it and wants `screenRequest` to use that verdict instead of re-scanning.
821
+ *
822
+ * Set only on the data-envelope message by `buildAgentMessages`, sourced from
823
+ * `MemoryContextParts.envelopeWarnings` -- itself an aggregate of `MemoryEntry.warnings` stamped
824
+ * once per fragment when it entered memory. `undefined` means "not pre-screened"; `screenRequest`
825
+ * falls back to scanning the content directly, which is what every other message role/slot still
826
+ * does and what a hand-built message (tests, other callers) gets by default.
827
+ */
828
+ envelopeWarnings?: string[];
921
829
  }
922
830
  /**
923
831
  * Generic LLM generation request
@@ -1083,112 +991,84 @@ interface LLMAdapter {
1083
991
  }
1084
992
 
1085
993
  /**
1086
- * Memory type definitions
1087
- * Types for agent memory management with semantic entry types
994
+ * Model Configuration
995
+ * Centralized model information, configuration, options, constraints, and validation
996
+ * Single source of truth for all model-related definitions
997
+ * Update manually when pricing changes or new models are added
1088
998
  */
999
+
1089
1000
  /**
1090
- * Semantic memory entry types
1091
- * Use-case agnostic types that describe the purpose of each entry
1092
- * Memory types mirror action types for clarity and filtering
1001
+ * Supported Open AI models (direct SDK access)
1093
1002
  */
1094
- type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'error';
1003
+ type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano';
1095
1004
  /**
1096
- * Who authored an entry's content.
1097
- *
1098
- * This is what lets the assembled prompt tell framework-authored text apart from text that
1099
- * originated outside the trust boundary. `'framework'` content is ours; the other three are not
1100
- * and are rendered inside the JSON data envelope (see `MemoryManager.toContextParts`).
1005
+ * Supported OpenRouter models (explicit union for type safety)
1101
1006
  */
1102
- type MemoryEntrySource = 'framework' | 'user' | 'tool' | 'model';
1007
+ type OpenRouterModel = 'openrouter/z-ai/glm-5';
1103
1008
  /**
1104
- * Memory entry - represents a single entry in agent memory
1105
- * Stored in agent memory, translated by adapters to vendor-specific formats
1009
+ * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
1106
1010
  */
1107
- interface MemoryEntry {
1108
- type: MemoryEntryType;
1109
- content: string;
1110
- timestamp: number;
1111
- turnNumber: number | null;
1112
- iterationNumber: number | null;
1113
- /**
1114
- * Provenance. **Optional on purpose** — `undefined` means unknown, which is what every
1115
- * pre-existing snapshot and every not-yet-redeployed tenant bundle produces. Read sites MUST
1116
- * test `== null`, never `=== undefined`: the `inTurnScope` predicate in `manager.ts` is the
1117
- * cautionary precedent, where a `=== undefined` check silently dropped every `null`-stamped
1118
- * entry. `isMemoryEntry` is deliberately NOT tightened to require this field; doing so would
1119
- * make every stored snapshot fail validation, and `restoreSessionMemory` fails open by
1120
- * starting the agent with empty memory rather than throwing.
1121
- */
1122
- source?: MemoryEntrySource;
1123
- /**
1124
- * Which tool produced this entry. Set on `tool-result` entries so the model can tell N parallel
1125
- * results apart -- the framework instructs batching independent tool calls in one iteration, and
1126
- * an anonymous result is unattributable the moment two land in the same iteration. `addToolError`
1127
- * already carries this (folded into its `content` JSON); this is the same fact for the success
1128
- * path, carried as a real field instead of prose the caller has to parse back out.
1129
- */
1130
- toolName?: string;
1131
- }
1011
+ type AnthropicModel = 'claude-opus-5' | 'claude-sonnet-5' | 'claude-haiku-4-5-20251001' | 'claude-haiku-4-5';
1012
+ /** Supported LLM models */
1013
+ type LLMModel = OpenAIModel | OpenRouterModel | AnthropicModel | 'mock';
1132
1014
  /**
1133
- * Agent memory - Self-orchestrated memory with session + working storage
1134
- * Agent has full control over what persists, framework handles auto-compaction
1015
+ * GPT-5 model options schema
1135
1016
  */
1136
- interface AgentMemory {
1137
- /**
1138
- * Session memory - Persists for session/conversation duration
1139
- * Never auto-trimmed by framework
1140
- * Agent-managed key-value store for critical information
1141
- * Agent provides strings, framework wraps in MemoryEntry
1142
- */
1143
- sessionMemory: Record<string, MemoryEntry>;
1144
- /**
1145
- * Working memory - Execution history
1146
- * Automatically compacted by framework when needed
1147
- * Agent doesn't control compaction
1148
- */
1149
- history: MemoryEntry[];
1150
- }
1017
+ declare const GPT5OptionsSchema: z.ZodObject<{
1018
+ reasoning_effort: z.ZodOptional<z.ZodEnum<{
1019
+ minimal: "minimal";
1020
+ low: "low";
1021
+ medium: "medium";
1022
+ high: "high";
1023
+ }>>;
1024
+ verbosity: z.ZodOptional<z.ZodEnum<{
1025
+ low: "low";
1026
+ medium: "medium";
1027
+ high: "high";
1028
+ }>>;
1029
+ }, z.core.$strip>;
1151
1030
  /**
1152
- * Memory status for agent awareness
1031
+ * OpenRouter model options schema
1032
+ * OpenRouter-specific options for routing and transforms
1153
1033
  */
1154
- interface MemoryStatus {
1155
- sessionMemoryKeys: number;
1156
- sessionMemoryLimit: number;
1157
- sessionMemoryTokens: number;
1158
- sessionMemoryTokenLimit: number;
1159
- /**
1160
- * History tokens as a percentage of `historyBudget` — history ALONE, not history plus session
1161
- * memory. It previously reported the combined total under this name, so session memory growth
1162
- * read as history pressure and triggered history compaction that could not relieve it.
1163
- */
1164
- historyPercent: number;
1165
- /**
1166
- * Tokens the history entries **in scope for the requested turn** occupy — the same set
1167
- * `toContextParts` puts in the envelope. Equal to `storedHistoryTokens` when `getStatus` is
1168
- * called without a turn.
1169
- *
1170
- * This is the number the model is shown, and it is scoped because the model is handed a scoped
1171
- * set. Counting the whole cross-turn array here meant the framing quoted the size of a store
1172
- * while the envelope beside it carried one turn's worth of it.
1173
- */
1174
- historyTokens: number;
1175
- /**
1176
- * Tokens the **entire** history array occupies, across every turn the session snapshot restored.
1177
- *
1178
- * This is what compaction measures, because compaction trims that array. Scoping it to a turn
1179
- * would let the store grow without bound whenever the current turn happened to be small.
1180
- */
1181
- storedHistoryTokens: number;
1182
- /** `storedHistoryTokens` as a percentage of `historyBudget`. The auto-compaction trigger. */
1183
- storedHistoryPercent: number;
1184
- historyBudget: number;
1185
- }
1034
+ declare const OpenRouterOptionsSchema: z.ZodObject<{
1035
+ transforms: z.ZodOptional<z.ZodArray<z.ZodString>>;
1036
+ route: z.ZodOptional<z.ZodEnum<{
1037
+ fallback: "fallback";
1038
+ }>>;
1039
+ }, z.core.$strip>;
1186
1040
  /**
1187
- * Memory constraints (optional limits)
1041
+ * Anthropic model options schema
1042
+ * Currently empty - future options must be added per supported model family
1188
1043
  */
1189
- interface MemoryConstraints {
1190
- maxSessionMemoryKeys?: number;
1191
- maxMemoryTokens?: number;
1044
+ declare const AnthropicOptionsSchema: z.ZodObject<{}, z.core.$strict>;
1045
+ /**
1046
+ * Infer TypeScript types from schemas
1047
+ */
1048
+ type GPT5Options = z.infer<typeof GPT5OptionsSchema>;
1049
+ type MockOptions = Record<string, never>;
1050
+ type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>;
1051
+ type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>;
1052
+ type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | AnthropicOptions;
1053
+ /**
1054
+ * Model configuration for LLM execution
1055
+ * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
1056
+ */
1057
+ interface ModelConfig {
1058
+ model: LLMModel;
1059
+ provider: 'openai' | 'anthropic' | 'openrouter' | 'mock';
1060
+ apiKey: string;
1061
+ temperature?: number;
1062
+ /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
1063
+ maxOutputTokens?: number;
1064
+ topP?: number;
1065
+ /**
1066
+ * Model-specific options (flat structure)
1067
+ * Options are model-specific, not vendor-specific
1068
+ * Available options defined in MODEL_INFO per model
1069
+ * Validated at build time via validateModelOptions()
1070
+ */
1071
+ modelOptions?: ModelSpecificOptions;
1192
1072
  }
1193
1073
 
1194
1074
  /**
@@ -1208,8 +1088,27 @@ interface MemoryConstraints {
1208
1088
  interface MemoryContextParts {
1209
1089
  /** Framework-authored. Memory status and a description of the envelope. Carries NO stored content. */
1210
1090
  framing: string;
1211
- /** Every stored fragment, JSON-encoded and source-tagged. Untrusted. */
1091
+ /** Every stored fragment, JSON-encoded. Untrusted. */
1212
1092
  dataEnvelope: string;
1093
+ /**
1094
+ * Union of prompt-injection warning types already found across every fragment `dataEnvelope`
1095
+ * actually carries this call, aggregated from verdicts stamped once when each fragment entered
1096
+ * memory (see `MemoryEntry.warnings`) rather than by re-scanning `dataEnvelope`'s text on every
1097
+ * iteration it gets rebuilt for. Elided fragments (see `ENVELOPE_FULL_RESULT_WINDOW`) contribute
1098
+ * nothing here — their original content isn't what gets sent once they're stubbed.
1099
+ *
1100
+ * This is metadata about the envelope, not part of it: folding a detector's own finding into the
1101
+ * model-visible JSON would hand a would-be attacker — plausibly the same person on the other end
1102
+ * of a session conversation — direct feedback on which pattern tripped. A caller wiring this up
1103
+ * (`screenRequest`'s `data-envelope` slot is the one that currently re-scans instead of reading
1104
+ * this) should treat it exactly the way `screenRequest` already treats cross-turn history: it
1105
+ * warns, but whether it blocks is that caller's decision to make, not this one's.
1106
+ *
1107
+ * Optional (not just possibly-empty): the fixture literals in `agent/reasoning/**` tests build
1108
+ * `MemoryContextParts` by hand without it, and requiring it would make this signature's landing
1109
+ * a forced edit across files this change does not otherwise touch.
1110
+ */
1111
+ envelopeWarnings?: string[];
1213
1112
  }
1214
1113
  /**
1215
1114
  * Memory Manager - Agent memory orchestration
@@ -1221,7 +1120,41 @@ declare class MemoryManager {
1221
1120
  private constraints;
1222
1121
  private logger?;
1223
1122
  private cachedSnapshot?;
1123
+ /**
1124
+ * Rolling correction for `estimateTokens`'s bias, learned from real provider usage.
1125
+ * `undefined` until the first `recordActualUsage` call -- the cold-start state, where
1126
+ * `estimate()` returns the raw `estimateTokens` output unscaled. See `recordActualUsage`.
1127
+ */
1128
+ private tokenCorrectionFactor?;
1224
1129
  constructor(memory: AgentMemory, constraints?: MemoryConstraints, logger?: AgentScopedLogger | undefined);
1130
+ /**
1131
+ * Record how far `estimateTokens` was from reality on a real provider call, and roll it into a
1132
+ * correction applied to every estimate this instance makes from here on -- `getStatus`'s three
1133
+ * token fields and `enforceSessionMemoryTokenLimit`'s eviction check, which is what
1134
+ * `autoCompact`/`enforceHardLimits` actually decide compaction from (C3 / Wave M3).
1135
+ *
1136
+ * `estimateTokens` is `chars / 3.5` -- a constant-ratio guess with no knowledge of JSON escaping,
1137
+ * key overhead, or real tokenizer behaviour. Every provider call already returns an EXACT count
1138
+ * (`usage.inputTokens`) that reaches `ai_calls` and is then dropped; this is where it stops being
1139
+ * dropped, without replacing the estimator outright -- a cold session still needs SOME number
1140
+ * before its first real call completes, so the estimator stays the prior and this only corrects
1141
+ * it once real data exists.
1142
+ *
1143
+ * `estimatedRequestTokens` must be `estimateTokens` applied to the SAME text `actualInputTokens`
1144
+ * was billed for -- the whole assembled request (system prompt, tools, conversation history, the
1145
+ * envelope, everything), not just what this class itself emits. `estimateTokens`'s bias is a
1146
+ * property of the heuristic, not of which slice of the request it is pointed at, so measuring it
1147
+ * against the full request (visible to the caller, not to this class) and applying the result to
1148
+ * this class's own estimates (which can only ever see its own slice) is a fair trade -- one ratio,
1149
+ * calibrated on real data, standing in for a per-segment breakdown nothing needs.
1150
+ *
1151
+ * Exponential moving average, not a straight replace: a single call's ratio is noisy, and a
1152
+ * straight replace lets one outlier swing every compaction decision made afterward. Each new
1153
+ * observation gets 30% weight, converging within a handful of calls without chasing one spike.
1154
+ */
1155
+ recordActualUsage(estimatedRequestTokens: number, actualInputTokens: number): void;
1156
+ /** `estimateTokens`, scaled by the learned correction once one exists. See `recordActualUsage`. */
1157
+ private estimate;
1225
1158
  /**
1226
1159
  * Set session memory entry (agent provides string, framework wraps it)
1227
1160
  * @param key - Session memory key
@@ -1317,7 +1250,15 @@ declare class MemoryManager {
1317
1250
  * treat "everything in this block" as data was also being handed the live question inside that
1318
1251
  * block.
1319
1252
  *
1320
- * Shows current iteration entries FIRST (reverse chronological) for LLM attention.
1253
+ * History entries stay chronological. They used to be split into a "current iteration" slot
1254
+ * (reverse chronological, for LLM positional bias) and an "earlier" slot -- but the LLM call
1255
+ * always happens BEFORE `addToHistory` writes that iteration's own entries, so the
1256
+ * current-iteration slot held nothing on any call that mattered. One chronological list replaces
1257
+ * both.
1258
+ *
1259
+ * Tool results (and tool errors) older than `ENVELOPE_FULL_RESULT_WINDOW` iterations are carried
1260
+ * as a short stub instead of their full content -- see `ENVELOPE_FULL_RESULT_WINDOW`. The STORE
1261
+ * (`this.memory.history`) is untouched; only what this call carries is capped.
1321
1262
  *
1322
1263
  * @param currentIteration - Current iteration number (0 = pre-iteration)
1323
1264
  * @param currentTurn - Current turn number (optional, for session context filtering)
@@ -1326,89 +1267,145 @@ declare class MemoryManager {
1326
1267
  }
1327
1268
 
1328
1269
  /**
1329
- * Agent-specific type definitions
1330
- * Types for autonomous agents with tools, memory, and constraints
1270
+ * Shared form field types for dynamic form generation
1271
+ * Used by: Command Queue, Execution Runner UI, future form-based features
1272
+ */
1273
+ /**
1274
+ * Supported form field types for action payloads
1275
+ * Maps to Mantine form components
1331
1276
  */
1277
+ type FormFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'radio' | 'richtext';
1278
+ /**
1279
+ * Form field definition
1280
+ */
1281
+ interface FormField {
1282
+ /** Field key in payload object */
1283
+ name: string;
1284
+ /** Field label for UI */
1285
+ label: string;
1286
+ /** Field type (determines UI component) */
1287
+ type: FormFieldType;
1288
+ /** Default value */
1289
+ defaultValue?: unknown;
1290
+ /** Required field */
1291
+ required?: boolean;
1292
+ /** Placeholder text */
1293
+ placeholder?: string;
1294
+ /** Help text */
1295
+ description?: string;
1296
+ /** Options for select/radio */
1297
+ options?: Array<{
1298
+ label: string;
1299
+ value: string | number;
1300
+ }>;
1301
+ /** Min/max for number */
1302
+ min?: number;
1303
+ max?: number;
1304
+ /** Path to context value for pre-filling (dot notation, e.g., 'proposal.summary') */
1305
+ defaultValueFromContext?: string;
1306
+ }
1307
+ /**
1308
+ * Form schema for action payload collection
1309
+ */
1310
+ interface FormSchema {
1311
+ /** Form title */
1312
+ title?: string;
1313
+ /** Form description */
1314
+ description?: string;
1315
+ /** Form fields */
1316
+ fields: FormField[];
1317
+ }
1332
1318
 
1333
1319
  /**
1334
- * Factory function for creating LLM adapters.
1335
- * Injected into the Agent class to decouple the engine from server-only provider SDKs.
1336
- * - API process: provides createLLMAdapter (real SDKs + process.env API keys)
1337
- * - SDK worker: provides PostMessageLLMAdapter (proxies via platform.call)
1338
- *
1339
- * Uses `any` for optional params so both the real createLLMAdapter (with typed
1340
- * AIUsageCollector/AICallContext) and the worker proxy (which ignores them) satisfy the type.
1320
+ * Execution interface configuration
1321
+ * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
1322
+ * Applies to both agents and workflows
1341
1323
  */
1342
- type LLMAdapterFactory = (config: ModelConfig, ...args: any[]) => LLMAdapter;
1343
- type AgentKind = 'orchestrator' | 'specialist' | 'utility' | 'platform';
1344
- interface AgentConfig extends ResourceDefinition {
1345
- type: 'agent';
1346
- /** OM descriptor backing canonical identity and governance metadata. */
1347
- resource?: AgentResourceEntry;
1348
- kind: AgentKind;
1349
- systemPrompt: string;
1350
- constraints?: AgentConstraints;
1351
- /**
1352
- * Session capability declaration (opt-in)
1353
- * If true, agent is designed for multi-turn session interactions
1354
- * Controls whether agent can use message action and appears in Sessions UI
1355
- *
1356
- * Use for:
1357
- * - Conversational agents with multi-turn interactions
1358
- * - Agents requiring persistent context across turns
1359
- * - Agents that need human-in-the-loop communication
1360
- */
1361
- sessionCapable?: boolean;
1324
+ interface ExecutionInterface {
1325
+ /** Form configuration for execution inputs */
1326
+ form: ExecutionFormSchema;
1327
+ /** Optional: Schedule configuration */
1328
+ schedule?: ScheduleConfig;
1329
+ /** Optional: Webhook trigger configuration */
1330
+ webhook?: WebhookConfig;
1331
+ }
1332
+ /**
1333
+ * Execution form schema
1334
+ * Extends FormSchema with execution-specific fields
1335
+ */
1336
+ interface ExecutionFormSchema extends FormSchema {
1362
1337
  /**
1363
- * Security level for system prompt hardening (auto-derived if omitted)
1364
- *
1365
- * - 'standard': Lightweight defense (3 rules) - default for non-session agents
1366
- * - 'hardened': Comprehensive defense (5 rules) - default for session-capable agents
1367
- * - 'none': No security prompt - for pure internal agents with no external input
1368
- *
1369
- * If omitted, derived from sessionCapable:
1370
- * sessionCapable: true -> 'hardened'
1371
- * sessionCapable: false -> 'standard'
1338
+ * Field mappings to resource input schema
1339
+ * Maps form field names to contract input paths
1340
+ * If omitted, field names must match contract input keys exactly
1372
1341
  */
1373
- securityLevel?: 'standard' | 'hardened' | 'none';
1342
+ fieldMappings?: Record<string, string>;
1374
1343
  /**
1375
- * Memory management preferences (opt-in)
1376
- * If provided, agent can use memoryOps to manage session memory
1377
- * If omitted, agent has no memory management capabilities
1378
- *
1379
- * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
1380
- * This guidance is injected into the system prompt when memory management is enabled.
1381
- *
1382
- * Use for:
1383
- * - Conversational agents needing cross-turn context
1384
- * - Agents managing complex user preferences
1385
- * - Agents tracking decisions over multiple iterations
1344
+ * Submit button configuration
1345
+ * Default: { label: 'Run', loadingLabel: 'Running...' }
1386
1346
  */
1387
- memoryPreferences?: string;
1347
+ submitButton?: {
1348
+ label?: string;
1349
+ loadingLabel?: string;
1350
+ confirmMessage?: string;
1351
+ };
1352
+ }
1353
+ /**
1354
+ * Schedule configuration for automated execution
1355
+ */
1356
+ interface ScheduleConfig {
1357
+ /** Whether scheduling is enabled for this resource */
1358
+ enabled: boolean;
1359
+ /** Default schedule (cron expression) */
1360
+ defaultSchedule?: string;
1361
+ /** Allowed schedule patterns (if restricted) */
1362
+ allowedPatterns?: string[];
1363
+ }
1364
+ /**
1365
+ * Webhook configuration for external triggers
1366
+ */
1367
+ interface WebhookConfig {
1368
+ /** Whether webhook trigger is enabled */
1369
+ enabled: boolean;
1370
+ /** Expected payload schema (for documentation) */
1371
+ payloadSchema?: unknown;
1388
1372
  }
1389
- interface AgentConstraints {
1390
- maxIterations?: number;
1391
- timeout?: number;
1392
- maxSessionMemoryKeys?: number;
1393
- maxMemoryTokens?: number;
1373
+
1374
+ interface WorkflowConfig extends ResourceDefinition {
1375
+ type: 'workflow';
1376
+ /** OM descriptor backing canonical identity and governance metadata. */
1377
+ resource?: WorkflowResourceEntry;
1394
1378
  }
1395
- interface AgentDefinition {
1396
- config: AgentConfig;
1379
+ interface WorkflowStepDefinition {
1380
+ id: string;
1381
+ name: string;
1382
+ description: string;
1383
+ }
1384
+ type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>;
1385
+ interface LinearNext {
1386
+ type: 'linear';
1387
+ target: string;
1388
+ }
1389
+ interface ConditionalNext {
1390
+ type: 'conditional';
1391
+ routes: Array<{
1392
+ condition: (data: unknown) => boolean;
1393
+ target: string;
1394
+ }>;
1395
+ default: string;
1396
+ }
1397
+ type NextConfig = LinearNext | ConditionalNext | null;
1398
+ interface WorkflowStep extends WorkflowStepDefinition {
1399
+ handler: StepHandler;
1400
+ inputSchema: z.ZodSchema;
1401
+ outputSchema: z.ZodSchema;
1402
+ next: NextConfig;
1403
+ }
1404
+ interface WorkflowDefinition {
1405
+ config: WorkflowConfig;
1397
1406
  contract: Contract;
1398
- tools: Tool[];
1399
- /**
1400
- * Model configuration for LLM execution
1401
- * Specifies provider, API key, and model-specific options
1402
- */
1403
- modelConfig: ModelConfig;
1404
- /**
1405
- * Preload memory before execution starts
1406
- * Handles BOTH context loading AND session restoration
1407
- *
1408
- * @param context - Execution context (includes sessionId if session turn)
1409
- * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
1410
- */
1411
- preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory;
1407
+ steps: Record<string, WorkflowStep>;
1408
+ entryPoint: string;
1412
1409
  /**
1413
1410
  * Metrics configuration for ROI calculations
1414
1411
  * Optional: Only needed if tracking automation savings
@@ -1416,30 +1413,19 @@ interface AgentDefinition {
1416
1413
  metricsConfig?: ResourceMetricsConfig;
1417
1414
  /**
1418
1415
  * Execution interface configuration (optional)
1419
- * If provided, agent appears in Execution Runner UI
1416
+ * If provided, workflow appears in Execution Runner UI
1420
1417
  */
1421
1418
  interface?: ExecutionInterface;
1422
- }
1423
- /**
1424
- * Agent execution context
1425
- * Groups all state needed for agent execution phases
1426
- */
1427
- interface IterationContext {
1428
- config: AgentConfig;
1429
- contract: Contract;
1430
- toolRegistry: Map<string, Tool>;
1431
- memoryManager: MemoryManager;
1432
- executionContext: ExecutionContext;
1433
- iteration: number;
1434
- logger: AgentScopedLogger;
1435
- modelConfig: ModelConfig;
1436
- adapterFactory: LLMAdapterFactory;
1437
1419
  /**
1438
- * The validated input for this execution, serialized. It travels here because the model gets
1439
- * it as its own `role:'user'` message; nothing else in this context carried it, so the input
1440
- * had to be read back out of memory history and shipped inside the memory block.
1420
+ * Lead-gen processing stage this workflow implements (optional).
1421
+ * Must match a key in the platform lead-gen stage catalog.
1422
+ * Used by org-os graph derivation to surface workflow→stage edges and
1423
+ * by pipeline_config validation to confirm each catalog stage has an
1424
+ * implementing workflow before a list is activated.
1425
+ *
1426
+ * Example: stageImplemented: 'verified' on the email-verification workflow.
1441
1427
  */
1442
- currentInput: string;
1428
+ stageImplemented?: string;
1443
1429
  }
1444
1430
 
1445
1431
  type Json = string | number | boolean | null | {
@@ -7472,6 +7458,32 @@ type StorageDownloadOutput = z.infer<typeof StorageDownloadOutputSchema>;
7472
7458
  type StorageDeleteOutput = z.infer<typeof StorageDeleteOutputSchema>;
7473
7459
  type StorageListOutput = z.infer<typeof StorageListOutputSchema>;
7474
7460
 
7461
+ /**
7462
+ * AIUsageCollector
7463
+ * Centralized token tracking that aggregates usage across all LLM calls in an execution
7464
+ */
7465
+ declare class AIUsageCollector {
7466
+ private model;
7467
+ private calls;
7468
+ private callSequence;
7469
+ /**
7470
+ * Record a single AI call with usage metrics
7471
+ *
7472
+ * @param usage - Token usage and latency data from LLM adapter
7473
+ * @param callType - Type discriminator (agent-reasoning, tool, etc.)
7474
+ * @param context - Optional typed context specific to callType
7475
+ */
7476
+ record(usage: LLMUsageData, callType?: BaseAICall['callType'], context?: AICallContext): void;
7477
+ /**
7478
+ * Get aggregated summary of all AI calls
7479
+ */
7480
+ getSummary(): AIUsageSummary;
7481
+ /**
7482
+ * Check if any usage has been recorded
7483
+ */
7484
+ hasUsage(): boolean;
7485
+ }
7486
+
7475
7487
  /**
7476
7488
  * Create record parameters
7477
7489
  */
@@ -9030,9 +9042,9 @@ declare const ProjectSchemas: {
9030
9042
  CreateProjectRequest: z.ZodObject<{
9031
9043
  name: z.ZodString;
9032
9044
  kind: z.ZodEnum<{
9033
- internal: "internal";
9034
9045
  other: "other";
9035
9046
  client_engagement: "client_engagement";
9047
+ internal: "internal";
9036
9048
  research: "research";
9037
9049
  }>;
9038
9050
  status: z.ZodOptional<z.ZodEnum<{
@@ -9055,9 +9067,9 @@ declare const ProjectSchemas: {
9055
9067
  UpdateProjectRequest: z.ZodObject<{
9056
9068
  name: z.ZodOptional<z.ZodString>;
9057
9069
  kind: z.ZodOptional<z.ZodEnum<{
9058
- internal: "internal";
9059
9070
  other: "other";
9060
9071
  client_engagement: "client_engagement";
9072
+ internal: "internal";
9061
9073
  research: "research";
9062
9074
  }>>;
9063
9075
  status: z.ZodOptional<z.ZodEnum<{
@@ -9080,9 +9092,9 @@ declare const ProjectSchemas: {
9080
9092
  }, z.core.$strict>;
9081
9093
  GetProjectsQuery: z.ZodObject<{
9082
9094
  kind: z.ZodOptional<z.ZodEnum<{
9083
- internal: "internal";
9084
9095
  other: "other";
9085
9096
  client_engagement: "client_engagement";
9097
+ internal: "internal";
9086
9098
  research: "research";
9087
9099
  }>>;
9088
9100
  status: z.ZodOptional<z.ZodEnum<{
@@ -9170,12 +9182,12 @@ declare const ProjectSchemas: {
9170
9182
  status: z.ZodOptional<z.ZodEnum<{
9171
9183
  completed: "completed";
9172
9184
  cancelled: "cancelled";
9185
+ rejected: "rejected";
9173
9186
  blocked: "blocked";
9174
9187
  in_progress: "in_progress";
9175
9188
  planned: "planned";
9176
9189
  submitted: "submitted";
9177
9190
  approved: "approved";
9178
- rejected: "rejected";
9179
9191
  revision_requested: "revision_requested";
9180
9192
  }>>;
9181
9193
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -9206,12 +9218,12 @@ declare const ProjectSchemas: {
9206
9218
  status: z.ZodOptional<z.ZodEnum<{
9207
9219
  completed: "completed";
9208
9220
  cancelled: "cancelled";
9221
+ rejected: "rejected";
9209
9222
  blocked: "blocked";
9210
9223
  in_progress: "in_progress";
9211
9224
  planned: "planned";
9212
9225
  submitted: "submitted";
9213
9226
  approved: "approved";
9214
- rejected: "rejected";
9215
9227
  revision_requested: "revision_requested";
9216
9228
  }>>;
9217
9229
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -9233,12 +9245,12 @@ declare const ProjectSchemas: {
9233
9245
  status: z.ZodOptional<z.ZodEnum<{
9234
9246
  completed: "completed";
9235
9247
  cancelled: "cancelled";
9248
+ rejected: "rejected";
9236
9249
  blocked: "blocked";
9237
9250
  in_progress: "in_progress";
9238
9251
  planned: "planned";
9239
9252
  submitted: "submitted";
9240
9253
  approved: "approved";
9241
- rejected: "rejected";
9242
9254
  revision_requested: "revision_requested";
9243
9255
  }>>;
9244
9256
  milestone_id: z.ZodOptional<z.ZodString>;
@@ -10587,29 +10599,147 @@ interface ResourceMetricsConfig {
10587
10599
  }
10588
10600
 
10589
10601
  /**
10590
- * AIUsageCollector
10591
- * Centralized token tracking that aggregates usage across all LLM calls in an execution
10602
+ * Agent-specific type definitions
10603
+ * Types for autonomous agents with tools, memory, and constraints
10592
10604
  */
10593
- declare class AIUsageCollector {
10594
- private model;
10595
- private calls;
10596
- private callSequence;
10605
+
10606
+ /**
10607
+ * Factory function for creating LLM adapters.
10608
+ * Injected into the Agent class to decouple the engine from server-only provider SDKs.
10609
+ * - API process: provides createLLMAdapter (real SDKs + process.env API keys)
10610
+ * - SDK worker: provides PostMessageLLMAdapter (proxies via platform.call)
10611
+ *
10612
+ * Uses `any` for optional params so both the real createLLMAdapter (with typed
10613
+ * AIUsageCollector/AICallContext) and the worker proxy (which ignores them) satisfy the type.
10614
+ */
10615
+ type LLMAdapterFactory = (config: ModelConfig, ...args: any[]) => LLMAdapter;
10616
+ type AgentKind = 'orchestrator' | 'specialist' | 'utility' | 'platform';
10617
+ interface AgentConfig extends ResourceDefinition {
10618
+ type: 'agent';
10619
+ /** OM descriptor backing canonical identity and governance metadata. */
10620
+ resource?: AgentResourceEntry;
10621
+ kind: AgentKind;
10622
+ systemPrompt: string;
10623
+ constraints?: AgentConstraints;
10597
10624
  /**
10598
- * Record a single AI call with usage metrics
10625
+ * Session capability declaration (opt-in)
10626
+ * If true, agent is designed for multi-turn session interactions
10627
+ * Controls whether agent can use message action and appears in Sessions UI
10599
10628
  *
10600
- * @param usage - Token usage and latency data from LLM adapter
10601
- * @param callType - Type discriminator (agent-reasoning, tool, etc.)
10602
- * @param context - Optional typed context specific to callType
10629
+ * Use for:
10630
+ * - Conversational agents with multi-turn interactions
10631
+ * - Agents requiring persistent context across turns
10632
+ * - Agents that need human-in-the-loop communication
10603
10633
  */
10604
- record(usage: LLMUsageData, callType?: BaseAICall['callType'], context?: AICallContext): void;
10634
+ sessionCapable?: boolean;
10605
10635
  /**
10606
- * Get aggregated summary of all AI calls
10636
+ * Overrides the default `message` requiredness for a session-capable agent (ignored for
10637
+ * non-session agents, which always get `AgentCapabilities.message: 'off'`). Defaults to
10638
+ * `'required'` -- see `AgentCapabilities.message`'s doc comment for why. Set `'optional'` only
10639
+ * when the agent legitimately needs tool-only turns with no reply, and the deploy target can
10640
+ * tolerate the blind-retry risk `validateResponseSchema` carries on any path where the schema is
10641
+ * not compiled into a sampling grammar.
10607
10642
  */
10608
- getSummary(): AIUsageSummary;
10643
+ messagePolicy?: 'optional' | 'required';
10609
10644
  /**
10610
- * Check if any usage has been recorded
10645
+ * Explicit opt-in to skip the iteration loop and produce `contract.outputSchema`-shaped output in
10646
+ * a single LLM call (round 3 decision B6: explicit opt-in, never inferred from `kind`,
10647
+ * `sessionCapable`, or tool count -- so no existing agent changes shape by default). Structurally
10648
+ * the normal path pays two calls minimum: `iterate()` always runs at least one, and `complete()`
10649
+ * runs a second whose prompt re-derives the answer from history rather than reading what the
10650
+ * iteration already decided. A single-shot classifier -- one input in, one structured output out,
10651
+ * no multi-step reasoning needed -- does not need that second derivation; `complete()` already
10652
+ * makes exactly the one call it needs, from `currentInput` directly.
10653
+ *
10654
+ * Requires `sessionCapable` to be falsy and `contract.outputSchema` to be present. `Agent`
10655
+ * validates both during initialization and throws `AgentInitializationError` if either is missing,
10656
+ * rather than silently falling back to the normal two-call path on a misconfigured opt-in. Tools
10657
+ * registered on the agent are never invoked in this path -- there is no iteration loop to call
10658
+ * them from, so an agent that needs tool calls before it can answer is not eligible regardless of
10659
+ * this flag.
10611
10660
  */
10612
- hasUsage(): boolean;
10661
+ singleShot?: boolean;
10662
+ /**
10663
+ * Security level for system prompt hardening (auto-derived if omitted)
10664
+ *
10665
+ * - 'standard': Lightweight defense (3 rules) - default for non-session agents
10666
+ * - 'hardened': Comprehensive defense (5 rules) - default for session-capable agents
10667
+ * - 'none': No security prompt - for pure internal agents with no external input
10668
+ *
10669
+ * If omitted, derived from sessionCapable:
10670
+ * sessionCapable: true -> 'hardened'
10671
+ * sessionCapable: false -> 'standard'
10672
+ */
10673
+ securityLevel?: 'standard' | 'hardened' | 'none';
10674
+ /**
10675
+ * Memory management preferences (opt-in)
10676
+ * If provided, agent can use memoryOps to manage session memory
10677
+ * If omitted, agent has no memory management capabilities
10678
+ *
10679
+ * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
10680
+ * This guidance is injected into the system prompt when memory management is enabled.
10681
+ *
10682
+ * Use for:
10683
+ * - Conversational agents needing cross-turn context
10684
+ * - Agents managing complex user preferences
10685
+ * - Agents tracking decisions over multiple iterations
10686
+ */
10687
+ memoryPreferences?: string;
10688
+ }
10689
+ interface AgentConstraints {
10690
+ maxIterations?: number;
10691
+ timeout?: number;
10692
+ maxSessionMemoryKeys?: number;
10693
+ maxMemoryTokens?: number;
10694
+ }
10695
+ interface AgentDefinition {
10696
+ config: AgentConfig;
10697
+ contract: Contract;
10698
+ tools: Tool[];
10699
+ /**
10700
+ * Model configuration for LLM execution
10701
+ * Specifies provider, API key, and model-specific options
10702
+ */
10703
+ modelConfig: ModelConfig;
10704
+ /**
10705
+ * Preload memory before execution starts
10706
+ * Handles BOTH context loading AND session restoration
10707
+ *
10708
+ * @param context - Execution context (includes sessionId if session turn)
10709
+ * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
10710
+ */
10711
+ preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory;
10712
+ /**
10713
+ * Metrics configuration for ROI calculations
10714
+ * Optional: Only needed if tracking automation savings
10715
+ */
10716
+ metricsConfig?: ResourceMetricsConfig;
10717
+ /**
10718
+ * Execution interface configuration (optional)
10719
+ * If provided, agent appears in Execution Runner UI
10720
+ */
10721
+ interface?: ExecutionInterface;
10722
+ }
10723
+ /**
10724
+ * Agent execution context
10725
+ * Groups all state needed for agent execution phases
10726
+ */
10727
+ interface IterationContext {
10728
+ config: AgentConfig;
10729
+ contract: Contract;
10730
+ toolRegistry: Map<string, Tool>;
10731
+ memoryManager: MemoryManager;
10732
+ executionContext: ExecutionContext;
10733
+ iteration: number;
10734
+ logger: AgentScopedLogger;
10735
+ modelConfig: ModelConfig;
10736
+ adapterFactory: LLMAdapterFactory;
10737
+ /**
10738
+ * The validated input for this execution, serialized. It travels here because the model gets
10739
+ * it as its own `role:'user'` message; nothing else in this context carried it, so the input
10740
+ * had to be read back out of memory history and shipped inside the memory block.
10741
+ */
10742
+ currentInput: string;
10613
10743
  }
10614
10744
 
10615
10745
  /**
@@ -10757,6 +10887,19 @@ interface Tool {
10757
10887
  outputSchema: z.ZodSchema;
10758
10888
  execute: (options: ToolExecutionOptions) => Promise<unknown>;
10759
10889
  timeout?: number;
10890
+ /**
10891
+ * Optional per-tool output size bound, in approximate tokens. Today the ONLY size bound on tool
10892
+ * output is a 4,000-token truncation applied post-hoc at memory insert -- after the payload is
10893
+ * already fully materialized, validated against `outputSchema`, emitted as a session message, and
10894
+ * logged. This field exists so a tool can declare its own bound up front instead.
10895
+ *
10896
+ * Enforcement is NOT here. `executor.ts:executeToolCall` is the single call site that produces the
10897
+ * value handed to all four sinks (memory, the `agent:tool_result` event, the session message, and
10898
+ * the log line) -- enforcing there, before that value is emitted, is what makes the four sinks agree
10899
+ * instead of three of them seeing the untruncated payload. See that file's own comment for the
10900
+ * exact insertion point.
10901
+ */
10902
+ maxOutputTokens?: number;
10760
10903
  }
10761
10904
 
10762
10905
  /**
@@ -11180,7 +11323,10 @@ type TypedAdapter<TMap extends ToolMethodMap$1> = {
11180
11323
  * parentExecutionId?, executionDepth }
11181
11324
  * Worker -> Parent: { type: 'result', status, output?, memorySnapshot?, error?, logs, metrics: { durationMs } }
11182
11325
  *
11183
- * Parent -> Worker: { type: 'abort' } (graceful abort before terminate)
11326
+ * Parent -> Worker: { type: 'abort', reason? } (graceful abort before terminate;
11327
+ * reason carries AbortSignal.reason
11328
+ * across the boundary -- see N6, agent-
11329
+ * framework-round-3.mdx)
11184
11330
  *
11185
11331
  * Worker -> Parent: { type: 'log', entry: { level, message, timestamp, executionId, context? } }
11186
11332
  *