@fevex/core 0.1.0-alpha.7 → 0.1.0-alpha.8

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.
Files changed (32) hide show
  1. package/README.md +20 -0
  2. package/dist/agents/index.d.mts +2 -2
  3. package/dist/artifacts/index.d.mts +1 -1
  4. package/dist/channels/index.d.mts +1 -1
  5. package/dist/evals/index.d.mts +4 -4
  6. package/dist/{fevex-CVMLnZsk.d.mts → fevex-DB0-k1fb.d.mts} +14 -10
  7. package/dist/http/index.d.mts +4 -4
  8. package/dist/{index-CzAi2Y_Z.d.mts → index-B8molngu.d.mts} +92 -3
  9. package/dist/{index-BgKFd9yw.d.mts → index-BfYzemR8.d.mts} +1 -1
  10. package/dist/{index-CbACw6xZ.d.mts → index-Bl0hR7EC.d.mts} +2 -2
  11. package/dist/{index-B0AdFbgr.d.mts → index-CAyAoOW0.d.mts} +2 -2
  12. package/dist/{index-Df84VWmN.d.mts → index-CL7mu_x9.d.mts} +1 -1
  13. package/dist/{index-1cHr7KB_.d.mts → index-CODYPevS.d.mts} +3 -3
  14. package/dist/{index-CpLDt6Rw.d.mts → index-CecXoEbs.d.mts} +3 -3
  15. package/dist/{index-BTD1c4Ys.d.mts → index-CuaetTLQ.d.mts} +3 -3
  16. package/dist/{index-5p3q2yIp.d.mts → index-DtMxzCqj.d.mts} +2 -2
  17. package/dist/{index-CseuTR-F.d.mts → index-RKE3-CKs.d.mts} +2 -2
  18. package/dist/index.d.mts +13 -13
  19. package/dist/index.mjs +209 -11
  20. package/dist/knowledge/index.d.mts +1 -1
  21. package/dist/models/index.d.mts +1 -1
  22. package/dist/observability/index.d.mts +1 -1
  23. package/dist/policies/index.d.mts +1 -1
  24. package/dist/runtime/index.d.mts +2 -2
  25. package/dist/runtime/index.mjs +105 -1
  26. package/dist/sandbox/index.d.mts +1 -1
  27. package/dist/teams/index.d.mts +1 -1
  28. package/dist/testing/index.d.mts +6 -6
  29. package/dist/tools/index.d.mts +2 -2
  30. package/dist/{types-B8laW1hM.d.mts → types-CckDlhYo.d.mts} +15 -1
  31. package/dist/workflows/index.d.mts +1 -1
  32. package/package.json +1 -1
package/README.md CHANGED
@@ -430,6 +430,7 @@ run.started
430
430
  model.started
431
431
  model.output.delta
432
432
  model.completed
433
+ context.compacted
433
434
  tool.started
434
435
  tool.completed
435
436
  tool.failed
@@ -500,6 +501,25 @@ summary when needed:
500
501
  await app.compactSession(first.sessionId, 'Account 42 is active.');
501
502
  ```
502
503
 
504
+ Automatic compaction is opt-in through a context budget:
505
+
506
+ ```ts
507
+ const support = defineAgent({
508
+ name: 'support',
509
+ instructions: 'Answer clearly.',
510
+ contextBudget: { contextWindow: 128_000, reserveOutputTokens: 8_000 },
511
+ });
512
+ ```
513
+
514
+ Before each model call, Fevex estimates the prompt. Above 80% of the usable
515
+ window it replaces older completed turns with a summary, keeps system
516
+ instructions, the current request and the latest tool batch intact, and emits
517
+ `context.compacted`. The summary is cached on the session and reused across
518
+ runs; the original history is not rewritten. Use `compaction.compactor` to
519
+ inject a summarizer; the default is a deterministic digest.
520
+ `limits.maxInputTokens` is still the cumulative spend cap, while
521
+ `contextBudget.contextWindow` is the model context window.
522
+
503
523
  Use `startAgent` when execution must continue without consuming a stream:
504
524
 
505
525
  ```ts
@@ -1,2 +1,2 @@
1
- import { n as AgentLimits, r as defineAgent, t as AgentDefinition } from "../index-CzAi2Y_Z.mjs";
2
- export { AgentDefinition, AgentLimits, defineAgent };
1
+ import { i as defineAgent, n as AgentLimits, r as ContextBudget, t as AgentDefinition } from "../index-B8molngu.mjs";
2
+ export { AgentDefinition, AgentLimits, ContextBudget, defineAgent };
@@ -1,2 +1,2 @@
1
- import { A as ArtifactError, C as FileSystemArtifactStore, D as ArtifactCatalog, E as CatalogedArtifactStoreOptions, F as ArtifactStore, I as ArtifactStoreContext, L as ArtifactWrite, M as ArtifactId, N as ArtifactQuery, O as ArtifactContent, P as ArtifactRecord, R as artifactTenantId, S as InMemoryArtifactCatalog, T as CatalogedArtifactStore, _ as S3ArtifactStore, b as InMemoryArtifactStore, j as ArtifactErrorCode, k as ArtifactDescriptor, v as S3ArtifactStoreOptions, w as FileSystemArtifactStoreOptions, x as InMemoryArtifactStoreOptions, y as S3ObjectClient, z as assertArtifactId } from "../types-B8laW1hM.mjs";
1
+ import { A as ArtifactError, C as FileSystemArtifactStore, D as ArtifactCatalog, E as CatalogedArtifactStoreOptions, F as ArtifactStore, I as ArtifactStoreContext, L as ArtifactWrite, M as ArtifactId, N as ArtifactQuery, O as ArtifactContent, P as ArtifactRecord, R as artifactTenantId, S as InMemoryArtifactCatalog, T as CatalogedArtifactStore, _ as S3ArtifactStore, b as InMemoryArtifactStore, j as ArtifactErrorCode, k as ArtifactDescriptor, v as S3ArtifactStoreOptions, w as FileSystemArtifactStoreOptions, x as InMemoryArtifactStoreOptions, y as S3ObjectClient, z as assertArtifactId } from "../types-CckDlhYo.mjs";
2
2
  export { ArtifactCatalog, ArtifactContent, ArtifactDescriptor, ArtifactError, ArtifactErrorCode, ArtifactId, ArtifactQuery, ArtifactRecord, ArtifactStore, ArtifactStoreContext, ArtifactWrite, CatalogedArtifactStore, CatalogedArtifactStoreOptions, FileSystemArtifactStore, FileSystemArtifactStoreOptions, InMemoryArtifactCatalog, InMemoryArtifactStore, InMemoryArtifactStoreOptions, S3ArtifactStore, S3ArtifactStoreOptions, S3ObjectClient, artifactTenantId, assertArtifactId };
@@ -1,2 +1,2 @@
1
- import { a as ChannelDeliveryOptions, c as ChannelEvent, d as ChannelMessage, f as ChannelOutput, h as ChannelRunResult, i as ChannelContext, l as ChannelEventType, m as ChannelRunOptions, n as handleChannelInput, o as ChannelElicitationContext, p as ChannelRunEvent, r as ChannelAdapter, s as ChannelError, t as deliverChannelRun, u as ChannelFailurePhase } from "../index-BTD1c4Ys.mjs";
1
+ import { a as ChannelDeliveryOptions, c as ChannelEvent, d as ChannelMessage, f as ChannelOutput, h as ChannelRunResult, i as ChannelContext, l as ChannelEventType, m as ChannelRunOptions, n as handleChannelInput, o as ChannelElicitationContext, p as ChannelRunEvent, r as ChannelAdapter, s as ChannelError, t as deliverChannelRun, u as ChannelFailurePhase } from "../index-CuaetTLQ.mjs";
2
2
  export { ChannelAdapter, ChannelContext, ChannelDeliveryOptions, ChannelElicitationContext, ChannelError, ChannelEvent, ChannelEventType, ChannelFailurePhase, ChannelMessage, ChannelOutput, ChannelRunEvent, ChannelRunOptions, ChannelRunResult, deliverChannelRun, handleChannelInput };
@@ -1,7 +1,7 @@
1
- import { l as JsonValue, o as ExecutionContext, t as AgentEvent } from "../types-B8laW1hM.mjs";
2
- import { r as ModelMetadata, s as ModelUsage } from "../index-BgKFd9yw.mjs";
3
- import { t as CostCalculator, u as TraceCost } from "../index-CpLDt6Rw.mjs";
4
- import { t as Fevex } from "../fevex-CVMLnZsk.mjs";
1
+ import { l as JsonValue, o as ExecutionContext, t as AgentEvent } from "../types-CckDlhYo.mjs";
2
+ import { r as ModelMetadata, s as ModelUsage } from "../index-BfYzemR8.mjs";
3
+ import { t as CostCalculator, u as TraceCost } from "../index-CecXoEbs.mjs";
4
+ import { t as Fevex } from "../fevex-DB0-k1fb.mjs";
5
5
  //#region src/evals/canonical-json.d.ts
6
6
  /** Serializes JSON-like data with stable object-key ordering. */
7
7
  declare function serializeCanonical(value: unknown): string;
@@ -1,13 +1,13 @@
1
- import { F as ArtifactStore, f as RunId, o as ExecutionContext, t as AgentEvent } from "./types-B8laW1hM.mjs";
2
- import { t as ModelGateway } from "./index-BgKFd9yw.mjs";
3
- import { B as TeamRun, C as PurgeRunsResult, F as RunStore, I as Session, J as WorkflowRun, L as SessionId, M as RunRequest, N as RunResult, S as PurgeRunsOptions, a as AgentRun, b as ListEventsOptions, f as CredentialStore, j as RunRecord, t as AgentDefinition, w as ResumeRunResolution } from "./index-CzAi2Y_Z.mjs";
4
- import { c as ContextProvider, f as MemoryStore } from "./index-B0AdFbgr.mjs";
5
- import { i as ObservabilityStats, r as ObservabilityOptions } from "./index-CpLDt6Rw.mjs";
6
- import { r as Sandbox } from "./index-Df84VWmN.mjs";
7
- import { g as ToolDefinition, s as ConnectionDefinition } from "./index-5p3q2yIp.mjs";
8
- import { r as PolicyDefinition } from "./index-CbACw6xZ.mjs";
9
- import { n as WorkflowDefinition } from "./index-CseuTR-F.mjs";
10
- import { t as TeamDefinition } from "./index-1cHr7KB_.mjs";
1
+ import { F as ArtifactStore, f as RunId, o as ExecutionContext, t as AgentEvent } from "./types-CckDlhYo.mjs";
2
+ import { t as ModelGateway } from "./index-BfYzemR8.mjs";
3
+ import { A as ListEventsOptions, G as RunStore, H as RunRequest, J as SessionId, K as Session, M as PurgeRunsOptions, N as PurgeRunsResult, P as ResumeRunResolution, S as CredentialStore, U as RunResult, V as RunRecord, Z as TeamRun, at as WorkflowRun, h as AgentRun, r as ContextBudget, s as ContextCompactionOptions, t as AgentDefinition } from "./index-B8molngu.mjs";
4
+ import { c as ContextProvider, f as MemoryStore } from "./index-CAyAoOW0.mjs";
5
+ import { i as ObservabilityStats, r as ObservabilityOptions } from "./index-CecXoEbs.mjs";
6
+ import { r as Sandbox } from "./index-CL7mu_x9.mjs";
7
+ import { g as ToolDefinition, s as ConnectionDefinition } from "./index-DtMxzCqj.mjs";
8
+ import { r as PolicyDefinition } from "./index-Bl0hR7EC.mjs";
9
+ import { n as WorkflowDefinition } from "./index-RKE3-CKs.mjs";
10
+ import { t as TeamDefinition } from "./index-CODYPevS.mjs";
11
11
  //#region src/fevex.d.ts
12
12
  interface FevexAdmissionRequest {
13
13
  kind: 'agent' | 'workflow' | 'team';
@@ -62,6 +62,10 @@ interface FevexConfig {
62
62
  tools?: ToolDefinition[];
63
63
  connections?: ConnectionDefinition[];
64
64
  contextProviders?: ContextProvider[];
65
+ /** Default context budget for agents that do not declare one. */
66
+ contextBudget?: ContextBudget;
67
+ /** Optional context compactor and token estimator. */
68
+ compaction?: ContextCompactionOptions;
65
69
  memoryStore?: MemoryStore;
66
70
  runStore?: RunStore;
67
71
  credentialStore?: CredentialStore;
@@ -1,7 +1,7 @@
1
- import { D as ArtifactCatalog, F as ArtifactStore, f as RunId, k as ArtifactDescriptor, l as JsonValue, o as ExecutionContext, t as AgentEvent } from "../types-B8laW1hM.mjs";
2
- import { c as ReasoningEffort } from "../index-BgKFd9yw.mjs";
3
- import { B as TeamRun, J as WorkflowRun, L as SessionId, a as AgentRun, j as RunRecord } from "../index-CzAi2Y_Z.mjs";
4
- import { t as Fevex } from "../fevex-CVMLnZsk.mjs";
1
+ import { D as ArtifactCatalog, F as ArtifactStore, f as RunId, k as ArtifactDescriptor, l as JsonValue, o as ExecutionContext, t as AgentEvent } from "../types-CckDlhYo.mjs";
2
+ import { c as ReasoningEffort } from "../index-BfYzemR8.mjs";
3
+ import { J as SessionId, V as RunRecord, Z as TeamRun, at as WorkflowRun, h as AgentRun } from "../index-B8molngu.mjs";
4
+ import { t as Fevex } from "../fevex-DB0-k1fb.mjs";
5
5
  //#region src/http/protocol.d.ts
6
6
  declare const FEVEX_HTTP_PROTOCOL_VERSION = "3";
7
7
  declare const FEVEX_HTTP_PROTOCOL_VERSION_HEADER = "Fevex-Protocol-Version";
@@ -1,6 +1,6 @@
1
1
  import { t as ExactDefinition } from "./exact-definition-NHBBFlFR.mjs";
2
- import { f as RunId, i as AgentMessage, l as JsonValue, o as ExecutionContext, s as JsonObject, t as AgentEvent } from "./types-B8laW1hM.mjs";
3
- import { c as ReasoningEffort, i as ModelRef, l as ToolChoice, r as ModelMetadata, s as ModelUsage } from "./index-BgKFd9yw.mjs";
2
+ import { f as RunId, g as ToolSpec, i as AgentMessage, l as JsonValue, o as ExecutionContext, s as JsonObject, t as AgentEvent } from "./types-CckDlhYo.mjs";
3
+ import { c as ReasoningEffort, i as ModelRef, l as ToolChoice, r as ModelMetadata, s as ModelUsage } from "./index-BfYzemR8.mjs";
4
4
  import { StandardSchemaV1 } from "@standard-schema/spec";
5
5
  //#region src/runtime/run-store.d.ts
6
6
  /** Stable identifier for conversation history shared across runs. */
@@ -170,11 +170,19 @@ interface TeamRun<TOutput = JsonValue> extends RunCorrelation {
170
170
  }
171
171
  type CoordinatorRun<TOutput = JsonValue> = WorkflowRun<TOutput> | TeamRun<TOutput>;
172
172
  type RunRecord<TOutput = unknown> = AgentRun<TOutput> | WorkflowRun<TOutput> | TeamRun<TOutput>;
173
+ interface SessionCompaction {
174
+ /** Derived summary for the first `coveredMessages` history entries. */
175
+ summary: string;
176
+ coveredMessages: number;
177
+ updatedAt: string;
178
+ }
173
179
  interface Session {
174
180
  /** Optimistic history revision. Missing on legacy sessions means zero. Store-managed. */
175
181
  revision?: number;
176
182
  id: SessionId;
177
183
  history: AgentMessage[];
184
+ /** Reusable summary; the original history remains the source of truth. */
185
+ compaction?: SessionCompaction;
178
186
  createdAt: string;
179
187
  updatedAt: string;
180
188
  }
@@ -246,6 +254,7 @@ interface RunCheckpoint {
246
254
  reasoning?: ReasoningEffort;
247
255
  definitionHash: string;
248
256
  limits?: AgentLimits;
257
+ contextBudget?: ContextBudget;
249
258
  messages: AgentMessage[];
250
259
  inputContent: string;
251
260
  context?: ExecutionContext;
@@ -392,6 +401,7 @@ interface RunRequest<TInput = unknown, TOutput = unknown> {
392
401
  reasoning?: ReasoningEffort;
393
402
  context?: ExecutionContext;
394
403
  limits?: AgentLimits;
404
+ contextBudget?: ContextBudget;
395
405
  elicitation?: ElicitationMode;
396
406
  approvalMode?: ApprovalMode;
397
407
  toolChoice?: ToolChoice;
@@ -408,6 +418,68 @@ interface RunResult<TOutput = unknown> {
408
418
  usage?: ModelUsage;
409
419
  }
410
420
  //#endregion
421
+ //#region src/runtime/compaction.d.ts
422
+ /** Estimates the input tokens of messages and tool definitions. */
423
+ type ContextTokenEstimator = (input: {
424
+ messages: AgentMessage[];
425
+ tools?: ToolSpec[];
426
+ }) => number;
427
+ interface ContextCompactionInput {
428
+ agentName: string;
429
+ sessionId: SessionId;
430
+ /** Older turns and earlier tool batches; system prefix, current request and latest batch are preserved. */
431
+ messages: AgentMessage[];
432
+ tools?: ToolSpec[];
433
+ /** Estimated tokens of the whole prompt before compaction. */
434
+ estimatedTokens: number;
435
+ /** Soft budget for the messages returned by the compactor. */
436
+ targetTokens: number;
437
+ /** Hard model context window. */
438
+ contextWindow: number;
439
+ step: number;
440
+ context?: ExecutionContext;
441
+ signal?: AbortSignal;
442
+ /** Estimates messages with the runtime's configured estimator. */
443
+ estimateTokens(messages: AgentMessage[]): number;
444
+ }
445
+ /** Returns the replacement for the older conversation messages. */
446
+ interface ContextCompactor {
447
+ compact(input: ContextCompactionInput): AgentMessage[] | Promise<AgentMessage[]>;
448
+ }
449
+ interface ContextCompactionOptions {
450
+ /** Defaults to a deterministic digest compactor. */
451
+ compactor?: ContextCompactor;
452
+ /** Defaults to a character-based estimate. */
453
+ estimateTokens?: ContextTokenEstimator;
454
+ }
455
+ interface ResolvedContextBudget {
456
+ contextWindow: number;
457
+ reserveOutputTokens: number;
458
+ compactAt: number;
459
+ targetTokens: number;
460
+ safetyFactor: number;
461
+ }
462
+ /** Validates a context budget and fills in defaults. */
463
+ declare function resolveContextBudget(budget: ContextBudget | undefined, label: string): ResolvedContextBudget | undefined;
464
+ /**
465
+ * Rough provider-neutral estimate: about four characters per token plus
466
+ * message and tool framing. Hosts can inject a real tokenizer instead.
467
+ */
468
+ declare function estimateContextTokens(input: {
469
+ messages: AgentMessage[];
470
+ tools?: ToolSpec[];
471
+ }): number;
472
+ interface DigestContextCompactorOptions {
473
+ /** Maximum characters kept from one message. Defaults to 400. */
474
+ maxCharsPerMessage?: number;
475
+ }
476
+ /**
477
+ * Deterministic compactor used when the host does not inject one. It keeps
478
+ * role-aware excerpts of older messages and drops the oldest excerpts first.
479
+ * It never calls a model.
480
+ */
481
+ declare function createDigestContextCompactor(options?: DigestContextCompactorOptions): ContextCompactor;
482
+ //#endregion
411
483
  //#region src/runtime/in-memory-run-store.d.ts
412
484
  /**
413
485
  * In-process durable store intended for development and tests.
@@ -441,6 +513,22 @@ interface AgentLimits {
441
513
  maxInputTokens?: number | false;
442
514
  maxOutputTokens?: number | false;
443
515
  }
516
+ /**
517
+ * Per-request model context budget. It is separate from
518
+ * {@link AgentLimits.maxInputTokens}, which caps cumulative spend for a run.
519
+ */
520
+ interface ContextBudget {
521
+ /** Model context window in tokens. */
522
+ contextWindow: number;
523
+ /** Tokens reserved for the next model output. Defaults to 0. */
524
+ reserveOutputTokens?: number;
525
+ /** Fraction of the usable window that triggers compaction. Defaults to 0.8. */
526
+ compactAt?: number;
527
+ /** Target tokens after compaction. Defaults below the compaction threshold. */
528
+ targetTokens?: number;
529
+ /** Multiplier applied to estimates to leave headroom. Defaults to 1.1. */
530
+ safetyFactor?: number;
531
+ }
444
532
  interface AgentDefinition<TInput = unknown, TOutput = unknown> {
445
533
  name: string;
446
534
  instructions: string;
@@ -461,7 +549,8 @@ interface AgentDefinition<TInput = unknown, TOutput = unknown> {
461
549
  inputSchema?: StandardSchemaV1<unknown, TInput>;
462
550
  outputSchema?: StandardSchemaV1<unknown, TOutput>;
463
551
  limits?: AgentLimits;
552
+ contextBudget?: ContextBudget;
464
553
  }
465
554
  declare function defineAgent<T extends AgentDefinition>(agent: ExactDefinition<T, AgentDefinition>): T;
466
555
  //#endregion
467
- export { validateListEventsOptions as $, RunPause as A, TeamRun as B, PurgeRunsResult as C, RunCheckpoint as D, RetainableRunStore as E, RunStore as F, WorkflowBudgetUsage as G, ToolExecutionRecord as H, Session as I, WorkflowRun as J, WorkflowCheckpoint as K, SessionId as L, RunRequest as M, RunResult as N, RunCorrelation as O, RunStatus as P, isRetainableRunStore as Q, StoredRunCheckpoint as R, PurgeRunsOptions as S, RetainableRunStatus as T, ToolExecutionResolution as U, TimerResolution as V, ToolExecutionStatus as W, WorkflowWaitRecord as X, WorkflowStepRecord as Y, isDurableRunStore as Z, EventResolution as _, AgentRun as a, ListEventsOptions as b, ApprovalRequest as c, CoordinatorRun as d, validatePurgeRunsOptions as et, CredentialStore as f, ElicitationResolution as g, ElicitationRequest as h, InMemoryRunStore as i, RunRecord as j, RunLease as k, ApprovalResolution as l, ElicitationMode as m, AgentLimits as n, AgentRunPause as o, DurableRunStore as p, WorkflowCompensationRecord as q, defineAgent as r, ApprovalMode as s, AgentDefinition as t, CoordinatorCheckpoint as u, ExecutionCommit as v, ResumeRunResolution as w, PendingToolExecution as x, ExecutionCreate as y, TeamCheckpoint as z };
556
+ export { ToolExecutionRecord as $, ListEventsOptions as A, RunPause as B, DurableRunStore as C, EventResolution as D, ElicitationResolution as E, RetainableRunStatus as F, RunStore as G, RunRequest as H, RetainableRunStore as I, SessionId as J, Session as K, RunCheckpoint as L, PurgeRunsOptions as M, PurgeRunsResult as N, ExecutionCommit as O, ResumeRunResolution as P, TimerResolution as Q, RunCorrelation as R, CredentialStore as S, ElicitationRequest as T, RunResult as U, RunRecord as V, RunStatus as W, TeamCheckpoint as X, StoredRunCheckpoint as Y, TeamRun as Z, ApprovalMode as _, InMemoryRunStore as a, WorkflowRun as at, CoordinatorCheckpoint as b, ContextCompactor as c, isDurableRunStore as ct, ResolvedContextBudget as d, validatePurgeRunsOptions as dt, ToolExecutionResolution as et, createDigestContextCompactor as f, AgentRunPause as g, AgentRun as h, defineAgent as i, WorkflowCompensationRecord as it, PendingToolExecution as j, ExecutionCreate as k, ContextTokenEstimator as l, isRetainableRunStore as lt, resolveContextBudget as m, AgentLimits as n, WorkflowBudgetUsage as nt, ContextCompactionInput as o, WorkflowStepRecord as ot, estimateContextTokens as p, SessionCompaction as q, ContextBudget as r, WorkflowCheckpoint as rt, ContextCompactionOptions as s, WorkflowWaitRecord as st, AgentDefinition as t, ToolExecutionStatus as tt, DigestContextCompactorOptions as u, validateListEventsOptions as ut, ApprovalRequest as v, ElicitationMode as w, CoordinatorRun as x, ApprovalResolution as y, RunLease as z };
@@ -1,4 +1,4 @@
1
- import { g as ToolSpec, i as AgentMessage, l as JsonValue, m as ToolCall, s as JsonObject } from "./types-B8laW1hM.mjs";
1
+ import { g as ToolSpec, i as AgentMessage, l as JsonValue, m as ToolCall, s as JsonObject } from "./types-CckDlhYo.mjs";
2
2
  //#region src/models/model.d.ts
3
3
  /** Provider-neutral reasoning levels accepted by model gateways. */
4
4
  type ReasoningEffort = 'provider-default' | 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
@@ -1,5 +1,5 @@
1
- import { f as RunId, l as JsonValue, o as ExecutionContext } from "./types-B8laW1hM.mjs";
2
- import { x as ToolRisk } from "./index-5p3q2yIp.mjs";
1
+ import { f as RunId, l as JsonValue, o as ExecutionContext } from "./types-CckDlhYo.mjs";
2
+ import { x as ToolRisk } from "./index-DtMxzCqj.mjs";
3
3
  //#region src/policies/policy.d.ts
4
4
  /** Authorization outcome returned by a policy. */
5
5
  type PolicyDecision = 'allow' | 'deny' | 'require_approval';
@@ -1,5 +1,5 @@
1
- import { l as JsonValue, o as ExecutionContext, s as JsonObject } from "./types-B8laW1hM.mjs";
2
- import { L as SessionId } from "./index-CzAi2Y_Z.mjs";
1
+ import { l as JsonValue, o as ExecutionContext, s as JsonObject } from "./types-CckDlhYo.mjs";
2
+ import { J as SessionId } from "./index-B8molngu.mjs";
3
3
  //#region src/knowledge/knowledge.d.ts
4
4
  /** Runtime context supplied to knowledge providers and memory stores. */
5
5
  interface KnowledgeContext {
@@ -1,4 +1,4 @@
1
- import { f as RunId, l as JsonValue, o as ExecutionContext } from "./types-B8laW1hM.mjs";
1
+ import { f as RunId, l as JsonValue, o as ExecutionContext } from "./types-CckDlhYo.mjs";
2
2
  //#region src/sandbox/sandbox.d.ts
3
3
  interface SandboxCapabilities {
4
4
  process?: {
@@ -1,7 +1,7 @@
1
1
  import { t as ExactDefinition } from "./exact-definition-NHBBFlFR.mjs";
2
- import { o as ExecutionContext } from "./types-B8laW1hM.mjs";
3
- import { n as AgentLimits } from "./index-CzAi2Y_Z.mjs";
4
- import { t as WorkflowAgentResult } from "./index-CseuTR-F.mjs";
2
+ import { o as ExecutionContext } from "./types-CckDlhYo.mjs";
3
+ import { n as AgentLimits } from "./index-B8molngu.mjs";
4
+ import { t as WorkflowAgentResult } from "./index-RKE3-CKs.mjs";
5
5
  import { StandardSchemaV1 } from "@standard-schema/spec";
6
6
  //#region src/teams/team.d.ts
7
7
  interface TeamMember {
@@ -1,6 +1,6 @@
1
- import { f as RunId, l as JsonValue, s as JsonObject } from "./types-B8laW1hM.mjs";
2
- import { r as ModelMetadata, s as ModelUsage } from "./index-BgKFd9yw.mjs";
3
- import { L as SessionId } from "./index-CzAi2Y_Z.mjs";
1
+ import { f as RunId, l as JsonValue, s as JsonObject } from "./types-CckDlhYo.mjs";
2
+ import { r as ModelMetadata, s as ModelUsage } from "./index-BfYzemR8.mjs";
3
+ import { J as SessionId } from "./index-B8molngu.mjs";
4
4
  //#region src/observability/trace.d.ts
5
5
  /** Final state represented by an exported run trace. */
6
6
  type TraceStatus = 'completed' | 'failed' | 'cancelled';
@@ -1,6 +1,6 @@
1
- import { f as RunId, o as ExecutionContext, s as JsonObject, t as AgentEvent } from "./types-B8laW1hM.mjs";
2
- import { L as SessionId, a as AgentRun, h as ElicitationRequest } from "./index-CzAi2Y_Z.mjs";
3
- import { t as Fevex } from "./fevex-CVMLnZsk.mjs";
1
+ import { f as RunId, o as ExecutionContext, s as JsonObject, t as AgentEvent } from "./types-CckDlhYo.mjs";
2
+ import { J as SessionId, T as ElicitationRequest, h as AgentRun } from "./index-B8molngu.mjs";
3
+ import { t as Fevex } from "./fevex-DB0-k1fb.mjs";
4
4
  //#region src/channels/channel.d.ts
5
5
  interface ChannelMessage {
6
6
  id: string;
@@ -1,6 +1,6 @@
1
1
  import { t as ExactDefinition } from "./exact-definition-NHBBFlFR.mjs";
2
- import { F as ArtifactStore, f as RunId, g as ToolSpec, h as ToolEventSource, l as JsonValue, o as ExecutionContext, s as JsonObject } from "./types-B8laW1hM.mjs";
3
- import { i as SandboxCapabilities, r as Sandbox } from "./index-Df84VWmN.mjs";
2
+ import { F as ArtifactStore, f as RunId, g as ToolSpec, h as ToolEventSource, l as JsonValue, o as ExecutionContext, s as JsonObject } from "./types-CckDlhYo.mjs";
3
+ import { i as SandboxCapabilities, r as Sandbox } from "./index-CL7mu_x9.mjs";
4
4
  import { StandardSchemaV1 } from "@standard-schema/spec";
5
5
  //#region src/tools/tool.d.ts
6
6
  interface ToolExecutionContext {
@@ -1,6 +1,6 @@
1
1
  import { t as ExactDefinition } from "./exact-definition-NHBBFlFR.mjs";
2
- import { f as RunId, l as JsonValue, o as ExecutionContext, s as JsonObject } from "./types-B8laW1hM.mjs";
3
- import { L as SessionId, M as RunRequest, N as RunResult, n as AgentLimits } from "./index-CzAi2Y_Z.mjs";
2
+ import { f as RunId, l as JsonValue, o as ExecutionContext, s as JsonObject } from "./types-CckDlhYo.mjs";
3
+ import { H as RunRequest, J as SessionId, U as RunResult, n as AgentLimits } from "./index-B8molngu.mjs";
4
4
  import { StandardSchemaV1 } from "@standard-schema/spec";
5
5
  //#region src/workflows/workflow.d.ts
6
6
  /** Context shared with workflow steps and compensation handlers. */
package/dist/index.d.mts CHANGED
@@ -1,14 +1,14 @@
1
- import { A as ArtifactError, C as FileSystemArtifactStore, D as ArtifactCatalog, E as CatalogedArtifactStoreOptions, F as ArtifactStore, I as ArtifactStoreContext, L as ArtifactWrite, M as ArtifactId, N as ArtifactQuery, O as ArtifactContent, P as ArtifactRecord, R as artifactTenantId, S as InMemoryArtifactCatalog, T as CatalogedArtifactStore, _ as S3ArtifactStore, a as AgentMessageRole, b as InMemoryArtifactStore, c as JsonPrimitive, d as PROVIDER_SCHEMA_UNSUPPORTED, f as RunId, g as ToolSpec, h as ToolEventSource, i as AgentMessage, j as ArtifactErrorCode, k as ArtifactDescriptor, l as JsonValue, m as ToolCall, n as AgentEventPayloads, o as ExecutionContext, p as SCHEMA_NOT_TRANSPORTABLE, r as AgentEventType, s as JsonObject, t as AgentEvent, u as PROVIDER_REASONING_UNSUPPORTED, v as S3ArtifactStoreOptions, w as FileSystemArtifactStoreOptions, x as InMemoryArtifactStoreOptions, y as S3ObjectClient, z as assertArtifactId } from "./types-B8laW1hM.mjs";
2
- import { a as ModelResult, c as ReasoningEffort, i as ModelRef, l as ToolChoice, n as ModelInput, o as ModelStreamEvent, r as ModelMetadata, s as ModelUsage, t as ModelGateway } from "./index-BgKFd9yw.mjs";
3
- import { $ as validateListEventsOptions, A as RunPause, B as TeamRun, C as PurgeRunsResult, D as RunCheckpoint, E as RetainableRunStore, F as RunStore, G as WorkflowBudgetUsage, H as ToolExecutionRecord, I as Session, J as WorkflowRun, K as WorkflowCheckpoint, L as SessionId, M as RunRequest, N as RunResult, O as RunCorrelation, P as RunStatus, Q as isRetainableRunStore, R as StoredRunCheckpoint, S as PurgeRunsOptions, T as RetainableRunStatus, U as ToolExecutionResolution, V as TimerResolution, W as ToolExecutionStatus, X as WorkflowWaitRecord, Y as WorkflowStepRecord, Z as isDurableRunStore, _ as EventResolution, a as AgentRun, b as ListEventsOptions, c as ApprovalRequest, d as CoordinatorRun, et as validatePurgeRunsOptions, f as CredentialStore, g as ElicitationResolution, h as ElicitationRequest, i as InMemoryRunStore, j as RunRecord, k as RunLease, l as ApprovalResolution, m as ElicitationMode, n as AgentLimits, o as AgentRunPause, p as DurableRunStore, q as WorkflowCompensationRecord, r as defineAgent, s as ApprovalMode, t as AgentDefinition, u as CoordinatorCheckpoint, v as ExecutionCommit, w as ResumeRunResolution, x as PendingToolExecution, y as ExecutionCreate, z as TeamCheckpoint } from "./index-CzAi2Y_Z.mjs";
4
- import { _ as defineContextProvider, a as AgentsMdOptions, c as ContextProvider, d as MemoryRecord, f as MemoryStore, g as createMemoryContextProvider, h as SkillDefinition, i as InMemoryMemoryStore, l as KnowledgeContext, m as ProgressiveSkillProvider, n as loadSkillFile, o as createAgentsMdContextProvider, p as MemoryWrite, r as loadSkillFiles, s as ContextBlock, t as LoadSkillFileOptions, u as MemoryQuery, v as defineSkill, y as isProgressiveSkillProvider } from "./index-B0AdFbgr.mjs";
5
- import { a as SandboxError, c as sandboxResultToJson, i as SandboxCapabilities, n as createLocalSandbox, o as SandboxRunRequest, r as Sandbox, s as SandboxRunResult, t as LocalSandboxOptions } from "./index-Df84VWmN.mjs";
6
- import { C as toToolSpec, S as defineTool, _ as ToolExecutionContext, a as compileFevexJsonSchema, b as ToolRetryPolicy, c as ConnectionToolPolicy, d as ToolProvider, f as ToolProviderContext, g as ToolDefinition, h as ToolApproval, i as FevexJsonSchemaValidator, l as IntegrationError, m as defineConnection, n as FevexJsonSchemaProfileLimits, o as validateFevexJsonSchemaProfile, p as ToolProviderTool, r as FevexJsonSchemaProfileOptions, s as ConnectionDefinition, t as FEVEX_JSON_SCHEMA_PROFILE_VERSION, u as IntegrationErrorCategory, v as ToolIdempotency, x as ToolRisk, y as ToolResult } from "./index-5p3q2yIp.mjs";
7
- import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "./index-CbACw6xZ.mjs";
8
- import { a as WorkflowStep, c as defineWorkflow, i as WorkflowEventResult, n as WorkflowDefinition, o as WorkflowStepContext, r as WorkflowEventDefinition, s as WorkflowStepOptions, t as WorkflowAgentResult } from "./index-CseuTR-F.mjs";
9
- import { a as TeamMember, c as defineTeam, i as TeamLimits, n as TeamDelegation, o as TeamStep, r as TeamHandoff, s as TeamTaskResult, t as TeamDefinition } from "./index-1cHr7KB_.mjs";
10
- import { a as FevexLimits, c as createFevex, i as FevexConfig, n as FevexAdmission, o as FevexShutdownOptions, r as FevexAdmissionRequest, s as FevexShutdownResult, t as Fevex } from "./fevex-CVMLnZsk.mjs";
11
- import { a as ChannelDeliveryOptions, c as ChannelEvent, d as ChannelMessage, f as ChannelOutput, h as ChannelRunResult, i as ChannelContext, l as ChannelEventType, m as ChannelRunOptions, n as handleChannelInput, o as ChannelElicitationContext, p as ChannelRunEvent, r as ChannelAdapter, s as ChannelError, t as deliverChannelRun, u as ChannelFailurePhase } from "./index-BTD1c4Ys.mjs";
1
+ import { A as ArtifactError, C as FileSystemArtifactStore, D as ArtifactCatalog, E as CatalogedArtifactStoreOptions, F as ArtifactStore, I as ArtifactStoreContext, L as ArtifactWrite, M as ArtifactId, N as ArtifactQuery, O as ArtifactContent, P as ArtifactRecord, R as artifactTenantId, S as InMemoryArtifactCatalog, T as CatalogedArtifactStore, _ as S3ArtifactStore, a as AgentMessageRole, b as InMemoryArtifactStore, c as JsonPrimitive, d as PROVIDER_SCHEMA_UNSUPPORTED, f as RunId, g as ToolSpec, h as ToolEventSource, i as AgentMessage, j as ArtifactErrorCode, k as ArtifactDescriptor, l as JsonValue, m as ToolCall, n as AgentEventPayloads, o as ExecutionContext, p as SCHEMA_NOT_TRANSPORTABLE, r as AgentEventType, s as JsonObject, t as AgentEvent, u as PROVIDER_REASONING_UNSUPPORTED, v as S3ArtifactStoreOptions, w as FileSystemArtifactStoreOptions, x as InMemoryArtifactStoreOptions, y as S3ObjectClient, z as assertArtifactId } from "./types-CckDlhYo.mjs";
2
+ import { a as ModelResult, c as ReasoningEffort, i as ModelRef, l as ToolChoice, n as ModelInput, o as ModelStreamEvent, r as ModelMetadata, s as ModelUsage, t as ModelGateway } from "./index-BfYzemR8.mjs";
3
+ import { $ as ToolExecutionRecord, A as ListEventsOptions, B as RunPause, C as DurableRunStore, D as EventResolution, E as ElicitationResolution, F as RetainableRunStatus, G as RunStore, H as RunRequest, I as RetainableRunStore, J as SessionId, K as Session, L as RunCheckpoint, M as PurgeRunsOptions, N as PurgeRunsResult, O as ExecutionCommit, P as ResumeRunResolution, Q as TimerResolution, R as RunCorrelation, S as CredentialStore, T as ElicitationRequest, U as RunResult, V as RunRecord, W as RunStatus, X as TeamCheckpoint, Y as StoredRunCheckpoint, Z as TeamRun, _ as ApprovalMode, a as InMemoryRunStore, at as WorkflowRun, b as CoordinatorCheckpoint, c as ContextCompactor, ct as isDurableRunStore, d as ResolvedContextBudget, dt as validatePurgeRunsOptions, et as ToolExecutionResolution, f as createDigestContextCompactor, g as AgentRunPause, h as AgentRun, i as defineAgent, it as WorkflowCompensationRecord, j as PendingToolExecution, k as ExecutionCreate, l as ContextTokenEstimator, lt as isRetainableRunStore, m as resolveContextBudget, n as AgentLimits, nt as WorkflowBudgetUsage, o as ContextCompactionInput, ot as WorkflowStepRecord, p as estimateContextTokens, q as SessionCompaction, r as ContextBudget, rt as WorkflowCheckpoint, s as ContextCompactionOptions, st as WorkflowWaitRecord, t as AgentDefinition, tt as ToolExecutionStatus, u as DigestContextCompactorOptions, ut as validateListEventsOptions, v as ApprovalRequest, w as ElicitationMode, x as CoordinatorRun, y as ApprovalResolution, z as RunLease } from "./index-B8molngu.mjs";
4
+ import { _ as defineContextProvider, a as AgentsMdOptions, c as ContextProvider, d as MemoryRecord, f as MemoryStore, g as createMemoryContextProvider, h as SkillDefinition, i as InMemoryMemoryStore, l as KnowledgeContext, m as ProgressiveSkillProvider, n as loadSkillFile, o as createAgentsMdContextProvider, p as MemoryWrite, r as loadSkillFiles, s as ContextBlock, t as LoadSkillFileOptions, u as MemoryQuery, v as defineSkill, y as isProgressiveSkillProvider } from "./index-CAyAoOW0.mjs";
5
+ import { a as SandboxError, c as sandboxResultToJson, i as SandboxCapabilities, n as createLocalSandbox, o as SandboxRunRequest, r as Sandbox, s as SandboxRunResult, t as LocalSandboxOptions } from "./index-CL7mu_x9.mjs";
6
+ import { C as toToolSpec, S as defineTool, _ as ToolExecutionContext, a as compileFevexJsonSchema, b as ToolRetryPolicy, c as ConnectionToolPolicy, d as ToolProvider, f as ToolProviderContext, g as ToolDefinition, h as ToolApproval, i as FevexJsonSchemaValidator, l as IntegrationError, m as defineConnection, n as FevexJsonSchemaProfileLimits, o as validateFevexJsonSchemaProfile, p as ToolProviderTool, r as FevexJsonSchemaProfileOptions, s as ConnectionDefinition, t as FEVEX_JSON_SCHEMA_PROFILE_VERSION, u as IntegrationErrorCategory, v as ToolIdempotency, x as ToolRisk, y as ToolResult } from "./index-DtMxzCqj.mjs";
7
+ import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "./index-Bl0hR7EC.mjs";
8
+ import { a as WorkflowStep, c as defineWorkflow, i as WorkflowEventResult, n as WorkflowDefinition, o as WorkflowStepContext, r as WorkflowEventDefinition, s as WorkflowStepOptions, t as WorkflowAgentResult } from "./index-RKE3-CKs.mjs";
9
+ import { a as TeamMember, c as defineTeam, i as TeamLimits, n as TeamDelegation, o as TeamStep, r as TeamHandoff, s as TeamTaskResult, t as TeamDefinition } from "./index-CODYPevS.mjs";
10
+ import { a as FevexLimits, c as createFevex, i as FevexConfig, n as FevexAdmission, o as FevexShutdownOptions, r as FevexAdmissionRequest, s as FevexShutdownResult, t as Fevex } from "./fevex-DB0-k1fb.mjs";
11
+ import { a as ChannelDeliveryOptions, c as ChannelEvent, d as ChannelMessage, f as ChannelOutput, h as ChannelRunResult, i as ChannelContext, l as ChannelEventType, m as ChannelRunOptions, n as handleChannelInput, o as ChannelElicitationContext, p as ChannelRunEvent, r as ChannelAdapter, s as ChannelError, t as deliverChannelRun, u as ChannelFailurePhase } from "./index-CuaetTLQ.mjs";
12
12
  //#region src/configuration-error.d.ts
13
13
  /**
14
14
  * Composition error codes.
@@ -25,7 +25,7 @@ declare class FevexConfigurationError extends Error {
25
25
  }
26
26
  //#endregion
27
27
  //#region src/run-error.d.ts
28
- type FevexRunErrorCode = 'INVALID_CURSOR' | 'AGENT_NOT_FOUND' | 'WORKFLOW_NOT_FOUND' | 'TEAM_NOT_FOUND' | 'MODEL_NOT_FOUND' | 'SESSION_NOT_FOUND' | 'DURABLE_STORE_REQUIRED' | 'RUN_CONFLICT' | 'RUN_NOT_RESUMABLE' | 'RUN_NOT_RECOVERABLE' | 'CHECKPOINT_UNSUPPORTED' | 'RUN_DEFINITION_CHANGED' | 'POLICY_DENIED' | 'ADMISSION_DENIED' | 'RUNTIME_CLOSED' | 'RETENTION_UNSUPPORTED' | 'EVENT_LIMIT_EXCEEDED' | 'CREDENTIAL_NOT_FOUND' | 'SANDBOX_REQUIRED' | 'ELICITATION_INVALID' | 'APPROVAL_INVALID' | 'RUN_PAUSED' | 'TOOL_EXECUTION_UNKNOWN';
28
+ type FevexRunErrorCode = 'INVALID_CURSOR' | 'AGENT_NOT_FOUND' | 'WORKFLOW_NOT_FOUND' | 'TEAM_NOT_FOUND' | 'MODEL_NOT_FOUND' | 'SESSION_NOT_FOUND' | 'DURABLE_STORE_REQUIRED' | 'RUN_CONFLICT' | 'RUN_NOT_RESUMABLE' | 'RUN_NOT_RECOVERABLE' | 'CHECKPOINT_UNSUPPORTED' | 'RUN_DEFINITION_CHANGED' | 'POLICY_DENIED' | 'ADMISSION_DENIED' | 'RUNTIME_CLOSED' | 'RETENTION_UNSUPPORTED' | 'EVENT_LIMIT_EXCEEDED' | 'CONTEXT_BUDGET_EXCEEDED' | 'CREDENTIAL_NOT_FOUND' | 'SANDBOX_REQUIRED' | 'ELICITATION_INVALID' | 'APPROVAL_INVALID' | 'RUN_PAUSED' | 'TOOL_EXECUTION_UNKNOWN';
29
29
  declare class FevexRunError extends Error {
30
30
  readonly code: FevexRunErrorCode;
31
31
  readonly runId?: RunId | undefined;
@@ -39,4 +39,4 @@ declare class RunPausedError extends FevexRunError {
39
39
  constructor(runId: RunId, pause: RunPause);
40
40
  }
41
41
  //#endregion
42
- export { AgentDefinition, AgentEvent, AgentEventPayloads, AgentEventType, AgentLimits, AgentMessage, AgentMessageRole, AgentRun, AgentRunPause, AgentsMdOptions, ApprovalMode, ApprovalRequest, ApprovalResolution, ArtifactCatalog, ArtifactContent, ArtifactDescriptor, ArtifactError, ArtifactErrorCode, ArtifactId, ArtifactQuery, ArtifactRecord, ArtifactStore, ArtifactStoreContext, ArtifactWrite, CatalogedArtifactStore, CatalogedArtifactStoreOptions, ChannelAdapter, ChannelContext, ChannelDeliveryOptions, ChannelElicitationContext, ChannelError, ChannelEvent, ChannelEventType, ChannelFailurePhase, ChannelMessage, ChannelOutput, ChannelRunEvent, ChannelRunOptions, ChannelRunResult, ConnectionDefinition, ConnectionToolPolicy, ContextBlock, ContextProvider, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionContext, ExecutionCreate, FEVEX_JSON_SCHEMA_PROFILE_VERSION, Fevex, FevexAdmission, FevexAdmissionRequest, FevexConfig, FevexConfigurationError, FevexConfigurationErrorCode, FevexJsonSchemaProfileLimits, FevexJsonSchemaProfileOptions, FevexJsonSchemaValidator, FevexLimits, FevexRunError, FevexRunErrorCode, FevexShutdownOptions, FevexShutdownResult, FileSystemArtifactStore, FileSystemArtifactStoreOptions, InMemoryArtifactCatalog, InMemoryArtifactStore, InMemoryArtifactStoreOptions, InMemoryMemoryStore, InMemoryRunStore, IntegrationError, IntegrationErrorCategory, JsonObject, JsonPrimitive, JsonValue, KnowledgeContext, ListEventsOptions, LoadSkillFileOptions, LocalSandboxOptions, MemoryQuery, MemoryRecord, MemoryStore, MemoryWrite, ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, PROVIDER_REASONING_UNSUPPORTED, PROVIDER_SCHEMA_UNSUPPORTED, PendingToolExecution, PolicyAuthorization, PolicyDecision, PolicyDefinition, ProgressiveSkillProvider, PurgeRunsOptions, PurgeRunsResult, ReasoningEffort, ResumeRunResolution, RetainableRunStatus, RetainableRunStore, RunCheckpoint, RunCorrelation, RunId, RunLease, RunPause, RunPausedError, RunRecord, RunRequest, RunResult, RunStatus, RunStore, S3ArtifactStore, S3ArtifactStoreOptions, S3ObjectClient, SCHEMA_NOT_TRANSPORTABLE, Sandbox, SandboxCapabilities, SandboxError, SandboxRunRequest, SandboxRunResult, Session, SessionId, SkillDefinition, StoredRunCheckpoint, TeamCheckpoint, type TeamDefinition, type TeamDelegation, type TeamHandoff, type TeamLimits, type TeamMember, TeamRun, type TeamStep, type TeamTaskResult, TimerResolution, ToolApproval, ToolCall, ToolChoice, ToolDefinition, ToolEventSource, ToolExecutionContext, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, ToolIdempotency, ToolProvider, ToolProviderContext, ToolProviderTool, ToolResult, ToolRetryPolicy, ToolRisk, ToolSpec, WorkflowAgentResult, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowDefinition, WorkflowEventDefinition, WorkflowEventResult, WorkflowRun, WorkflowStep, WorkflowStepContext, WorkflowStepOptions, WorkflowStepRecord, WorkflowWaitRecord, artifactTenantId, assertArtifactId, compileFevexJsonSchema, createAgentsMdContextProvider, createFevex, createLocalSandbox, createMemoryContextProvider, defineAgent, defineConnection, defineContextProvider, definePolicy, defineSkill, defineTeam, defineTool, defineWorkflow, deliverChannelRun, handleChannelInput, isDurableRunStore, isProgressiveSkillProvider, isRetainableRunStore, loadSkillFile, loadSkillFiles, sandboxResultToJson, toToolSpec, validateFevexJsonSchemaProfile, validateListEventsOptions, validatePurgeRunsOptions };
42
+ export { AgentDefinition, AgentEvent, AgentEventPayloads, AgentEventType, AgentLimits, AgentMessage, AgentMessageRole, AgentRun, AgentRunPause, AgentsMdOptions, ApprovalMode, ApprovalRequest, ApprovalResolution, ArtifactCatalog, ArtifactContent, ArtifactDescriptor, ArtifactError, ArtifactErrorCode, ArtifactId, ArtifactQuery, ArtifactRecord, ArtifactStore, ArtifactStoreContext, ArtifactWrite, CatalogedArtifactStore, CatalogedArtifactStoreOptions, ChannelAdapter, ChannelContext, ChannelDeliveryOptions, ChannelElicitationContext, ChannelError, ChannelEvent, ChannelEventType, ChannelFailurePhase, ChannelMessage, ChannelOutput, ChannelRunEvent, ChannelRunOptions, ChannelRunResult, ConnectionDefinition, ConnectionToolPolicy, ContextBlock, ContextBudget, ContextCompactionInput, ContextCompactionOptions, ContextCompactor, ContextProvider, ContextTokenEstimator, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DigestContextCompactorOptions, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionContext, ExecutionCreate, FEVEX_JSON_SCHEMA_PROFILE_VERSION, Fevex, FevexAdmission, FevexAdmissionRequest, FevexConfig, FevexConfigurationError, FevexConfigurationErrorCode, FevexJsonSchemaProfileLimits, FevexJsonSchemaProfileOptions, FevexJsonSchemaValidator, FevexLimits, FevexRunError, FevexRunErrorCode, FevexShutdownOptions, FevexShutdownResult, FileSystemArtifactStore, FileSystemArtifactStoreOptions, InMemoryArtifactCatalog, InMemoryArtifactStore, InMemoryArtifactStoreOptions, InMemoryMemoryStore, InMemoryRunStore, IntegrationError, IntegrationErrorCategory, JsonObject, JsonPrimitive, JsonValue, KnowledgeContext, ListEventsOptions, LoadSkillFileOptions, LocalSandboxOptions, MemoryQuery, MemoryRecord, MemoryStore, MemoryWrite, ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, PROVIDER_REASONING_UNSUPPORTED, PROVIDER_SCHEMA_UNSUPPORTED, PendingToolExecution, PolicyAuthorization, PolicyDecision, PolicyDefinition, ProgressiveSkillProvider, PurgeRunsOptions, PurgeRunsResult, ReasoningEffort, ResolvedContextBudget, ResumeRunResolution, RetainableRunStatus, RetainableRunStore, RunCheckpoint, RunCorrelation, RunId, RunLease, RunPause, RunPausedError, RunRecord, RunRequest, RunResult, RunStatus, RunStore, S3ArtifactStore, S3ArtifactStoreOptions, S3ObjectClient, SCHEMA_NOT_TRANSPORTABLE, Sandbox, SandboxCapabilities, SandboxError, SandboxRunRequest, SandboxRunResult, Session, SessionCompaction, SessionId, SkillDefinition, StoredRunCheckpoint, TeamCheckpoint, type TeamDefinition, type TeamDelegation, type TeamHandoff, type TeamLimits, type TeamMember, TeamRun, type TeamStep, type TeamTaskResult, TimerResolution, ToolApproval, ToolCall, ToolChoice, ToolDefinition, ToolEventSource, ToolExecutionContext, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, ToolIdempotency, ToolProvider, ToolProviderContext, ToolProviderTool, ToolResult, ToolRetryPolicy, ToolRisk, ToolSpec, WorkflowAgentResult, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowDefinition, WorkflowEventDefinition, WorkflowEventResult, WorkflowRun, WorkflowStep, WorkflowStepContext, WorkflowStepOptions, WorkflowStepRecord, WorkflowWaitRecord, artifactTenantId, assertArtifactId, compileFevexJsonSchema, createAgentsMdContextProvider, createDigestContextCompactor, createFevex, createLocalSandbox, createMemoryContextProvider, defineAgent, defineConnection, defineContextProvider, definePolicy, defineSkill, defineTeam, defineTool, defineWorkflow, deliverChannelRun, estimateContextTokens, handleChannelInput, isDurableRunStore, isProgressiveSkillProvider, isRetainableRunStore, loadSkillFile, loadSkillFiles, resolveContextBudget, sandboxResultToJson, toToolSpec, validateFevexJsonSchemaProfile, validateListEventsOptions, validatePurgeRunsOptions };
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { n as RunPausedError, t as FevexRunError } from "./run-error-Cr17wPGH.mj
4
4
  import { ChannelError, deliverChannelRun, handleChannelInput } from "./channels/index.mjs";
5
5
  import { InMemoryMemoryStore, createAgentsMdContextProvider, createMemoryContextProvider, defineContextProvider, defineSkill, isProgressiveSkillProvider, loadSkillFile, loadSkillFiles } from "./knowledge/index.mjs";
6
6
  import { n as teamAsWorkflow, t as defineTeam } from "./teams-Ctz676G4.mjs";
7
- import { InMemoryRunStore, isDurableRunStore, isRetainableRunStore, validateListEventsOptions, validatePurgeRunsOptions } from "./runtime/index.mjs";
7
+ import { InMemoryRunStore, createDigestContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions } from "./runtime/index.mjs";
8
8
  import { FEVEX_JSON_SCHEMA_PROFILE_VERSION, IntegrationError, compileFevexJsonSchema, defineConnection, defineTool, toToolSpec, validateFevexJsonSchemaProfile } from "./tools/index.mjs";
9
9
  import { _ as serializeValue, a as assertTokenBudget, c as eventUsage, d as remainingDeadlineMs, f as remainingOutputTokens, g as serializeJsonValue, h as toErrorMessage, i as assertContinuationBudget, l as isTimeoutError, m as runSignal, n as abortable, o as cancellationReason, p as resumeDeadlineSignal, r as addUsage, s as deadlineAtFromMs, u as minDeadline, v as toJsonValue } from "./run-support-CmZ6Xo6H.mjs";
10
10
  import { t as readModelStream } from "./model-stream-JQdHDDcj.mjs";
@@ -300,6 +300,16 @@ function createComposition(config) {
300
300
  assertConfiguration(config.tools === void 0 || Array.isArray(config.tools), "INVALID_CONFIG", "Fevex config \"tools\" must be an array");
301
301
  assertConfiguration(config.connections === void 0 || Array.isArray(config.connections), "INVALID_CONFIG", "Fevex config \"connections\" must be an array");
302
302
  assertConfiguration(config.contextProviders === void 0 || Array.isArray(config.contextProviders), "INVALID_CONFIG", "Fevex config \"contextProviders\" must be an array");
303
+ if (config.contextBudget !== void 0) try {
304
+ resolveContextBudget(config.contextBudget, "Fevex config \"contextBudget\"");
305
+ } catch (error) {
306
+ throw configurationError("INVALID_CONFIG", error.message);
307
+ }
308
+ if (config.compaction !== void 0) {
309
+ assertConfiguration(typeof config.compaction === "object" && config.compaction !== null && !Array.isArray(config.compaction), "INVALID_CONFIG", "Fevex config \"compaction\" must be an object");
310
+ assertConfiguration(config.compaction.compactor === void 0 || isRecord(config.compaction.compactor) && typeof config.compaction.compactor.compact === "function", "INVALID_CONFIG", "Fevex config \"compaction.compactor\" must implement compact");
311
+ assertConfiguration(config.compaction.estimateTokens === void 0 || typeof config.compaction.estimateTokens === "function", "INVALID_CONFIG", "Fevex config \"compaction.estimateTokens\" must be a function");
312
+ }
303
313
  assertConfiguration(config.memoryStore === void 0 || isMemoryStore(config.memoryStore), "INVALID_CONFIG", "Fevex config \"memoryStore\" must implement MemoryStore");
304
314
  assertConfiguration(config.onEvent === void 0 || typeof config.onEvent === "function", "INVALID_CONFIG", "Fevex config \"onEvent\" must be a function");
305
315
  assertConfiguration(config.runStore === void 0 || isRunStore(config.runStore), "INVALID_CONFIG", "Fevex config \"runStore\" must implement RunStore");
@@ -475,6 +485,11 @@ function createComposition(config) {
475
485
  assertConfiguration(definition.approvalMode === void 0 || definition.approvalMode === "pause" || definition.approvalMode === "deny", "INVALID_AGENT", `Agent "${name}" approvalMode is invalid`);
476
486
  assertConfiguration(definition.toolChoice === void 0 || definition.toolChoice === "auto" || definition.toolChoice === "required" || definition.toolChoice === "none" || isRecord(definition.toolChoice) && typeof definition.toolChoice.name === "string" && Boolean(definition.toolChoice.name.trim()), "INVALID_AGENT", `Agent "${name}" toolChoice is invalid`);
477
487
  assertConfiguration(definition.limits === void 0 || isRecord(definition.limits), "INVALID_AGENT", `Agent "${name}" limits must be an object`);
488
+ if (definition.contextBudget !== void 0) try {
489
+ resolveContextBudget(definition.contextBudget, `Agent "${name}" contextBudget`);
490
+ } catch (error) {
491
+ throw configurationError("INVALID_AGENT", error.message);
492
+ }
478
493
  if (definition.outputSchema !== void 0) assertConfiguration(isStandardSchema(definition.outputSchema), "INVALID_AGENT", `Output schema for agent "${name}" must implement Standard Schema`);
479
494
  const rawLimits = definition.limits;
480
495
  assertLimit(rawLimits?.maxSteps, "maxSteps", 1, name);
@@ -498,6 +513,7 @@ function createComposition(config) {
498
513
  ...definition.toolChoice === void 0 ? {} : { toolChoice: typeof definition.toolChoice === "string" ? definition.toolChoice : { name: definition.toolChoice.name } },
499
514
  ...definition.elicitation === void 0 ? {} : { elicitation: definition.elicitation },
500
515
  ...definition.approvalMode === void 0 ? {} : { approvalMode: definition.approvalMode },
516
+ ...definition.contextBudget === void 0 ? {} : { contextBudget: { ...definition.contextBudget } },
501
517
  ...definition.inputSchema === void 0 ? {} : { inputSchema: definition.inputSchema },
502
518
  ...definition.outputSchema === void 0 ? {} : { outputSchema: definition.outputSchema },
503
519
  ...rawLimits === void 0 ? {} : { limits: {
@@ -621,6 +637,11 @@ function createComposition(config) {
621
637
  teams,
622
638
  tools,
623
639
  contextProviders,
640
+ contextBudget: config.contextBudget === void 0 ? void 0 : { ...config.contextBudget },
641
+ compaction: {
642
+ compactor: config.compaction?.compactor ?? createDigestContextCompactor(),
643
+ estimateTokens: config.compaction?.estimateTokens ?? estimateContextTokens
644
+ },
624
645
  memoryStore: config.memoryStore ?? (usesMemory ? new InMemoryMemoryStore() : void 0),
625
646
  runStore: config.runStore ?? new InMemoryRunStore(),
626
647
  credentialStore: config.credentialStore,
@@ -778,6 +799,103 @@ const runErrorPayload = (error) => {
778
799
  };
779
800
  };
780
801
  //#endregion
802
+ //#region src/internal/context-compaction.ts
803
+ /** Maximum summary characters copied into the context.compacted event. */
804
+ const MAX_COMPACTION_EVENT_SUMMARY_CHARS = 4e3;
805
+ async function compactContext(input) {
806
+ const estimateWith = (messages, includeTools) => {
807
+ const value = input.estimateTokens({
808
+ messages,
809
+ ...includeTools ? { tools: input.tools } : {}
810
+ });
811
+ if (!Number.isFinite(value) || value < 0) throw new TypeError("Context token estimator must return a non-negative finite number");
812
+ return Math.ceil(value * input.contextBudget.safetyFactor);
813
+ };
814
+ const estimate = (messages) => estimateWith(messages, true);
815
+ const estimated = estimate(input.messages);
816
+ const usable = input.contextBudget.contextWindow - input.contextBudget.reserveOutputTokens;
817
+ const threshold = Math.floor(usable * input.contextBudget.compactAt);
818
+ if (input.allowCompaction === false || estimated <= threshold) {
819
+ if (estimated > usable) throw new FevexRunError("CONTEXT_BUDGET_EXCEEDED", `Agent "${input.agentName}" context budget exceeded: ${estimated} tokens > ${usable} usable${input.allowCompaction === false ? " after compaction" : ""}.`, input.runId);
820
+ return;
821
+ }
822
+ const split = splitContextForCompaction(input.messages);
823
+ if (split === void 0 || split.compactable.length === 0) {
824
+ if (estimated > usable) throw new FevexRunError("CONTEXT_BUDGET_EXCEEDED", `Agent "${input.agentName}" context budget exceeded: ${estimated} tokens > ${usable} usable. The preserved system prefix and current turn cannot be compacted further.`, input.runId);
825
+ return;
826
+ }
827
+ const preservedTokens = estimate([...split.prefix, ...split.currentTurn]);
828
+ const available = Math.max(1, Math.min(input.contextBudget.targetTokens, usable - 1) - preservedTokens);
829
+ const compactedMessages = validateCompactedMessages(await abortable(() => input.compactor.compact({
830
+ agentName: input.agentName,
831
+ sessionId: input.sessionId,
832
+ messages: split.compactable,
833
+ tools: input.tools,
834
+ estimatedTokens: estimated,
835
+ targetTokens: available,
836
+ contextWindow: input.contextBudget.contextWindow,
837
+ step: input.step,
838
+ ...input.context === void 0 ? {} : { context: input.context },
839
+ signal: input.signal,
840
+ estimateTokens: (messages) => estimateWith(messages, false)
841
+ }), input.signal));
842
+ const messages = [
843
+ ...split.prefix,
844
+ ...compactedMessages,
845
+ ...split.currentTurn
846
+ ];
847
+ const compactedTokens = estimate(messages);
848
+ if (compactedTokens > usable) throw new FevexRunError("CONTEXT_BUDGET_EXCEEDED", `Agent "${input.agentName}" context budget exceeded after compaction: ${compactedTokens} tokens > ${usable} usable. The preserved system prefix and current turn cannot be compacted further.`, input.runId);
849
+ return {
850
+ messages,
851
+ removedMessages: split.compactable.length,
852
+ estimatedTokens: estimated,
853
+ compactedTokens,
854
+ summary: compactedMessages.map((message) => message.content).join("\n\n")
855
+ };
856
+ }
857
+ function splitContextForCompaction(messages) {
858
+ let lastUser = -1;
859
+ for (let index = messages.length - 1; index >= 0; index -= 1) if (messages[index].role === "user") {
860
+ lastUser = index;
861
+ break;
862
+ }
863
+ if (lastUser < 0) return void 0;
864
+ let lastToolBatch = -1;
865
+ for (let index = messages.length - 1; index > lastUser; index -= 1) {
866
+ const message = messages[index];
867
+ if (message.role === "assistant" && (message.toolCalls?.length ?? 0) > 0) {
868
+ lastToolBatch = index;
869
+ break;
870
+ }
871
+ }
872
+ const prefix = messages.filter((message) => message.role === "system");
873
+ const currentTurn = (lastToolBatch === -1 ? messages.slice(lastUser) : [messages[lastUser], ...messages.slice(lastToolBatch)]).filter((message) => message.role !== "system");
874
+ const preserved = /* @__PURE__ */ new Set([...prefix, ...currentTurn]);
875
+ return {
876
+ prefix,
877
+ currentTurn,
878
+ compactable: messages.filter((message) => message.role !== "system" && !preserved.has(message))
879
+ };
880
+ }
881
+ function validateCompactedMessages(value) {
882
+ if (!Array.isArray(value) || value.length === 0) throw new TypeError("Context compactor must return at least one message");
883
+ const roles = /* @__PURE__ */ new Set([
884
+ "system",
885
+ "user",
886
+ "assistant",
887
+ "tool"
888
+ ]);
889
+ for (const [index, message] of value.entries()) {
890
+ if (typeof message !== "object" || message === null || Array.isArray(message)) throw new TypeError(`Context compactor message at index ${index} must be an object`);
891
+ const record = message;
892
+ if (typeof record.role !== "string" || !roles.has(record.role)) throw new TypeError(`Context compactor message at index ${index} has an invalid role`);
893
+ if (typeof record.content !== "string") throw new TypeError(`Context compactor message at index ${index} must have string content`);
894
+ if (record.toolCalls !== void 0 && !Array.isArray(record.toolCalls)) throw new TypeError(`Context compactor message at index ${index} has invalid toolCalls`);
895
+ }
896
+ return value;
897
+ }
898
+ //#endregion
781
899
  //#region src/internal/definition-hash.ts
782
900
  function canonicalize(value) {
783
901
  if (Array.isArray(value)) return value.map(canonicalize);
@@ -804,7 +922,7 @@ async function sha256(value) {
804
922
  const digest = await crypto.subtle.digest("SHA-256", encoded);
805
923
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
806
924
  }
807
- async function definitionHash(name, modelName, agent, tools) {
925
+ async function definitionHash(name, modelName, agent, tools, contextBudget) {
808
926
  const toolDefinitions = await Promise.all((agent.tools ?? []).map((toolName) => transportableTool(tools.get(toolName))));
809
927
  return sha256({
810
928
  name,
@@ -820,6 +938,7 @@ async function definitionHash(name, modelName, agent, tools) {
820
938
  elicitation: agent.elicitation,
821
939
  approvalMode: agent.approvalMode,
822
940
  limits: agent.limits,
941
+ contextBudget,
823
942
  inputSchema: agent.inputSchema === void 0 ? void 0 : toTransportableSchema(agent.inputSchema, "input", `Input schema for agent "${name}" is not transportable`),
824
943
  outputSchema: agent.outputSchema === void 0 ? void 0 : toTransportableSchema(agent.outputSchema, "output", `Output schema for agent "${name}" is not transportable`)
825
944
  });
@@ -904,12 +1023,13 @@ function addWorkflowBudget(first, second) {
904
1023
  * engine — that direction is what keeps the two separable.
905
1024
  */
906
1025
  function createAgentEngine(composition, core) {
907
- const { models, agents, tools, contextProviders, memoryStore, runStore, credentialStore, sandbox, artifacts, policies } = composition;
1026
+ const { models, agents, tools, contextProviders, contextBudget: defaultContextBudget, compaction, memoryStore, runStore, credentialStore, sandbox, artifacts, policies } = composition;
908
1027
  const { activeRuns, activeSessions, runtimeOwner, isClosed, admitStart, markInternalRun, resolveModel, resolveCheckpointModel, notifyObserver, createEvent, emitEvent, releaseExecution, commit, startLease, cancelExecution, authorize } = core;
909
1028
  const prepareExecutionBody = async (name, request, internal = false, correlation = {}) => {
910
1029
  if (!internal && isClosed()) throw new FevexRunError("RUNTIME_CLOSED", "Runtime is not accepting new runs");
911
1030
  const agent = agents.get(name);
912
1031
  if (!agent) throw new FevexRunError("AGENT_NOT_FOUND", `Agent "${name}" is not registered`);
1032
+ const contextBudget = resolveContextBudget(request.contextBudget ?? agent.contextBudget ?? defaultContextBudget, `Agent "${name}" contextBudget`);
913
1033
  const { modelName, model } = resolveModel(agent, request.model);
914
1034
  const now = (/* @__PURE__ */ new Date()).toISOString();
915
1035
  let session;
@@ -967,7 +1087,7 @@ function createAgentEngine(composition, core) {
967
1087
  content: agent.instructions
968
1088
  },
969
1089
  ...knowledge.skills,
970
- ...session.history,
1090
+ ...sessionHistoryMessages(session),
971
1091
  ...knowledge.context,
972
1092
  ...knowledge.memory,
973
1093
  {
@@ -980,8 +1100,9 @@ function createAgentEngine(composition, core) {
980
1100
  runId: run.id,
981
1101
  ...request.model !== void 0 || typeof agent.model === "string" ? { modelName } : {},
982
1102
  ...request.reasoning === void 0 ? {} : { reasoning: request.reasoning },
983
- definitionHash: await definitionHash(name, modelName, agent, tools),
1103
+ definitionHash: await definitionHash(name, modelName, agent, tools, contextBudget),
984
1104
  limits: combineLimits(agent.limits, request.limits),
1105
+ ...contextBudget === void 0 ? {} : { contextBudget },
985
1106
  messages,
986
1107
  inputContent,
987
1108
  context: request.context,
@@ -1039,6 +1160,7 @@ function createAgentEngine(composition, core) {
1039
1160
  const durableCheckpoint = async (state, model, modelName, messages, inputContent, usage, providerState, step, toolCallCount, seenToolCallIds, pendingTools, pendingIndex) => {
1040
1161
  const agent = agents.get(state.run.agentName);
1041
1162
  if (agent.model !== void 0 && typeof agent.model !== "string") throw new FevexRunError("RUN_NOT_RESUMABLE", "Durable continuation requires a named model", state.run.id);
1163
+ const contextBudget = resolveContextBudget(state.checkpoint?.contextBudget ?? state.request.contextBudget ?? agent.contextBudget ?? defaultContextBudget, `Agent "${state.run.agentName}" contextBudget`);
1042
1164
  let serializedState;
1043
1165
  if (providerState !== void 0) {
1044
1166
  if (!model.stateCodec) throw new FevexRunError("RUN_NOT_RESUMABLE", "ModelGateway must provide stateCodec for durable continuation", state.run.id);
@@ -1049,8 +1171,9 @@ function createAgentEngine(composition, core) {
1049
1171
  runId: state.run.id,
1050
1172
  modelName,
1051
1173
  ...state.request.reasoning === void 0 ? {} : { reasoning: state.request.reasoning },
1052
- definitionHash: await definitionHash(state.run.agentName, modelName, agent, tools),
1174
+ definitionHash: await definitionHash(state.run.agentName, modelName, agent, tools, contextBudget),
1053
1175
  limits: state.checkpoint?.limits ?? combineLimits(agent.limits, state.request.limits),
1176
+ ...contextBudget === void 0 ? {} : { contextBudget },
1054
1177
  messages: structuredClone(messages),
1055
1178
  inputContent,
1056
1179
  context: state.request.context,
@@ -1109,6 +1232,7 @@ function createAgentEngine(composition, core) {
1109
1232
  const { request } = state;
1110
1233
  const agent = agents.get(name);
1111
1234
  const { modelName, model } = resolveModel(agent, state.checkpoint?.modelName ?? request.model);
1235
+ const contextBudget = resolveContextBudget(state.checkpoint?.contextBudget ?? request.contextBudget ?? agent.contextBudget ?? defaultContextBudget, `Agent "${name}" contextBudget`);
1112
1236
  const events = [...state.initialEvents ?? []];
1113
1237
  const firstEvents = state.initialEvents ?? [];
1114
1238
  state.initialEvents = void 0;
@@ -1126,12 +1250,13 @@ function createAgentEngine(composition, core) {
1126
1250
  let seenToolCallIds;
1127
1251
  let pendingTools;
1128
1252
  let pendingIndex;
1253
+ let compactionApplied = false;
1129
1254
  try {
1130
1255
  for (const event of firstEvents) yield event;
1131
1256
  if (state.checkpoint) {
1132
1257
  const checkpoint = state.checkpoint;
1133
1258
  if (checkpoint.version !== 2) throw new FevexRunError("CHECKPOINT_UNSUPPORTED", `Checkpoint for run "${state.run.id}" is unsupported`, state.run.id);
1134
- const hash = await definitionHash(name, modelName, agent, tools);
1259
+ const hash = await definitionHash(name, modelName, agent, tools, contextBudget);
1135
1260
  if (checkpoint.definitionHash !== hash) throw new FevexRunError("RUN_DEFINITION_CHANGED", `Definition for agent "${name}" changed`, state.run.id);
1136
1261
  inputContent = checkpoint.inputContent;
1137
1262
  messages = checkpoint.messages;
@@ -1153,7 +1278,7 @@ function createAgentEngine(composition, core) {
1153
1278
  content: agent.instructions
1154
1279
  },
1155
1280
  ...knowledge.skills,
1156
- ...state.session.history,
1281
+ ...sessionHistoryMessages(state.session),
1157
1282
  ...knowledge.context,
1158
1283
  ...knowledge.memory,
1159
1284
  {
@@ -1232,6 +1357,59 @@ function createAgentEngine(composition, core) {
1232
1357
  while (step <= maxSteps) {
1233
1358
  request.signal.throwIfAborted();
1234
1359
  if (pendingTools.length === 0) {
1360
+ if (contextBudget !== void 0) {
1361
+ const compacted = await compactContext({
1362
+ runId: state.run.id,
1363
+ agentName: name,
1364
+ sessionId: state.session.id,
1365
+ messages,
1366
+ tools: allTools,
1367
+ contextBudget,
1368
+ compactor: compaction.compactor,
1369
+ estimateTokens: compaction.estimateTokens,
1370
+ step,
1371
+ ...request.context === void 0 ? {} : { context: request.context },
1372
+ signal: request.signal,
1373
+ allowCompaction: !compactionApplied
1374
+ });
1375
+ if (compacted !== void 0) {
1376
+ messages = compacted.messages;
1377
+ compactionApplied = true;
1378
+ const previous = state.session.compaction;
1379
+ const combined = previous === void 0 ? compacted.summary : `${previous.summary}\n\n${compacted.summary}`;
1380
+ const maxSummaryChars = Math.max(200, contextBudget.targetTokens * 4);
1381
+ state.session.compaction = {
1382
+ summary: combined.length > maxSummaryChars ? `…${combined.slice(combined.length - maxSummaryChars + 1)}` : combined,
1383
+ coveredMessages: state.session.history.length,
1384
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1385
+ };
1386
+ const summaryTruncated = compacted.summary.length > MAX_COMPACTION_EVENT_SUMMARY_CHARS;
1387
+ const event = createEvent(state, "context.compacted", {
1388
+ step,
1389
+ removedMessages: compacted.removedMessages,
1390
+ estimatedTokens: compacted.estimatedTokens,
1391
+ compactedTokens: compacted.compactedTokens,
1392
+ targetTokens: contextBudget.targetTokens,
1393
+ contextWindow: contextBudget.contextWindow,
1394
+ summary: summaryTruncated ? `${compacted.summary.slice(0, MAX_COMPACTION_EVENT_SUMMARY_CHARS - 1)}…` : compacted.summary,
1395
+ ...summaryTruncated ? { summaryTruncated: true } : {}
1396
+ });
1397
+ if (isDurableRunStore(runStore)) {
1398
+ const checkpoint = await durableCheckpoint(state, model, modelName, messages, inputContent, usage, providerState, step, toolCallCount, seenToolCallIds, pendingTools, pendingIndex);
1399
+ await commit(state, {
1400
+ checkpoint,
1401
+ session: state.session,
1402
+ events: [event]
1403
+ });
1404
+ state.checkpoint = checkpoint;
1405
+ } else {
1406
+ await runStore.appendEvent(event);
1407
+ notifyObserver(event);
1408
+ }
1409
+ events.push(event);
1410
+ yield event;
1411
+ }
1412
+ }
1235
1413
  const hasToolBudget = step < maxSteps && toolCallCount < maxToolCalls;
1236
1414
  const modelToolChoice = hasToolBudget && allTools.length ? currentToolChoice === "auto" ? void 0 : currentToolChoice : void 0;
1237
1415
  yield await emit("model.started", { step });
@@ -2113,6 +2291,14 @@ function createAgentEngine(composition, core) {
2113
2291
  cancelStoredAgent
2114
2292
  };
2115
2293
  }
2294
+ function sessionHistoryMessages(session) {
2295
+ const compaction = session.compaction;
2296
+ if (compaction === void 0 || compaction.coveredMessages <= 0 || compaction.coveredMessages > session.history.length) return session.history;
2297
+ return [{
2298
+ role: "system",
2299
+ content: `[Compacted conversation]\n${compaction.summary}`
2300
+ }, ...session.history.slice(compaction.coveredMessages)];
2301
+ }
2116
2302
  function readSkillInput(input) {
2117
2303
  if (typeof input !== "object" || input === null || Array.isArray(input)) throw new TypeError(`${LOAD_SKILL_TOOL_NAME} input must be an object`);
2118
2304
  const record = input;
@@ -2284,6 +2470,17 @@ function annotation(event) {
2284
2470
  delayMs: event.payload.delayMs
2285
2471
  }
2286
2472
  };
2473
+ case "context.compacted": return {
2474
+ name: event.type,
2475
+ timestamp: event.timestamp,
2476
+ attributes: {
2477
+ removedMessages: event.payload.removedMessages,
2478
+ estimatedTokens: event.payload.estimatedTokens,
2479
+ compactedTokens: event.payload.compactedTokens,
2480
+ targetTokens: event.payload.targetTokens,
2481
+ contextWindow: event.payload.contextWindow
2482
+ }
2483
+ };
2287
2484
  case "tool.execution_unknown": return {
2288
2485
  name: event.type,
2289
2486
  timestamp: event.timestamp,
@@ -2882,12 +3079,12 @@ function createRunCore({ models, agents, tools, runStore, policies, onEvent, obs
2882
3079
  };
2883
3080
  const resolveCheckpointModel = async (agentName, agent, checkpoint) => {
2884
3081
  const preferred = resolveModel(agent, checkpoint.modelName);
2885
- if (checkpoint.definitionHash === await definitionHash(agentName, preferred.modelName, agent, tools)) return preferred;
3082
+ if (checkpoint.definitionHash === await definitionHash(agentName, preferred.modelName, agent, tools, checkpoint.contextBudget)) return preferred;
2886
3083
  if (checkpoint.modelName !== void 0) return void 0;
2887
3084
  for (const candidateName of models.keys()) {
2888
3085
  if (candidateName === preferred.modelName) continue;
2889
3086
  const candidate = resolveModel(agent, candidateName);
2890
- if (checkpoint.definitionHash === await definitionHash(agentName, candidate.modelName, agent, tools)) return candidate;
3087
+ if (checkpoint.definitionHash === await definitionHash(agentName, candidate.modelName, agent, tools, checkpoint.contextBudget)) return candidate;
2891
3088
  }
2892
3089
  };
2893
3090
  const scheduleTraceExport = (event) => {
@@ -4408,6 +4605,7 @@ function createRuntime(composition) {
4408
4605
  role: "system",
4409
4606
  content: summary
4410
4607
  }];
4608
+ session.compaction = void 0;
4411
4609
  session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4412
4610
  await runStore.saveSession(session);
4413
4611
  return structuredClone(session);
@@ -4433,4 +4631,4 @@ function createFevex(config) {
4433
4631
  return createRuntime(createComposition(config));
4434
4632
  }
4435
4633
  //#endregion
4436
- export { ArtifactError, CatalogedArtifactStore, ChannelError, FEVEX_JSON_SCHEMA_PROFILE_VERSION, FevexConfigurationError, FevexRunError, FileSystemArtifactStore, InMemoryArtifactCatalog, InMemoryArtifactStore, InMemoryMemoryStore, InMemoryRunStore, IntegrationError, PROVIDER_REASONING_UNSUPPORTED, PROVIDER_SCHEMA_UNSUPPORTED, RunPausedError, S3ArtifactStore, SCHEMA_NOT_TRANSPORTABLE, SandboxError, artifactTenantId, assertArtifactId, compileFevexJsonSchema, createAgentsMdContextProvider, createFevex, createLocalSandbox, createMemoryContextProvider, defineAgent, defineConnection, defineContextProvider, definePolicy, defineSkill, defineTeam, defineTool, defineWorkflow, deliverChannelRun, handleChannelInput, isDurableRunStore, isProgressiveSkillProvider, isRetainableRunStore, loadSkillFile, loadSkillFiles, sandboxResultToJson, toToolSpec, validateFevexJsonSchemaProfile, validateListEventsOptions, validatePurgeRunsOptions };
4634
+ export { ArtifactError, CatalogedArtifactStore, ChannelError, FEVEX_JSON_SCHEMA_PROFILE_VERSION, FevexConfigurationError, FevexRunError, FileSystemArtifactStore, InMemoryArtifactCatalog, InMemoryArtifactStore, InMemoryMemoryStore, InMemoryRunStore, IntegrationError, PROVIDER_REASONING_UNSUPPORTED, PROVIDER_SCHEMA_UNSUPPORTED, RunPausedError, S3ArtifactStore, SCHEMA_NOT_TRANSPORTABLE, SandboxError, artifactTenantId, assertArtifactId, compileFevexJsonSchema, createAgentsMdContextProvider, createDigestContextCompactor, createFevex, createLocalSandbox, createMemoryContextProvider, defineAgent, defineConnection, defineContextProvider, definePolicy, defineSkill, defineTeam, defineTool, defineWorkflow, deliverChannelRun, estimateContextTokens, handleChannelInput, isDurableRunStore, isProgressiveSkillProvider, isRetainableRunStore, loadSkillFile, loadSkillFiles, resolveContextBudget, sandboxResultToJson, toToolSpec, validateFevexJsonSchemaProfile, validateListEventsOptions, validatePurgeRunsOptions };
@@ -1,2 +1,2 @@
1
- import { _ as defineContextProvider, a as AgentsMdOptions, c as ContextProvider, d as MemoryRecord, f as MemoryStore, g as createMemoryContextProvider, h as SkillDefinition, i as InMemoryMemoryStore, l as KnowledgeContext, m as ProgressiveSkillProvider, n as loadSkillFile, o as createAgentsMdContextProvider, p as MemoryWrite, r as loadSkillFiles, s as ContextBlock, t as LoadSkillFileOptions, u as MemoryQuery, v as defineSkill, y as isProgressiveSkillProvider } from "../index-B0AdFbgr.mjs";
1
+ import { _ as defineContextProvider, a as AgentsMdOptions, c as ContextProvider, d as MemoryRecord, f as MemoryStore, g as createMemoryContextProvider, h as SkillDefinition, i as InMemoryMemoryStore, l as KnowledgeContext, m as ProgressiveSkillProvider, n as loadSkillFile, o as createAgentsMdContextProvider, p as MemoryWrite, r as loadSkillFiles, s as ContextBlock, t as LoadSkillFileOptions, u as MemoryQuery, v as defineSkill, y as isProgressiveSkillProvider } from "../index-CAyAoOW0.mjs";
2
2
  export { AgentsMdOptions, ContextBlock, ContextProvider, InMemoryMemoryStore, KnowledgeContext, LoadSkillFileOptions, MemoryQuery, MemoryRecord, MemoryStore, MemoryWrite, ProgressiveSkillProvider, SkillDefinition, createAgentsMdContextProvider, createMemoryContextProvider, defineContextProvider, defineSkill, isProgressiveSkillProvider, loadSkillFile, loadSkillFiles };
@@ -1,2 +1,2 @@
1
- import { a as ModelResult, c as ReasoningEffort, i as ModelRef, l as ToolChoice, n as ModelInput, o as ModelStreamEvent, r as ModelMetadata, s as ModelUsage, t as ModelGateway } from "../index-BgKFd9yw.mjs";
1
+ import { a as ModelResult, c as ReasoningEffort, i as ModelRef, l as ToolChoice, n as ModelInput, o as ModelStreamEvent, r as ModelMetadata, s as ModelUsage, t as ModelGateway } from "../index-BfYzemR8.mjs";
2
2
  export { ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, ReasoningEffort, ToolChoice };
@@ -1,2 +1,2 @@
1
- import { _ as TraceSpanKind, a as RunTrace, c as TraceContentKind, d as TraceExportQueueOptions, f as TraceExporter, g as TraceSpan, h as TraceRunKind, i as ObservabilityStats, l as TraceContentPolicy, m as TraceRedactorInput, n as CostCalculatorInput, o as TraceAnnotation, p as TraceRedactor, r as ObservabilityOptions, s as TraceContent, t as CostCalculator, u as TraceCost, v as TraceStatus } from "../index-CpLDt6Rw.mjs";
1
+ import { _ as TraceSpanKind, a as RunTrace, c as TraceContentKind, d as TraceExportQueueOptions, f as TraceExporter, g as TraceSpan, h as TraceRunKind, i as ObservabilityStats, l as TraceContentPolicy, m as TraceRedactorInput, n as CostCalculatorInput, o as TraceAnnotation, p as TraceRedactor, r as ObservabilityOptions, s as TraceContent, t as CostCalculator, u as TraceCost, v as TraceStatus } from "../index-CecXoEbs.mjs";
2
2
  export { CostCalculator, CostCalculatorInput, ObservabilityOptions, ObservabilityStats, RunTrace, TraceAnnotation, TraceContent, TraceContentKind, TraceContentPolicy, TraceCost, TraceExportQueueOptions, TraceExporter, TraceRedactor, TraceRedactorInput, TraceRunKind, TraceSpan, TraceSpanKind, TraceStatus };
@@ -1,2 +1,2 @@
1
- import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "../index-CbACw6xZ.mjs";
1
+ import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "../index-Bl0hR7EC.mjs";
2
2
  export { PolicyAuthorization, PolicyDecision, PolicyDefinition, definePolicy };
@@ -1,2 +1,2 @@
1
- import { $ as validateListEventsOptions, A as RunPause, B as TeamRun, C as PurgeRunsResult, D as RunCheckpoint, E as RetainableRunStore, F as RunStore, G as WorkflowBudgetUsage, H as ToolExecutionRecord, I as Session, J as WorkflowRun, K as WorkflowCheckpoint, L as SessionId, M as RunRequest, N as RunResult, O as RunCorrelation, P as RunStatus, Q as isRetainableRunStore, R as StoredRunCheckpoint, S as PurgeRunsOptions, T as RetainableRunStatus, U as ToolExecutionResolution, V as TimerResolution, W as ToolExecutionStatus, X as WorkflowWaitRecord, Y as WorkflowStepRecord, Z as isDurableRunStore, _ as EventResolution, a as AgentRun, b as ListEventsOptions, c as ApprovalRequest, d as CoordinatorRun, et as validatePurgeRunsOptions, f as CredentialStore, g as ElicitationResolution, h as ElicitationRequest, i as InMemoryRunStore, j as RunRecord, k as RunLease, l as ApprovalResolution, m as ElicitationMode, o as AgentRunPause, p as DurableRunStore, q as WorkflowCompensationRecord, s as ApprovalMode, u as CoordinatorCheckpoint, v as ExecutionCommit, w as ResumeRunResolution, x as PendingToolExecution, y as ExecutionCreate, z as TeamCheckpoint } from "../index-CzAi2Y_Z.mjs";
2
- export { AgentRun, AgentRunPause, ApprovalMode, ApprovalRequest, ApprovalResolution, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionCreate, InMemoryRunStore, ListEventsOptions, PendingToolExecution, PurgeRunsOptions, PurgeRunsResult, ResumeRunResolution, RetainableRunStatus, RetainableRunStore, RunCheckpoint, RunCorrelation, RunLease, RunPause, RunRecord, RunRequest, RunResult, RunStatus, RunStore, Session, SessionId, StoredRunCheckpoint, TeamCheckpoint, TeamRun, TimerResolution, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowRun, WorkflowStepRecord, WorkflowWaitRecord, isDurableRunStore, isRetainableRunStore, validateListEventsOptions, validatePurgeRunsOptions };
1
+ import { $ as ToolExecutionRecord, A as ListEventsOptions, B as RunPause, C as DurableRunStore, D as EventResolution, E as ElicitationResolution, F as RetainableRunStatus, G as RunStore, H as RunRequest, I as RetainableRunStore, J as SessionId, K as Session, L as RunCheckpoint, M as PurgeRunsOptions, N as PurgeRunsResult, O as ExecutionCommit, P as ResumeRunResolution, Q as TimerResolution, R as RunCorrelation, S as CredentialStore, T as ElicitationRequest, U as RunResult, V as RunRecord, W as RunStatus, X as TeamCheckpoint, Y as StoredRunCheckpoint, Z as TeamRun, _ as ApprovalMode, a as InMemoryRunStore, at as WorkflowRun, b as CoordinatorCheckpoint, c as ContextCompactor, ct as isDurableRunStore, d as ResolvedContextBudget, dt as validatePurgeRunsOptions, et as ToolExecutionResolution, f as createDigestContextCompactor, g as AgentRunPause, h as AgentRun, it as WorkflowCompensationRecord, j as PendingToolExecution, k as ExecutionCreate, l as ContextTokenEstimator, lt as isRetainableRunStore, m as resolveContextBudget, nt as WorkflowBudgetUsage, o as ContextCompactionInput, ot as WorkflowStepRecord, p as estimateContextTokens, q as SessionCompaction, rt as WorkflowCheckpoint, s as ContextCompactionOptions, st as WorkflowWaitRecord, tt as ToolExecutionStatus, u as DigestContextCompactorOptions, ut as validateListEventsOptions, v as ApprovalRequest, w as ElicitationMode, x as CoordinatorRun, y as ApprovalResolution, z as RunLease } from "../index-B8molngu.mjs";
2
+ export { AgentRun, AgentRunPause, ApprovalMode, ApprovalRequest, ApprovalResolution, ContextCompactionInput, ContextCompactionOptions, ContextCompactor, ContextTokenEstimator, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DigestContextCompactorOptions, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionCreate, InMemoryRunStore, ListEventsOptions, PendingToolExecution, PurgeRunsOptions, PurgeRunsResult, ResolvedContextBudget, ResumeRunResolution, RetainableRunStatus, RetainableRunStore, RunCheckpoint, RunCorrelation, RunLease, RunPause, RunRecord, RunRequest, RunResult, RunStatus, RunStore, Session, SessionCompaction, SessionId, StoredRunCheckpoint, TeamCheckpoint, TeamRun, TimerResolution, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowRun, WorkflowStepRecord, WorkflowWaitRecord, createDigestContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions };
@@ -1,4 +1,108 @@
1
1
  import { t as FevexRunError } from "../run-error-Cr17wPGH.mjs";
2
+ //#region src/runtime/compaction.ts
3
+ /** Validates a context budget and fills in defaults. */
4
+ function resolveContextBudget(budget, label) {
5
+ if (budget === void 0) return void 0;
6
+ if (!isRecord(budget)) throw new TypeError(`${label} must be an object`);
7
+ const contextWindow = budget.contextWindow;
8
+ if (!Number.isSafeInteger(contextWindow) || contextWindow <= 0) throw new TypeError(`${label}.contextWindow must be a positive safe integer`);
9
+ const reserveOutputTokens = budget.reserveOutputTokens ?? 0;
10
+ if (!Number.isSafeInteger(reserveOutputTokens) || reserveOutputTokens < 0 || reserveOutputTokens >= contextWindow) throw new TypeError(`${label}.reserveOutputTokens must be a non-negative safe integer below contextWindow`);
11
+ const usable = contextWindow - reserveOutputTokens;
12
+ const compactAt = budget.compactAt ?? .8;
13
+ if (typeof compactAt !== "number" || !Number.isFinite(compactAt) || compactAt <= 0 || compactAt > 1) throw new TypeError(`${label}.compactAt must be greater than 0 and at most 1`);
14
+ const targetTokens = budget.targetTokens ?? Math.max(1, Math.floor(usable * Math.min(.5, compactAt * .9)));
15
+ if (!Number.isSafeInteger(targetTokens) || targetTokens <= 0 || targetTokens >= usable) throw new TypeError(`${label}.targetTokens must be a positive safe integer below the usable window`);
16
+ if (targetTokens > Math.floor(usable * compactAt)) throw new TypeError(`${label}.targetTokens must not exceed the compaction threshold`);
17
+ const safetyFactor = budget.safetyFactor ?? 1.1;
18
+ if (typeof safetyFactor !== "number" || !Number.isFinite(safetyFactor) || safetyFactor < 1 || safetyFactor > 2) throw new TypeError(`${label}.safetyFactor must be between 1 and 2`);
19
+ return {
20
+ contextWindow,
21
+ reserveOutputTokens,
22
+ compactAt,
23
+ targetTokens,
24
+ safetyFactor
25
+ };
26
+ }
27
+ /**
28
+ * Rough provider-neutral estimate: about four characters per token plus
29
+ * message and tool framing. Hosts can inject a real tokenizer instead.
30
+ */
31
+ function estimateContextTokens(input) {
32
+ let characters = 0;
33
+ for (const message of input.messages) {
34
+ characters += message.role.length + message.content.length + 16;
35
+ if (message.name !== void 0) characters += message.name.length;
36
+ if (message.toolCallId !== void 0) characters += message.toolCallId.length;
37
+ if (message.toolCalls !== void 0) characters += JSON.stringify(message.toolCalls).length;
38
+ }
39
+ if (input.tools?.length) characters += JSON.stringify(input.tools).length;
40
+ return Math.max(1, Math.ceil(characters / 4));
41
+ }
42
+ /**
43
+ * Deterministic compactor used when the host does not inject one. It keeps
44
+ * role-aware excerpts of older messages and drops the oldest excerpts first.
45
+ * It never calls a model.
46
+ */
47
+ function createDigestContextCompactor(options = {}) {
48
+ const maxChars = options.maxCharsPerMessage ?? 400;
49
+ if (!Number.isSafeInteger(maxChars) || maxChars < 40) throw new TypeError("Digest compactor maxCharsPerMessage must be a safe integer of at least 40");
50
+ return { compact(input) {
51
+ if (input.messages.length === 0) return [{
52
+ role: "system",
53
+ content: "[Compacted earlier conversation]"
54
+ }];
55
+ let perMessage = maxChars;
56
+ let lines = input.messages.flatMap((message) => digestMessage(message, perMessage));
57
+ while (input.estimateTokens([{
58
+ role: "system",
59
+ content: digestContent(lines, input.messages.length)
60
+ }]) > input.targetTokens && perMessage > 40) {
61
+ perMessage = Math.max(40, Math.floor(perMessage * .7));
62
+ lines = input.messages.flatMap((message) => digestMessage(message, perMessage));
63
+ }
64
+ let selected = lines;
65
+ let content = digestContent(selected, input.messages.length);
66
+ while (input.estimateTokens([{
67
+ role: "system",
68
+ content
69
+ }]) > input.targetTokens && selected.length > 1) {
70
+ selected = selected.slice(1);
71
+ content = digestContent(selected, input.messages.length);
72
+ }
73
+ const limit = Math.max(80, input.targetTokens * 4);
74
+ if (content.length > limit) content = `${content.slice(0, Math.max(0, limit - 1))}…`;
75
+ return [{
76
+ role: "system",
77
+ content
78
+ }];
79
+ } };
80
+ }
81
+ function digestContent(lines, totalMessages) {
82
+ const omitted = Math.max(0, totalMessages - lines.length);
83
+ return [`[Compacted conversation: ${totalMessages} earlier messages${omitted ? `, ${omitted} omitted` : ""}]`, ...lines].join("\n");
84
+ }
85
+ function digestMessage(message, maxChars) {
86
+ const content = truncate(message.content, maxChars);
87
+ if (message.role === "user") return content ? [`User: ${content}`] : [];
88
+ if (message.role === "assistant") {
89
+ const lines = [];
90
+ if (content) lines.push(`Assistant: ${content}`);
91
+ for (const call of message.toolCalls ?? []) lines.push(`Tool call ${call.name}: ${truncate(JSON.stringify(call.input), Math.min(maxChars, 200))}`);
92
+ return lines;
93
+ }
94
+ if (message.role === "tool") return content ? [`Tool result${message.name === void 0 ? "" : ` (${message.name})`}: ${content}`] : [];
95
+ return content ? [`System: ${content}`] : [];
96
+ }
97
+ function truncate(value, maxChars) {
98
+ const normalized = value.replace(/\s+/g, " ").trim();
99
+ if (normalized.length <= maxChars) return normalized;
100
+ return `${normalized.slice(0, Math.max(0, maxChars - 1))}…`;
101
+ }
102
+ function isRecord(value) {
103
+ return typeof value === "object" && value !== null && !Array.isArray(value);
104
+ }
105
+ //#endregion
2
106
  //#region src/runtime/run-store.ts
3
107
  function validateListEventsOptions(options) {
4
108
  if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new TypeError("Event limit must be a positive safe integer");
@@ -180,4 +284,4 @@ var InMemoryRunStore = class {
180
284
  }
181
285
  };
182
286
  //#endregion
183
- export { InMemoryRunStore, isDurableRunStore, isRetainableRunStore, validateListEventsOptions, validatePurgeRunsOptions };
287
+ export { InMemoryRunStore, createDigestContextCompactor, estimateContextTokens, isDurableRunStore, isRetainableRunStore, resolveContextBudget, validateListEventsOptions, validatePurgeRunsOptions };
@@ -1,2 +1,2 @@
1
- import { a as SandboxError, c as sandboxResultToJson, i as SandboxCapabilities, n as createLocalSandbox, o as SandboxRunRequest, r as Sandbox, s as SandboxRunResult, t as LocalSandboxOptions } from "../index-Df84VWmN.mjs";
1
+ import { a as SandboxError, c as sandboxResultToJson, i as SandboxCapabilities, n as createLocalSandbox, o as SandboxRunRequest, r as Sandbox, s as SandboxRunResult, t as LocalSandboxOptions } from "../index-CL7mu_x9.mjs";
2
2
  export { LocalSandboxOptions, Sandbox, SandboxCapabilities, SandboxError, SandboxRunRequest, SandboxRunResult, createLocalSandbox, sandboxResultToJson };
@@ -1,2 +1,2 @@
1
- import { a as TeamMember, c as defineTeam, i as TeamLimits, n as TeamDelegation, o as TeamStep, r as TeamHandoff, s as TeamTaskResult, t as TeamDefinition } from "../index-1cHr7KB_.mjs";
1
+ import { a as TeamMember, c as defineTeam, i as TeamLimits, n as TeamDelegation, o as TeamStep, r as TeamHandoff, s as TeamTaskResult, t as TeamDefinition } from "../index-CODYPevS.mjs";
2
2
  export { type TeamDefinition, type TeamDelegation, type TeamHandoff, type TeamLimits, type TeamMember, type TeamStep, type TeamTaskResult, defineTeam };
@@ -1,9 +1,9 @@
1
- import { m as ToolCall } from "../types-B8laW1hM.mjs";
2
- import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-BgKFd9yw.mjs";
3
- import { h as ElicitationRequest, p as DurableRunStore } from "../index-CzAi2Y_Z.mjs";
4
- import { f as MemoryStore } from "../index-B0AdFbgr.mjs";
5
- import { d as ToolProvider } from "../index-5p3q2yIp.mjs";
6
- import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index-BTD1c4Ys.mjs";
1
+ import { m as ToolCall } from "../types-CckDlhYo.mjs";
2
+ import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-BfYzemR8.mjs";
3
+ import { C as DurableRunStore, T as ElicitationRequest } from "../index-B8molngu.mjs";
4
+ import { f as MemoryStore } from "../index-CAyAoOW0.mjs";
5
+ import { d as ToolProvider } from "../index-DtMxzCqj.mjs";
6
+ import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index-CuaetTLQ.mjs";
7
7
  //#region src/testing/contracts.d.ts
8
8
  interface ModelGatewayContract {
9
9
  output?: unknown;
@@ -1,3 +1,3 @@
1
- import { g as ToolSpec, m as ToolCall } from "../types-B8laW1hM.mjs";
2
- import { C as toToolSpec, S as defineTool, _ as ToolExecutionContext, a as compileFevexJsonSchema, b as ToolRetryPolicy, c as ConnectionToolPolicy, d as ToolProvider, f as ToolProviderContext, g as ToolDefinition, h as ToolApproval, i as FevexJsonSchemaValidator, l as IntegrationError, m as defineConnection, n as FevexJsonSchemaProfileLimits, o as validateFevexJsonSchemaProfile, p as ToolProviderTool, r as FevexJsonSchemaProfileOptions, s as ConnectionDefinition, t as FEVEX_JSON_SCHEMA_PROFILE_VERSION, u as IntegrationErrorCategory, v as ToolIdempotency, x as ToolRisk, y as ToolResult } from "../index-5p3q2yIp.mjs";
1
+ import { g as ToolSpec, m as ToolCall } from "../types-CckDlhYo.mjs";
2
+ import { C as toToolSpec, S as defineTool, _ as ToolExecutionContext, a as compileFevexJsonSchema, b as ToolRetryPolicy, c as ConnectionToolPolicy, d as ToolProvider, f as ToolProviderContext, g as ToolDefinition, h as ToolApproval, i as FevexJsonSchemaValidator, l as IntegrationError, m as defineConnection, n as FevexJsonSchemaProfileLimits, o as validateFevexJsonSchemaProfile, p as ToolProviderTool, r as FevexJsonSchemaProfileOptions, s as ConnectionDefinition, t as FEVEX_JSON_SCHEMA_PROFILE_VERSION, u as IntegrationErrorCategory, v as ToolIdempotency, x as ToolRisk, y as ToolResult } from "../index-DtMxzCqj.mjs";
3
3
  export { ConnectionDefinition, ConnectionToolPolicy, FEVEX_JSON_SCHEMA_PROFILE_VERSION, FevexJsonSchemaProfileLimits, FevexJsonSchemaProfileOptions, FevexJsonSchemaValidator, IntegrationError, IntegrationErrorCategory, ToolApproval, type ToolCall, ToolDefinition, ToolExecutionContext, ToolIdempotency, ToolProvider, ToolProviderContext, ToolProviderTool, ToolResult, ToolRetryPolicy, ToolRisk, type ToolSpec, compileFevexJsonSchema, defineConnection, defineTool, toToolSpec, validateFevexJsonSchemaProfile };
@@ -258,7 +258,7 @@ interface ToolEventSource {
258
258
  connectionName: string;
259
259
  remoteToolName: string;
260
260
  }
261
- type AgentEventType = 'run.started' | 'run.recovered' | 'run.paused' | 'run.resumed' | 'model.started' | 'model.output.delta' | 'model.completed' | 'tool.started' | 'tool.completed' | 'tool.failed' | 'tool.retrying' | 'tool.execution_unknown' | 'artifact.created' | 'elicitation.requested' | 'elicitation.resolved' | 'approval.requested' | 'approval.resolved' | 'run.completed' | 'run.failed' | 'run.cancelled' | 'workflow.run.started' | 'workflow.run.recovered' | 'workflow.step.started' | 'workflow.step.completed' | 'workflow.step.failed' | 'workflow.compensation.started' | 'workflow.compensation.completed' | 'workflow.compensation.failed' | 'workflow.wait.started' | 'workflow.wait.completed' | 'workflow.run.paused' | 'workflow.run.resumed' | 'workflow.run.completed' | 'workflow.run.failed' | 'workflow.run.cancelled' | 'team.run.started' | 'team.run.recovered' | 'team.agent.assigned' | 'team.handoff.created' | 'team.task.completed' | 'team.task.failed' | 'team.merge.started' | 'team.merge.completed' | 'team.merge.failed' | 'team.run.paused' | 'team.run.resumed' | 'team.run.completed' | 'team.run.failed' | 'team.run.cancelled';
261
+ type AgentEventType = 'run.started' | 'run.recovered' | 'run.paused' | 'run.resumed' | 'model.started' | 'model.output.delta' | 'model.completed' | 'context.compacted' | 'tool.started' | 'tool.completed' | 'tool.failed' | 'tool.retrying' | 'tool.execution_unknown' | 'artifact.created' | 'elicitation.requested' | 'elicitation.resolved' | 'approval.requested' | 'approval.resolved' | 'run.completed' | 'run.failed' | 'run.cancelled' | 'workflow.run.started' | 'workflow.run.recovered' | 'workflow.step.started' | 'workflow.step.completed' | 'workflow.step.failed' | 'workflow.compensation.started' | 'workflow.compensation.completed' | 'workflow.compensation.failed' | 'workflow.wait.started' | 'workflow.wait.completed' | 'workflow.run.paused' | 'workflow.run.resumed' | 'workflow.run.completed' | 'workflow.run.failed' | 'workflow.run.cancelled' | 'team.run.started' | 'team.run.recovered' | 'team.agent.assigned' | 'team.handoff.created' | 'team.task.completed' | 'team.task.failed' | 'team.merge.started' | 'team.merge.completed' | 'team.merge.failed' | 'team.run.paused' | 'team.run.resumed' | 'team.run.completed' | 'team.run.failed' | 'team.run.cancelled';
262
262
  interface AgentEventPayloads {
263
263
  'run.started': undefined;
264
264
  'run.recovered': {
@@ -292,6 +292,20 @@ interface AgentEventPayloads {
292
292
  teamDelegationId?: string;
293
293
  teamAgentName?: string;
294
294
  };
295
+ 'context.compacted': {
296
+ step: number;
297
+ removedMessages: number;
298
+ estimatedTokens: number;
299
+ compactedTokens: number;
300
+ targetTokens: number;
301
+ contextWindow: number;
302
+ summary: string;
303
+ summaryTruncated?: boolean;
304
+ workflowStepId?: string;
305
+ workflowAgentName?: string;
306
+ teamDelegationId?: string;
307
+ teamAgentName?: string;
308
+ };
295
309
  'tool.started': {
296
310
  step: number;
297
311
  toolCallId: string;
@@ -1,2 +1,2 @@
1
- import { a as WorkflowStep, c as defineWorkflow, i as WorkflowEventResult, n as WorkflowDefinition, o as WorkflowStepContext, r as WorkflowEventDefinition, s as WorkflowStepOptions, t as WorkflowAgentResult } from "../index-CseuTR-F.mjs";
1
+ import { a as WorkflowStep, c as defineWorkflow, i as WorkflowEventResult, n as WorkflowDefinition, o as WorkflowStepContext, r as WorkflowEventDefinition, s as WorkflowStepOptions, t as WorkflowAgentResult } from "../index-RKE3-CKs.mjs";
2
2
  export { WorkflowAgentResult, WorkflowDefinition, WorkflowEventDefinition, WorkflowEventResult, WorkflowStep, WorkflowStepContext, WorkflowStepOptions, defineWorkflow };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fevex/core",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.8",
4
4
  "description": "Agent Engineering Framework for code-first, provider-neutral AI agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",