@fevex/core 0.1.0-alpha.3 → 0.1.0-alpha.5

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 (41) hide show
  1. package/README.md +183 -2
  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 +2 -2
  7. package/dist/channels/index.mjs +70 -28
  8. package/dist/evals/index.d.mts +4 -4
  9. package/dist/{fevex-Ddyi6z6L.d.mts → fevex-B5NxFKcV.d.mts} +41 -11
  10. package/dist/http/index.d.mts +65 -5
  11. package/dist/http/index.mjs +236 -16
  12. package/dist/{index-Bgcxgy66.d.mts → index--_LdSEuF.d.mts} +31 -10
  13. package/dist/{index-CrOId2px.d.mts → index-BFnWUu7j.d.mts} +1 -1
  14. package/dist/{index-CTIwrVf9.d.mts → index-BPwkgdo3.d.mts} +1 -1
  15. package/dist/{index-DviHtsLo.d.mts → index-Br-zPxZH.d.mts} +2 -2
  16. package/dist/{index-Dx_LotWZ.d.mts → index-CGmHXV31.d.mts} +38 -3
  17. package/dist/{index-CqOjvtQ9.d.mts → index-CKQCNvJz.d.mts} +4 -2
  18. package/dist/{index-dkFyTNh4.d.mts → index-Cb3AB98n.d.mts} +2 -2
  19. package/dist/{index-B4PIkqOU.d.mts → index-D6lnI92z.d.mts} +3 -3
  20. package/dist/{index-Bg9rr8Qe.d.mts → index-Dsulk-n6.d.mts} +3 -3
  21. package/dist/{index-DeXUtyd9.d.mts → index-aayvtf0J.d.mts} +2 -2
  22. package/dist/index.d.mts +13 -13
  23. package/dist/index.mjs +464 -103
  24. package/dist/knowledge/index.d.mts +1 -1
  25. package/dist/model-stream-JQdHDDcj.mjs +131 -0
  26. package/dist/models/index.d.mts +1 -1
  27. package/dist/observability/index.d.mts +1 -1
  28. package/dist/policies/index.d.mts +1 -1
  29. package/dist/{model-stream-u2xMsEaf.mjs → run-support-CmZ6Xo6H.mjs} +41 -130
  30. package/dist/runtime/index.d.mts +2 -2
  31. package/dist/runtime/index.mjs +43 -1
  32. package/dist/sandbox/index.d.mts +1 -1
  33. package/dist/sandbox/index.mjs +42 -17
  34. package/dist/teams/index.d.mts +1 -1
  35. package/dist/testing/index.d.mts +13 -7
  36. package/dist/testing/index.mjs +98 -2
  37. package/dist/tools/index.d.mts +2 -2
  38. package/dist/types-BDVUoAU6.d.mts +559 -0
  39. package/dist/workflows/index.d.mts +1 -1
  40. package/package.json +6 -2
  41. 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-DeXUtyd9.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-aayvtf0J.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-BPwkgdo3.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-B4PIkqOU.mjs";
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-D6lnI92z.mjs";
2
2
  export { CostCalculator, CostCalculatorInput, ObservabilityOptions, RunTrace, TraceAnnotation, TraceContent, TraceContentKind, TraceContentPolicy, TraceCost, TraceExporter, TraceRedactor, TraceRedactorInput, 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-Cb3AB98n.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-Dx_LotWZ.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 validatePurgeRunsOptions, A as RunRecord, B as TimerResolution, C as PurgeRunsResult, D as RunCheckpoint, E as RetainableRunStore, F as Session, G as WorkflowCheckpoint, H as ToolExecutionResolution, I as SessionId, J as WorkflowStepRecord, K as WorkflowCompensationRecord, L as StoredRunCheckpoint, M as RunResult, N as RunStatus, O as RunLease, P as RunStore, Q as validateListEventsOptions, R as TeamCheckpoint, S as PurgeRunsOptions, T as RetainableRunStatus, U as ToolExecutionStatus, V as ToolExecutionRecord, W as WorkflowBudgetUsage, X as isDurableRunStore, Y as WorkflowWaitRecord, Z as isRetainableRunStore, _ 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 RunRequest, k as RunPause, l as ApprovalResolution, m as ElicitationMode, o as AgentRunPause, p as DurableRunStore, q as WorkflowRun, s as ApprovalMode, u as CoordinatorCheckpoint, v as ExecutionCommit, w as ResumeRunResolution, x as PendingToolExecution, y as ExecutionCreate, z as TeamRun } from "../index-CGmHXV31.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, 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-BFnWUu7j.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;
@@ -59,8 +59,14 @@ function createLocalSandbox(options) {
59
59
  async function runProcess(options) {
60
60
  const started = Date.now();
61
61
  let timedOut = false;
62
- let stdout = "";
63
- let stderr = "";
62
+ const stdout = {
63
+ text: "",
64
+ bytes: 0
65
+ };
66
+ const stderr = {
67
+ text: "",
68
+ bytes: 0
69
+ };
64
70
  return await new Promise((resolvePromise, reject) => {
65
71
  options.signal?.throwIfAborted();
66
72
  const child = spawn(options.command, [...options.args], {
@@ -73,35 +79,51 @@ async function runProcess(options) {
73
79
  "pipe"
74
80
  ]
75
81
  });
76
- const abort = () => {
82
+ let aborted = false;
83
+ let killTimer;
84
+ const terminate = () => {
85
+ if (killTimer !== void 0) return;
77
86
  child.kill("SIGTERM");
78
- reject(options.signal?.reason ?? new DOMException("Sandbox aborted", "AbortError"));
87
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 100);
88
+ };
89
+ const abort = () => {
90
+ aborted = true;
91
+ clearTimeout(timer);
92
+ terminate();
79
93
  };
80
94
  const timer = setTimeout(() => {
81
95
  timedOut = true;
82
- child.kill("SIGTERM");
96
+ terminate();
83
97
  }, options.timeoutMs);
98
+ const cleanup = () => {
99
+ clearTimeout(timer);
100
+ clearTimeout(killTimer);
101
+ options.signal?.removeEventListener("abort", abort);
102
+ };
84
103
  options.signal?.addEventListener("abort", abort, { once: true });
104
+ if (options.signal?.aborted) abort();
85
105
  child.stdout.setEncoding("utf8");
86
106
  child.stderr.setEncoding("utf8");
87
107
  child.stdout.on("data", (chunk) => {
88
- stdout = appendLimited(stdout, String(chunk), options.maxOutputBytes);
108
+ appendLimited(stdout, String(chunk), options.maxOutputBytes);
89
109
  });
90
110
  child.stderr.on("data", (chunk) => {
91
- stderr = appendLimited(stderr, String(chunk), options.maxOutputBytes);
111
+ appendLimited(stderr, String(chunk), options.maxOutputBytes);
92
112
  });
93
113
  child.on("error", (error) => {
94
- clearTimeout(timer);
95
- options.signal?.removeEventListener("abort", abort);
114
+ cleanup();
96
115
  reject(new SandboxError("SANDBOX_PROCESS_ERROR", "Sandbox process failed", { cause: error }));
97
116
  });
98
117
  child.on("close", (exitCode) => {
99
- clearTimeout(timer);
100
- options.signal?.removeEventListener("abort", abort);
118
+ cleanup();
119
+ if (aborted) {
120
+ reject(options.signal?.reason ?? new DOMException("Sandbox aborted", "AbortError"));
121
+ return;
122
+ }
101
123
  resolvePromise({
102
124
  exitCode,
103
- stdout,
104
- stderr,
125
+ stdout: stdout.text,
126
+ stderr: stderr.text,
105
127
  durationMs: Date.now() - started,
106
128
  timedOut
107
129
  });
@@ -110,9 +132,12 @@ async function runProcess(options) {
110
132
  else child.stdin.end();
111
133
  });
112
134
  }
113
- function appendLimited(current, chunk, maxBytes) {
114
- const next = current + chunk;
115
- return Buffer.byteLength(next) <= maxBytes ? next : next.slice(0, maxBytes);
135
+ function appendLimited(output, chunk, maxBytes) {
136
+ const remaining = maxBytes - output.bytes;
137
+ if (remaining <= 0) return;
138
+ const bytes = Buffer.from(chunk).subarray(0, remaining);
139
+ output.bytes += bytes.length;
140
+ output.text += new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes, { stream: true });
116
141
  }
117
142
  function isInside(rootDir, value) {
118
143
  const path = relative(rootDir, value);
@@ -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-Bg9rr8Qe.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-Dsulk-n6.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 { p as DurableRunStore } from "../index-Dx_LotWZ.mjs";
4
- import { s as MemoryStore } from "../index-DeXUtyd9.mjs";
5
- import { d as ToolProvider } from "../index-CqOjvtQ9.mjs";
6
- import { c as ChannelMessage, l as ChannelOutput, n as ChannelAdapter } from "../index-Bgcxgy66.mjs";
1
+ import { m as ToolCall } from "../types-BDVUoAU6.mjs";
2
+ import { a as ModelResult, n as ModelInput, t as ModelGateway } from "../index-BPwkgdo3.mjs";
3
+ import { h as ElicitationRequest, p as DurableRunStore } from "../index-CGmHXV31.mjs";
4
+ import { s as MemoryStore } from "../index-aayvtf0J.mjs";
5
+ import { d as ToolProvider } from "../index-CKQCNvJz.mjs";
6
+ import { d as ChannelMessage, f as ChannelOutput, o as ChannelElicitationContext, r as ChannelAdapter } from "../index--_LdSEuF.mjs";
7
7
  //#region src/testing/contracts.d.ts
8
8
  interface ModelGatewayContract {
9
9
  output?: unknown;
@@ -17,6 +17,11 @@ interface ChannelAdapterContract<TInput, TOutput> {
17
17
  output: ChannelOutput;
18
18
  delivered: TOutput;
19
19
  ignoredInput?: TInput;
20
+ elicitation?: {
21
+ request: ElicitationRequest;
22
+ context: ChannelElicitationContext;
23
+ delivered: TOutput;
24
+ };
20
25
  }
21
26
  interface ToolProviderContract {
22
27
  allowedTool: string;
@@ -31,6 +36,7 @@ declare function testToolProvider(provider: ToolProvider, contract: ToolProvider
31
36
  declare function testChannelAdapter<TInput, TOutput>(adapter: ChannelAdapter<TInput, TOutput>, contract: ChannelAdapterContract<TInput, TOutput>): Promise<void>;
32
37
  declare function testModelGateway(model: ModelGateway, contract?: ModelGatewayContract): Promise<void>;
33
38
  declare function testRunStore(store: DurableRunStore): Promise<void>;
39
+ declare function testRetentionStore(store: DurableRunStore): Promise<void>;
34
40
  //#endregion
35
41
  //#region src/testing/fake-model.d.ts
36
42
  interface FakeModel extends ModelGateway {
@@ -39,4 +45,4 @@ interface FakeModel extends ModelGateway {
39
45
  /** Creates a deterministic model gateway for unit tests. */
40
46
  declare function fakeModel(...responses: ModelResult[]): FakeModel;
41
47
  //#endregion
42
- export { ChannelAdapterContract, FakeModel, ModelGatewayContract, ToolProviderContract, fakeModel, testChannelAdapter, testMemoryStore, testModelGateway, testRunStore, testToolProvider };
48
+ export { ChannelAdapterContract, FakeModel, ModelGatewayContract, ToolProviderContract, fakeModel, testChannelAdapter, testMemoryStore, testModelGateway, testRetentionStore, testRunStore, testToolProvider };