@fevex/core 0.1.0-alpha.4 → 0.1.0-alpha.6

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 (42) hide show
  1. package/README.md +240 -11
  2. package/dist/agents/index.d.mts +1 -1
  3. package/dist/artifacts/index.d.mts +2 -0
  4. package/dist/artifacts/index.mjs +2 -0
  5. package/dist/artifacts-gUzemET7.mjs +440 -0
  6. package/dist/channels/index.d.mts +1 -1
  7. package/dist/evals/index.d.mts +4 -4
  8. package/dist/fevex-B4QY5Z6e.d.mts +119 -0
  9. package/dist/http/index.d.mts +65 -5
  10. package/dist/http/index.mjs +238 -16
  11. package/dist/{index-C-IFfCNw.d.mts → index-1cHr7KB_.d.mts} +3 -3
  12. package/dist/{index-CqOjvtQ9.d.mts → index-5p3q2yIp.d.mts} +4 -2
  13. package/dist/{index-hhbgvfIt.d.mts → index-BJktlD4E.d.mts} +2 -2
  14. package/dist/{index-CTIwrVf9.d.mts → index-BgKFd9yw.d.mts} +1 -1
  15. package/dist/{index-dkFyTNh4.d.mts → index-CbACw6xZ.d.mts} +2 -2
  16. package/dist/index-CpLDt6Rw.d.mts +118 -0
  17. package/dist/{index-CknU-glw.d.mts → index-CseuTR-F.d.mts} +2 -2
  18. package/dist/{index-CaE864Kz.d.mts → index-CzAi2Y_Z.d.mts} +45 -6
  19. package/dist/{index-DyyNLuwO.d.mts → index-DVw0zOc_.d.mts} +3 -3
  20. package/dist/{index-CrOId2px.d.mts → index-Df84VWmN.d.mts} +1 -1
  21. package/dist/index.d.mts +13 -13
  22. package/dist/index.mjs +904 -153
  23. package/dist/knowledge/index.d.mts +1 -1
  24. package/dist/model-stream-JQdHDDcj.mjs +131 -0
  25. package/dist/models/index.d.mts +1 -1
  26. package/dist/observability/index.d.mts +2 -2
  27. package/dist/policies/index.d.mts +1 -1
  28. package/dist/{model-stream-u2xMsEaf.mjs → run-support-CmZ6Xo6H.mjs} +41 -130
  29. package/dist/runtime/index.d.mts +2 -2
  30. package/dist/runtime/index.mjs +43 -1
  31. package/dist/sandbox/index.d.mts +1 -1
  32. package/dist/sandbox/index.mjs +1 -1
  33. package/dist/teams/index.d.mts +1 -1
  34. package/dist/testing/index.d.mts +8 -7
  35. package/dist/testing/index.mjs +94 -2
  36. package/dist/tools/index.d.mts +2 -2
  37. package/dist/types-B8laW1hM.d.mts +561 -0
  38. package/dist/workflows/index.d.mts +1 -1
  39. package/package.json +6 -2
  40. package/dist/fevex-BoPbZ-Tw.d.mts +0 -60
  41. package/dist/index-voIZhQXB.d.mts +0 -80
  42. package/dist/types-CuoRx12Q.d.mts +0 -333
@@ -1,2 +1,2 @@
1
- import { a as MemoryQuery, c as MemoryWrite, d as defineContextProvider, f as defineSkill, i as KnowledgeContext, l as SkillDefinition, n as ContextBlock, o as MemoryRecord, r as ContextProvider, s as MemoryStore, t as InMemoryMemoryStore, u as createMemoryContextProvider } from "../index-hhbgvfIt.mjs";
1
+ import { a as MemoryQuery, c as MemoryWrite, d as defineContextProvider, f as defineSkill, i as KnowledgeContext, l as SkillDefinition, n as ContextBlock, o as MemoryRecord, r as ContextProvider, s as MemoryStore, t as InMemoryMemoryStore, u as createMemoryContextProvider } from "../index-BJktlD4E.mjs";
2
2
  export { ContextBlock, ContextProvider, InMemoryMemoryStore, KnowledgeContext, MemoryQuery, MemoryRecord, MemoryStore, MemoryWrite, SkillDefinition, createMemoryContextProvider, defineContextProvider, defineSkill };
@@ -0,0 +1,131 @@
1
+ import { n as abortable } from "./run-support-CmZ6Xo6H.mjs";
2
+ //#region src/internal/model-stream.ts
3
+ const MAX_DELTA_CHARS = 512;
4
+ const MAX_DELTA_DELAY_MS = 32;
5
+ function isRecord(value) {
6
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7
+ }
8
+ function canonicalJson(value) {
9
+ if (Array.isArray(value)) return value.map(canonicalJson);
10
+ if (!isRecord(value)) return value;
11
+ const prototype = Object.getPrototypeOf(value);
12
+ if (prototype !== Object.prototype && prototype !== null) return value;
13
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonicalJson(item)]));
14
+ }
15
+ function assertConsistentOutput(result, outputText) {
16
+ if (result.output === void 0) {
17
+ if (outputText) throw new TypeError("Model stream emitted output without a final output");
18
+ return;
19
+ }
20
+ if (typeof result.output === "string") {
21
+ if (result.output !== outputText) throw new TypeError("Model stream deltas do not match the final output");
22
+ return;
23
+ }
24
+ if (!outputText) throw new TypeError("Model stream returned JSON output without output deltas");
25
+ let parsed;
26
+ try {
27
+ parsed = JSON.parse(outputText);
28
+ } catch (error) {
29
+ throw new TypeError("Model stream output deltas are not valid JSON", { cause: error });
30
+ }
31
+ if (JSON.stringify(canonicalJson(parsed)) !== JSON.stringify(canonicalJson(result.output))) throw new TypeError("Model stream deltas do not match the final JSON output");
32
+ }
33
+ function assertStreamEvent(value) {
34
+ if (!isRecord(value)) throw new TypeError("ModelGateway stream event must be an object");
35
+ if (value.type === "output.delta") {
36
+ if (typeof value.delta !== "string") throw new TypeError("ModelGateway output.delta must contain a string delta");
37
+ return;
38
+ }
39
+ if (value.type === "completed") {
40
+ if (!isRecord(value.result)) throw new TypeError("ModelGateway completed event must contain a result");
41
+ return;
42
+ }
43
+ throw new TypeError("ModelGateway returned an unknown stream event");
44
+ }
45
+ function takeCharacters(value, count) {
46
+ const characters = Array.from(value);
47
+ return [characters.slice(0, count).join(""), characters.slice(count).join("")];
48
+ }
49
+ async function* readModelStream(model, input) {
50
+ input.signal?.throwIfAborted();
51
+ const stream = model.stream(input);
52
+ if (!stream || typeof stream[Symbol.asyncIterator] !== "function") throw new TypeError("ModelGateway.stream must return an AsyncIterable");
53
+ const iterator = stream[Symbol.asyncIterator]();
54
+ let pending;
55
+ let completed;
56
+ let outputText = "";
57
+ let buffer = "";
58
+ let firstDelta = true;
59
+ let bufferedAt = 0;
60
+ const next = () => {
61
+ const promise = abortable(() => iterator.next(), input.signal);
62
+ promise.catch(() => {});
63
+ return promise;
64
+ };
65
+ try {
66
+ while (true) {
67
+ if (buffer && Array.from(buffer).length >= MAX_DELTA_CHARS) {
68
+ const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
69
+ buffer = rest;
70
+ bufferedAt = performance.now();
71
+ yield chunk;
72
+ continue;
73
+ }
74
+ pending ??= next();
75
+ let item;
76
+ if (buffer) {
77
+ const remaining = Math.max(0, MAX_DELTA_DELAY_MS - (performance.now() - bufferedAt));
78
+ const raced = await Promise.race([pending.then((value) => ({
79
+ type: "item",
80
+ value
81
+ })), new Promise((resolve) => {
82
+ setTimeout(() => resolve({ type: "flush" }), remaining);
83
+ })]);
84
+ if (raced.type === "flush") {
85
+ const chunk = buffer;
86
+ buffer = "";
87
+ bufferedAt = 0;
88
+ yield chunk;
89
+ continue;
90
+ }
91
+ item = raced.value;
92
+ } else item = await pending;
93
+ pending = void 0;
94
+ if (item.done) {
95
+ if (!completed) throw new TypeError("ModelGateway stream ended without completed");
96
+ assertConsistentOutput(completed, outputText);
97
+ return completed;
98
+ }
99
+ assertStreamEvent(item.value);
100
+ if (completed) throw new TypeError("ModelGateway stream emitted an event after completed");
101
+ if (item.value.type === "completed") {
102
+ completed = item.value.result;
103
+ if (buffer) {
104
+ const chunk = buffer;
105
+ buffer = "";
106
+ bufferedAt = 0;
107
+ yield chunk;
108
+ }
109
+ continue;
110
+ }
111
+ if (!item.value.delta) continue;
112
+ outputText += item.value.delta;
113
+ buffer += item.value.delta;
114
+ if (firstDelta) {
115
+ const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
116
+ firstDelta = false;
117
+ buffer = rest;
118
+ bufferedAt = performance.now();
119
+ yield chunk;
120
+ } else if (!bufferedAt) bufferedAt = performance.now();
121
+ }
122
+ } catch (error) {
123
+ if (buffer) yield buffer;
124
+ throw error;
125
+ } finally {
126
+ if (pending) pending.catch(() => {});
127
+ if (iterator.return) Promise.resolve(iterator.return()).catch(() => {});
128
+ }
129
+ }
130
+ //#endregion
131
+ export { readModelStream as t };
@@ -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-CTIwrVf9.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-BgKFd9yw.mjs";
2
2
  export { ModelGateway, ModelInput, ModelMetadata, ModelRef, ModelResult, ModelStreamEvent, ModelUsage, ReasoningEffort, ToolChoice };
@@ -1,2 +1,2 @@
1
- import { a as TraceAnnotation, c as TraceContentPolicy, d as TraceRedactor, f as TraceRedactorInput, h as TraceStatus, i as RunTrace, l as TraceCost, m as TraceSpanKind, n as CostCalculatorInput, o as TraceContent, p as TraceSpan, r as ObservabilityOptions, s as TraceContentKind, t as CostCalculator, u as TraceExporter } from "../index-voIZhQXB.mjs";
2
- export { CostCalculator, CostCalculatorInput, ObservabilityOptions, RunTrace, TraceAnnotation, TraceContent, TraceContentKind, TraceContentPolicy, TraceCost, TraceExporter, TraceRedactor, TraceRedactorInput, TraceSpan, TraceSpanKind, TraceStatus };
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";
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-dkFyTNh4.mjs";
1
+ import { i as definePolicy, n as PolicyDecision, r as PolicyDefinition, t as PolicyAuthorization } from "../index-CbACw6xZ.mjs";
2
2
  export { PolicyAuthorization, PolicyDecision, PolicyDefinition, definePolicy };
@@ -1,3 +1,4 @@
1
+ import { t as FevexRunError } from "./run-error-Cr17wPGH.mjs";
1
2
  //#region src/internal/json.ts
2
3
  const invalidJsonValue = Symbol("invalid-json-value");
3
4
  function normalizeJsonValue(value, seen = /* @__PURE__ */ new WeakSet()) {
@@ -50,6 +51,45 @@ function serializeValue(value, errorMessage) {
50
51
  }
51
52
  //#endregion
52
53
  //#region src/internal/run-support.ts
54
+ /** Largest delay accepted by Node and Bun timers. */
55
+ const MAX_DEADLINE_MS = 2147483647;
56
+ function deadlineAtFromMs(deadlineMs) {
57
+ if (deadlineMs === void 0) return void 0;
58
+ if (!Number.isSafeInteger(deadlineMs) || deadlineMs <= 0 || deadlineMs > 2147483647) throw new TypeError(`deadlineMs must be a positive safe integer up to ${MAX_DEADLINE_MS}`);
59
+ return new Date(Date.now() + deadlineMs).toISOString();
60
+ }
61
+ function runSignal(controller, request) {
62
+ const signals = [controller.signal];
63
+ if (request.signal) signals.push(request.signal);
64
+ if (request.deadlineMs !== void 0) {
65
+ deadlineAtFromMs(request.deadlineMs);
66
+ signals.push(AbortSignal.timeout(request.deadlineMs));
67
+ }
68
+ return AbortSignal.any(signals);
69
+ }
70
+ function resumeDeadlineSignal(deadlineAt, runId, code) {
71
+ if (deadlineAt === void 0) return void 0;
72
+ const expiresAt = Date.parse(deadlineAt);
73
+ if (!Number.isFinite(expiresAt)) throw new FevexRunError(code, `Run "${runId}" has an invalid deadline`, runId);
74
+ if (expiresAt <= Date.now()) throw new FevexRunError(code, `Run "${runId}" deadline has passed`, runId);
75
+ return AbortSignal.timeout(expiresAt - Date.now());
76
+ }
77
+ function remainingDeadlineMs(deadlineAt, runId) {
78
+ if (deadlineAt === void 0) return void 0;
79
+ const expiresAt = Date.parse(deadlineAt);
80
+ if (!Number.isFinite(expiresAt)) throw new FevexRunError("RUN_NOT_RESUMABLE", `Run "${runId}" has an invalid deadline`, runId);
81
+ const remaining = expiresAt - Date.now();
82
+ if (remaining <= 0) throw new FevexRunError("RUN_NOT_RESUMABLE", `Run "${runId}" deadline has passed`, runId);
83
+ return remaining;
84
+ }
85
+ function isTimeoutError(error) {
86
+ return typeof error === "object" && error !== null && error.name === "TimeoutError";
87
+ }
88
+ function minDeadline(first, second) {
89
+ if (first === void 0) return second;
90
+ if (second === void 0) return first;
91
+ return Math.min(first, second);
92
+ }
53
93
  function toErrorMessage(error) {
54
94
  if (error instanceof Error) return error.message;
55
95
  if (typeof error === "string") return error;
@@ -119,133 +159,4 @@ function eventUsage(usage) {
119
159
  return value;
120
160
  }
121
161
  //#endregion
122
- //#region src/internal/model-stream.ts
123
- const MAX_DELTA_CHARS = 512;
124
- const MAX_DELTA_DELAY_MS = 32;
125
- function isRecord(value) {
126
- return typeof value === "object" && value !== null && !Array.isArray(value);
127
- }
128
- function canonicalJson(value) {
129
- if (Array.isArray(value)) return value.map(canonicalJson);
130
- if (!isRecord(value)) return value;
131
- const prototype = Object.getPrototypeOf(value);
132
- if (prototype !== Object.prototype && prototype !== null) return value;
133
- return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonicalJson(item)]));
134
- }
135
- function assertConsistentOutput(result, outputText) {
136
- if (result.output === void 0) {
137
- if (outputText) throw new TypeError("Model stream emitted output without a final output");
138
- return;
139
- }
140
- if (typeof result.output === "string") {
141
- if (result.output !== outputText) throw new TypeError("Model stream deltas do not match the final output");
142
- return;
143
- }
144
- if (!outputText) throw new TypeError("Model stream returned JSON output without output deltas");
145
- let parsed;
146
- try {
147
- parsed = JSON.parse(outputText);
148
- } catch (error) {
149
- throw new TypeError("Model stream output deltas are not valid JSON", { cause: error });
150
- }
151
- if (JSON.stringify(canonicalJson(parsed)) !== JSON.stringify(canonicalJson(result.output))) throw new TypeError("Model stream deltas do not match the final JSON output");
152
- }
153
- function assertStreamEvent(value) {
154
- if (!isRecord(value)) throw new TypeError("ModelGateway stream event must be an object");
155
- if (value.type === "output.delta") {
156
- if (typeof value.delta !== "string") throw new TypeError("ModelGateway output.delta must contain a string delta");
157
- return;
158
- }
159
- if (value.type === "completed") {
160
- if (!isRecord(value.result)) throw new TypeError("ModelGateway completed event must contain a result");
161
- return;
162
- }
163
- throw new TypeError("ModelGateway returned an unknown stream event");
164
- }
165
- function takeCharacters(value, count) {
166
- const characters = Array.from(value);
167
- return [characters.slice(0, count).join(""), characters.slice(count).join("")];
168
- }
169
- async function* readModelStream(model, input) {
170
- input.signal?.throwIfAborted();
171
- const stream = model.stream(input);
172
- if (!stream || typeof stream[Symbol.asyncIterator] !== "function") throw new TypeError("ModelGateway.stream must return an AsyncIterable");
173
- const iterator = stream[Symbol.asyncIterator]();
174
- let pending;
175
- let completed;
176
- let outputText = "";
177
- let buffer = "";
178
- let firstDelta = true;
179
- let bufferedAt = 0;
180
- const next = () => {
181
- const promise = abortable(() => iterator.next(), input.signal);
182
- promise.catch(() => {});
183
- return promise;
184
- };
185
- try {
186
- while (true) {
187
- if (buffer && Array.from(buffer).length >= MAX_DELTA_CHARS) {
188
- const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
189
- buffer = rest;
190
- bufferedAt = performance.now();
191
- yield chunk;
192
- continue;
193
- }
194
- pending ??= next();
195
- let item;
196
- if (buffer) {
197
- const remaining = Math.max(0, MAX_DELTA_DELAY_MS - (performance.now() - bufferedAt));
198
- const raced = await Promise.race([pending.then((value) => ({
199
- type: "item",
200
- value
201
- })), new Promise((resolve) => {
202
- setTimeout(() => resolve({ type: "flush" }), remaining);
203
- })]);
204
- if (raced.type === "flush") {
205
- const chunk = buffer;
206
- buffer = "";
207
- bufferedAt = 0;
208
- yield chunk;
209
- continue;
210
- }
211
- item = raced.value;
212
- } else item = await pending;
213
- pending = void 0;
214
- if (item.done) {
215
- if (!completed) throw new TypeError("ModelGateway stream ended without completed");
216
- assertConsistentOutput(completed, outputText);
217
- return completed;
218
- }
219
- assertStreamEvent(item.value);
220
- if (completed) throw new TypeError("ModelGateway stream emitted an event after completed");
221
- if (item.value.type === "completed") {
222
- completed = item.value.result;
223
- if (buffer) {
224
- const chunk = buffer;
225
- buffer = "";
226
- bufferedAt = 0;
227
- yield chunk;
228
- }
229
- continue;
230
- }
231
- if (!item.value.delta) continue;
232
- outputText += item.value.delta;
233
- buffer += item.value.delta;
234
- if (firstDelta) {
235
- const [chunk, rest] = takeCharacters(buffer, MAX_DELTA_CHARS);
236
- firstDelta = false;
237
- buffer = rest;
238
- bufferedAt = performance.now();
239
- yield chunk;
240
- } else if (!bufferedAt) bufferedAt = performance.now();
241
- }
242
- } catch (error) {
243
- if (buffer) yield buffer;
244
- throw error;
245
- } finally {
246
- if (pending) pending.catch(() => {});
247
- if (iterator.return) Promise.resolve(iterator.return()).catch(() => {});
248
- }
249
- }
250
- //#endregion
251
- export { assertTokenBudget as a, remainingOutputTokens as c, serializeValue as d, toJsonValue as f, assertContinuationBudget as i, toErrorMessage as l, abortable as n, cancellationReason as o, addUsage as r, eventUsage as s, readModelStream as t, serializeJsonValue as u };
162
+ export { serializeValue as _, assertTokenBudget as a, eventUsage as c, remainingDeadlineMs as d, remainingOutputTokens as f, serializeJsonValue as g, toErrorMessage as h, assertContinuationBudget as i, isTimeoutError as l, runSignal as m, abortable as n, cancellationReason as o, resumeDeadlineSignal as p, addUsage as r, deadlineAtFromMs as s, MAX_DEADLINE_MS as t, minDeadline as u, toJsonValue as v };
@@ -1,2 +1,2 @@
1
- import { A as RunStore, B as WorkflowBudgetUsage, C as RunCheckpoint, D as RunRequest, E as RunRecord, F as TeamRun, G as WorkflowWaitRecord, H as WorkflowCompensationRecord, I as TimerResolution, K as isDurableRunStore, L as ToolExecutionRecord, M as SessionId, N as StoredRunCheckpoint, O as RunResult, P as TeamCheckpoint, R as ToolExecutionResolution, S as ResumeRunResolution, T as RunPause, U as WorkflowRun, V as WorkflowCheckpoint, W as WorkflowStepRecord, _ as EventResolution, a as AgentRun, b as ListEventsOptions, c as ApprovalRequest, d as CoordinatorRun, f as CredentialStore, g as ElicitationResolution, h as ElicitationRequest, i as InMemoryRunStore, j as Session, k as RunStatus, l as ApprovalResolution, m as ElicitationMode, o as AgentRunPause, p as DurableRunStore, q as validateListEventsOptions, s as ApprovalMode, u as CoordinatorCheckpoint, v as ExecutionCommit, w as RunLease, x as PendingToolExecution, y as ExecutionCreate, z as ToolExecutionStatus } from "../index-CaE864Kz.mjs";
2
- export { AgentRun, AgentRunPause, ApprovalMode, ApprovalRequest, ApprovalResolution, CoordinatorCheckpoint, CoordinatorRun, CredentialStore, DurableRunStore, ElicitationMode, ElicitationRequest, ElicitationResolution, EventResolution, ExecutionCommit, ExecutionCreate, InMemoryRunStore, ListEventsOptions, PendingToolExecution, ResumeRunResolution, RunCheckpoint, RunLease, RunPause, RunRecord, RunRequest, RunResult, RunStatus, RunStore, Session, SessionId, StoredRunCheckpoint, TeamCheckpoint, TeamRun, TimerResolution, ToolExecutionRecord, ToolExecutionResolution, ToolExecutionStatus, WorkflowBudgetUsage, WorkflowCheckpoint, WorkflowCompensationRecord, WorkflowRun, WorkflowStepRecord, WorkflowWaitRecord, isDurableRunStore, validateListEventsOptions };
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 };
@@ -4,6 +4,24 @@ function validateListEventsOptions(options) {
4
4
  if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new TypeError("Event limit must be a positive safe integer");
5
5
  if (options.order !== void 0 && options.order !== "asc" && options.order !== "desc") throw new TypeError("Event order must be asc or desc");
6
6
  }
7
+ function isRetainableRunStore(store) {
8
+ return typeof store.purgeRuns === "function";
9
+ }
10
+ function validatePurgeRunsOptions(options = {}) {
11
+ const statuses = options.statuses ?? [
12
+ "completed",
13
+ "failed",
14
+ "cancelled"
15
+ ];
16
+ if (statuses.length === 0 || statuses.some((status) => status !== "completed" && status !== "failed" && status !== "cancelled")) throw new TypeError("Purge statuses must contain only completed, failed or cancelled");
17
+ if (options.before !== void 0 && Number.isNaN(Date.parse(options.before))) throw new TypeError("Purge before must be an ISO timestamp");
18
+ if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new TypeError("Purge limit must be a positive safe integer");
19
+ return {
20
+ statuses,
21
+ ...options.before === void 0 ? {} : { before: new Date(options.before).toISOString() },
22
+ ...options.limit === void 0 ? {} : { limit: options.limit }
23
+ };
24
+ }
7
25
  function isDurableRunStore(store) {
8
26
  const value = store;
9
27
  return [
@@ -118,6 +136,30 @@ var InMemoryRunStore = class {
118
136
  #sessionBusy(sessionId, exceptRunId) {
119
137
  return [...this.#runs.values()].some((run) => run.sessionId === sessionId && run.id !== exceptRunId && (run.status === "running" || run.status === "paused"));
120
138
  }
139
+ async purgeRuns(options = {}) {
140
+ const { statuses, before, limit } = validatePurgeRunsOptions(options);
141
+ const allowed = new Set(statuses);
142
+ const beforeTime = before === void 0 ? void 0 : Date.parse(before);
143
+ const candidates = [...this.#runs.entries()].filter(([, run]) => allowed.has(run.status) && (beforeTime === void 0 || Date.parse(run.createdAt) < beforeTime)).sort(([, first], [, second]) => Date.parse(first.createdAt) - Date.parse(second.createdAt)).slice(0, limit);
144
+ for (const [runId] of candidates) {
145
+ this.#runs.delete(runId);
146
+ this.#events.delete(runId);
147
+ this.#checkpoints.delete(runId);
148
+ this.#leases.delete(runId);
149
+ for (const key of this.#toolExecutions.keys()) if (key.startsWith(`${runId}:`)) this.#toolExecutions.delete(key);
150
+ }
151
+ const affectedSessions = new Set(candidates.map(([, run]) => run.sessionId));
152
+ const usedSessions = new Set([...this.#runs.values()].map(({ sessionId }) => sessionId));
153
+ let sessions = 0;
154
+ for (const sessionId of affectedSessions) {
155
+ if (usedSessions.has(sessionId)) continue;
156
+ if (this.#sessions.delete(sessionId)) sessions += 1;
157
+ }
158
+ return {
159
+ runs: candidates.length,
160
+ sessions
161
+ };
162
+ }
121
163
  async acquireLease(lease) {
122
164
  const current = this.#leases.get(lease.runId);
123
165
  if (current && Date.parse(current.expiresAt) > Date.now()) return false;
@@ -138,4 +180,4 @@ var InMemoryRunStore = class {
138
180
  }
139
181
  };
140
182
  //#endregion
141
- export { InMemoryRunStore, isDurableRunStore, validateListEventsOptions };
183
+ export { InMemoryRunStore, isDurableRunStore, isRetainableRunStore, 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-CrOId2px.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-Df84VWmN.mjs";
2
2
  export { LocalSandboxOptions, Sandbox, SandboxCapabilities, SandboxError, SandboxRunRequest, SandboxRunResult, createLocalSandbox, sandboxResultToJson };
@@ -1,6 +1,6 @@
1
+ import { relative, resolve } from "node:path";
1
2
  import { spawn } from "node:child_process";
2
3
  import { realpathSync } from "node:fs";
3
- import { relative, resolve } from "node:path";
4
4
  //#region src/sandbox/sandbox.ts
5
5
  var SandboxError = class extends Error {
6
6
  code;
@@ -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-C-IFfCNw.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-1cHr7KB_.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-CuoRx12Q.mjs";
2
- import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-CTIwrVf9.mjs";
3
- import { h as ElicitationRequest, p as DurableRunStore } from "../index-CaE864Kz.mjs";
4
- import { s as MemoryStore } from "../index-hhbgvfIt.mjs";
5
- import { d as ToolProvider } from "../index-CqOjvtQ9.mjs";
6
- import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index-DyyNLuwO.mjs";
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 { s as MemoryStore } from "../index-BJktlD4E.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-DVw0zOc_.mjs";
7
7
  //#region src/testing/contracts.d.ts
8
8
  interface ModelGatewayContract {
9
9
  output?: unknown;
@@ -36,6 +36,7 @@ declare function testToolProvider(provider: ToolProvider, contract: ToolProvider
36
36
  declare function testChannelAdapter<TInput, TOutput>(adapter: ChannelAdapter<TInput, TOutput>, contract: ChannelAdapterContract<TInput, TOutput>): Promise<void>;
37
37
  declare function testModelGateway(model: ModelGateway, contract?: ModelGatewayContract): Promise<void>;
38
38
  declare function testRunStore(store: DurableRunStore): Promise<void>;
39
+ declare function testRetentionStore(store: DurableRunStore): Promise<void>;
39
40
  //#endregion
40
41
  //#region src/testing/fake-model.d.ts
41
42
  interface FakeModel extends ModelGateway {
@@ -44,4 +45,4 @@ interface FakeModel extends ModelGateway {
44
45
  /** Creates a deterministic model gateway for unit tests. */
45
46
  declare function fakeModel(...responses: ModelResult[]): FakeModel;
46
47
  //#endregion
47
- export { ChannelAdapterContract, FakeModel, ModelGatewayContract, ToolProviderContract, fakeModel, testChannelAdapter, testMemoryStore, testModelGateway, testRunStore, testToolProvider };
48
+ export { ChannelAdapterContract, FakeModel, ModelGatewayContract, ToolProviderContract, fakeModel, testChannelAdapter, testMemoryStore, testModelGateway, testRetentionStore, testRunStore, testToolProvider };
@@ -1,5 +1,6 @@
1
+ import { isRetainableRunStore } from "../runtime/index.mjs";
1
2
  import { IntegrationError } from "../tools/index.mjs";
2
- import { t as readModelStream } from "../model-stream-u2xMsEaf.mjs";
3
+ import { t as readModelStream } from "../model-stream-JQdHDDcj.mjs";
3
4
  //#region src/testing/contracts.ts
4
5
  const contractOutputSchema = {
5
6
  type: "object",
@@ -599,6 +600,97 @@ async function testRunStore(store) {
599
600
  }), "The current generation must be able to commit");
600
601
  await store.releaseLease(runId, takeoverLease.ownerId, takeoverLease.generation);
601
602
  }
603
+ async function testRetentionStore(store) {
604
+ assert(isRetainableRunStore(store), "RunStore must implement purgeRuns");
605
+ const suffix = crypto.randomUUID();
606
+ const now = Date.now();
607
+ const old = (/* @__PURE__ */ new Date(now - 2 * 864e5)).toISOString();
608
+ const before = (/* @__PURE__ */ new Date(now - 864e5)).toISOString();
609
+ const recent = new Date(now).toISOString();
610
+ const entries = [
611
+ {
612
+ id: `retention-old-completed-${suffix}`,
613
+ status: "completed",
614
+ createdAt: old
615
+ },
616
+ {
617
+ id: `retention-old-failed-${suffix}`,
618
+ status: "failed",
619
+ createdAt: old
620
+ },
621
+ {
622
+ id: `retention-recent-completed-${suffix}`,
623
+ status: "completed",
624
+ createdAt: recent
625
+ },
626
+ {
627
+ id: `retention-old-running-${suffix}`,
628
+ status: "running",
629
+ createdAt: old
630
+ }
631
+ ];
632
+ for (const entry of entries) {
633
+ const sessionId = `retention-session-${entry.id}`;
634
+ await store.saveSession({
635
+ id: sessionId,
636
+ history: [],
637
+ createdAt: entry.createdAt,
638
+ updatedAt: entry.createdAt
639
+ });
640
+ await store.saveRun({
641
+ id: entry.id,
642
+ sessionId,
643
+ agentName: "retention-agent",
644
+ status: entry.status,
645
+ revision: 1,
646
+ createdAt: entry.createdAt,
647
+ updatedAt: entry.createdAt
648
+ });
649
+ await store.appendEvent({
650
+ id: `retention-event-${entry.id}`,
651
+ sequence: 1,
652
+ type: "run.started",
653
+ runId: entry.id,
654
+ timestamp: entry.createdAt
655
+ });
656
+ }
657
+ const purged = await store.purgeRuns({ before });
658
+ assert(purged.runs === 2, "Retention must delete only old terminal runs");
659
+ assert(purged.sessions === 2, "Retention must delete sessions left without runs");
660
+ assert(!await store.getRun(entries[0].id), "Retention must delete the completed run");
661
+ assert(!await store.getRun(entries[1].id), "Retention must delete the failed run");
662
+ assert(await store.getRun(entries[2].id), "Retention must keep recent terminal runs");
663
+ assert(await store.getRun(entries[3].id), "Retention must keep active runs");
664
+ assert(!await store.getSession(`retention-session-${entries[0].id}`), "Retention must delete empty sessions");
665
+ assert(await store.getSession(`retention-session-${entries[2].id}`), "Retention must keep sessions with runs");
666
+ assert((await store.purgeRuns({ limit: 1 })).runs === 1, "Retention must honor the limit");
667
+ await store.purgeRuns({ before: new Date(Date.now() + 864e5).toISOString() });
668
+ assert(!await store.getRun(entries[2].id), "Retention must purge remaining terminal runs");
669
+ assert(await store.getRun(entries[3].id), "Retention must keep active runs after a full purge");
670
+ const boundaryId = `retention-boundary-${suffix}`;
671
+ const boundarySessionId = `retention-boundary-session-${suffix}`;
672
+ const boundaryCreatedAt = "2020-01-01T00:00:00.100Z";
673
+ await store.saveSession({
674
+ id: boundarySessionId,
675
+ history: [],
676
+ createdAt: boundaryCreatedAt,
677
+ updatedAt: boundaryCreatedAt
678
+ });
679
+ await store.saveRun({
680
+ id: boundaryId,
681
+ sessionId: boundarySessionId,
682
+ agentName: "retention-agent",
683
+ status: "completed",
684
+ revision: 1,
685
+ createdAt: boundaryCreatedAt,
686
+ updatedAt: boundaryCreatedAt
687
+ });
688
+ assert((await store.purgeRuns({
689
+ before: "2020-01-01T00:00:00.500Z",
690
+ statuses: ["completed"]
691
+ })).runs === 1, "Retention must compare subsecond timestamps");
692
+ assert(!await store.getRun(boundaryId), "Retention must delete the boundary run");
693
+ }
602
694
  //#endregion
603
695
  //#region src/testing/fake-model.ts
604
696
  /** Creates a deterministic model gateway for unit tests. */
@@ -626,4 +718,4 @@ function fakeModel(...responses) {
626
718
  };
627
719
  }
628
720
  //#endregion
629
- export { fakeModel, testChannelAdapter, testMemoryStore, testModelGateway, testRunStore, testToolProvider };
721
+ export { fakeModel, testChannelAdapter, testMemoryStore, testModelGateway, testRetentionStore, testRunStore, testToolProvider };
@@ -1,3 +1,3 @@
1
- import { g as ToolSpec, m as ToolCall } from "../types-CuoRx12Q.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-CqOjvtQ9.mjs";
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";
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 };