@elevasis/sdk 1.43.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,247 +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
- metricsConfig?: object;
357
- }
358
- /**
359
- * Serialized workflow definition (JSON-safe)
360
- * Result of serializeDefinition(WorkflowDefinition)
361
- */
362
- interface SerializedWorkflowDefinition {
363
- config: {
364
- resourceId: string;
365
- name: string;
366
- description: string;
367
- version: string;
368
- type: 'workflow';
369
- status: 'dev' | 'prod';
370
- links?: ResourceLink[];
371
- category?: ResourceCategory;
372
- /** Whether this resource is archived and should be excluded from registration and deployment */
373
- archived?: boolean;
374
- };
375
- entryPoint: string;
376
- steps: Array<{
377
- id: string;
378
- name: string;
379
- description: string;
380
- inputSchema?: object;
381
- outputSchema?: object;
382
- next: {
383
- type: 'linear' | 'conditional';
384
- target?: string;
385
- routes?: Array<{
386
- target: string;
387
- }>;
388
- default?: string;
389
- } | null;
390
- }>;
391
- contract: {
392
- inputSchema: object;
393
- outputSchema?: object;
394
- };
395
- metricsConfig?: object;
396
- }
397
-
398
- /**
399
- * Model Configuration
400
- * Centralized model information, configuration, options, constraints, and validation
401
- * Single source of truth for all model-related definitions
402
- * Update manually when pricing changes or new models are added
403
- */
404
-
405
- /**
406
- * Supported Open AI models (direct SDK access)
407
- */
408
- type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano';
409
- /**
410
- * Supported OpenRouter models (explicit union for type safety)
411
- */
412
- type OpenRouterModel = 'openrouter/z-ai/glm-5';
413
- /**
414
- * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
415
- */
416
- type AnthropicModel = 'claude-opus-5' | 'claude-sonnet-5' | 'claude-haiku-4-5-20251001' | 'claude-haiku-4-5';
417
- /** Supported LLM models */
418
- type LLMModel = OpenAIModel | OpenRouterModel | AnthropicModel | 'mock';
419
- /**
420
- * GPT-5 model options schema
421
- */
422
- declare const GPT5OptionsSchema: z.ZodObject<{
423
- reasoning_effort: z.ZodOptional<z.ZodEnum<{
424
- minimal: "minimal";
425
- low: "low";
426
- medium: "medium";
427
- high: "high";
428
- }>>;
429
- verbosity: z.ZodOptional<z.ZodEnum<{
430
- low: "low";
431
- medium: "medium";
432
- high: "high";
433
- }>>;
434
- }, z.core.$strip>;
435
- /**
436
- * OpenRouter model options schema
437
- * OpenRouter-specific options for routing and transforms
438
- */
439
- declare const OpenRouterOptionsSchema: z.ZodObject<{
440
- transforms: z.ZodOptional<z.ZodArray<z.ZodString>>;
441
- route: z.ZodOptional<z.ZodEnum<{
442
- fallback: "fallback";
443
- }>>;
444
- }, z.core.$strip>;
445
- /**
446
- * Anthropic model options schema
447
- * Currently empty - future options must be added per supported model family
448
- */
449
- declare const AnthropicOptionsSchema: z.ZodObject<{}, z.core.$strict>;
450
- /**
451
- * Infer TypeScript types from schemas
452
- */
453
- type GPT5Options = z.infer<typeof GPT5OptionsSchema>;
454
- type MockOptions = Record<string, never>;
455
- type OpenRouterOptions = z.infer<typeof OpenRouterOptionsSchema>;
456
- type AnthropicOptions = z.infer<typeof AnthropicOptionsSchema>;
457
- type ModelSpecificOptions = GPT5Options | MockOptions | OpenRouterOptions | AnthropicOptions;
458
- /**
459
- * Model configuration for LLM execution
460
- * Belongs in resource definition (AgentDefinition, WorkflowDefinition, etc.)
461
- */
462
- interface ModelConfig {
463
- model: LLMModel;
464
- provider: 'openai' | 'anthropic' | 'openrouter' | 'mock';
465
- apiKey: string;
466
- temperature?: number;
467
- /** Maximum output tokens per LLM call. NOT the model's context window — see ModelInfo.maxTokens for that. */
468
- maxOutputTokens?: number;
469
- topP?: number;
470
- /**
471
- * Model-specific options (flat structure)
472
- * Options are model-specific, not vendor-specific
473
- * Available options defined in MODEL_INFO per model
474
- * Validated at build time via validateModelOptions()
475
- */
476
- modelOptions?: ModelSpecificOptions;
477
- }
478
-
479
- /**
480
- * Types for the schema compiler. `compile.ts` walks a `JsonSchema` once, driven entirely by a
481
- * `ProviderDialect`, and every server adapter compiles through it.
482
- */
483
- /**
484
- * What happened to `strict` on a request, recorded per call rather than inferred.
485
- *
486
- * `applied` and `notAttempted` are the two states that a refusal-only field cannot tell apart --
487
- * both leave `strictRefusalReasons` empty. Recording the verdict positively is what makes "was
488
- * this agent's output actually enforced?" answerable from an `ai_calls` row.
489
- */
490
- type StrictStatus = 'applied' | 'refused' | 'compileRejected' | 'notAttempted';
491
- /**
492
- * A JSON Schema node, typed enough to be useful without pretending to validate the spec.
493
- *
494
- * The compiler has to accept schemas that arrive OUTSIDE the strict subset (that is the whole
495
- * point of a dialect that can refuse or rewrite them) as well as the `$ref`/`$defs`/`const`/
496
- * `$schema` shapes the strict subset has no vocabulary for at all. The index signature exists
497
- * because tenant schemas carry keywords (`minLength`, `pattern`, `minimum`, ...) this compiler
498
- * drops or refuses on, and they still need somewhere to type-check while they pass through
499
- * `Object.entries`.
500
- */
501
- interface JsonSchema {
502
- type?: string | string[];
503
- /**
504
- * The value is `JsonSchema | undefined`, not `JsonSchema`, because a property really can be
505
- * declared with nothing describing it. `buildIterationResponseSchema` emits one per tool as
506
- * `input: tool.inputSchema`, and `ToolDefinition.inputSchema` is typed `unknown` -- a tool
507
- * deployed without one puts `undefined` under a key that exists.
508
- *
509
- * Both readers already handle it: `compileSchema` passes each value through `convertNode`, which
510
- * takes `unknown`, and `collectErrors` opens with `if (!schema || typeof schema !== 'object')`
511
- * above a comment naming this exact case. Declaring the value non-optional only hid that they
512
- * were right to.
513
- */
514
- properties?: Record<string, JsonSchema | undefined>;
515
- items?: JsonSchema;
516
- anyOf?: JsonSchema[];
517
- oneOf?: JsonSchema[];
518
- allOf?: JsonSchema[];
519
- required?: string[];
520
- additionalProperties?: boolean | JsonSchema;
521
- minItems?: number;
522
- maxItems?: number;
523
- format?: string;
524
- enum?: unknown[];
525
- const?: unknown;
526
- description?: string;
527
- default?: unknown;
528
- $ref?: string;
529
- $defs?: Record<string, JsonSchema>;
530
- definitions?: Record<string, JsonSchema>;
531
- $schema?: string;
532
- $id?: string;
533
- $anchor?: string;
534
- /**
535
- * OpenAPI's nullability spelling, which is not JSON Schema's. It is declared because
536
- * `response-schema-validator.ts` READS it (`schemaPermitsNull`) -- Google's schema dialect is
537
- * OpenAPI-derived, so a schema that reaches the validator can carry it. No dialect in `compile.ts`
538
- * writes or rewrites it; the canonical spelling this compiler emits is `type: ['x', 'null']`.
539
- */
540
- nullable?: boolean;
541
- [key: string]: unknown;
542
- }
543
-
544
303
  declare const ResourceGovernanceStatusSchema: z.ZodEnum<{
545
304
  active: "active";
546
305
  deprecated: "deprecated";
@@ -903,165 +662,194 @@ type AgentResourceEntry = z.infer<typeof AgentResourceEntrySchema$1>;
903
662
  type ResourceEntry$1 = z.infer<typeof ResourceEntrySchema$1>;
904
663
 
905
664
  /**
906
- * Shared form field types for dynamic form generation
907
- * Used by: Command Queue, Execution Runner UI, future form-based features
665
+ * Memory type definitions
666
+ * Types for agent memory management with semantic entry types
908
667
  */
909
668
  /**
910
- * Supported form field types for action payloads
911
- * Maps to Mantine form components
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
912
672
  */
913
- type FormFieldType = 'text' | 'textarea' | 'number' | 'select' | 'checkbox' | 'radio' | 'richtext';
673
+ type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'error';
914
674
  /**
915
- * Form field definition
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`).
916
680
  */
917
- interface FormField {
918
- /** Field key in payload object */
919
- name: string;
920
- /** Field label for UI */
921
- label: string;
922
- /** Field type (determines UI component) */
923
- type: FormFieldType;
924
- /** Default value */
925
- defaultValue?: unknown;
926
- /** Required field */
927
- required?: boolean;
928
- /** Placeholder text */
929
- placeholder?: string;
930
- /** Help text */
931
- description?: string;
932
- /** Options for select/radio */
933
- options?: Array<{
934
- label: string;
935
- value: string | number;
936
- }>;
937
- /** Min/max for number */
938
- min?: number;
939
- max?: number;
940
- /** Path to context value for pre-filling (dot notation, e.g., 'proposal.summary') */
941
- defaultValueFromContext?: string;
942
- }
681
+ type MemoryEntrySource = 'framework' | 'user' | 'tool' | 'model';
943
682
  /**
944
- * Form schema for action payload collection
683
+ * Memory entry - represents a single entry in agent memory
684
+ * Stored in agent memory, translated by adapters to vendor-specific formats
945
685
  */
946
- interface FormSchema {
947
- /** Form title */
948
- title?: string;
949
- /** Form description */
950
- description?: string;
951
- /** Form fields */
952
- fields: FormField[];
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[];
953
727
  }
954
-
955
728
  /**
956
- * Execution interface configuration
957
- * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
958
- * Applies to both agents and workflows
729
+ * Agent memory - Self-orchestrated memory with session + working storage
730
+ * Agent has full control over what persists, framework handles auto-compaction
959
731
  */
960
- interface ExecutionInterface {
961
- /** Form configuration for execution inputs */
962
- form: ExecutionFormSchema;
963
- /** Optional: Schedule configuration */
964
- schedule?: ScheduleConfig;
965
- /** Optional: Webhook trigger configuration */
966
- webhook?: WebhookConfig;
732
+ interface AgentMemory {
733
+ /**
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
738
+ */
739
+ sessionMemory: Record<string, MemoryEntry>;
740
+ /**
741
+ * Working memory - Execution history
742
+ * Automatically compacted by framework when needed
743
+ * Agent doesn't control compaction
744
+ */
745
+ history: MemoryEntry[];
967
746
  }
968
747
  /**
969
- * Execution form schema
970
- * Extends FormSchema with execution-specific fields
748
+ * Memory status for agent awareness
971
749
  */
972
- interface ExecutionFormSchema extends FormSchema {
750
+ interface MemoryStatus {
751
+ sessionMemoryKeys: number;
752
+ sessionMemoryLimit: number;
753
+ sessionMemoryTokens: number;
754
+ sessionMemoryTokenLimit: number;
973
755
  /**
974
- * Field mappings to resource input schema
975
- * Maps form field names to contract input paths
976
- * If omitted, field names must match contract input keys exactly
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.
977
759
  */
978
- fieldMappings?: Record<string, string>;
760
+ historyPercent: number;
979
761
  /**
980
- * Submit button configuration
981
- * Default: { label: 'Run', loadingLabel: 'Running...' }
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.
982
769
  */
983
- submitButton?: {
984
- label?: string;
985
- loadingLabel?: string;
986
- confirmMessage?: string;
987
- };
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;
988
781
  }
989
782
  /**
990
- * Schedule configuration for automated execution
783
+ * Memory constraints (optional limits)
991
784
  */
992
- interface ScheduleConfig {
993
- /** Whether scheduling is enabled for this resource */
994
- enabled: boolean;
995
- /** Default schedule (cron expression) */
996
- defaultSchedule?: string;
997
- /** Allowed schedule patterns (if restricted) */
998
- allowedPatterns?: string[];
785
+ interface MemoryConstraints {
786
+ maxSessionMemoryKeys?: number;
787
+ maxMemoryTokens?: number;
999
788
  }
789
+
1000
790
  /**
1001
- * Webhook configuration for external triggers
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.
1002
793
  */
1003
- interface WebhookConfig {
1004
- /** Whether webhook trigger is enabled */
1005
- enabled: boolean;
1006
- /** Expected payload schema (for documentation) */
1007
- payloadSchema?: unknown;
1008
- }
1009
-
1010
- interface WorkflowConfig extends ResourceDefinition {
1011
- type: 'workflow';
1012
- /** OM descriptor backing canonical identity and governance metadata. */
1013
- resource?: WorkflowResourceEntry;
1014
- }
1015
- interface WorkflowStepDefinition {
1016
- id: string;
1017
- name: string;
1018
- description: string;
1019
- }
1020
- type StepHandler = (input: unknown, context: ExecutionContext) => Promise<unknown>;
1021
- interface LinearNext {
1022
- type: 'linear';
1023
- target: string;
1024
- }
1025
- interface ConditionalNext {
1026
- type: 'conditional';
1027
- routes: Array<{
1028
- condition: (data: unknown) => boolean;
1029
- target: string;
1030
- }>;
1031
- default: string;
1032
- }
1033
- type NextConfig = LinearNext | ConditionalNext | null;
1034
- interface WorkflowStep extends WorkflowStepDefinition {
1035
- handler: StepHandler;
1036
- inputSchema: z.ZodSchema;
1037
- outputSchema: z.ZodSchema;
1038
- next: NextConfig;
1039
- }
1040
- interface WorkflowDefinition {
1041
- config: WorkflowConfig;
1042
- contract: Contract;
1043
- steps: Record<string, WorkflowStep>;
1044
- entryPoint: string;
1045
- /**
1046
- * Metrics configuration for ROI calculations
1047
- * Optional: Only needed if tracking automation savings
1048
- */
1049
- metricsConfig?: ResourceMetricsConfig;
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[];
1050
814
  /**
1051
- * Execution interface configuration (optional)
1052
- * 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.
1053
824
  */
1054
- 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;
1055
845
  /**
1056
- * Lead-gen processing stage this workflow implements (optional).
1057
- * Must match a key in the platform lead-gen stage catalog.
1058
- * Used by org-os graph derivation to surface workflow→stage edges and
1059
- * by pipeline_config validation to confirm each catalog stage has an
1060
- * implementing workflow before a list is activated.
1061
- *
1062
- * 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']`.
1063
850
  */
1064
- stageImplemented?: string;
851
+ nullable?: boolean;
852
+ [key: string]: unknown;
1065
853
  }
1066
854
 
1067
855
  /**
@@ -1076,6 +864,31 @@ interface WorkflowDefinition {
1076
864
  interface LLMMessage {
1077
865
  role: 'system' | 'user' | 'assistant';
1078
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[];
1079
892
  }
1080
893
  /**
1081
894
  * Generic LLM generation request
@@ -1241,112 +1054,84 @@ interface LLMAdapter {
1241
1054
  }
1242
1055
 
1243
1056
  /**
1244
- * Memory type definitions
1245
- * 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
1246
1061
  */
1062
+
1247
1063
  /**
1248
- * Semantic memory entry types
1249
- * Use-case agnostic types that describe the purpose of each entry
1250
- * Memory types mirror action types for clarity and filtering
1064
+ * Supported Open AI models (direct SDK access)
1251
1065
  */
1252
- type MemoryEntryType = 'context' | 'input' | 'reasoning' | 'tool-result' | 'error';
1066
+ type OpenAIModel = 'gpt-5' | 'gpt-5.4-mini' | 'gpt-5.4-nano';
1253
1067
  /**
1254
- * Who authored an entry's content.
1255
- *
1256
- * This is what lets the assembled prompt tell framework-authored text apart from text that
1257
- * originated outside the trust boundary. `'framework'` content is ours; the other three are not
1258
- * and are rendered inside the JSON data envelope (see `MemoryManager.toContextParts`).
1068
+ * Supported OpenRouter models (explicit union for type safety)
1259
1069
  */
1260
- type MemoryEntrySource = 'framework' | 'user' | 'tool' | 'model';
1070
+ type OpenRouterModel = 'openrouter/z-ai/glm-5';
1261
1071
  /**
1262
- * Memory entry - represents a single entry in agent memory
1263
- * Stored in agent memory, translated by adapters to vendor-specific formats
1072
+ * Supported Anthropic models (direct SDK access via @anthropic-ai/sdk)
1264
1073
  */
1265
- interface MemoryEntry {
1266
- type: MemoryEntryType;
1267
- content: string;
1268
- timestamp: number;
1269
- turnNumber: number | null;
1270
- iterationNumber: number | null;
1271
- /**
1272
- * Provenance. **Optional on purpose** — `undefined` means unknown, which is what every
1273
- * pre-existing snapshot and every not-yet-redeployed tenant bundle produces. Read sites MUST
1274
- * test `== null`, never `=== undefined`: the `inTurnScope` predicate in `manager.ts` is the
1275
- * cautionary precedent, where a `=== undefined` check silently dropped every `null`-stamped
1276
- * entry. `isMemoryEntry` is deliberately NOT tightened to require this field; doing so would
1277
- * make every stored snapshot fail validation, and `restoreSessionMemory` fails open by
1278
- * starting the agent with empty memory rather than throwing.
1279
- */
1280
- source?: MemoryEntrySource;
1281
- /**
1282
- * Which tool produced this entry. Set on `tool-result` entries so the model can tell N parallel
1283
- * results apart -- the framework instructs batching independent tool calls in one iteration, and
1284
- * an anonymous result is unattributable the moment two land in the same iteration. `addToolError`
1285
- * already carries this (folded into its `content` JSON); this is the same fact for the success
1286
- * path, carried as a real field instead of prose the caller has to parse back out.
1287
- */
1288
- toolName?: string;
1289
- }
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';
1290
1077
  /**
1291
- * Agent memory - Self-orchestrated memory with session + working storage
1292
- * Agent has full control over what persists, framework handles auto-compaction
1078
+ * GPT-5 model options schema
1293
1079
  */
1294
- interface AgentMemory {
1295
- /**
1296
- * Session memory - Persists for session/conversation duration
1297
- * Never auto-trimmed by framework
1298
- * Agent-managed key-value store for critical information
1299
- * Agent provides strings, framework wraps in MemoryEntry
1300
- */
1301
- sessionMemory: Record<string, MemoryEntry>;
1302
- /**
1303
- * Working memory - Execution history
1304
- * Automatically compacted by framework when needed
1305
- * Agent doesn't control compaction
1306
- */
1307
- history: MemoryEntry[];
1308
- }
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>;
1309
1093
  /**
1310
- * Memory status for agent awareness
1094
+ * OpenRouter model options schema
1095
+ * OpenRouter-specific options for routing and transforms
1311
1096
  */
1312
- interface MemoryStatus {
1313
- sessionMemoryKeys: number;
1314
- sessionMemoryLimit: number;
1315
- sessionMemoryTokens: number;
1316
- sessionMemoryTokenLimit: number;
1317
- /**
1318
- * History tokens as a percentage of `historyBudget` — history ALONE, not history plus session
1319
- * memory. It previously reported the combined total under this name, so session memory growth
1320
- * read as history pressure and triggered history compaction that could not relieve it.
1321
- */
1322
- historyPercent: number;
1323
- /**
1324
- * Tokens the history entries **in scope for the requested turn** occupy — the same set
1325
- * `toContextParts` puts in the envelope. Equal to `storedHistoryTokens` when `getStatus` is
1326
- * called without a turn.
1327
- *
1328
- * This is the number the model is shown, and it is scoped because the model is handed a scoped
1329
- * set. Counting the whole cross-turn array here meant the framing quoted the size of a store
1330
- * while the envelope beside it carried one turn's worth of it.
1331
- */
1332
- historyTokens: number;
1333
- /**
1334
- * Tokens the **entire** history array occupies, across every turn the session snapshot restored.
1335
- *
1336
- * This is what compaction measures, because compaction trims that array. Scoping it to a turn
1337
- * would let the store grow without bound whenever the current turn happened to be small.
1338
- */
1339
- storedHistoryTokens: number;
1340
- /** `storedHistoryTokens` as a percentage of `historyBudget`. The auto-compaction trigger. */
1341
- storedHistoryPercent: number;
1342
- historyBudget: number;
1343
- }
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>;
1344
1103
  /**
1345
- * Memory constraints (optional limits)
1104
+ * Anthropic model options schema
1105
+ * Currently empty - future options must be added per supported model family
1346
1106
  */
1347
- interface MemoryConstraints {
1348
- maxSessionMemoryKeys?: number;
1349
- 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;
1350
1135
  }
1351
1136
 
1352
1137
  /**
@@ -1366,8 +1151,27 @@ interface MemoryConstraints {
1366
1151
  interface MemoryContextParts {
1367
1152
  /** Framework-authored. Memory status and a description of the envelope. Carries NO stored content. */
1368
1153
  framing: string;
1369
- /** Every stored fragment, JSON-encoded and source-tagged. Untrusted. */
1154
+ /** Every stored fragment, JSON-encoded. Untrusted. */
1370
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[];
1371
1175
  }
1372
1176
  /**
1373
1177
  * Memory Manager - Agent memory orchestration
@@ -1379,7 +1183,41 @@ declare class MemoryManager {
1379
1183
  private constraints;
1380
1184
  private logger?;
1381
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?;
1382
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;
1383
1221
  /**
1384
1222
  * Set session memory entry (agent provides string, framework wraps it)
1385
1223
  * @param key - Session memory key
@@ -1475,7 +1313,15 @@ declare class MemoryManager {
1475
1313
  * treat "everything in this block" as data was also being handed the live question inside that
1476
1314
  * block.
1477
1315
  *
1478
- * 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.
1479
1325
  *
1480
1326
  * @param currentIteration - Current iteration number (0 = pre-iteration)
1481
1327
  * @param currentTurn - Current turn number (optional, for session context filtering)
@@ -1484,89 +1330,145 @@ declare class MemoryManager {
1484
1330
  }
1485
1331
 
1486
1332
  /**
1487
- * Agent-specific type definitions
1488
- * Types for autonomous agents with tools, memory, and constraints
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
+ }
1370
+ /**
1371
+ * Form schema for action payload collection
1489
1372
  */
1373
+ interface FormSchema {
1374
+ /** Form title */
1375
+ title?: string;
1376
+ /** Form description */
1377
+ description?: string;
1378
+ /** Form fields */
1379
+ fields: FormField[];
1380
+ }
1490
1381
 
1491
1382
  /**
1492
- * Factory function for creating LLM adapters.
1493
- * Injected into the Agent class to decouple the engine from server-only provider SDKs.
1494
- * - API process: provides createLLMAdapter (real SDKs + process.env API keys)
1495
- * - SDK worker: provides PostMessageLLMAdapter (proxies via platform.call)
1496
- *
1497
- * Uses `any` for optional params so both the real createLLMAdapter (with typed
1498
- * AIUsageCollector/AICallContext) and the worker proxy (which ignores them) satisfy the type.
1383
+ * Execution interface configuration
1384
+ * Defines how a resource is executed via the UI (forms, scheduling, webhooks)
1385
+ * Applies to both agents and workflows
1499
1386
  */
1500
- type LLMAdapterFactory = (config: ModelConfig, ...args: any[]) => LLMAdapter;
1501
- type AgentKind = 'orchestrator' | 'specialist' | 'utility' | 'platform';
1502
- interface AgentConfig extends ResourceDefinition {
1503
- type: 'agent';
1504
- /** OM descriptor backing canonical identity and governance metadata. */
1505
- resource?: AgentResourceEntry;
1506
- kind: AgentKind;
1507
- systemPrompt: string;
1508
- constraints?: AgentConstraints;
1509
- /**
1510
- * Session capability declaration (opt-in)
1511
- * If true, agent is designed for multi-turn session interactions
1512
- * Controls whether agent can use message action and appears in Sessions UI
1513
- *
1514
- * Use for:
1515
- * - Conversational agents with multi-turn interactions
1516
- * - Agents requiring persistent context across turns
1517
- * - Agents that need human-in-the-loop communication
1518
- */
1519
- sessionCapable?: boolean;
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;
1394
+ }
1395
+ /**
1396
+ * Execution form schema
1397
+ * Extends FormSchema with execution-specific fields
1398
+ */
1399
+ interface ExecutionFormSchema extends FormSchema {
1520
1400
  /**
1521
- * Security level for system prompt hardening (auto-derived if omitted)
1522
- *
1523
- * - 'standard': Lightweight defense (3 rules) - default for non-session agents
1524
- * - 'hardened': Comprehensive defense (5 rules) - default for session-capable agents
1525
- * - 'none': No security prompt - for pure internal agents with no external input
1526
- *
1527
- * If omitted, derived from sessionCapable:
1528
- * sessionCapable: true -> 'hardened'
1529
- * sessionCapable: false -> 'standard'
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
1530
1404
  */
1531
- securityLevel?: 'standard' | 'hardened' | 'none';
1405
+ fieldMappings?: Record<string, string>;
1532
1406
  /**
1533
- * Memory management preferences (opt-in)
1534
- * If provided, agent can use memoryOps to manage session memory
1535
- * If omitted, agent has no memory management capabilities
1536
- *
1537
- * Agent-specific guidance on what to preserve, when to persist, and what to clean up.
1538
- * This guidance is injected into the system prompt when memory management is enabled.
1539
- *
1540
- * Use for:
1541
- * - Conversational agents needing cross-turn context
1542
- * - Agents managing complex user preferences
1543
- * - Agents tracking decisions over multiple iterations
1407
+ * Submit button configuration
1408
+ * Default: { label: 'Run', loadingLabel: 'Running...' }
1544
1409
  */
1545
- memoryPreferences?: string;
1410
+ submitButton?: {
1411
+ label?: string;
1412
+ loadingLabel?: string;
1413
+ confirmMessage?: string;
1414
+ };
1546
1415
  }
1547
- interface AgentConstraints {
1548
- maxIterations?: number;
1549
- timeout?: number;
1550
- maxSessionMemoryKeys?: number;
1551
- maxMemoryTokens?: number;
1416
+ /**
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[];
1552
1426
  }
1553
- interface AgentDefinition {
1554
- config: AgentConfig;
1427
+ /**
1428
+ * Webhook configuration for external triggers
1429
+ */
1430
+ interface WebhookConfig {
1431
+ /** Whether webhook trigger is enabled */
1432
+ enabled: boolean;
1433
+ /** Expected payload schema (for documentation) */
1434
+ payloadSchema?: unknown;
1435
+ }
1436
+
1437
+ interface WorkflowConfig extends ResourceDefinition {
1438
+ type: 'workflow';
1439
+ /** OM descriptor backing canonical identity and governance metadata. */
1440
+ resource?: WorkflowResourceEntry;
1441
+ }
1442
+ interface WorkflowStepDefinition {
1443
+ id: string;
1444
+ name: string;
1445
+ description: string;
1446
+ }
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;
1555
1469
  contract: Contract;
1556
- tools: Tool[];
1557
- /**
1558
- * Model configuration for LLM execution
1559
- * Specifies provider, API key, and model-specific options
1560
- */
1561
- modelConfig: ModelConfig;
1562
- /**
1563
- * Preload memory before execution starts
1564
- * Handles BOTH context loading AND session restoration
1565
- *
1566
- * @param context - Execution context (includes sessionId if session turn)
1567
- * @returns Initial AgentMemory state (sessionMemory entries + optionally history)
1568
- */
1569
- preloadMemory?: (context: ExecutionContext) => Promise<AgentMemory> | AgentMemory;
1470
+ steps: Record<string, WorkflowStep>;
1471
+ entryPoint: string;
1570
1472
  /**
1571
1473
  * Metrics configuration for ROI calculations
1572
1474
  * Optional: Only needed if tracking automation savings
@@ -1574,30 +1476,19 @@ interface AgentDefinition {
1574
1476
  metricsConfig?: ResourceMetricsConfig;
1575
1477
  /**
1576
1478
  * Execution interface configuration (optional)
1577
- * If provided, agent appears in Execution Runner UI
1479
+ * If provided, workflow appears in Execution Runner UI
1578
1480
  */
1579
1481
  interface?: ExecutionInterface;
1580
- }
1581
- /**
1582
- * Agent execution context
1583
- * Groups all state needed for agent execution phases
1584
- */
1585
- interface IterationContext {
1586
- config: AgentConfig;
1587
- contract: Contract;
1588
- toolRegistry: Map<string, Tool>;
1589
- memoryManager: MemoryManager;
1590
- executionContext: ExecutionContext;
1591
- iteration: number;
1592
- logger: AgentScopedLogger;
1593
- modelConfig: ModelConfig;
1594
- adapterFactory: LLMAdapterFactory;
1595
1482
  /**
1596
- * The validated input for this execution, serialized. It travels here because the model gets
1597
- * it as its own `role:'user'` message; nothing else in this context carried it, so the input
1598
- * 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.
1599
1490
  */
1600
- currentInput: string;
1491
+ stageImplemented?: string;
1601
1492
  }
1602
1493
 
1603
1494
  type Json = string | number | boolean | null | {
@@ -8326,6 +8217,32 @@ type StorageDownloadOutput = z.infer<typeof StorageDownloadOutputSchema>;
8326
8217
  type StorageDeleteOutput = z.infer<typeof StorageDeleteOutputSchema>;
8327
8218
  type StorageListOutput = z.infer<typeof StorageListOutputSchema>;
8328
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
+
8329
8246
  /**
8330
8247
  * Create record parameters
8331
8248
  */
@@ -9930,9 +9847,9 @@ declare const ProjectSchemas: {
9930
9847
  CreateProjectRequest: z.ZodObject<{
9931
9848
  name: z.ZodString;
9932
9849
  kind: z.ZodEnum<{
9933
- internal: "internal";
9934
9850
  other: "other";
9935
9851
  client_engagement: "client_engagement";
9852
+ internal: "internal";
9936
9853
  research: "research";
9937
9854
  }>;
9938
9855
  status: z.ZodOptional<z.ZodEnum<{
@@ -9955,9 +9872,9 @@ declare const ProjectSchemas: {
9955
9872
  UpdateProjectRequest: z.ZodObject<{
9956
9873
  name: z.ZodOptional<z.ZodString>;
9957
9874
  kind: z.ZodOptional<z.ZodEnum<{
9958
- internal: "internal";
9959
9875
  other: "other";
9960
9876
  client_engagement: "client_engagement";
9877
+ internal: "internal";
9961
9878
  research: "research";
9962
9879
  }>>;
9963
9880
  status: z.ZodOptional<z.ZodEnum<{
@@ -9980,9 +9897,9 @@ declare const ProjectSchemas: {
9980
9897
  }, z.core.$strict>;
9981
9898
  GetProjectsQuery: z.ZodObject<{
9982
9899
  kind: z.ZodOptional<z.ZodEnum<{
9983
- internal: "internal";
9984
9900
  other: "other";
9985
9901
  client_engagement: "client_engagement";
9902
+ internal: "internal";
9986
9903
  research: "research";
9987
9904
  }>>;
9988
9905
  status: z.ZodOptional<z.ZodEnum<{
@@ -10070,12 +9987,12 @@ declare const ProjectSchemas: {
10070
9987
  status: z.ZodOptional<z.ZodEnum<{
10071
9988
  completed: "completed";
10072
9989
  cancelled: "cancelled";
9990
+ rejected: "rejected";
10073
9991
  blocked: "blocked";
10074
9992
  in_progress: "in_progress";
10075
9993
  planned: "planned";
10076
9994
  submitted: "submitted";
10077
9995
  approved: "approved";
10078
- rejected: "rejected";
10079
9996
  revision_requested: "revision_requested";
10080
9997
  }>>;
10081
9998
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -10106,12 +10023,12 @@ declare const ProjectSchemas: {
10106
10023
  status: z.ZodOptional<z.ZodEnum<{
10107
10024
  completed: "completed";
10108
10025
  cancelled: "cancelled";
10026
+ rejected: "rejected";
10109
10027
  blocked: "blocked";
10110
10028
  in_progress: "in_progress";
10111
10029
  planned: "planned";
10112
10030
  submitted: "submitted";
10113
10031
  approved: "approved";
10114
- rejected: "rejected";
10115
10032
  revision_requested: "revision_requested";
10116
10033
  }>>;
10117
10034
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -10133,12 +10050,12 @@ declare const ProjectSchemas: {
10133
10050
  status: z.ZodOptional<z.ZodEnum<{
10134
10051
  completed: "completed";
10135
10052
  cancelled: "cancelled";
10053
+ rejected: "rejected";
10136
10054
  blocked: "blocked";
10137
10055
  in_progress: "in_progress";
10138
10056
  planned: "planned";
10139
10057
  submitted: "submitted";
10140
10058
  approved: "approved";
10141
- rejected: "rejected";
10142
10059
  revision_requested: "revision_requested";
10143
10060
  }>>;
10144
10061
  milestone_id: z.ZodOptional<z.ZodString>;
@@ -11504,29 +11421,255 @@ interface ResourceMetricsConfig {
11504
11421
  }
11505
11422
 
11506
11423
  /**
11507
- * AIUsageCollector
11508
- * 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
11509
11426
  */
11510
- declare class AIUsageCollector {
11511
- private model;
11512
- private calls;
11513
- 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;
11514
11446
  /**
11515
- * 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
11516
11450
  *
11517
- * @param usage - Token usage and latency data from LLM adapter
11518
- * @param callType - Type discriminator (agent-reasoning, tool, etc.)
11519
- * @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
11520
11455
  */
11521
- record(usage: LLMUsageData, callType?: BaseAICall['callType'], context?: AICallContext): void;
11456
+ sessionCapable?: boolean;
11522
11457
  /**
11523
- * 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.
11524
11464
  */
11525
- getSummary(): AIUsageSummary;
11465
+ messagePolicy?: 'optional' | 'required';
11526
11466
  /**
11527
- * 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.
11528
11482
  */
11529
- 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;
11530
11673
  }
11531
11674
 
11532
11675
  /**
@@ -11674,12 +11817,31 @@ interface Tool {
11674
11817
  outputSchema: z.ZodSchema;
11675
11818
  execute: (options: ToolExecutionOptions) => Promise<unknown>;
11676
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;
11677
11833
  }
11678
11834
  /**
11679
11835
  * Tooling error types
11680
11836
  * Used across platform tools and integration tools
11681
11837
  */
11682
- 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';
11683
11845
 
11684
11846
  /**
11685
11847
  * Supported integration types