@anvia/studio 0.7.29 → 0.7.31

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 (31) hide show
  1. package/dist/index.d.ts +3 -1
  2. package/dist/index.js +969 -940
  3. package/dist/index.js.map +1 -1
  4. package/dist/ui/assets/{evals-page-7nLpk1vO.js → evals-page-DN6aZ9dT.js} +2 -2
  5. package/dist/ui/assets/{evals-page-7nLpk1vO.js.map → evals-page-DN6aZ9dT.js.map} +1 -1
  6. package/dist/ui/assets/index-D7w3LxHM.js +55 -0
  7. package/dist/ui/assets/index-D7w3LxHM.js.map +1 -0
  8. package/dist/ui/assets/{knowledge-page-DevVjoVt.js → knowledge-page-DYwhR8Ly.js} +2 -2
  9. package/dist/ui/assets/{knowledge-page-DevVjoVt.js.map → knowledge-page-DYwhR8Ly.js.map} +1 -1
  10. package/dist/ui/assets/{mcps-page-gSjG8fUN.js → mcps-page-B3e3YF6D.js} +2 -2
  11. package/dist/ui/assets/{mcps-page-gSjG8fUN.js.map → mcps-page-B3e3YF6D.js.map} +1 -1
  12. package/dist/ui/assets/{memory-page-LbQjoiJi.js → memory-page-BeR1NNHY.js} +2 -2
  13. package/dist/ui/assets/{memory-page-LbQjoiJi.js.map → memory-page-BeR1NNHY.js.map} +1 -1
  14. package/dist/ui/assets/{pipelines-page-BDnSsw3p.js → pipelines-page-DdYD59h4.js} +2 -2
  15. package/dist/ui/assets/{pipelines-page-BDnSsw3p.js.map → pipelines-page-DdYD59h4.js.map} +1 -1
  16. package/dist/ui/assets/{sessions-page-DuFkengk.js → sessions-page-SAmGnFSU.js} +2 -2
  17. package/dist/ui/assets/{sessions-page-DuFkengk.js.map → sessions-page-SAmGnFSU.js.map} +1 -1
  18. package/dist/ui/assets/{status-page-Cp63l30c.js → status-page-g__90tnX.js} +2 -2
  19. package/dist/ui/assets/{status-page-Cp63l30c.js.map → status-page-g__90tnX.js.map} +1 -1
  20. package/dist/ui/assets/{tool-runner-D09nhpss.js → tool-runner-CcqIP2r3.js} +2 -2
  21. package/dist/ui/assets/{tool-runner-D09nhpss.js.map → tool-runner-CcqIP2r3.js.map} +1 -1
  22. package/dist/ui/assets/{tools-page-BwgQMVke.js → tools-page-By0mx0ua.js} +2 -2
  23. package/dist/ui/assets/{tools-page-BwgQMVke.js.map → tools-page-By0mx0ua.js.map} +1 -1
  24. package/dist/ui/assets/{trace-browser-B7BK2f--.js → trace-browser-BDet5qes.js} +2 -2
  25. package/dist/ui/assets/{trace-browser-B7BK2f--.js.map → trace-browser-BDet5qes.js.map} +1 -1
  26. package/dist/ui/assets/{transcript-item-DEZpZ7fg.js → transcript-item-3F08pehk.js} +3 -3
  27. package/dist/ui/assets/{transcript-item-DEZpZ7fg.js.map → transcript-item-3F08pehk.js.map} +1 -1
  28. package/dist/ui/index.html +1 -1
  29. package/package.json +4 -4
  30. package/dist/ui/assets/index-CDwzNuFN.js +0 -55
  31. package/dist/ui/assets/index-CDwzNuFN.js.map +0 -1
package/dist/index.js CHANGED
@@ -4,17 +4,6 @@ import { Pipeline } from "@anvia/core/pipeline";
4
4
  import { serve } from "@hono/node-server";
5
5
  import { Hono as HonoApp } from "hono";
6
6
 
7
- // src/shared/compact.ts
8
- function compact(obj) {
9
- const result = {};
10
- for (const [key, value] of Object.entries(obj)) {
11
- if (value !== void 0) {
12
- result[key] = value;
13
- }
14
- }
15
- return result;
16
- }
17
-
18
7
  // src/runtime/json.ts
19
8
  function toJsonValue(value) {
20
9
  return toJsonValueInternal(value, /* @__PURE__ */ new WeakSet());
@@ -212,7 +201,6 @@ var StudioRunTraceObserver = class {
212
201
  const trace = {
213
202
  id: this.props.id,
214
203
  sessionId,
215
- ...compact({ name: this.props.args.trace?.name }),
216
204
  status,
217
205
  trace: this.trace,
218
206
  startedAt: this.startedAt.toISOString(),
@@ -223,13 +211,14 @@ var StudioRunTraceObserver = class {
223
211
  prompt: this.props.args.prompt,
224
212
  history: this.props.args.history
225
213
  }),
226
- ...compact({ output: result.output }),
227
- ...compact({ error: result.error }),
228
- ...compact({ usage: result.usage }),
229
214
  metadata,
230
215
  observations: this.observations,
231
216
  observationCount: this.observations.length
232
217
  };
218
+ if (this.props.args.trace?.name !== void 0) trace.name = this.props.args.trace.name;
219
+ if (result.output !== void 0) trace.output = result.output;
220
+ if (result.error !== void 0) trace.error = result.error;
221
+ if (result.usage !== void 0) trace.usage = result.usage;
233
222
  await store.saveTrace(trace);
234
223
  }
235
224
  };
@@ -252,41 +241,42 @@ var ChildAgentToolTraceAccumulator = class {
252
241
  const agentName = wrapper.agentName;
253
242
  const childTurn = typeof child.turn === "number" ? child.turn : this.parent.turn;
254
243
  if (!this.agentStarts.has(agentId)) {
255
- this.agentStarts.set(agentId, {
244
+ const start = {
256
245
  startedAt: /* @__PURE__ */ new Date(),
257
- agentId,
258
- ...compact({ agentName })
259
- });
246
+ agentId
247
+ };
248
+ if (agentName !== void 0) start.agentName = agentName;
249
+ this.agentStarts.set(agentId, start);
260
250
  }
261
251
  if (child.type === "turn_start") {
262
- this.generationStarts.set(generationKey(agentId, childTurn), {
252
+ const start = {
263
253
  startedAt: /* @__PURE__ */ new Date(),
264
254
  input: toJsonValue({
265
255
  prompt: child.prompt,
266
256
  history: child.history
267
257
  }),
268
258
  agentId,
269
- ...compact({ agentName }),
270
259
  childTurn
271
- });
260
+ };
261
+ if (agentName !== void 0) start.agentName = agentName;
262
+ this.generationStarts.set(generationKey(agentId, childTurn), start);
272
263
  return;
273
264
  }
274
265
  if (child.type === "turn_end") {
275
266
  const key = generationKey(agentId, childTurn);
276
267
  const start = this.generationStarts.get(key);
277
268
  this.generationStarts.delete(key);
278
- this.completedObservations.push(
279
- traceObservation({
280
- kind: "generation",
281
- name: `${agentLabel(agentId, agentName)}.model.turn.${childTurn}`,
282
- status: "success",
283
- turn: this.parent.turn,
284
- startedAt: start?.startedAt ?? /* @__PURE__ */ new Date(),
285
- ...compact({ input: start?.input }),
286
- output: toJsonValue(child.response),
287
- metadata: this.childMetadata(agentId, agentName, childTurn)
288
- })
289
- );
269
+ const observation = {
270
+ kind: "generation",
271
+ name: `${agentLabel(agentId, agentName)}.model.turn.${childTurn}`,
272
+ status: "success",
273
+ turn: this.parent.turn,
274
+ startedAt: start?.startedAt ?? /* @__PURE__ */ new Date(),
275
+ output: toJsonValue(child.response),
276
+ metadata: this.childMetadata(agentId, agentName, childTurn)
277
+ };
278
+ if (start?.input !== void 0) observation.input = start.input;
279
+ this.completedObservations.push(traceObservation(observation));
290
280
  return;
291
281
  }
292
282
  if (child.type === "tool_call" && isRecord(child.toolCall)) {
@@ -294,16 +284,17 @@ var ChildAgentToolTraceAccumulator = class {
294
284
  const toolCallFunction = isRecord(toolCall.function) ? toolCall.function : void 0;
295
285
  const toolName = typeof toolCallFunction?.name === "string" ? toolCallFunction.name : "tool";
296
286
  const callId = typeof toolCall.callId === "string" ? toolCall.callId : typeof toolCall.id === "string" ? toolCall.id : void 0;
297
- this.toolStarts.push({
287
+ const start = {
298
288
  startedAt: /* @__PURE__ */ new Date(),
299
289
  agentId,
300
- ...compact({ agentName }),
301
290
  childTurn,
302
291
  toolName,
303
- ...compact({ toolCallId: callId }),
304
292
  input: toJsonValue(toolCallFunction?.arguments ?? {}),
305
293
  completed: false
306
- });
294
+ };
295
+ if (agentName !== void 0) start.agentName = agentName;
296
+ if (callId !== void 0) start.toolCallId = callId;
297
+ this.toolStarts.push(start);
307
298
  return;
308
299
  }
309
300
  if (child.type === "tool_result") {
@@ -315,22 +306,20 @@ var ChildAgentToolTraceAccumulator = class {
315
306
  if (start !== void 0) {
316
307
  start.completed = true;
317
308
  }
318
- this.completedObservations.push(
319
- traceObservation({
320
- kind: "tool",
321
- name: `${agentLabel(agentId, agentName)}.${toolName}`,
322
- status: "success",
323
- turn: this.parent.turn,
324
- startedAt: start?.startedAt ?? /* @__PURE__ */ new Date(),
325
- ...compact({ input }),
326
- ...typeof child.result === "string" ? { output: parseOrString(child.result) } : {},
327
- metadata: {
328
- ...this.childMetadata(agentId, agentName, childTurn),
329
- ...compact({ toolCallId }),
330
- ...compact({ internalCallId })
331
- }
332
- })
333
- );
309
+ const metadata = this.childMetadata(agentId, agentName, childTurn);
310
+ if (toolCallId !== void 0) metadata.toolCallId = toolCallId;
311
+ if (internalCallId !== void 0) metadata.internalCallId = internalCallId;
312
+ const observation = {
313
+ kind: "tool",
314
+ name: `${agentLabel(agentId, agentName)}.${toolName}`,
315
+ status: "success",
316
+ turn: this.parent.turn,
317
+ startedAt: start?.startedAt ?? /* @__PURE__ */ new Date(),
318
+ metadata
319
+ };
320
+ if (input !== void 0) observation.input = input;
321
+ if (typeof child.result === "string") observation.output = parseOrString(child.result);
322
+ this.completedObservations.push(traceObservation(observation));
334
323
  return;
335
324
  }
336
325
  if (child.type === "error") {
@@ -415,21 +404,24 @@ function agentLabel(agentId, agentName) {
415
404
  }
416
405
  function traceObservation(props) {
417
406
  const endedAt = props.endedAt ?? /* @__PURE__ */ new Date();
418
- return {
407
+ const observation = {
419
408
  id: globalThis.crypto.randomUUID(),
420
- ...props.parentObservationId === void 0 ? {} : { parentObservationId: props.parentObservationId },
421
409
  kind: props.kind,
422
410
  name: props.name,
423
411
  status: props.status,
424
412
  turn: props.turn,
425
413
  startedAt: props.startedAt.toISOString(),
426
414
  endedAt: endedAt.toISOString(),
427
- durationMs: durationMs(props.startedAt, endedAt),
428
- ...compact({ input: props.input }),
429
- ...compact({ output: props.output }),
430
- ...compact({ error: props.error }),
431
- ...compact({ metadata: props.metadata })
415
+ durationMs: durationMs(props.startedAt, endedAt)
432
416
  };
417
+ if (props.parentObservationId !== void 0) {
418
+ observation.parentObservationId = props.parentObservationId;
419
+ }
420
+ if (props.input !== void 0) observation.input = props.input;
421
+ if (props.output !== void 0) observation.output = props.output;
422
+ if (props.error !== void 0) observation.error = props.error;
423
+ if (props.metadata !== void 0) observation.metadata = props.metadata;
424
+ return observation;
433
425
  }
434
426
  function traceMetadata(args, messages) {
435
427
  return compactJsonObject({
@@ -593,14 +585,15 @@ import { readFile } from "fs/promises";
593
585
  import { fileURLToPath } from "url";
594
586
  function resolveStudioUiOptions(ui) {
595
587
  const options = typeof ui === "object" ? ui : {};
596
- return {
588
+ const resolved = {
597
589
  path: normalizeUiPath(options.path ?? "/ui"),
598
590
  title: options.title ?? "Anvia Studio",
599
591
  rootRoutes: options.rootRoutes ?? true,
600
592
  redirectRoot: options.redirectRoot ?? true,
601
- ...options.clientScript === void 0 ? {} : { clientScript: options.clientScript },
602
593
  protectShell: options.protectShell ?? false
603
594
  };
595
+ if (options.clientScript !== void 0) resolved.clientScript = options.clientScript;
596
+ return resolved;
604
597
  }
605
598
  function isStudioUiEnabled(ui) {
606
599
  return ui !== false;
@@ -1046,23 +1039,25 @@ function createStudioModelRegistry(config) {
1046
1039
  }
1047
1040
  staticModels.set(modelId, { ...model, id: modelId });
1048
1041
  }
1049
- providers.set(id, {
1042
+ const runtimeProvider = {
1050
1043
  ...provider,
1051
1044
  id,
1052
- ...compact({
1053
- defaultModel: provider.defaultModel !== void 0 ? normalizeModelId(provider.defaultModel) : void 0
1054
- }),
1055
1045
  staticModels
1056
- });
1046
+ };
1047
+ if (provider.defaultModel !== void 0) {
1048
+ runtimeProvider.defaultModel = normalizeModelId(provider.defaultModel);
1049
+ }
1050
+ providers.set(id, runtimeProvider);
1057
1051
  }
1058
- return {
1059
- ...compact({
1060
- defaultModel: config.default !== void 0 ? normalizeModelRef(config.default) : void 0
1061
- }),
1052
+ const registry = {
1062
1053
  providers,
1063
1054
  agentPolicies: normalizeAgentPolicies(config.agents ?? {}),
1064
1055
  modelCache: /* @__PURE__ */ new Map()
1065
1056
  };
1057
+ if (config.default !== void 0) {
1058
+ Object.assign(registry, { defaultModel: normalizeModelRef(config.default) });
1059
+ }
1060
+ return registry;
1066
1061
  }
1067
1062
  function studioModelsConfig(registry, agents) {
1068
1063
  if (registry === void 0) {
@@ -1072,25 +1067,25 @@ function studioModelsConfig(registry, agents) {
1072
1067
  const models = [...provider.staticModels.values()].map(
1073
1068
  (model) => modelSummary(provider, model.id, model)
1074
1069
  );
1075
- return {
1070
+ const config2 = {
1076
1071
  id: provider.id,
1077
- ...compact({
1078
- name: provider.name,
1079
- defaultModel: provider.defaultModel,
1080
- metadata: provider.metadata
1081
- }),
1082
1072
  models
1083
1073
  };
1074
+ if (provider.name !== void 0) config2.name = provider.name;
1075
+ if (provider.defaultModel !== void 0) config2.defaultModel = provider.defaultModel;
1076
+ if (provider.metadata !== void 0) config2.metadata = provider.metadata;
1077
+ return config2;
1084
1078
  });
1085
1079
  const agentIds = new Set(agents.map((agent) => agent.id));
1086
1080
  const agentsConfig = Object.fromEntries(
1087
1081
  [...registry.agentPolicies.entries()].filter(([agentId]) => agentIds.has(agentId)).map(([agentId, policy]) => [agentId, publicPolicy(policy)])
1088
1082
  );
1089
- return {
1083
+ const config = {
1090
1084
  providers,
1091
- ...compact({ default: registry.defaultModel }),
1092
1085
  agents: agentsConfig
1093
1086
  };
1087
+ if (registry.defaultModel !== void 0) config.default = registry.defaultModel;
1088
+ return config;
1094
1089
  }
1095
1090
  function registerModelRoutes(app, props) {
1096
1091
  app.get("/models", async (c) => {
@@ -1100,10 +1095,13 @@ function registerModelRoutes(app, props) {
1100
1095
  const providers = await Promise.all(
1101
1096
  [...props.registry.providers.values()].map((provider) => providerCatalog(provider))
1102
1097
  );
1103
- return c.json({
1104
- providers,
1105
- ...compact({ defaultModel: props.registry.defaultModel })
1106
- });
1098
+ const response = {
1099
+ providers
1100
+ };
1101
+ if (props.registry.defaultModel !== void 0) {
1102
+ response.defaultModel = props.registry.defaultModel;
1103
+ }
1104
+ return c.json(response);
1107
1105
  });
1108
1106
  app.get("/models/:providerId", async (c) => {
1109
1107
  if (props.registry === void 0) {
@@ -1213,12 +1211,13 @@ async function agentModelsCatalog(registry, agent) {
1213
1211
  }
1214
1212
  });
1215
1213
  const defaultModel = policy?.default ?? registry.defaultModel;
1216
- return {
1214
+ const summary = {
1217
1215
  agentId: agent.id,
1218
- ...compact({ defaultModel }),
1219
- models: [...models, ...exactPolicyModels],
1220
- ...compact({ warnings: warnings.length === 0 ? void 0 : warnings })
1216
+ models: [...models, ...exactPolicyModels]
1221
1217
  };
1218
+ if (defaultModel !== void 0) summary.defaultModel = defaultModel;
1219
+ if (warnings.length > 0) summary.warnings = warnings;
1220
+ return summary;
1222
1221
  }
1223
1222
  async function providerCatalog(provider) {
1224
1223
  const models = /* @__PURE__ */ new Map();
@@ -1231,48 +1230,43 @@ async function providerCatalog(provider) {
1231
1230
  const listed = await provider.listModels();
1232
1231
  for (const model of listed.data) {
1233
1232
  const staticModel = provider.staticModels.get(model.id);
1234
- models.set(
1235
- model.id,
1236
- modelSummary(provider, model.id, {
1237
- id: model.id,
1238
- ...compact({ name: model.name, description: model.description }),
1239
- ...staticModel ?? {},
1240
- metadata: {
1241
- ...compact({
1242
- type: model.type,
1243
- createdAt: model.createdAt,
1244
- ownedBy: model.ownedBy,
1245
- contextLength: model.contextLength
1246
- }),
1247
- ...staticModel?.metadata ?? {}
1248
- }
1249
- })
1250
- );
1233
+ const definition = { id: model.id };
1234
+ if (model.name !== void 0) definition.name = model.name;
1235
+ if (model.description !== void 0) definition.description = model.description;
1236
+ Object.assign(definition, staticModel);
1237
+ const metadata = {};
1238
+ if (model.type !== void 0) metadata.type = model.type;
1239
+ if (model.createdAt !== void 0) metadata.createdAt = model.createdAt;
1240
+ if (model.ownedBy !== void 0) metadata.ownedBy = model.ownedBy;
1241
+ if (model.contextLength !== void 0) metadata.contextLength = model.contextLength;
1242
+ Object.assign(metadata, staticModel?.metadata);
1243
+ definition.metadata = metadata;
1244
+ models.set(model.id, modelSummary(provider, model.id, definition));
1251
1245
  }
1252
1246
  } catch (error) {
1253
1247
  const serialized = serializeError(error);
1254
1248
  warning = typeof serialized === "object" && serialized !== null && "message" in serialized ? String(serialized.message) : String(error);
1255
1249
  }
1256
1250
  }
1257
- return {
1251
+ const catalog = {
1258
1252
  id: provider.id,
1259
- ...compact({
1260
- name: provider.name,
1261
- defaultModel: provider.defaultModel,
1262
- metadata: provider.metadata,
1263
- warning
1264
- }),
1265
1253
  models: [...models.values()].sort((left, right) => left.ref.localeCompare(right.ref))
1266
1254
  };
1255
+ if (provider.name !== void 0) catalog.name = provider.name;
1256
+ if (provider.defaultModel !== void 0) catalog.defaultModel = provider.defaultModel;
1257
+ if (provider.metadata !== void 0) catalog.metadata = provider.metadata;
1258
+ if (warning !== void 0) catalog.warning = warning;
1259
+ return catalog;
1267
1260
  }
1268
1261
  function modelSummary(provider, modelId, model) {
1269
- return {
1262
+ const summary = {
1270
1263
  ...model,
1271
1264
  id: modelId,
1272
1265
  ref: `${provider.id}:${modelId}`,
1273
- providerId: provider.id,
1274
- ...compact({ providerName: provider.name })
1266
+ providerId: provider.id
1275
1267
  };
1268
+ if (provider.name !== void 0) summary.providerName = provider.name;
1269
+ return summary;
1276
1270
  }
1277
1271
  function ensureModelAllowed(registry, agentId, ref) {
1278
1272
  const { providerId } = parseModelRef(ref);
@@ -1291,21 +1285,23 @@ function allowedByPolicy(allowed, ref) {
1291
1285
  }
1292
1286
  function normalizeAgentPolicies(policies) {
1293
1287
  return new Map(
1294
- Object.entries(policies).map(([agentId, policy]) => [
1295
- agentId.trim(),
1296
- {
1297
- ...compact({
1298
- default: policy.default !== void 0 ? normalizeModelRef(policy.default) : void 0,
1299
- allowed: policy.allowed?.map(
1300
- (entry) => typeof entry === "string" && entry.trim().endsWith(":*") ? `${normalizeProviderId(entry.trim().slice(0, -2))}:*` : normalizeModelRef(entry)
1301
- )
1302
- })
1288
+ Object.entries(policies).map(([agentId, policy]) => {
1289
+ const normalized = {};
1290
+ if (policy.default !== void 0) normalized.default = normalizeModelRef(policy.default);
1291
+ if (policy.allowed !== void 0) {
1292
+ normalized.allowed = policy.allowed.map(
1293
+ (entry) => typeof entry === "string" && entry.trim().endsWith(":*") ? `${normalizeProviderId(entry.trim().slice(0, -2))}:*` : normalizeModelRef(entry)
1294
+ );
1303
1295
  }
1304
- ])
1296
+ return [agentId.trim(), normalized];
1297
+ })
1305
1298
  );
1306
1299
  }
1307
1300
  function publicPolicy(policy) {
1308
- return compact({ default: policy.default, allowed: policy.allowed });
1301
+ const config = {};
1302
+ if (policy.default !== void 0) config.default = policy.default;
1303
+ if (policy.allowed !== void 0) config.allowed = policy.allowed;
1304
+ return config;
1309
1305
  }
1310
1306
  function modelWarnings(ref, model, request) {
1311
1307
  const warnings = [];
@@ -1425,20 +1421,21 @@ function studioStreamError(error) {
1425
1421
 
1426
1422
  // src/runtime/trace-summary.ts
1427
1423
  function traceSummary(trace) {
1428
- return compact({
1424
+ const summary = {
1429
1425
  id: trace.id,
1430
1426
  sessionId: trace.sessionId,
1431
- name: trace.name,
1432
1427
  status: trace.status,
1433
1428
  startedAt: trace.startedAt,
1434
- endedAt: trace.endedAt,
1435
- durationMs: trace.durationMs,
1436
- output: trace.output,
1437
- error: trace.error,
1438
- usage: trace.usage,
1439
- metadata: trace.metadata,
1440
1429
  observationCount: trace.observations.length
1441
- });
1430
+ };
1431
+ if (trace.name !== void 0) summary.name = trace.name;
1432
+ if (trace.endedAt !== void 0) summary.endedAt = trace.endedAt;
1433
+ if (trace.durationMs !== void 0) summary.durationMs = trace.durationMs;
1434
+ if (trace.output !== void 0) summary.output = trace.output;
1435
+ if (trace.error !== void 0) summary.error = trace.error;
1436
+ if (trace.usage !== void 0) summary.usage = trace.usage;
1437
+ if (trace.metadata !== void 0) summary.metadata = trace.metadata;
1438
+ return summary;
1442
1439
  }
1443
1440
 
1444
1441
  // src/runtime/observability.ts
@@ -1465,14 +1462,13 @@ var StudioObservabilityHub = class {
1465
1462
  }
1466
1463
  };
1467
1464
  function observeStores(stores, hub) {
1468
- return {
1469
- ...stores,
1470
- ...compact({
1471
- sessions: stores.sessions !== void 0 ? observeSessionStore(stores.sessions, hub) : void 0,
1472
- traces: stores.traces !== void 0 ? observeTraceStore(stores.traces, hub) : void 0,
1473
- pipelineLogs: stores.pipelineLogs !== void 0 ? observePipelineLogStore(stores.pipelineLogs, hub) : void 0
1474
- })
1475
- };
1465
+ const observed = { ...stores };
1466
+ if (stores.sessions !== void 0) observed.sessions = observeSessionStore(stores.sessions, hub);
1467
+ if (stores.traces !== void 0) observed.traces = observeTraceStore(stores.traces, hub);
1468
+ if (stores.pipelineLogs !== void 0) {
1469
+ observed.pipelineLogs = observePipelineLogStore(stores.pipelineLogs, hub);
1470
+ }
1471
+ return observed;
1476
1472
  }
1477
1473
  function registerObservabilityRoutes(app, hub) {
1478
1474
  app.get("/observability/events", (c) => {
@@ -1492,7 +1488,9 @@ function registerObservabilityRoutes(app, hub) {
1492
1488
  });
1493
1489
  }
1494
1490
  function observabilityEvents(hub, types) {
1495
- const subscription = hub.subscribe(compact({ types }));
1491
+ const options = {};
1492
+ if (types !== void 0) options.types = types;
1493
+ const subscription = hub.subscribe(options);
1496
1494
  return {
1497
1495
  [Symbol.asyncIterator]() {
1498
1496
  return {
@@ -1636,15 +1634,14 @@ function transcriptFromMessages(messages) {
1636
1634
  let textEntryAdded = false;
1637
1635
  for (const content of message.content) {
1638
1636
  if (content.type === "text") {
1639
- transcript.push(
1640
- compact({
1641
- entryId: transcript.length,
1642
- kind: "message",
1643
- role: "user",
1644
- text: content.text,
1645
- attachments: attachments.length === 0 ? void 0 : attachments
1646
- })
1647
- );
1637
+ const entry = {
1638
+ entryId: transcript.length,
1639
+ kind: "message",
1640
+ role: "user",
1641
+ text: content.text
1642
+ };
1643
+ if (!textEntryAdded && attachments.length > 0) entry.attachments = attachments;
1644
+ transcript.push(entry);
1648
1645
  textEntryAdded = true;
1649
1646
  }
1650
1647
  }
@@ -1678,14 +1675,13 @@ function transcriptFromMessages(messages) {
1678
1675
  if (content.type === "text") {
1679
1676
  appendAssistantTranscriptText(transcript, content.text);
1680
1677
  } else if (content.type === "reasoning") {
1681
- transcript.push(
1682
- compact({
1683
- entryId: transcript.length,
1684
- kind: "reasoning",
1685
- reasoningId: content.id,
1686
- text: content.text
1687
- })
1688
- );
1678
+ const entry = {
1679
+ entryId: transcript.length,
1680
+ kind: "reasoning",
1681
+ text: content.text
1682
+ };
1683
+ if (content.id !== void 0) entry.reasoningId = content.id;
1684
+ transcript.push(entry);
1689
1685
  } else if (content.type === "tool_call") {
1690
1686
  transcript.push({
1691
1687
  entryId: transcript.length,
@@ -1705,23 +1701,22 @@ function attachmentsFromMessage(message) {
1705
1701
  }
1706
1702
  return message.content.flatMap((content) => {
1707
1703
  if (content.type === "image") {
1708
- return [
1709
- {
1710
- kind: "image",
1711
- ...content.source.type === "base64" ? { data: content.source.data, mediaType: content.source.mediaType } : { url: content.source.url }
1712
- }
1713
- ];
1704
+ const attachment = { kind: "image" };
1705
+ if (content.source.type === "base64") {
1706
+ attachment.data = content.source.data;
1707
+ attachment.mediaType = content.source.mediaType;
1708
+ } else {
1709
+ attachment.url = content.source.url;
1710
+ }
1711
+ return [attachment];
1714
1712
  }
1715
1713
  if (content.type === "document") {
1716
- return [
1717
- compact({
1718
- kind: "document",
1719
- name: content.source.filename,
1720
- mediaType: content.source.mediaType,
1721
- data: content.source.type === "base64" ? content.source.data : void 0,
1722
- url: content.source.type === "url" ? content.source.url : void 0
1723
- })
1724
- ];
1714
+ const attachment = { kind: "document" };
1715
+ if (content.source.filename !== void 0) attachment.name = content.source.filename;
1716
+ if (content.source.mediaType !== void 0) attachment.mediaType = content.source.mediaType;
1717
+ if (content.source.type === "base64") attachment.data = content.source.data;
1718
+ if (content.source.type === "url") attachment.url = content.source.url;
1719
+ return [attachment];
1725
1720
  }
1726
1721
  return [];
1727
1722
  });
@@ -1817,15 +1812,15 @@ function streamAgentRunEvents(_c, events) {
1817
1812
  return streamStudioJsonl(events);
1818
1813
  }
1819
1814
  function traceForRun(trace, agentId, session) {
1820
- const metadata = {
1821
- ...trace?.metadata ?? {},
1822
- agentId
1823
- };
1824
- return {
1825
- ...trace ?? {},
1826
- metadata,
1827
- ...trace?.sessionId !== void 0 ? { sessionId: trace.sessionId } : session === void 0 ? {} : { sessionId: session.id }
1828
- };
1815
+ const options = {};
1816
+ if (trace !== void 0) Object.assign(options, trace);
1817
+ const metadata = {};
1818
+ if (trace?.metadata !== void 0) Object.assign(metadata, trace.metadata);
1819
+ metadata.agentId = agentId;
1820
+ options.metadata = metadata;
1821
+ if (trace?.sessionId !== void 0) options.sessionId = trace.sessionId;
1822
+ else if (session !== void 0) options.sessionId = session.id;
1823
+ return options;
1829
1824
  }
1830
1825
  async function* persistStreamingSessionTranscript(props) {
1831
1826
  const transcript = [messageToTranscriptEntry(props.message, 0)];
@@ -1840,14 +1835,15 @@ async function* persistStreamingSessionTranscript(props) {
1840
1835
  try {
1841
1836
  for await (const event of props.stream) {
1842
1837
  acceptTranscriptStreamEvent(transcript, event);
1843
- const nextSession = await props.store.saveSessionRunTranscript({
1838
+ const saveInput = {
1844
1839
  id: props.session.id,
1845
1840
  runId: props.runId,
1846
1841
  ...title,
1847
1842
  transcript,
1848
- status: event.type === "final" ? "success" : event.type === "error" ? "error" : "running",
1849
- ...event.type === "error" ? { error: serializeError(event.error) } : {}
1850
- });
1843
+ status: event.type === "final" ? "success" : event.type === "error" ? "error" : "running"
1844
+ };
1845
+ if (event.type === "error") saveInput.error = serializeError(event.error);
1846
+ const nextSession = await props.store.saveSessionRunTranscript(saveInput);
1851
1847
  if (nextSession === void 0) {
1852
1848
  throw new Error("Session not found");
1853
1849
  }
@@ -1894,17 +1890,16 @@ function acceptTranscriptStreamEvent(transcript, event) {
1894
1890
  if (event.type === "tool_result") {
1895
1891
  const matched = findTranscriptToolEntry(transcript, event.toolName, event.toolCallId);
1896
1892
  if (matched === void 0) {
1897
- transcript.push(
1898
- compact({
1899
- entryId: transcript.length,
1900
- kind: "tool",
1901
- toolName: event.toolName,
1902
- callId: event.toolCallId,
1903
- args: event.args,
1904
- result: event.result,
1905
- structuredResult: event.structuredResult
1906
- })
1907
- );
1893
+ const entry = {
1894
+ entryId: transcript.length,
1895
+ kind: "tool",
1896
+ toolName: event.toolName
1897
+ };
1898
+ if (event.toolCallId !== void 0) entry.callId = event.toolCallId;
1899
+ if (event.args !== void 0) entry.args = event.args;
1900
+ if (event.result !== void 0) entry.result = event.result;
1901
+ if (event.structuredResult !== void 0) entry.structuredResult = event.structuredResult;
1902
+ transcript.push(entry);
1908
1903
  return;
1909
1904
  }
1910
1905
  matched.args = matched.args ?? event.args;
@@ -1916,17 +1911,16 @@ function acceptTranscriptStreamEvent(transcript, event) {
1916
1911
  if (event.type === "agent_tool_event") {
1917
1912
  const matched = findTranscriptToolEntry(transcript, event.toolName, event.toolCallId);
1918
1913
  if (matched === void 0) {
1919
- transcript.push(
1920
- compact({
1921
- entryId: transcript.length,
1922
- kind: "tool",
1923
- toolName: event.toolName,
1924
- callId: event.toolCallId,
1925
- childEvents: [childAgentTranscriptEvent(event)].filter(
1926
- (childEvent) => childEvent !== void 0
1927
- )
1928
- })
1929
- );
1914
+ const entry = {
1915
+ entryId: transcript.length,
1916
+ kind: "tool",
1917
+ toolName: event.toolName,
1918
+ childEvents: [childAgentTranscriptEvent(event)].filter(
1919
+ (childEvent) => childEvent !== void 0
1920
+ )
1921
+ };
1922
+ if (event.toolCallId !== void 0) entry.callId = event.toolCallId;
1923
+ transcript.push(entry);
1930
1924
  return;
1931
1925
  }
1932
1926
  appendChildAgentTranscriptEvent(matched, event);
@@ -1952,13 +1946,14 @@ function acceptTranscriptStreamEvent(transcript, event) {
1952
1946
  approvalCallId(event.approval)
1953
1947
  );
1954
1948
  if (matched !== void 0) {
1955
- matched.approval = compact({
1949
+ const approval = {
1956
1950
  id: event.approval.id,
1957
1951
  status: event.approval.status,
1958
- requestedAt: event.approval.requestedAt,
1959
- resolvedAt: event.approval.resolvedAt,
1960
- reason: event.approval.reason
1961
- });
1952
+ requestedAt: event.approval.requestedAt
1953
+ };
1954
+ if (event.approval.resolvedAt !== void 0) approval.resolvedAt = event.approval.resolvedAt;
1955
+ if (event.approval.reason !== void 0) approval.reason = event.approval.reason;
1956
+ matched.approval = approval;
1962
1957
  }
1963
1958
  }
1964
1959
  if (event.type === "tool_question_request") {
@@ -1983,14 +1978,15 @@ function acceptTranscriptStreamEvent(transcript, event) {
1983
1978
  questionCallId(event.question)
1984
1979
  );
1985
1980
  if (matched !== void 0) {
1986
- matched.question = compact({
1981
+ const question = {
1987
1982
  id: event.question.id,
1988
1983
  status: event.question.status,
1989
1984
  requestedAt: event.question.requestedAt,
1990
- answeredAt: event.question.answeredAt,
1991
- questions: event.question.questions,
1992
- answers: event.question.answers
1993
- });
1985
+ questions: event.question.questions
1986
+ };
1987
+ if (event.question.answeredAt !== void 0) question.answeredAt = event.question.answeredAt;
1988
+ if (event.question.answers !== void 0) question.answers = event.question.answers;
1989
+ matched.question = question;
1994
1990
  }
1995
1991
  }
1996
1992
  if (event.type === "final" && event.trace?.traceId !== void 0) {
@@ -2044,51 +2040,56 @@ function appendChildAgentTranscriptEvent(entry, event) {
2044
2040
  function childAgentTranscriptEvent(event) {
2045
2041
  const child = event.event;
2046
2042
  if (child.type === "text_delta") {
2047
- return compact({
2043
+ const entry = {
2048
2044
  kind: "message",
2049
2045
  agentId: event.agentId,
2050
- agentName: event.agentName,
2051
2046
  text: child.delta
2052
- });
2047
+ };
2048
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2049
+ return entry;
2053
2050
  }
2054
2051
  if (child.type === "reasoning_delta") {
2055
- return compact({
2052
+ const entry = {
2056
2053
  kind: "reasoning",
2057
2054
  agentId: event.agentId,
2058
- agentName: event.agentName,
2059
- reasoningId: child.id,
2060
2055
  text: child.delta
2061
- });
2056
+ };
2057
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2058
+ if (child.id !== void 0) entry.reasoningId = child.id;
2059
+ return entry;
2062
2060
  }
2063
2061
  if (child.type === "tool_call") {
2064
- return compact({
2062
+ const entry = {
2065
2063
  kind: "tool",
2066
2064
  agentId: event.agentId,
2067
- agentName: event.agentName,
2068
2065
  toolName: child.toolCall.function.name,
2069
2066
  callId: child.toolCall.callId ?? child.toolCall.id,
2070
2067
  args: formatJson(child.toolCall.function.arguments)
2071
- });
2068
+ };
2069
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2070
+ return entry;
2072
2071
  }
2073
2072
  if (child.type === "tool_result") {
2074
- return compact({
2073
+ const entry = {
2075
2074
  kind: "tool",
2076
2075
  agentId: event.agentId,
2077
- agentName: event.agentName,
2078
- toolName: child.toolName,
2079
- callId: child.toolCallId,
2080
- args: child.args,
2081
- result: child.result,
2082
- structuredResult: child.structuredResult
2083
- });
2076
+ toolName: child.toolName
2077
+ };
2078
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2079
+ if (child.toolCallId !== void 0) entry.callId = child.toolCallId;
2080
+ if (child.args !== void 0) entry.args = child.args;
2081
+ if (child.result !== void 0) entry.result = child.result;
2082
+ if (child.structuredResult !== void 0) entry.structuredResult = child.structuredResult;
2083
+ return entry;
2084
2084
  }
2085
2085
  if (child.type === "error") {
2086
- return compact({
2086
+ const entry = {
2087
2087
  kind: "message",
2088
2088
  agentId: event.agentId,
2089
- agentName: event.agentName,
2090
2089
  text: `Error: ${errorText(child.error)}`
2091
- });
2090
+ };
2091
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2092
+ return entry;
2092
2093
  }
2093
2094
  return void 0;
2094
2095
  }
@@ -2112,13 +2113,14 @@ function findChildAgentToolEvent(childEvents, event) {
2112
2113
  }
2113
2114
  function messageToTranscriptEntry(message, entryId) {
2114
2115
  const role = typeof message === "string" || message.role !== "assistant" ? "user" : "assistant";
2115
- return {
2116
+ const entry = {
2116
2117
  entryId,
2117
2118
  kind: "message",
2118
2119
  role,
2119
- text: extractMessageText(message),
2120
- ...role === "user" ? optionalTranscriptAttachments(message) : {}
2120
+ text: extractMessageText(message)
2121
2121
  };
2122
+ if (role === "user") Object.assign(entry, optionalTranscriptAttachments(message));
2123
+ return entry;
2122
2124
  }
2123
2125
  function appendTranscriptAssistantText(transcript, delta) {
2124
2126
  const last = transcript.at(-1);
@@ -2161,14 +2163,13 @@ function appendTranscriptReasoningText(transcript, delta, reasoningId) {
2161
2163
  last.text = `${last.text}${delta}`;
2162
2164
  return;
2163
2165
  }
2164
- transcript.push(
2165
- compact({
2166
- entryId: transcript.length,
2167
- kind: "reasoning",
2168
- reasoningId,
2169
- text: delta
2170
- })
2171
- );
2166
+ const entry = {
2167
+ entryId: transcript.length,
2168
+ kind: "reasoning",
2169
+ text: delta
2170
+ };
2171
+ if (reasoningId !== void 0) entry.reasoningId = reasoningId;
2172
+ transcript.push(entry);
2172
2173
  }
2173
2174
  function findTranscriptToolEntry(transcript, toolName, callId) {
2174
2175
  for (let index = transcript.length - 1; index >= 0; index -= 1) {
@@ -2221,23 +2222,22 @@ function optionalTranscriptAttachments(message) {
2221
2222
  }
2222
2223
  const attachments = message.content.flatMap((content) => {
2223
2224
  if (content.type === "image") {
2224
- return [
2225
- {
2226
- kind: "image",
2227
- ...content.source.type === "base64" ? { data: content.source.data, mediaType: content.source.mediaType } : { url: content.source.url }
2228
- }
2229
- ];
2225
+ const attachment = { kind: "image" };
2226
+ if (content.source.type === "base64") {
2227
+ attachment.data = content.source.data;
2228
+ attachment.mediaType = content.source.mediaType;
2229
+ } else {
2230
+ attachment.url = content.source.url;
2231
+ }
2232
+ return [attachment];
2230
2233
  }
2231
2234
  if (content.type === "document") {
2232
- return [
2233
- compact({
2234
- kind: "document",
2235
- name: content.source.filename,
2236
- mediaType: content.source.mediaType,
2237
- data: content.source.type === "base64" ? content.source.data : void 0,
2238
- url: content.source.type === "url" ? content.source.url : void 0
2239
- })
2240
- ];
2235
+ const attachment = { kind: "document" };
2236
+ if (content.source.filename !== void 0) attachment.name = content.source.filename;
2237
+ if (content.source.mediaType !== void 0) attachment.mediaType = content.source.mediaType;
2238
+ if (content.source.type === "base64") attachment.data = content.source.data;
2239
+ if (content.source.type === "url") attachment.url = content.source.url;
2240
+ return [attachment];
2241
2241
  }
2242
2242
  return [];
2243
2243
  });
@@ -2295,10 +2295,9 @@ function parseUiRunRequestBody(c, body) {
2295
2295
  };
2296
2296
  }
2297
2297
  const history = messages.slice(0, -1);
2298
- return {
2299
- message,
2300
- ...history.length === 0 ? {} : { history }
2301
- };
2298
+ const request = { message };
2299
+ if (history.length > 0) request.history = history;
2300
+ return request;
2302
2301
  }
2303
2302
  function parseRunRequestOptions(c, body, request) {
2304
2303
  if ("sessionId" in body) {
@@ -2404,14 +2403,23 @@ function sessionCreatedLog(session) {
2404
2403
  category: "session",
2405
2404
  event: "session.created",
2406
2405
  message: "Session created",
2407
- metadata: compact({
2406
+ metadata: {
2408
2407
  agentId: session.agentId,
2409
2408
  hasTitle: session.title !== void 0,
2410
2409
  titleLength: session.title?.length ?? 0
2411
- })
2410
+ }
2412
2411
  };
2413
2412
  }
2414
2413
  function runReceivedLog(props) {
2414
+ const metadata = {
2415
+ agentId: props.agentId,
2416
+ stream: props.stream,
2417
+ message: messageSummary(props.message),
2418
+ hasTrace: props.hasTrace,
2419
+ metadataKeys: Object.keys(props.metadata ?? {})
2420
+ };
2421
+ if (props.maxTurns !== void 0) metadata.maxTurns = props.maxTurns;
2422
+ if (props.toolConcurrency !== void 0) metadata.toolConcurrency = props.toolConcurrency;
2415
2423
  return {
2416
2424
  sessionId: props.sessionId,
2417
2425
  runId: props.runId,
@@ -2419,15 +2427,7 @@ function runReceivedLog(props) {
2419
2427
  category: "api",
2420
2428
  event: "run.received",
2421
2429
  message: "Run request received",
2422
- metadata: compact({
2423
- agentId: props.agentId,
2424
- stream: props.stream,
2425
- message: messageSummary(props.message),
2426
- maxTurns: props.maxTurns,
2427
- toolConcurrency: props.toolConcurrency,
2428
- hasTrace: props.hasTrace,
2429
- metadataKeys: Object.keys(props.metadata ?? {})
2430
- })
2430
+ metadata
2431
2431
  };
2432
2432
  }
2433
2433
  function runStartedLog(session, runId) {
@@ -2438,10 +2438,10 @@ function runStartedLog(session, runId) {
2438
2438
  category: "run",
2439
2439
  event: "run.started",
2440
2440
  message: "Run started",
2441
- metadata: compact({
2441
+ metadata: {
2442
2442
  agentId: session.agentId,
2443
2443
  existingMessageCount: session.messageCount
2444
- })
2444
+ }
2445
2445
  };
2446
2446
  }
2447
2447
  function memoryLoadedLog(session, runId) {
@@ -2452,13 +2452,20 @@ function memoryLoadedLog(session, runId) {
2452
2452
  category: "memory",
2453
2453
  event: "memory.loaded",
2454
2454
  message: "Session memory loaded",
2455
- metadata: compact({
2455
+ metadata: {
2456
2456
  messageCount: session.messageCount,
2457
2457
  transcriptEntries: session.transcript.length
2458
- })
2458
+ }
2459
2459
  };
2460
2460
  }
2461
2461
  function runCompletedLog(props) {
2462
+ const metadata = {
2463
+ durationMs: props.durationMs,
2464
+ outputBytes: byteLength2(props.output)
2465
+ };
2466
+ const usage = usageSummary(props.usage);
2467
+ if (usage !== void 0) metadata.usage = usage;
2468
+ if (props.messageCount !== void 0) metadata.messageCount = props.messageCount;
2462
2469
  return {
2463
2470
  sessionId: props.sessionId,
2464
2471
  runId: props.runId,
@@ -2466,15 +2473,12 @@ function runCompletedLog(props) {
2466
2473
  category: "run",
2467
2474
  event: "run.completed",
2468
2475
  message: "Run completed",
2469
- metadata: compact({
2470
- durationMs: props.durationMs,
2471
- usage: usageSummary(props.usage),
2472
- outputBytes: byteLength2(props.output),
2473
- messageCount: props.messageCount
2474
- })
2476
+ metadata
2475
2477
  };
2476
2478
  }
2477
2479
  function memorySavedLog(props) {
2480
+ const metadata = {};
2481
+ if (props.messageCount !== void 0) metadata.messageCount = props.messageCount;
2478
2482
  return {
2479
2483
  sessionId: props.sessionId,
2480
2484
  runId: props.runId,
@@ -2482,9 +2486,7 @@ function memorySavedLog(props) {
2482
2486
  category: "memory",
2483
2487
  event: "memory.saved",
2484
2488
  message: "Session memory saved",
2485
- metadata: compact({
2486
- messageCount: props.messageCount
2487
- })
2489
+ metadata
2488
2490
  };
2489
2491
  }
2490
2492
  function runFailedLog(sessionId, runId, error, startedAt) {
@@ -2495,10 +2497,10 @@ function runFailedLog(sessionId, runId, error, startedAt) {
2495
2497
  category: "run",
2496
2498
  event: "run.failed",
2497
2499
  message: "Run failed",
2498
- metadata: compact({
2500
+ metadata: {
2499
2501
  durationMs: Date.now() - startedAt,
2500
2502
  error: serializeError(error)
2501
- })
2503
+ }
2502
2504
  };
2503
2505
  }
2504
2506
  function logsFromStreamEvent(props) {
@@ -2512,11 +2514,11 @@ function logsFromStreamEvent(props) {
2512
2514
  category: "prompt",
2513
2515
  event: "prompt.prepared",
2514
2516
  message: `Turn ${event.turn} prompt prepared`,
2515
- metadata: compact({
2517
+ metadata: {
2516
2518
  turn: event.turn,
2517
2519
  prompt: messageSummary(event.prompt),
2518
2520
  historyCount: event.history.length
2519
- })
2521
+ }
2520
2522
  }
2521
2523
  ];
2522
2524
  }
@@ -2529,16 +2531,27 @@ function logsFromStreamEvent(props) {
2529
2531
  category: "tool",
2530
2532
  event: "tool.called",
2531
2533
  message: `Tool ${event.toolCall.function.name} called`,
2532
- metadata: compact({
2534
+ metadata: {
2533
2535
  turn: event.turn,
2534
2536
  toolName: event.toolCall.function.name,
2535
2537
  callId: event.toolCall.callId ?? event.toolCall.id,
2536
2538
  argumentBytes: byteLength2(formatUnknown(event.toolCall.function.arguments))
2537
- })
2539
+ }
2538
2540
  }
2539
2541
  ];
2540
2542
  }
2541
2543
  if (event.type === "tool_result") {
2544
+ const metadata = {
2545
+ turn: event.turn,
2546
+ toolName: event.toolName,
2547
+ argumentBytes: byteLength2(event.args),
2548
+ resultBytes: byteLength2(event.result)
2549
+ };
2550
+ if (event.toolCallId !== void 0) metadata.callId = event.toolCallId;
2551
+ if (event.internalCallId !== void 0) metadata.internalCallId = event.internalCallId;
2552
+ if (event.structuredResult !== void 0) {
2553
+ metadata.structuredResultBytes = byteLength2(JSON.stringify(event.structuredResult));
2554
+ }
2542
2555
  return [
2543
2556
  {
2544
2557
  sessionId,
@@ -2547,19 +2560,17 @@ function logsFromStreamEvent(props) {
2547
2560
  category: "tool",
2548
2561
  event: "tool.completed",
2549
2562
  message: `Tool ${event.toolName} completed`,
2550
- metadata: compact({
2551
- turn: event.turn,
2552
- toolName: event.toolName,
2553
- callId: event.toolCallId,
2554
- internalCallId: event.internalCallId,
2555
- argumentBytes: byteLength2(event.args),
2556
- resultBytes: byteLength2(event.result),
2557
- structuredResultBytes: event.structuredResult === void 0 ? void 0 : byteLength2(JSON.stringify(event.structuredResult))
2558
- })
2563
+ metadata
2559
2564
  }
2560
2565
  ];
2561
2566
  }
2562
2567
  if (event.type === "turn_end") {
2568
+ const metadata = {
2569
+ turn: event.turn,
2570
+ contentCount: event.response.choice.length
2571
+ };
2572
+ const usage = usageSummary(event.response.usage);
2573
+ if (usage !== void 0) metadata.usage = usage;
2563
2574
  return [
2564
2575
  {
2565
2576
  sessionId,
@@ -2568,11 +2579,7 @@ function logsFromStreamEvent(props) {
2568
2579
  category: "model",
2569
2580
  event: "model.turn.completed",
2570
2581
  message: `Model turn ${event.turn} completed`,
2571
- metadata: compact({
2572
- turn: event.turn,
2573
- contentCount: event.response.choice.length,
2574
- usage: usageSummary(event.response.usage)
2575
- })
2582
+ metadata
2576
2583
  }
2577
2584
  ];
2578
2585
  }
@@ -2593,6 +2600,14 @@ function logsFromStreamEvent(props) {
2593
2600
  return [runFailedLog(sessionId, runId, event.error, props.startedAt)];
2594
2601
  }
2595
2602
  if (event.type === "tool_approval_request") {
2603
+ const metadata = {
2604
+ approvalId: event.approval.id,
2605
+ toolName: event.approval.toolName,
2606
+ status: event.approval.status,
2607
+ hasReason: event.approval.reason !== void 0,
2608
+ argumentBytes: byteLength2(event.approval.args)
2609
+ };
2610
+ if (event.approval.callId !== void 0) metadata.callId = event.approval.callId;
2596
2611
  return [
2597
2612
  {
2598
2613
  sessionId,
@@ -2601,18 +2616,18 @@ function logsFromStreamEvent(props) {
2601
2616
  category: "approval",
2602
2617
  event: "approval.requested",
2603
2618
  message: `Approval requested for ${event.approval.toolName}`,
2604
- metadata: compact({
2605
- approvalId: event.approval.id,
2606
- toolName: event.approval.toolName,
2607
- callId: event.approval.callId,
2608
- status: event.approval.status,
2609
- hasReason: event.approval.reason !== void 0,
2610
- argumentBytes: byteLength2(event.approval.args)
2611
- })
2619
+ metadata
2612
2620
  }
2613
2621
  ];
2614
2622
  }
2615
2623
  if (event.type === "tool_approval_result") {
2624
+ const metadata = {
2625
+ approvalId: event.approval.id,
2626
+ toolName: event.approval.toolName,
2627
+ status: event.approval.status,
2628
+ hasReason: event.approval.reason !== void 0
2629
+ };
2630
+ if (event.approval.callId !== void 0) metadata.callId = event.approval.callId;
2616
2631
  return [
2617
2632
  {
2618
2633
  sessionId,
@@ -2621,17 +2636,19 @@ function logsFromStreamEvent(props) {
2621
2636
  category: "approval",
2622
2637
  event: "approval.resolved",
2623
2638
  message: `Approval ${event.approval.status} for ${event.approval.toolName}`,
2624
- metadata: compact({
2625
- approvalId: event.approval.id,
2626
- toolName: event.approval.toolName,
2627
- callId: event.approval.callId,
2628
- status: event.approval.status,
2629
- hasReason: event.approval.reason !== void 0
2630
- })
2639
+ metadata
2631
2640
  }
2632
2641
  ];
2633
2642
  }
2634
2643
  if (event.type === "tool_question_request") {
2644
+ const metadata = {
2645
+ questionId: event.question.id,
2646
+ toolName: event.question.toolName,
2647
+ status: event.question.status,
2648
+ questionCount: event.question.questions.length,
2649
+ argumentBytes: byteLength2(event.question.args)
2650
+ };
2651
+ if (event.question.callId !== void 0) metadata.callId = event.question.callId;
2635
2652
  return [
2636
2653
  {
2637
2654
  sessionId,
@@ -2640,18 +2657,20 @@ function logsFromStreamEvent(props) {
2640
2657
  category: "question",
2641
2658
  event: "question.requested",
2642
2659
  message: `Question requested by ${event.question.toolName}`,
2643
- metadata: compact({
2644
- questionId: event.question.id,
2645
- toolName: event.question.toolName,
2646
- callId: event.question.callId,
2647
- status: event.question.status,
2648
- questionCount: event.question.questions.length,
2649
- argumentBytes: byteLength2(event.question.args)
2650
- })
2660
+ metadata
2651
2661
  }
2652
2662
  ];
2653
2663
  }
2654
2664
  if (event.type === "tool_question_result") {
2665
+ const metadata = {
2666
+ questionId: event.question.id,
2667
+ toolName: event.question.toolName,
2668
+ status: event.question.status,
2669
+ questionCount: event.question.questions.length,
2670
+ argumentBytes: byteLength2(event.question.args),
2671
+ answerCount: event.question.answers?.length ?? 0
2672
+ };
2673
+ if (event.question.callId !== void 0) metadata.callId = event.question.callId;
2655
2674
  return [
2656
2675
  {
2657
2676
  sessionId,
@@ -2660,13 +2679,7 @@ function logsFromStreamEvent(props) {
2660
2679
  category: "question",
2661
2680
  event: "question.answered",
2662
2681
  message: `Question answered for ${event.question.toolName}`,
2663
- metadata: compact({
2664
- questionId: event.question.id,
2665
- toolName: event.question.toolName,
2666
- callId: event.question.callId,
2667
- status: event.question.status,
2668
- answerCount: event.question.answers?.length ?? 0
2669
- })
2682
+ metadata
2670
2683
  }
2671
2684
  ];
2672
2685
  }
@@ -2692,7 +2705,7 @@ function childAgentLog(event, sessionId, runId) {
2692
2705
  category: "tool",
2693
2706
  event: "child_tool.called",
2694
2707
  message: `Child agent ${event.agentName ?? event.agentId} called ${child.toolCall.function.name}`,
2695
- metadata: compact({
2708
+ metadata: {
2696
2709
  parentToolName: event.toolName,
2697
2710
  agentId: event.agentId,
2698
2711
  hasAgentName: event.agentName !== void 0,
@@ -2701,11 +2714,24 @@ function childAgentLog(event, sessionId, runId) {
2701
2714
  toolName: child.toolCall.function.name,
2702
2715
  callId: child.toolCall.callId ?? child.toolCall.id,
2703
2716
  argumentBytes: byteLength2(formatUnknown(child.toolCall.function.arguments))
2704
- })
2717
+ }
2705
2718
  }
2706
2719
  ];
2707
2720
  }
2708
2721
  if (child.type === "tool_result") {
2722
+ const metadata = {
2723
+ parentToolName: event.toolName,
2724
+ agentId: event.agentId,
2725
+ hasAgentName: event.agentName !== void 0,
2726
+ turn: event.turn,
2727
+ childTurn: child.turn,
2728
+ toolName: child.toolName,
2729
+ resultBytes: byteLength2(child.result)
2730
+ };
2731
+ if (child.toolCallId !== void 0) metadata.callId = child.toolCallId;
2732
+ if (child.structuredResult !== void 0) {
2733
+ metadata.structuredResultBytes = byteLength2(JSON.stringify(child.structuredResult));
2734
+ }
2709
2735
  return [
2710
2736
  {
2711
2737
  sessionId,
@@ -2714,17 +2740,7 @@ function childAgentLog(event, sessionId, runId) {
2714
2740
  category: "tool",
2715
2741
  event: "child_tool.completed",
2716
2742
  message: `Child agent ${event.agentName ?? event.agentId} completed ${child.toolName}`,
2717
- metadata: compact({
2718
- parentToolName: event.toolName,
2719
- agentId: event.agentId,
2720
- hasAgentName: event.agentName !== void 0,
2721
- turn: event.turn,
2722
- childTurn: child.turn,
2723
- toolName: child.toolName,
2724
- callId: child.toolCallId,
2725
- resultBytes: byteLength2(child.result),
2726
- structuredResultBytes: child.structuredResult === void 0 ? void 0 : byteLength2(JSON.stringify(child.structuredResult))
2727
- })
2743
+ metadata
2728
2744
  }
2729
2745
  ];
2730
2746
  }
@@ -2737,17 +2753,26 @@ function childAgentLog(event, sessionId, runId) {
2737
2753
  category: "run",
2738
2754
  event: "child_agent.turn_started",
2739
2755
  message: `Child agent ${event.agentName ?? event.agentId} turn ${child.turn} started`,
2740
- metadata: compact({
2756
+ metadata: {
2741
2757
  parentToolName: event.toolName,
2742
2758
  agentId: event.agentId,
2743
2759
  hasAgentName: event.agentName !== void 0,
2744
2760
  childTurn: child.turn,
2745
2761
  historyCount: child.history.length
2746
- })
2762
+ }
2747
2763
  }
2748
2764
  ];
2749
2765
  }
2750
2766
  if (child.type === "final") {
2767
+ const metadata = {
2768
+ parentToolName: event.toolName,
2769
+ agentId: event.agentId,
2770
+ hasAgentName: event.agentName !== void 0,
2771
+ outputBytes: byteLength2(child.output),
2772
+ messageCount: child.messages.length
2773
+ };
2774
+ const usage = usageSummary(child.usage);
2775
+ if (usage !== void 0) metadata.usage = usage;
2751
2776
  return [
2752
2777
  {
2753
2778
  sessionId,
@@ -2756,14 +2781,7 @@ function childAgentLog(event, sessionId, runId) {
2756
2781
  category: "run",
2757
2782
  event: "child_agent.completed",
2758
2783
  message: `Child agent ${event.agentName ?? event.agentId} completed`,
2759
- metadata: compact({
2760
- parentToolName: event.toolName,
2761
- agentId: event.agentId,
2762
- hasAgentName: event.agentName !== void 0,
2763
- usage: usageSummary(child.usage),
2764
- outputBytes: byteLength2(child.output),
2765
- messageCount: child.messages.length
2766
- })
2784
+ metadata
2767
2785
  }
2768
2786
  ];
2769
2787
  }
@@ -2776,12 +2794,12 @@ function childAgentLog(event, sessionId, runId) {
2776
2794
  category: "run",
2777
2795
  event: "child_agent.failed",
2778
2796
  message: `Child agent ${event.agentName ?? event.agentId} failed`,
2779
- metadata: compact({
2797
+ metadata: {
2780
2798
  parentToolName: event.toolName,
2781
2799
  agentId: event.agentId,
2782
2800
  hasAgentName: event.agentName !== void 0,
2783
2801
  error: serializeError(child.error)
2784
- })
2802
+ }
2785
2803
  }
2786
2804
  ];
2787
2805
  }
@@ -2807,13 +2825,20 @@ function usageSummary(value) {
2807
2825
  return void 0;
2808
2826
  }
2809
2827
  const record = value;
2810
- return compact({
2811
- inputTokens: numericValue(record.inputTokens),
2812
- outputTokens: numericValue(record.outputTokens),
2813
- totalTokens: numericValue(record.totalTokens),
2814
- cachedInputTokens: numericValue(record.cachedInputTokens),
2815
- cacheCreationInputTokens: numericValue(record.cacheCreationInputTokens)
2816
- });
2828
+ const summary = {};
2829
+ const inputTokens = numericValue(record.inputTokens);
2830
+ const outputTokens = numericValue(record.outputTokens);
2831
+ const totalTokens = numericValue(record.totalTokens);
2832
+ const cachedInputTokens = numericValue(record.cachedInputTokens);
2833
+ const cacheCreationInputTokens = numericValue(record.cacheCreationInputTokens);
2834
+ if (inputTokens !== void 0) summary.inputTokens = inputTokens;
2835
+ if (outputTokens !== void 0) summary.outputTokens = outputTokens;
2836
+ if (totalTokens !== void 0) summary.totalTokens = totalTokens;
2837
+ if (cachedInputTokens !== void 0) summary.cachedInputTokens = cachedInputTokens;
2838
+ if (cacheCreationInputTokens !== void 0) {
2839
+ summary.cacheCreationInputTokens = cacheCreationInputTokens;
2840
+ }
2841
+ return summary;
2817
2842
  }
2818
2843
  function numericValue(value) {
2819
2844
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -2937,25 +2962,27 @@ async function recordRunReceived(props) {
2937
2962
  if (props.session === void 0) {
2938
2963
  return;
2939
2964
  }
2940
- await appendSessionLog(
2941
- props.store,
2942
- runReceivedLog({
2943
- sessionId: props.session.id,
2944
- runId: props.runId,
2945
- agentId: props.agentId,
2946
- message: props.body.message,
2947
- stream: props.body.stream === true,
2948
- ...compact({ maxTurns: props.body.maxTurns }),
2949
- ...compact({ toolConcurrency: props.body.toolConcurrency }),
2950
- hasTrace: props.body.trace !== void 0,
2951
- ...props.body.metadata === void 0 && props.selectedModel.ref === void 0 ? {} : {
2952
- metadata: {
2953
- ...props.body.metadata ?? {},
2954
- ...props.selectedModel.ref === void 0 ? {} : { [STUDIO_MODEL_METADATA_KEY]: props.selectedModel.ref }
2955
- }
2956
- }
2957
- })
2958
- );
2965
+ const input = {
2966
+ sessionId: props.session.id,
2967
+ runId: props.runId,
2968
+ agentId: props.agentId,
2969
+ message: props.body.message,
2970
+ stream: props.body.stream === true,
2971
+ hasTrace: props.body.trace !== void 0
2972
+ };
2973
+ if (props.body.maxTurns !== void 0) input.maxTurns = props.body.maxTurns;
2974
+ if (props.body.toolConcurrency !== void 0) {
2975
+ input.toolConcurrency = props.body.toolConcurrency;
2976
+ }
2977
+ if (props.body.metadata !== void 0 || props.selectedModel.ref !== void 0) {
2978
+ const metadata = {};
2979
+ Object.assign(metadata, props.body.metadata);
2980
+ if (props.selectedModel.ref !== void 0) {
2981
+ metadata[STUDIO_MODEL_METADATA_KEY] = props.selectedModel.ref;
2982
+ }
2983
+ input.metadata = metadata;
2984
+ }
2985
+ await appendSessionLog(props.store, runReceivedLog(input));
2959
2986
  }
2960
2987
  async function recordSelectedModelWarnings(props) {
2961
2988
  if (props.session === void 0 || props.selectedModel.ref === void 0) {
@@ -2973,19 +3000,18 @@ async function recordSelectedModelWarnings(props) {
2973
3000
  });
2974
3001
  }
2975
3002
  if (sessionModelRef(props.session.metadata) !== props.selectedModel.ref) {
2976
- await props.store?.updateSessionMetadata?.(props.session.id, {
2977
- ...props.session.metadata ?? {},
2978
- [STUDIO_MODEL_METADATA_KEY]: props.selectedModel.ref
2979
- });
3003
+ const metadata = {};
3004
+ Object.assign(metadata, props.session.metadata);
3005
+ metadata[STUDIO_MODEL_METADATA_KEY] = props.selectedModel.ref;
3006
+ await props.store?.updateSessionMetadata?.(props.session.id, metadata);
2980
3007
  }
2981
3008
  }
2982
3009
  function runMemoryMetadata(agentId, body, selectedModel, runId) {
2983
- return {
2984
- agentId,
2985
- ...body.metadata ?? {},
2986
- ...selectedModel.ref === void 0 ? {} : { [STUDIO_MODEL_METADATA_KEY]: selectedModel.ref },
2987
- studioRunId: runId
2988
- };
3010
+ const metadata = { agentId };
3011
+ Object.assign(metadata, body.metadata);
3012
+ if (selectedModel.ref !== void 0) metadata[STUDIO_MODEL_METADATA_KEY] = selectedModel.ref;
3013
+ metadata.studioRunId = runId;
3014
+ return metadata;
2989
3015
  }
2990
3016
  function createRunRequest(props) {
2991
3017
  const request = props.session !== void 0 ? props.runAgent.memory === void 0 ? props.runAgent.prompt([...props.session.messages, props.promptMessage]) : props.runAgent.session(props.session.id, { metadata: props.memoryMetadata }).prompt(props.body.message) : props.runAgent.prompt(
@@ -3006,24 +3032,24 @@ function createRunRequest(props) {
3006
3032
  }
3007
3033
  function handleStreamingAgentRun(c, run, props) {
3008
3034
  const runtimeEvents = new AsyncEventQueue();
3009
- run.request.approvals(
3010
- props.approvalRuntime.createApprovals({
3011
- runId: run.runId,
3012
- agentId: run.agentId,
3013
- ...compact({ sessionId: run.session?.id }),
3014
- ...compact({ metadata: run.body.metadata }),
3015
- emit: (event) => runtimeEvents.push(event)
3016
- })
3017
- );
3035
+ const approvalContext = {
3036
+ runId: run.runId,
3037
+ agentId: run.agentId,
3038
+ emit: (event) => runtimeEvents.push(event)
3039
+ };
3040
+ if (run.session !== void 0) approvalContext.sessionId = run.session.id;
3041
+ if (run.body.metadata !== void 0) approvalContext.metadata = run.body.metadata;
3042
+ run.request.approvals(props.approvalRuntime.createApprovals(approvalContext));
3043
+ const questionContext = {
3044
+ runId: run.runId,
3045
+ agentId: run.agentId,
3046
+ emit: (event) => runtimeEvents.push(event)
3047
+ };
3048
+ if (run.session !== void 0) questionContext.sessionId = run.session.id;
3049
+ if (run.body.metadata !== void 0) questionContext.metadata = run.body.metadata;
3018
3050
  const effectiveHook = composeHooks(
3019
3051
  run.runAgent.hook,
3020
- props.questionRuntime.createHook({
3021
- runId: run.runId,
3022
- agentId: run.agentId,
3023
- ...compact({ sessionId: run.session?.id }),
3024
- ...compact({ metadata: run.body.metadata }),
3025
- emit: (event) => runtimeEvents.push(event)
3026
- })
3052
+ props.questionRuntime.createHook(questionContext)
3027
3053
  );
3028
3054
  if (effectiveHook !== void 0) {
3029
3055
  run.request.requestHook(effectiveHook);
@@ -3061,23 +3087,23 @@ async function startBufferedSessionRun(run, props) {
3061
3087
  await appendSessionLog(run.sessionStore, runStartedLog(run.session, run.runId));
3062
3088
  await appendSessionLog(run.sessionStore, memoryLoadedLog(run.session, run.runId));
3063
3089
  }
3090
+ const questionContext = {
3091
+ runId: run.runId,
3092
+ agentId: run.agentId
3093
+ };
3094
+ if (run.session !== void 0) questionContext.sessionId = run.session.id;
3095
+ if (run.body.metadata !== void 0) questionContext.metadata = run.body.metadata;
3064
3096
  const effectiveHook = composeHooks(
3065
3097
  run.runAgent.hook,
3066
- props.questionRuntime.createHook({
3067
- runId: run.runId,
3068
- agentId: run.agentId,
3069
- ...compact({ sessionId: run.session?.id }),
3070
- ...compact({ metadata: run.body.metadata })
3071
- })
3072
- );
3073
- run.request.approvals(
3074
- props.approvalRuntime.createApprovals({
3075
- runId: run.runId,
3076
- agentId: run.agentId,
3077
- ...compact({ sessionId: run.session?.id }),
3078
- ...compact({ metadata: run.body.metadata })
3079
- })
3098
+ props.questionRuntime.createHook(questionContext)
3080
3099
  );
3100
+ const approvalContext = {
3101
+ runId: run.runId,
3102
+ agentId: run.agentId
3103
+ };
3104
+ if (run.session !== void 0) approvalContext.sessionId = run.session.id;
3105
+ if (run.body.metadata !== void 0) approvalContext.metadata = run.body.metadata;
3106
+ run.request.approvals(props.approvalRuntime.createApprovals(approvalContext));
3081
3107
  if (effectiveHook !== void 0) {
3082
3108
  run.request.requestHook(effectiveHook);
3083
3109
  }
@@ -3251,10 +3277,8 @@ async function parseApprovalDecisionRequest(c) {
3251
3277
  if ("reason" in body && typeof body.reason !== "string") {
3252
3278
  return { error: errorResponse(c, 400, "bad_request", "reason must be a string") };
3253
3279
  }
3254
- return compact({
3255
- approved: body.approved,
3256
- reason: typeof body.reason === "string" && body.reason.trim().length > 0 ? body.reason.trim() : void 0
3257
- });
3280
+ const reason = typeof body.reason === "string" && body.reason.trim().length > 0 ? body.reason.trim() : void 0;
3281
+ return approvalDecision(body.approved, reason);
3258
3282
  }
3259
3283
  function createApprovalRuntime() {
3260
3284
  const approvals = /* @__PURE__ */ new Map();
@@ -3263,19 +3287,18 @@ function createApprovalRuntime() {
3263
3287
  createApprovals(context) {
3264
3288
  return {
3265
3289
  async handler(request) {
3266
- const decision = await requestApproval(
3267
- approvals,
3268
- context,
3269
- compact({
3270
- toolName: request.toolName,
3271
- toolCallId: request.toolCallId,
3272
- internalCallId: request.internalCallId,
3273
- args: request.rawArgs,
3274
- reason: request.reason,
3275
- rejectMessage: request.rejectMessage
3276
- })
3277
- );
3278
- return decision.approved ? compact({ approved: true, reason: decision.reason }) : compact({ approved: false, reason: decision.reason });
3290
+ const approvalRequest = {
3291
+ toolName: request.toolName,
3292
+ internalCallId: request.internalCallId,
3293
+ args: request.rawArgs
3294
+ };
3295
+ if (request.toolCallId !== void 0) approvalRequest.toolCallId = request.toolCallId;
3296
+ if (request.reason !== void 0) approvalRequest.reason = request.reason;
3297
+ if (request.rejectMessage !== void 0) {
3298
+ approvalRequest.rejectMessage = request.rejectMessage;
3299
+ }
3300
+ const decision = await requestApproval(approvals, context, approvalRequest);
3301
+ return approvalDecision(decision.approved, decision.reason);
3279
3302
  }
3280
3303
  };
3281
3304
  },
@@ -3311,16 +3334,11 @@ function createApprovalRuntime() {
3311
3334
  const resolved = resolveApproval(
3312
3335
  approval,
3313
3336
  decision.approved ? "approved" : "rejected",
3314
- compact({ reason })
3337
+ reason === void 0 ? {} : { reason }
3315
3338
  );
3316
3339
  approvals.set(id, resolved);
3317
3340
  approval.emit?.({ type: "tool_approval_result", approval: resolved });
3318
- approval.resolve(
3319
- compact({
3320
- approved: decision.approved,
3321
- reason
3322
- })
3323
- );
3341
+ approval.resolve(approvalDecision(decision.approved, reason));
3324
3342
  return publicApproval(resolved);
3325
3343
  }
3326
3344
  };
@@ -3328,35 +3346,28 @@ function createApprovalRuntime() {
3328
3346
  async function requestApproval(approvals, context, request) {
3329
3347
  const id = globalThis.crypto.randomUUID();
3330
3348
  const approval = {
3331
- ...compact({
3332
- id,
3333
- runId: context.runId,
3334
- agentId: context.agentId,
3335
- sessionId: context.sessionId,
3336
- toolName: request.toolName,
3337
- callId: request.toolCallId,
3338
- internalCallId: request.internalCallId,
3339
- args: request.args,
3340
- status: "pending",
3341
- requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
3342
- reason: request.reason,
3343
- rejectMessage: request.rejectMessage,
3344
- emit: context.emit
3345
- }),
3349
+ id,
3350
+ runId: context.runId,
3351
+ agentId: context.agentId,
3352
+ toolName: request.toolName,
3353
+ internalCallId: request.internalCallId,
3354
+ args: request.args,
3355
+ status: "pending",
3356
+ requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
3346
3357
  resolve: () => {
3347
3358
  }
3348
3359
  };
3360
+ if (context.sessionId !== void 0) approval.sessionId = context.sessionId;
3361
+ if (request.toolCallId !== void 0) approval.callId = request.toolCallId;
3362
+ if (request.reason !== void 0) approval.reason = request.reason;
3363
+ if (request.rejectMessage !== void 0) approval.rejectMessage = request.rejectMessage;
3364
+ if (context.emit !== void 0) approval.emit = context.emit;
3349
3365
  const decision = new Promise((resolve2) => {
3350
3366
  approval.resolve = (decision2) => {
3351
3367
  const current = approvals.get(id);
3352
3368
  if (!isPendingApproval(current)) {
3353
3369
  if (current !== void 0) {
3354
- resolve2(
3355
- compact({
3356
- approved: current.status === "approved",
3357
- reason: current.reason
3358
- })
3359
- );
3370
+ resolve2(approvalDecision(current.status === "approved", current.reason));
3360
3371
  }
3361
3372
  return;
3362
3373
  }
@@ -3364,16 +3375,11 @@ async function requestApproval(approvals, context, request) {
3364
3375
  const resolved = resolveApproval(
3365
3376
  current,
3366
3377
  decision2.approved ? "approved" : "rejected",
3367
- compact({ reason })
3378
+ reason === void 0 ? {} : { reason }
3368
3379
  );
3369
3380
  approvals.set(id, resolved);
3370
3381
  context.emit?.({ type: "tool_approval_result", approval: resolved });
3371
- resolve2(
3372
- compact({
3373
- approved: decision2.approved,
3374
- reason
3375
- })
3376
- );
3382
+ resolve2(approvalDecision(decision2.approved, reason));
3377
3383
  };
3378
3384
  });
3379
3385
  approvals.set(id, approval);
@@ -3384,14 +3390,18 @@ function isPendingApproval(approval) {
3384
3390
  return approval !== void 0 && approval.status === "pending" && "resolve" in approval;
3385
3391
  }
3386
3392
  function resolveApproval(approval, status, options = {}) {
3387
- return publicApproval({
3393
+ const resolved = {
3388
3394
  ...approval,
3389
- ...compact({
3390
- status,
3391
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
3392
- reason: options.reason
3393
- })
3394
- });
3395
+ status,
3396
+ resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
3397
+ };
3398
+ if (options.reason !== void 0) resolved.reason = options.reason;
3399
+ return publicApproval(resolved);
3400
+ }
3401
+ function approvalDecision(approved, reason) {
3402
+ const decision = { approved };
3403
+ if (reason !== void 0) decision.reason = reason;
3404
+ return decision;
3395
3405
  }
3396
3406
  function publicApproval(approval) {
3397
3407
  const { emit, rejectMessage, resolve: resolve2, ...rest } = approval;
@@ -3407,18 +3417,19 @@ var PREVIEW_VALUE_MAX_LENGTH = 500;
3407
3417
  function evalConfig(suite) {
3408
3418
  const casePreviews = suite.cases.slice(0, CASE_PREVIEW_LIMIT).map(casePreview);
3409
3419
  const metricSummaries = suite.metrics.map(metricSummary);
3410
- return compact({
3420
+ const config = {
3411
3421
  id: suite.id ?? suite.name,
3412
3422
  name: suite.name,
3413
- description: suite.description,
3414
3423
  caseCount: suite.cases.length,
3415
3424
  metricNames: suite.metrics.map((metric) => metric.name),
3416
3425
  casePreviewCount: casePreviews.length,
3417
3426
  casePreviews,
3418
- metricSummaries,
3419
- concurrency: suite.concurrency,
3420
- metadata: suite.metadata
3421
- });
3427
+ metricSummaries
3428
+ };
3429
+ if (suite.description !== void 0) config.description = suite.description;
3430
+ if (suite.concurrency !== void 0) config.concurrency = suite.concurrency;
3431
+ if (suite.metadata !== void 0) config.metadata = suite.metadata;
3432
+ return config;
3422
3433
  }
3423
3434
  function casePreview(testCase, index) {
3424
3435
  if (!isRecord2(testCase)) {
@@ -3427,24 +3438,29 @@ function casePreview(testCase, index) {
3427
3438
  input: previewValue(testCase)
3428
3439
  };
3429
3440
  }
3430
- return compact({
3431
- id: typeof testCase.id === "string" && testCase.id.length > 0 ? testCase.id : `case-${index + 1}`,
3432
- input: "input" in testCase ? previewValue(testCase.input) : void 0,
3433
- expected: "expected" in testCase ? previewValue(testCase.expected) : void 0,
3434
- metadataKeys: metadataKeys(testCase.metadata)
3435
- });
3441
+ const preview = {
3442
+ id: typeof testCase.id === "string" && testCase.id.length > 0 ? testCase.id : `case-${index + 1}`
3443
+ };
3444
+ if ("input" in testCase) preview.input = previewValue(testCase.input);
3445
+ if ("expected" in testCase) preview.expected = previewValue(testCase.expected);
3446
+ const keys = metadataKeys(testCase.metadata);
3447
+ if (keys !== void 0) preview.metadataKeys = keys;
3448
+ return preview;
3436
3449
  }
3437
3450
  function metricSummary(metric, index) {
3438
3451
  if (!isRecord2(metric)) {
3439
3452
  return { name: `metric-${index + 1}` };
3440
3453
  }
3441
- return compact({
3442
- name: typeof metric.name === "string" && metric.name.length > 0 ? metric.name : `metric-${index + 1}`,
3443
- dataType: metricDataType(metric.dataType),
3444
- configId: typeof metric.configId === "string" ? metric.configId : void 0,
3445
- scoreConfigId: typeof metric.scoreConfigId === "string" ? metric.scoreConfigId : void 0,
3446
- metadataKeys: metadataKeys(metric.metadata)
3447
- });
3454
+ const summary = {
3455
+ name: typeof metric.name === "string" && metric.name.length > 0 ? metric.name : `metric-${index + 1}`
3456
+ };
3457
+ const dataType = metricDataType(metric.dataType);
3458
+ if (dataType !== void 0) summary.dataType = dataType;
3459
+ if (typeof metric.configId === "string") summary.configId = metric.configId;
3460
+ if (typeof metric.scoreConfigId === "string") summary.scoreConfigId = metric.scoreConfigId;
3461
+ const keys = metadataKeys(metric.metadata);
3462
+ if (keys !== void 0) summary.metadataKeys = keys;
3463
+ return summary;
3448
3464
  }
3449
3465
  function previewValue(value) {
3450
3466
  const jsonValue = toJsonValue(value);
@@ -3489,11 +3505,10 @@ function approvalMetadata(tool) {
3489
3505
  return { required: false };
3490
3506
  }
3491
3507
  const policy = approval;
3492
- return {
3493
- required: true,
3494
- ...typeof policy.reason === "string" ? { reason: policy.reason } : {},
3495
- ...typeof policy.rejectMessage === "string" ? { rejectMessage: policy.rejectMessage } : {}
3496
- };
3508
+ const metadata = { required: true };
3509
+ if (typeof policy.reason === "string") metadata.reason = policy.reason;
3510
+ if (typeof policy.rejectMessage === "string") metadata.rejectMessage = policy.rejectMessage;
3511
+ return metadata;
3497
3512
  }
3498
3513
  function mcpServerName(tool) {
3499
3514
  const metadata = tool[MCP_TOOL_METADATA_KEY];
@@ -3514,22 +3529,21 @@ function runnerId(options) {
3514
3529
  function agentConfig(agent) {
3515
3530
  const name = agent.name ?? agent.agent.name;
3516
3531
  const description = agent.description ?? agent.agent.description;
3517
- return compact({
3532
+ const config = {
3518
3533
  id: agent.id,
3519
- name,
3520
- description,
3521
- quickPrompts: agent.quickPrompts ?? [],
3522
- metadata: agent.metadata
3523
- });
3534
+ quickPrompts: agent.quickPrompts ?? []
3535
+ };
3536
+ if (name !== void 0) config.name = name;
3537
+ if (description !== void 0) config.description = description;
3538
+ if (agent.metadata !== void 0) config.metadata = agent.metadata;
3539
+ return config;
3524
3540
  }
3525
3541
  function agentRuntimeSummary(agent) {
3526
3542
  const tools = agentToolItems(agent);
3527
3543
  const name = agent.name ?? agent.agent.name;
3528
3544
  const description = agent.description ?? agent.agent.description;
3529
- return compact({
3545
+ const summary = {
3530
3546
  id: agent.id,
3531
- name,
3532
- description,
3533
3547
  model: toJsonValue2(agent.agent.model),
3534
3548
  toolCount: tools.length,
3535
3549
  staticToolCount: tools.filter((item) => item.source === "static").length,
@@ -3541,35 +3555,37 @@ function agentRuntimeSummary(agent) {
3541
3555
  observerCount: agent.agent.observers.length,
3542
3556
  hasMemory: agent.agent.memory !== void 0,
3543
3557
  hasHook: agent.agent.hook !== void 0,
3544
- hasOutputSchema: agent.agent.outputSchema !== void 0,
3545
- defaultMaxTurns: agent.agent.defaultMaxTurns,
3546
- metadata: agent.metadata
3547
- });
3558
+ hasOutputSchema: agent.agent.outputSchema !== void 0
3559
+ };
3560
+ if (name !== void 0) summary.name = name;
3561
+ if (description !== void 0) summary.description = description;
3562
+ if (agent.agent.defaultMaxTurns !== void 0) {
3563
+ summary.defaultMaxTurns = agent.agent.defaultMaxTurns;
3564
+ }
3565
+ if (agent.metadata !== void 0) summary.metadata = agent.metadata;
3566
+ return summary;
3548
3567
  }
3549
3568
  function pipelineConfig(pipeline) {
3550
3569
  const graph = pipeline.pipeline.graph();
3551
3570
  const stageNodes = graph.nodes.filter((node) => node.kind !== "input" && node.kind !== "output");
3552
- return compact({
3571
+ const config = {
3553
3572
  id: pipeline.id,
3554
- name: pipeline.name,
3555
- description: pipeline.description,
3556
- metadata: pipeline.metadata,
3557
3573
  stageCount: stageNodes.length,
3558
3574
  edgeCount: graph.edges.length,
3559
3575
  hasParallelStages: graph.nodes.some((node) => node.kind === "parallel"),
3560
3576
  agentCount: graph.nodes.filter((node) => node.kind === "agent").length,
3561
3577
  extractorCount: graph.nodes.filter((node) => node.kind === "extractor").length
3562
- });
3578
+ };
3579
+ if (pipeline.name !== void 0) config.name = pipeline.name;
3580
+ if (pipeline.description !== void 0) config.description = pipeline.description;
3581
+ if (pipeline.metadata !== void 0) config.metadata = pipeline.metadata;
3582
+ return config;
3563
3583
  }
3564
3584
  function buildConfig(options, agents, pipelines, stores) {
3565
3585
  const models = options.models === void 0 ? void 0 : studioModelsConfig(createStudioModelRegistry(options.models), agents);
3566
- return compact({
3586
+ const config = {
3567
3587
  id: runnerId(options),
3568
- name: options.name,
3569
- description: options.description,
3570
- version: options.version,
3571
3588
  agents: agents.map(agentConfig),
3572
- models,
3573
3589
  pipelines: pipelines.map(pipelineConfig),
3574
3590
  evals: options.evals.map(evalConfig),
3575
3591
  chat: {
@@ -3577,7 +3593,12 @@ function buildConfig(options, agents, pipelines, stores) {
3577
3593
  },
3578
3594
  capabilities: capabilityConfig(options, agents, pipelines, stores),
3579
3595
  unsupportedCapabilities: unsupportedCapabilities(stores)
3580
- });
3596
+ };
3597
+ if (options.name !== void 0) config.name = options.name;
3598
+ if (options.description !== void 0) config.description = options.description;
3599
+ if (options.version !== void 0) config.version = options.version;
3600
+ if (models !== void 0) config.models = models;
3601
+ return config;
3581
3602
  }
3582
3603
  function capabilityConfig(_options, agents, pipelines, stores) {
3583
3604
  const capabilities = {
@@ -3619,10 +3640,10 @@ function capabilityConfig(_options, agents, pipelines, stores) {
3619
3640
  return capabilities;
3620
3641
  }
3621
3642
  function unsupportedCapabilities(stores) {
3622
- return [
3623
- ...stores.sessions === void 0 ? ["sessions"] : [],
3624
- ...stores.traces === void 0 ? ["traces"] : []
3625
- ];
3643
+ const capabilities = [];
3644
+ if (stores.sessions === void 0) capabilities.push("sessions");
3645
+ if (stores.traces === void 0) capabilities.push("traces");
3646
+ return capabilities;
3626
3647
  }
3627
3648
  function toJsonValue2(value) {
3628
3649
  return serializeUnknown(value);
@@ -3655,10 +3676,9 @@ function registerEvalRoutes(app, props) {
3655
3676
  }
3656
3677
  const runId = globalThis.crypto.randomUUID();
3657
3678
  const startedAt = Date.now();
3658
- const result = await runEvalSuite({
3659
- ...suite,
3660
- ...compact({ concurrency: body.concurrency })
3661
- });
3679
+ const runOptions = { ...suite };
3680
+ if (body.concurrency !== void 0) runOptions.concurrency = body.concurrency;
3681
+ const result = await runEvalSuite(runOptions);
3662
3682
  const endedAt = Date.now();
3663
3683
  const jsonResult = toJsonValue(result);
3664
3684
  const response = {
@@ -3733,18 +3753,19 @@ function registerKnowledgeRoutes(app, props) {
3733
3753
  }
3734
3754
  async function agentKnowledgeConfig(agent) {
3735
3755
  const agentName = agent.name ?? agent.agent.name;
3736
- return {
3756
+ const config = {
3737
3757
  agentId: agent.id,
3738
- ...compact({ agentName }),
3739
3758
  sources: await knowledgeSources(agent),
3740
- staticContext: agent.agent.staticContext.map((document) => ({
3741
- id: document.id,
3742
- text: document.text,
3743
- ...compact({
3744
- additionalProps: document.additionalProps !== void 0 ? jsonObjectFromRecord(document.additionalProps) : void 0
3745
- })
3746
- }))
3759
+ staticContext: agent.agent.staticContext.map((document) => {
3760
+ const item = { id: document.id, text: document.text };
3761
+ if (document.additionalProps !== void 0) {
3762
+ item.additionalProps = jsonObjectFromRecord(document.additionalProps);
3763
+ }
3764
+ return item;
3765
+ })
3747
3766
  };
3767
+ if (agentName !== void 0) config.agentName = agentName;
3768
+ return config;
3748
3769
  }
3749
3770
  async function knowledgeSources(agent) {
3750
3771
  const sources = [
@@ -3761,34 +3782,40 @@ async function knowledgeSources(agent) {
3761
3782
  agent.agent.dynamicContexts.map(async (registration, index) => {
3762
3783
  const inspect = inspectFn(registration.index);
3763
3784
  const count = await inspectableCount(inspect, registration.options.filter);
3764
- return {
3785
+ const source = {
3765
3786
  sourceId: dynamicContextSourceId(index),
3766
3787
  kind: "dynamic_context",
3767
3788
  label: `Dynamic context ${index + 1}`,
3768
3789
  count: 1,
3769
3790
  registrationIndex: index,
3770
3791
  topK: registration.options.topK,
3771
- ...compact({ threshold: registration.options.threshold }),
3772
- inspectable: inspect !== void 0,
3773
- ...compact({ itemCount: count })
3792
+ inspectable: inspect !== void 0
3774
3793
  };
3794
+ if (registration.options.threshold !== void 0) {
3795
+ source.threshold = registration.options.threshold;
3796
+ }
3797
+ if (count !== void 0) source.itemCount = count;
3798
+ return source;
3775
3799
  })
3776
3800
  );
3777
3801
  const dynamicToolSources = await Promise.all(
3778
3802
  agent.agent.dynamicTools.map(async (registration, index) => {
3779
3803
  const inspect = inspectFn(registration.index);
3780
3804
  const count = await inspectableCount(inspect, registration.options.filter);
3781
- return {
3805
+ const source = {
3782
3806
  sourceId: dynamicToolsSourceId(index),
3783
3807
  kind: "dynamic_tools",
3784
3808
  label: `Dynamic tools ${index + 1}`,
3785
3809
  count: 1,
3786
3810
  registrationIndex: index,
3787
3811
  topK: registration.options.topK,
3788
- ...compact({ threshold: registration.options.threshold }),
3789
- inspectable: inspect !== void 0,
3790
- ...compact({ itemCount: count })
3812
+ inspectable: inspect !== void 0
3791
3813
  };
3814
+ if (registration.options.threshold !== void 0) {
3815
+ source.threshold = registration.options.threshold;
3816
+ }
3817
+ if (count !== void 0) source.itemCount = count;
3818
+ return source;
3792
3819
  })
3793
3820
  );
3794
3821
  return [...sources, ...dynamicContextSources, ...dynamicToolSources];
@@ -3819,14 +3846,16 @@ async function knowledgeItemsPage(agent, sourceId, request) {
3819
3846
  cursor: request.cursor,
3820
3847
  filter: registration.options.filter
3821
3848
  });
3822
- return {
3849
+ const result = {
3823
3850
  agentId: agent.id,
3824
3851
  sourceId,
3825
3852
  kind: "dynamic_context",
3826
3853
  inspectable: true,
3827
- items: page.items.map((item) => dynamicContextItem(item)),
3828
- ...compact({ nextCursor: page.nextCursor, totalCount: page.totalCount })
3854
+ items: page.items.map((item) => dynamicContextItem(item))
3829
3855
  };
3856
+ if (page.nextCursor !== void 0) result.nextCursor = page.nextCursor;
3857
+ if (page.totalCount !== void 0) result.totalCount = page.totalCount;
3858
+ return result;
3830
3859
  }
3831
3860
  const dynamicToolsIndex = dynamicSourceIndex(sourceId, "dynamic_tools");
3832
3861
  if (dynamicToolsIndex !== void 0) {
@@ -3843,14 +3872,16 @@ async function knowledgeItemsPage(agent, sourceId, request) {
3843
3872
  cursor: request.cursor,
3844
3873
  filter: registration.options.filter
3845
3874
  });
3846
- return {
3875
+ const result = {
3847
3876
  agentId: agent.id,
3848
3877
  sourceId,
3849
3878
  kind: "dynamic_tools",
3850
3879
  inspectable: true,
3851
- items: page.items.map((item) => dynamicToolItem(item)),
3852
- ...compact({ nextCursor: page.nextCursor, totalCount: page.totalCount })
3880
+ items: page.items.map((item) => dynamicToolItem(item))
3853
3881
  };
3882
+ if (page.nextCursor !== void 0) result.nextCursor = page.nextCursor;
3883
+ if (page.totalCount !== void 0) result.totalCount = page.totalCount;
3884
+ return result;
3854
3885
  }
3855
3886
  return void 0;
3856
3887
  }
@@ -3865,24 +3896,26 @@ function staticKnowledgeItemsPage(agent, request) {
3865
3896
  const start = Math.max(0, Math.trunc(Number(request.cursor ?? "0")));
3866
3897
  const page = agent.agent.staticContext.slice(start, start + request.limit);
3867
3898
  const nextOffset = start + page.length;
3868
- return {
3899
+ const result = {
3869
3900
  agentId: agent.id,
3870
3901
  sourceId: staticSourceId(),
3871
3902
  kind: "static_context",
3872
3903
  inspectable: true,
3873
- items: page.map((document) => ({
3874
- id: document.id,
3875
- kind: "static_context",
3876
- text: document.text,
3877
- ...compact({
3878
- metadata: document.additionalProps !== void 0 ? jsonObjectFromRecord(document.additionalProps) : void 0
3879
- })
3880
- })),
3881
- ...compact({
3882
- nextCursor: nextOffset < agent.agent.staticContext.length ? String(nextOffset) : void 0
3904
+ items: page.map((document) => {
3905
+ const item = {
3906
+ id: document.id,
3907
+ kind: "static_context",
3908
+ text: document.text
3909
+ };
3910
+ if (document.additionalProps !== void 0) {
3911
+ item.metadata = jsonObjectFromRecord(document.additionalProps);
3912
+ }
3913
+ return item;
3883
3914
  }),
3884
3915
  totalCount: agent.agent.staticContext.length
3885
3916
  };
3917
+ if (nextOffset < agent.agent.staticContext.length) result.nextCursor = String(nextOffset);
3918
+ return result;
3886
3919
  }
3887
3920
  function nonInspectablePage(agentId, sourceId, kind) {
3888
3921
  return {
@@ -3896,31 +3929,30 @@ function nonInspectablePage(agentId, sourceId, kind) {
3896
3929
  }
3897
3930
  function dynamicContextItem(item) {
3898
3931
  const text = isRecord3(item.document) && typeof item.document.text === "string" ? item.document.text : typeof item.document === "string" ? item.document : void 0;
3899
- return {
3932
+ const result = {
3900
3933
  id: item.id,
3901
- kind: "dynamic_context",
3902
- ...text === void 0 ? { document: toJsonValue(item.document) } : { text },
3903
- ...compact({
3904
- metadata: item.metadata !== void 0 ? jsonObjectFromRecord(item.metadata) : void 0
3905
- })
3934
+ kind: "dynamic_context"
3906
3935
  };
3936
+ if (text === void 0) result.document = toJsonValue(item.document);
3937
+ else result.text = text;
3938
+ if (item.metadata !== void 0) result.metadata = jsonObjectFromRecord(item.metadata);
3939
+ return result;
3907
3940
  }
3908
3941
  function dynamicToolItem(item) {
3909
3942
  const document = isRecord3(item.document) ? item.document : {};
3910
3943
  const definition = isRecord3(document.definition) ? document.definition : {};
3911
3944
  const toolName = typeof document.toolName === "string" ? document.toolName : typeof definition.name === "string" ? definition.name : item.id;
3912
3945
  const description = typeof definition.description === "string" ? definition.description : "";
3913
- return {
3946
+ const result = {
3914
3947
  id: item.id,
3915
3948
  kind: "dynamic_tool",
3916
3949
  toolName,
3917
3950
  description,
3918
3951
  parameterKeys: parameterKeys(definition.parameters),
3919
- document: toJsonValue(item.document),
3920
- ...compact({
3921
- metadata: item.metadata !== void 0 ? jsonObjectFromRecord(item.metadata) : void 0
3922
- })
3952
+ document: toJsonValue(item.document)
3923
3953
  };
3954
+ if (item.metadata !== void 0) result.metadata = jsonObjectFromRecord(item.metadata);
3955
+ return result;
3924
3956
  }
3925
3957
  function parameterKeys(parameters) {
3926
3958
  if (!isRecord3(parameters) || !isRecord3(parameters.properties)) {
@@ -3973,21 +4005,20 @@ function evidenceFromTrace(trace) {
3973
4005
  return [];
3974
4006
  }
3975
4007
  const query = queryFromGenerationInput(observation.input);
3976
- return [
3977
- {
3978
- traceId: trace.id,
3979
- sessionId: trace.sessionId,
3980
- observationId: observation.id,
3981
- observationName: observation.name,
3982
- turn: observation.turn,
3983
- startedAt: observation.startedAt,
3984
- ...compact({ query }),
3985
- documentCount: documents.length,
3986
- toolCount: tools.length,
3987
- documents,
3988
- tools
3989
- }
3990
- ];
4008
+ const evidence = {
4009
+ traceId: trace.id,
4010
+ sessionId: trace.sessionId,
4011
+ observationId: observation.id,
4012
+ observationName: observation.name,
4013
+ turn: observation.turn,
4014
+ startedAt: observation.startedAt,
4015
+ documentCount: documents.length,
4016
+ toolCount: tools.length,
4017
+ documents,
4018
+ tools
4019
+ };
4020
+ if (query !== void 0) evidence.query = query;
4021
+ return [evidence];
3991
4022
  });
3992
4023
  }
3993
4024
  function queryFromGenerationInput(value) {
@@ -4053,7 +4084,11 @@ function evidenceDocument(value) {
4053
4084
  if (id === void 0 && text === void 0 && additionalProps === void 0) {
4054
4085
  return [];
4055
4086
  }
4056
- return [compact({ id, text, additionalProps })];
4087
+ const document = {};
4088
+ if (id !== void 0) document.id = id;
4089
+ if (text !== void 0) document.text = text;
4090
+ if (additionalProps !== void 0) document.additionalProps = additionalProps;
4091
+ return [document];
4057
4092
  }
4058
4093
  function evidenceToolName(value) {
4059
4094
  if (!isRecord3(value) || typeof value.name !== "string") {
@@ -4164,10 +4199,9 @@ function registerMemoryRoutes(app, props) {
4164
4199
  }
4165
4200
  const agentId = optionalQueryString(c.req.query("agentId"));
4166
4201
  const userId = optionalQueryString(c.req.query("userId"));
4167
- const sessions = await props.sessionStore.listSessions({
4168
- ...compact({ agentId }),
4169
- limit: 100
4170
- });
4202
+ const listInput = { limit: 100 };
4203
+ if (agentId !== void 0) listInput.agentId = agentId;
4204
+ const sessions = await props.sessionStore.listSessions(listInput);
4171
4205
  const conversations = sessions.map(memoryConversationSummary).filter((session) => userId === void 0 || session.userId === userId).slice(0, limit);
4172
4206
  return c.json({
4173
4207
  conversations,
@@ -4197,16 +4231,17 @@ function registerMemoryRoutes(app, props) {
4197
4231
  });
4198
4232
  }
4199
4233
  function memoryConversationSummary(session) {
4200
- return compact({
4234
+ const summary = {
4201
4235
  id: session.id,
4202
4236
  userId: sessionUserId(session),
4203
4237
  agentId: session.agentId,
4204
- title: session.title,
4205
4238
  createdAt: session.createdAt,
4206
4239
  updatedAt: session.updatedAt,
4207
- messageCount: session.messageCount,
4208
- metadata: session.metadata
4209
- });
4240
+ messageCount: session.messageCount
4241
+ };
4242
+ if (session.title !== void 0) summary.title = session.title;
4243
+ if (session.metadata !== void 0) summary.metadata = session.metadata;
4244
+ return summary;
4210
4245
  }
4211
4246
  function sessionUserId(session) {
4212
4247
  const userId = session.metadata?.userId;
@@ -4224,6 +4259,12 @@ async function* emitPipelineLog(store, input) {
4224
4259
  }
4225
4260
  }
4226
4261
  function pipelineRunReceivedLog(props) {
4262
+ const metadata = {
4263
+ stream: props.stream,
4264
+ metadataKeys: Object.keys(props.metadata ?? {})
4265
+ };
4266
+ const inputBytes = byteLength3(formatUnknown(props.input));
4267
+ if (inputBytes !== void 0) metadata.inputBytes = inputBytes;
4227
4268
  return {
4228
4269
  pipelineId: props.pipeline.id,
4229
4270
  runId: props.runId,
@@ -4231,11 +4272,7 @@ function pipelineRunReceivedLog(props) {
4231
4272
  category: "api",
4232
4273
  event: "pipeline.run_received",
4233
4274
  message: "Pipeline run request received",
4234
- metadata: compact({
4235
- stream: props.stream,
4236
- inputBytes: byteLength3(formatUnknown(props.input)),
4237
- metadataKeys: Object.keys(props.metadata ?? {})
4238
- })
4275
+ metadata
4239
4276
  };
4240
4277
  }
4241
4278
  function pipelineRunStartedLog(pipeline, runId) {
@@ -4247,13 +4284,16 @@ function pipelineRunStartedLog(pipeline, runId) {
4247
4284
  category: "run",
4248
4285
  event: "pipeline.run_started",
4249
4286
  message: "Pipeline run started",
4250
- metadata: compact({
4287
+ metadata: {
4251
4288
  stageCount: graph.nodes.filter((node) => node.kind !== "input" && node.kind !== "output").length,
4252
4289
  edgeCount: graph.edges.length
4253
- })
4290
+ }
4254
4291
  };
4255
4292
  }
4256
4293
  function pipelineRunCompletedLog(props) {
4294
+ const metadata = { durationMs: props.durationMs };
4295
+ const outputBytes = byteLength3(formatUnknown(props.output));
4296
+ if (outputBytes !== void 0) metadata.outputBytes = outputBytes;
4257
4297
  return {
4258
4298
  pipelineId: props.pipelineId,
4259
4299
  runId: props.runId,
@@ -4261,10 +4301,7 @@ function pipelineRunCompletedLog(props) {
4261
4301
  category: "run",
4262
4302
  event: "pipeline.run_completed",
4263
4303
  message: "Pipeline run completed",
4264
- metadata: compact({
4265
- durationMs: props.durationMs,
4266
- outputBytes: byteLength3(formatUnknown(props.output))
4267
- })
4304
+ metadata
4268
4305
  };
4269
4306
  }
4270
4307
  function pipelineRunFailedLog(pipelineId, runId, error, startedAt) {
@@ -4275,10 +4312,10 @@ function pipelineRunFailedLog(pipelineId, runId, error, startedAt) {
4275
4312
  category: "run",
4276
4313
  event: "pipeline.run_failed",
4277
4314
  message: "Pipeline run failed",
4278
- metadata: compact({
4315
+ metadata: {
4279
4316
  durationMs: Date.now() - startedAt,
4280
4317
  error: serializeError(error)
4281
- })
4318
+ }
4282
4319
  };
4283
4320
  }
4284
4321
  function pipelineStageLog(pipelineId, runId, event) {
@@ -4302,10 +4339,10 @@ function pipelineStageLog(pipelineId, runId, event) {
4302
4339
  category,
4303
4340
  event: `${event.node.kind}.completed`,
4304
4341
  message: `${event.node.label} completed`,
4305
- metadata: compact({
4342
+ metadata: {
4306
4343
  ...nodeMetadata(event.node),
4307
4344
  durationMs: event.durationMs
4308
- })
4345
+ }
4309
4346
  };
4310
4347
  }
4311
4348
  return {
@@ -4315,11 +4352,11 @@ function pipelineStageLog(pipelineId, runId, event) {
4315
4352
  category,
4316
4353
  event: `${event.node.kind}.failed`,
4317
4354
  message: `${event.node.label} failed`,
4318
- metadata: compact({
4355
+ metadata: {
4319
4356
  ...nodeMetadata(event.node),
4320
4357
  durationMs: event.durationMs,
4321
4358
  error: serializeError(event.error)
4322
- })
4359
+ }
4323
4360
  };
4324
4361
  }
4325
4362
  function stageCategory(node) {
@@ -4335,14 +4372,15 @@ function stageCategory(node) {
4335
4372
  return "stage";
4336
4373
  }
4337
4374
  function nodeMetadata(node) {
4338
- return compact({
4375
+ const metadata = {
4339
4376
  nodeId: node.id,
4340
4377
  kind: node.kind,
4341
- label: node.label,
4342
- agentId: node.agentId,
4343
- pipelineId: node.pipelineId,
4344
- branchKey: node.branchKey
4345
- });
4378
+ label: node.label
4379
+ };
4380
+ if (node.agentId !== void 0) metadata.agentId = node.agentId;
4381
+ if (node.pipelineId !== void 0) metadata.pipelineId = node.pipelineId;
4382
+ if (node.branchKey !== void 0) metadata.branchKey = node.branchKey;
4383
+ return metadata;
4346
4384
  }
4347
4385
  function byteLength3(value) {
4348
4386
  return value === void 0 ? void 0 : new TextEncoder().encode(value).length;
@@ -4385,16 +4423,16 @@ function registerPipelineRoutes(app, props) {
4385
4423
  if (after === false) {
4386
4424
  return errorResponse(c, 400, "bad_request", "after must be a non-negative integer");
4387
4425
  }
4388
- const logs = await props.logStore.listPipelineLogs({
4426
+ const listInput = {
4389
4427
  pipelineId,
4390
- limit,
4391
- ...compact({ after })
4392
- });
4428
+ limit
4429
+ };
4430
+ if (after !== void 0) listInput.after = after;
4431
+ const logs = await props.logStore.listPipelineLogs(listInput);
4393
4432
  const last = logs.at(-1);
4394
- return c.json({
4395
- logs,
4396
- ...logs.length === limit && last !== void 0 ? { nextCursor: last.sequence } : {}
4397
- });
4433
+ const response = { logs };
4434
+ if (logs.length === limit && last !== void 0) response.nextCursor = last.sequence;
4435
+ return c.json(response);
4398
4436
  });
4399
4437
  app.get("/pipelines/:pipelineId/runs", async (c) => {
4400
4438
  const pipelineId = c.req.param("pipelineId");
@@ -4457,45 +4495,47 @@ function registerPipelineRoutes(app, props) {
4457
4495
  if (sourceRun.status === "running") {
4458
4496
  return errorResponse(c, 409, "conflict", "Cannot replay a running pipeline run");
4459
4497
  }
4460
- return executePipelineRun(c, props, pipeline, {
4498
+ const replayRequest = {
4461
4499
  input: sourceRun.input,
4462
- ...compact({ stream: body.stream }),
4463
4500
  metadata: replayMetadata(sourceRun.metadata, body.metadata, sourceRun.runId)
4464
- });
4501
+ };
4502
+ if (body.stream !== void 0) replayRequest.stream = body.stream;
4503
+ return executePipelineRun(c, props, pipeline, replayRequest);
4465
4504
  });
4466
4505
  }
4467
4506
  async function executePipelineRun(c, props, pipeline, body) {
4468
4507
  const runId = globalThis.crypto.randomUUID();
4469
4508
  const startedAt = Date.now();
4470
4509
  const startedAtIso = new Date(startedAt).toISOString();
4471
- await appendPipelineLog(
4472
- props.logStore,
4473
- pipelineRunReceivedLog({
4474
- pipeline,
4475
- runId,
4476
- stream: body.stream === true,
4477
- input: body.input,
4478
- ...compact({ metadata: body.metadata })
4479
- })
4480
- );
4481
- await savePipelineRun(props.runStore, {
4510
+ const receivedInput = {
4511
+ pipeline,
4512
+ runId,
4513
+ stream: body.stream === true,
4514
+ input: body.input
4515
+ };
4516
+ if (body.metadata !== void 0) receivedInput.metadata = body.metadata;
4517
+ await appendPipelineLog(props.logStore, pipelineRunReceivedLog(receivedInput));
4518
+ const runningRecord = {
4482
4519
  runId,
4483
4520
  pipelineId: pipeline.id,
4484
4521
  status: "running",
4485
4522
  input: body.input,
4486
- ...compact({ metadata: body.metadata }),
4487
4523
  startedAt: startedAtIso
4488
- });
4524
+ };
4525
+ if (body.metadata !== void 0) runningRecord.metadata = body.metadata;
4526
+ await savePipelineRun(props.runStore, runningRecord);
4489
4527
  if (body.stream === true) {
4490
- return streamPipelineRun(c, {
4528
+ const streamOptions = {
4491
4529
  pipeline,
4492
4530
  runId,
4493
4531
  input: body.input,
4494
4532
  startedAt,
4495
- startedAtIso,
4496
- ...compact({ metadata: body.metadata }),
4497
- ...compact({ logStore: props.logStore, runStore: props.runStore })
4498
- });
4533
+ startedAtIso
4534
+ };
4535
+ if (body.metadata !== void 0) streamOptions.metadata = body.metadata;
4536
+ if (props.logStore !== void 0) streamOptions.logStore = props.logStore;
4537
+ if (props.runStore !== void 0) streamOptions.runStore = props.runStore;
4538
+ return streamPipelineRun(c, streamOptions);
4499
4539
  }
4500
4540
  try {
4501
4541
  await appendPipelineLog(props.logStore, pipelineRunStartedLog(pipeline, runId));
@@ -4508,17 +4548,18 @@ async function executePipelineRun(c, props, pipeline, body) {
4508
4548
  });
4509
4549
  const jsonOutput = toJsonValue(output);
4510
4550
  const endedAt = Date.now();
4511
- await savePipelineRun(props.runStore, {
4551
+ const successRecord = {
4512
4552
  runId,
4513
4553
  pipelineId: pipeline.id,
4514
4554
  status: "success",
4515
4555
  input: body.input,
4516
4556
  output: jsonOutput,
4517
- ...compact({ metadata: body.metadata }),
4518
4557
  startedAt: startedAtIso,
4519
4558
  endedAt: new Date(endedAt).toISOString(),
4520
4559
  durationMs: endedAt - startedAt
4521
- });
4560
+ };
4561
+ if (body.metadata !== void 0) successRecord.metadata = body.metadata;
4562
+ await savePipelineRun(props.runStore, successRecord);
4522
4563
  await appendPipelineLog(
4523
4564
  props.logStore,
4524
4565
  pipelineRunCompletedLog({
@@ -4536,17 +4577,18 @@ async function executePipelineRun(c, props, pipeline, body) {
4536
4577
  return c.json(response);
4537
4578
  } catch (error) {
4538
4579
  const endedAt = Date.now();
4539
- await savePipelineRun(props.runStore, {
4580
+ const errorRecord = {
4540
4581
  runId,
4541
4582
  pipelineId: pipeline.id,
4542
4583
  status: "error",
4543
4584
  input: body.input,
4544
4585
  error: serializeError(error),
4545
- ...compact({ metadata: body.metadata }),
4546
4586
  startedAt: startedAtIso,
4547
4587
  endedAt: new Date(endedAt).toISOString(),
4548
4588
  durationMs: endedAt - startedAt
4549
- });
4589
+ };
4590
+ if (body.metadata !== void 0) errorRecord.metadata = body.metadata;
4591
+ await savePipelineRun(props.runStore, errorRecord);
4550
4592
  await appendPipelineLog(
4551
4593
  props.logStore,
4552
4594
  pipelineRunFailedLog(pipeline.id, runId, error, startedAt)
@@ -4583,17 +4625,18 @@ async function* pipelineRunEvents(props) {
4583
4625
  }).then(async (output) => {
4584
4626
  const jsonOutput = toJsonValue(output);
4585
4627
  const endedAt = Date.now();
4586
- await savePipelineRun(props.runStore, {
4628
+ const successRecord = {
4587
4629
  runId: props.runId,
4588
4630
  pipelineId: props.pipeline.id,
4589
4631
  status: "success",
4590
4632
  input: props.input,
4591
4633
  output: jsonOutput,
4592
- ...compact({ metadata: props.metadata }),
4593
4634
  startedAt: props.startedAtIso,
4594
4635
  endedAt: new Date(endedAt).toISOString(),
4595
4636
  durationMs: endedAt - props.startedAt
4596
- });
4637
+ };
4638
+ if (props.metadata !== void 0) successRecord.metadata = props.metadata;
4639
+ await savePipelineRun(props.runStore, successRecord);
4597
4640
  const log = await appendPipelineLog(
4598
4641
  props.logStore,
4599
4642
  pipelineRunCompletedLog({
@@ -4614,17 +4657,18 @@ async function* pipelineRunEvents(props) {
4614
4657
  });
4615
4658
  }).catch(async (error) => {
4616
4659
  const endedAt = Date.now();
4617
- await savePipelineRun(props.runStore, {
4660
+ const errorRecord = {
4618
4661
  runId: props.runId,
4619
4662
  pipelineId: props.pipeline.id,
4620
4663
  status: "error",
4621
4664
  input: props.input,
4622
4665
  error: serializeError(error),
4623
- ...compact({ metadata: props.metadata }),
4624
4666
  startedAt: props.startedAtIso,
4625
4667
  endedAt: new Date(endedAt).toISOString(),
4626
4668
  durationMs: endedAt - props.startedAt
4627
- });
4669
+ };
4670
+ if (props.metadata !== void 0) errorRecord.metadata = props.metadata;
4671
+ await savePipelineRun(props.runStore, errorRecord);
4628
4672
  const log = await appendPipelineLog(
4629
4673
  props.logStore,
4630
4674
  pipelineRunFailedLog(props.pipeline.id, props.runId, error, props.startedAt)
@@ -4705,11 +4749,10 @@ async function parsePipelineReplayRequest(c) {
4705
4749
  return request;
4706
4750
  }
4707
4751
  function replayMetadata(sourceMetadata, requestMetadata, sourceRunId) {
4708
- return {
4709
- ...sourceMetadata ?? {},
4710
- ...requestMetadata ?? {},
4711
- replayOf: sourceRunId
4712
- };
4752
+ const metadata = {};
4753
+ Object.assign(metadata, sourceMetadata, requestMetadata);
4754
+ metadata.replayOf = sourceRunId;
4755
+ return metadata;
4713
4756
  }
4714
4757
  function parsePipelineLogLimit(value) {
4715
4758
  if (value === void 0 || value.trim().length === 0) {
@@ -4811,14 +4854,13 @@ async function parseQuestionAnswerRequest(c) {
4811
4854
  if ("custom" in answer && typeof answer.custom !== "boolean") {
4812
4855
  return { error: errorResponse(c, 400, "bad_request", "custom must be a boolean") };
4813
4856
  }
4814
- answers.push(
4815
- compact({
4816
- questionId: answer.questionId.trim(),
4817
- answer: answer.answer.trim(),
4818
- choice: typeof answer.choice === "string" ? answer.choice : void 0,
4819
- custom: typeof answer.custom === "boolean" ? answer.custom : void 0
4820
- })
4821
- );
4857
+ const normalized = {
4858
+ questionId: answer.questionId.trim(),
4859
+ answer: answer.answer.trim()
4860
+ };
4861
+ if (typeof answer.choice === "string") normalized.choice = answer.choice;
4862
+ if (typeof answer.custom === "boolean") normalized.custom = answer.custom;
4863
+ answers.push(normalized);
4822
4864
  }
4823
4865
  return { answers };
4824
4866
  }
@@ -4836,17 +4878,14 @@ function createQuestionRuntime() {
4836
4878
  if ("error" in prompts) {
4837
4879
  return control.skip(prompts.error);
4838
4880
  }
4839
- const answers = await requestQuestion(
4840
- questions,
4841
- context,
4842
- compact({
4843
- toolName,
4844
- toolCallId,
4845
- internalCallId,
4846
- args,
4847
- questions: prompts.questions
4848
- })
4849
- );
4881
+ const request = {
4882
+ toolName,
4883
+ internalCallId,
4884
+ args,
4885
+ questions: prompts.questions
4886
+ };
4887
+ if (toolCallId !== void 0) request.toolCallId = toolCallId;
4888
+ const answers = await requestQuestion(questions, context, request);
4850
4889
  return control.skip(JSON.stringify({ answers }));
4851
4890
  }
4852
4891
  });
@@ -4890,23 +4929,21 @@ function createQuestionRuntime() {
4890
4929
  async function requestQuestion(questions, context, request) {
4891
4930
  const id = globalThis.crypto.randomUUID();
4892
4931
  const question = {
4893
- ...compact({
4894
- id,
4895
- runId: context.runId,
4896
- agentId: context.agentId,
4897
- sessionId: context.sessionId,
4898
- toolName: request.toolName,
4899
- callId: request.toolCallId,
4900
- internalCallId: request.internalCallId,
4901
- args: request.args,
4902
- questions: request.questions,
4903
- status: "pending",
4904
- requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
4905
- emit: context.emit
4906
- }),
4932
+ id,
4933
+ runId: context.runId,
4934
+ agentId: context.agentId,
4935
+ toolName: request.toolName,
4936
+ internalCallId: request.internalCallId,
4937
+ args: request.args,
4938
+ questions: request.questions,
4939
+ status: "pending",
4940
+ requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
4907
4941
  resolve: () => {
4908
4942
  }
4909
4943
  };
4944
+ if (context.sessionId !== void 0) question.sessionId = context.sessionId;
4945
+ if (request.toolCallId !== void 0) question.callId = request.toolCallId;
4946
+ if (context.emit !== void 0) question.emit = context.emit;
4910
4947
  const answer = new Promise((resolve2) => {
4911
4948
  question.resolve = (answers) => {
4912
4949
  resolve2(answers);
@@ -4991,10 +5028,9 @@ function registerSessionRoutes(app, props) {
4991
5028
  if (limit === void 0) {
4992
5029
  return errorResponse(c, 400, "bad_request", "limit must be a positive integer");
4993
5030
  }
4994
- const sessions = await props.sessionStore.listSessions({
4995
- ...compact({ agentId }),
4996
- limit
4997
- });
5031
+ const listInput = { limit };
5032
+ if (agentId !== void 0) listInput.agentId = agentId;
5033
+ const sessions = await props.sessionStore.listSessions(listInput);
4998
5034
  return c.json({ sessions });
4999
5035
  });
5000
5036
  app.post("/sessions", async (c) => {
@@ -5005,11 +5041,13 @@ function registerSessionRoutes(app, props) {
5005
5041
  if (!props.agentMap.has(body.agentId)) {
5006
5042
  return errorResponse(c, 404, "not_found", "Agent not found");
5007
5043
  }
5008
- const session = await props.sessionStore.createSession({
5044
+ const createInput = {
5009
5045
  id: globalThis.crypto.randomUUID(),
5010
- agentId: body.agentId,
5011
- ...compact({ title: body.title, metadata: body.metadata })
5012
- });
5046
+ agentId: body.agentId
5047
+ };
5048
+ if (body.title !== void 0) createInput.title = body.title;
5049
+ if (body.metadata !== void 0) createInput.metadata = body.metadata;
5050
+ const session = await props.sessionStore.createSession(createInput);
5013
5051
  await appendSessionLog(props.sessionStore, sessionCreatedLog(session));
5014
5052
  return c.json(session, 201);
5015
5053
  });
@@ -5043,16 +5081,16 @@ function registerSessionRoutes(app, props) {
5043
5081
  if (after === false) {
5044
5082
  return errorResponse(c, 400, "bad_request", "after must be a non-negative integer");
5045
5083
  }
5046
- const logs = await props.sessionStore.listSessionLogs({
5084
+ const listInput = {
5047
5085
  sessionId,
5048
- limit,
5049
- ...compact({ after })
5050
- });
5086
+ limit
5087
+ };
5088
+ if (after !== void 0) listInput.after = after;
5089
+ const logs = await props.sessionStore.listSessionLogs(listInput);
5051
5090
  const last = logs.at(-1);
5052
- return c.json({
5053
- logs,
5054
- ...logs.length === limit && last !== void 0 ? { nextCursor: last.sequence } : {}
5055
- });
5091
+ const response = { logs };
5092
+ if (logs.length === limit && last !== void 0) response.nextCursor = last.sequence;
5093
+ return c.json(response);
5056
5094
  });
5057
5095
  app.delete("/sessions/:sessionId", async (c) => {
5058
5096
  if (props.sessionStore.deleteSession === void 0) {
@@ -5137,19 +5175,17 @@ var InMemoryStudioStore = class {
5137
5175
  createSession(input) {
5138
5176
  const now = (/* @__PURE__ */ new Date()).toISOString();
5139
5177
  const session = {
5140
- ...compact({
5141
- id: input.id,
5142
- agentId: input.agentId,
5143
- title: input.title,
5144
- createdAt: now,
5145
- updatedAt: now,
5146
- messageCount: 0,
5147
- metadata: input.metadata
5148
- }),
5178
+ id: input.id,
5179
+ agentId: input.agentId,
5180
+ createdAt: now,
5181
+ updatedAt: now,
5182
+ messageCount: 0,
5149
5183
  messages: [],
5150
5184
  runs: [],
5151
5185
  logs: []
5152
5186
  };
5187
+ if (input.title !== void 0) session.title = input.title;
5188
+ if (input.metadata !== void 0) session.metadata = input.metadata;
5153
5189
  this.sessions.set(input.id, session);
5154
5190
  return sessionSummary(session);
5155
5191
  }
@@ -5225,18 +5261,18 @@ var InMemoryStudioStore = class {
5225
5261
  appendSessionLog(input) {
5226
5262
  const session = this.sessions.get(input.sessionId);
5227
5263
  const logs = session?.logs ?? [];
5228
- const entry = compact({
5264
+ const entry = {
5229
5265
  id: globalThis.crypto.randomUUID(),
5230
5266
  sessionId: input.sessionId,
5231
- runId: input.runId,
5232
5267
  sequence: logs.length,
5233
5268
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5234
5269
  level: input.level,
5235
5270
  category: input.category,
5236
5271
  event: input.event,
5237
- message: input.message,
5238
- metadata: input.metadata
5239
- });
5272
+ message: input.message
5273
+ };
5274
+ if (input.runId !== void 0) entry.runId = input.runId;
5275
+ if (input.metadata !== void 0) entry.metadata = input.metadata;
5240
5276
  if (session !== void 0) {
5241
5277
  session.logs.push(entry);
5242
5278
  session.updatedAt = entry.timestamp;
@@ -5255,7 +5291,7 @@ var InMemoryStudioStore = class {
5255
5291
  return this.sessions.delete(id);
5256
5292
  }
5257
5293
  listTraces(options) {
5258
- return [...this.traces.values()].filter((trace) => options.sessionId === void 0 || trace.sessionId === options.sessionId).filter((trace) => options.status === void 0 || trace.status === options.status).filter((trace) => options.agentId === void 0 || traceAgentId(trace) === options.agentId).sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt)).slice(0, options.limit).map(traceSummary2);
5294
+ return [...this.traces.values()].filter((trace) => options.sessionId === void 0 || trace.sessionId === options.sessionId).filter((trace) => options.status === void 0 || trace.status === options.status).filter((trace) => options.agentId === void 0 || traceAgentId(trace) === options.agentId).sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt)).slice(0, options.limit).map(traceSummary);
5259
5295
  }
5260
5296
  listSessionTraces(options) {
5261
5297
  return this.listTraces({ sessionId: options.sessionId, limit: options.limit });
@@ -5269,18 +5305,18 @@ var InMemoryStudioStore = class {
5269
5305
  }
5270
5306
  appendPipelineLog(input) {
5271
5307
  const logs = this.pipelineLogs.get(input.pipelineId) ?? [];
5272
- const entry = compact({
5308
+ const entry = {
5273
5309
  id: globalThis.crypto.randomUUID(),
5274
5310
  pipelineId: input.pipelineId,
5275
- runId: input.runId,
5276
5311
  sequence: logs.length,
5277
5312
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5278
5313
  level: input.level,
5279
5314
  category: input.category,
5280
5315
  event: input.event,
5281
- message: input.message,
5282
- metadata: input.metadata
5283
- });
5316
+ message: input.message
5317
+ };
5318
+ if (input.runId !== void 0) entry.runId = input.runId;
5319
+ if (input.metadata !== void 0) entry.metadata = input.metadata;
5284
5320
  this.pipelineLogs.set(input.pipelineId, [...logs, entry]);
5285
5321
  return entry;
5286
5322
  }
@@ -5288,18 +5324,18 @@ var InMemoryStudioStore = class {
5288
5324
  return (this.pipelineLogs.get(options.pipelineId) ?? []).filter((log) => options.after === void 0 || log.sequence > options.after).slice(0, options.limit);
5289
5325
  }
5290
5326
  savePipelineRun(input) {
5291
- const record = compact({
5327
+ const record = {
5292
5328
  runId: input.runId,
5293
5329
  pipelineId: input.pipelineId,
5294
5330
  status: input.status,
5295
5331
  input: input.input,
5296
- output: input.output,
5297
- error: input.error,
5298
- metadata: input.metadata,
5299
- startedAt: input.startedAt,
5300
- endedAt: input.endedAt,
5301
- durationMs: input.durationMs
5302
- });
5332
+ startedAt: input.startedAt
5333
+ };
5334
+ if (input.output !== void 0) record.output = input.output;
5335
+ if (input.error !== void 0) record.error = input.error;
5336
+ if (input.metadata !== void 0) record.metadata = input.metadata;
5337
+ if (input.endedAt !== void 0) record.endedAt = input.endedAt;
5338
+ if (input.durationMs !== void 0) record.durationMs = input.durationMs;
5303
5339
  this.pipelineRuns.set(input.runId, record);
5304
5340
  return record;
5305
5341
  }
@@ -5312,15 +5348,16 @@ var InMemoryStudioStore = class {
5312
5348
  }
5313
5349
  };
5314
5350
  function sessionSummary(session) {
5315
- return compact({
5351
+ const summary = {
5316
5352
  id: session.id,
5317
5353
  agentId: session.agentId,
5318
- title: session.title,
5319
5354
  createdAt: session.createdAt,
5320
5355
  updatedAt: session.updatedAt,
5321
- messageCount: session.messages.length,
5322
- metadata: session.metadata
5323
- });
5356
+ messageCount: session.messages.length
5357
+ };
5358
+ if (session.title !== void 0) summary.title = session.title;
5359
+ if (session.metadata !== void 0) summary.metadata = session.metadata;
5360
+ return summary;
5324
5361
  }
5325
5362
  function materializeSession(session) {
5326
5363
  return {
@@ -5329,22 +5366,6 @@ function materializeSession(session) {
5329
5366
  transcript: renumberTranscript(session.runs.flatMap((run) => run.transcript))
5330
5367
  };
5331
5368
  }
5332
- function traceSummary2(trace) {
5333
- return compact({
5334
- id: trace.id,
5335
- sessionId: trace.sessionId,
5336
- name: trace.name,
5337
- status: trace.status,
5338
- startedAt: trace.startedAt,
5339
- endedAt: trace.endedAt,
5340
- durationMs: trace.durationMs,
5341
- output: trace.output,
5342
- error: trace.error,
5343
- usage: trace.usage,
5344
- metadata: trace.metadata,
5345
- observationCount: trace.observations.length
5346
- });
5347
- }
5348
5369
  function traceAgentId(trace) {
5349
5370
  const nestedMetadata = trace.metadata?.metadata;
5350
5371
  return isJsonObject(nestedMetadata) && typeof nestedMetadata.agentId === "string" ? nestedMetadata.agentId : void 0;
@@ -5370,12 +5391,12 @@ function resolveStores(options) {
5370
5391
  const traces = resolveTraceStore(options, sessions, defaultStore);
5371
5392
  const pipelineLogs = resolvePipelineLogStore(options, sessions, defaultStore);
5372
5393
  const pipelineRuns = resolvePipelineRunStore(options, sessions, pipelineLogs, defaultStore);
5373
- return compact({
5374
- sessions,
5375
- traces,
5376
- pipelineLogs,
5377
- pipelineRuns
5378
- });
5394
+ const stores = {};
5395
+ if (sessions !== void 0) stores.sessions = sessions;
5396
+ if (traces !== void 0) stores.traces = traces;
5397
+ if (pipelineLogs !== void 0) stores.pipelineLogs = pipelineLogs;
5398
+ if (pipelineRuns !== void 0) stores.pipelineRuns = pipelineRuns;
5399
+ return stores;
5379
5400
  }
5380
5401
  function defaultStudioStore() {
5381
5402
  return createInMemoryStudioStore();
@@ -5472,35 +5493,38 @@ function normalizePipelines(pipelines) {
5472
5493
  // src/runtime/status.ts
5473
5494
  function registerStatusRoutes(app, props) {
5474
5495
  app.get("/status", async (c) => {
5496
+ const runner = { id: runnerId(props.options) };
5497
+ if (props.options.name !== void 0) runner.name = props.options.name;
5498
+ if (props.options.version !== void 0) runner.version = props.options.version;
5499
+ const storage = {};
5500
+ if (props.stores.sessions?.kind !== void 0) storage.sessions = props.stores.sessions.kind;
5501
+ if (props.stores.traces?.kind !== void 0) storage.traces = props.stores.traces.kind;
5502
+ if (props.stores.pipelineLogs !== void 0) storage.pipelineLogs = "available";
5503
+ if (props.stores.pipelineRuns !== void 0) storage.pipelineRuns = "available";
5504
+ const counts = {
5505
+ agents: props.agents.length,
5506
+ pipelines: props.pipelines.length
5507
+ };
5508
+ if (props.stores.sessions !== void 0) {
5509
+ counts.sessions = (await props.stores.sessions.listSessions({ limit: 100 })).length;
5510
+ }
5511
+ if (props.stores.traces?.listTraces !== void 0) {
5512
+ counts.traces = (await props.stores.traces.listTraces({ limit: 100 })).length;
5513
+ }
5514
+ if (props.stores.pipelineRuns !== void 0 && props.pipelines.length > 0) {
5515
+ counts.pipelineRuns = (await Promise.all(
5516
+ props.pipelines.map(
5517
+ (pipeline) => props.stores.pipelineRuns?.listPipelineRuns({
5518
+ pipelineId: pipeline.id,
5519
+ limit: 100
5520
+ })
5521
+ )
5522
+ )).reduce((sum, runs) => sum + (runs?.length ?? 0), 0);
5523
+ }
5475
5524
  const summary = {
5476
- runner: {
5477
- id: runnerId(props.options),
5478
- ...compact({ name: props.options.name, version: props.options.version })
5479
- },
5480
- storage: {
5481
- ...compact({
5482
- sessions: props.stores.sessions?.kind,
5483
- traces: props.stores.traces?.kind,
5484
- pipelineLogs: props.stores.pipelineLogs !== void 0 ? "available" : void 0,
5485
- pipelineRuns: props.stores.pipelineRuns !== void 0 ? "available" : void 0
5486
- })
5487
- },
5488
- counts: {
5489
- agents: props.agents.length,
5490
- pipelines: props.pipelines.length,
5491
- ...compact({
5492
- sessions: props.stores.sessions !== void 0 ? (await props.stores.sessions.listSessions({ limit: 100 })).length : void 0,
5493
- traces: props.stores.traces?.listTraces !== void 0 ? (await props.stores.traces.listTraces({ limit: 100 })).length : void 0,
5494
- pipelineRuns: props.stores.pipelineRuns !== void 0 && props.pipelines.length > 0 ? (await Promise.all(
5495
- props.pipelines.map(
5496
- (pipeline) => props.stores.pipelineRuns?.listPipelineRuns({
5497
- pipelineId: pipeline.id,
5498
- limit: 100
5499
- })
5500
- )
5501
- )).reduce((sum, runs) => sum + (runs?.length ?? 0), 0) : void 0
5502
- })
5503
- },
5525
+ runner,
5526
+ storage,
5527
+ counts,
5504
5528
  capabilities: capabilityConfig(props.options, props.agents, props.pipelines, props.stores),
5505
5529
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
5506
5530
  };
@@ -5610,15 +5634,16 @@ async function agentToolMetadata(agent) {
5610
5634
  seen.add(key);
5611
5635
  const definition = await tool.definition("");
5612
5636
  const serverName = mcpServerName(tool);
5613
- metadata.push({
5637
+ const item = {
5614
5638
  agentId: agent.id,
5615
5639
  name: definition.name,
5616
5640
  description: definition.description,
5617
5641
  parameters: definition.parameters,
5618
5642
  source,
5619
- ...serverName === void 0 ? {} : { mcpServerName: serverName },
5620
5643
  approval: approvalMetadata(tool)
5621
- });
5644
+ };
5645
+ if (serverName !== void 0) item.mcpServerName = serverName;
5646
+ metadata.push(item);
5622
5647
  }
5623
5648
  return metadata.sort((left, right) => {
5624
5649
  if (left.source !== right.source) {
@@ -5650,10 +5675,11 @@ function registerTraceRoutes(app, traceStore) {
5650
5675
  }
5651
5676
  const agentId = optionalQueryString(c.req.query("agentId"));
5652
5677
  const sessionId = optionalQueryString(c.req.query("sessionId"));
5653
- const traces = await traceStore.listTraces({
5654
- limit,
5655
- ...compact({ agentId, sessionId, status })
5656
- });
5678
+ const input = { limit };
5679
+ if (agentId !== void 0) input.agentId = agentId;
5680
+ if (sessionId !== void 0) input.sessionId = sessionId;
5681
+ if (status !== void 0) input.status = status;
5682
+ const traces = await traceStore.listTraces(input);
5657
5683
  if (c.req.query("include") === "detail") {
5658
5684
  const detailed = await Promise.all(
5659
5685
  traces.map((trace) => Promise.resolve(traceStore.getTrace(trace.id)))
@@ -5699,11 +5725,12 @@ var Studio = class {
5699
5725
  this.close();
5700
5726
  this.studio = createStudioApp(this.options);
5701
5727
  const port = serveOptions.port ?? Number(process.env.RUNNER_PORT ?? 4021);
5702
- this.server = serve({
5728
+ const serverOptions = {
5703
5729
  fetch: (request) => this.fetch(request),
5704
- ...compact({ hostname: serveOptions.hostname }),
5705
5730
  port
5706
- });
5731
+ };
5732
+ if (serveOptions.hostname !== void 0) serverOptions.hostname = serveOptions.hostname;
5733
+ this.server = serve(serverOptions);
5707
5734
  const log = serveOptions.log ?? true;
5708
5735
  if (log) {
5709
5736
  const host = serveOptions.hostname ?? "localhost";
@@ -5737,14 +5764,15 @@ function studioOptionsFromTargets(targets, options) {
5737
5764
  // biome-ignore lint/suspicious/noExplicitAny: Studio accepts heterogeneous user pipelines.
5738
5765
  (target) => target instanceof Pipeline
5739
5766
  );
5740
- return {
5767
+ const runtimeOptions = {
5741
5768
  agents: inferStudioAgents(agents, options.quickPrompts ?? {}),
5742
5769
  pipelines: inferStudioPipelines(pipelines),
5743
- evals: options.evals ?? [],
5744
- ...compact({ models: options.models }),
5745
- ...compact({ stores: options.stores }),
5746
- ...compact({ ui: options.ui })
5770
+ evals: options.evals ?? []
5747
5771
  };
5772
+ if (options.models !== void 0) runtimeOptions.models = options.models;
5773
+ if (options.stores !== void 0) runtimeOptions.stores = options.stores;
5774
+ if (options.ui !== void 0) runtimeOptions.ui = options.ui;
5775
+ return runtimeOptions;
5748
5776
  }
5749
5777
  function inferStudioAgents(agents, quickPrompts) {
5750
5778
  const ids = /* @__PURE__ */ new Set();
@@ -5762,13 +5790,14 @@ function inferStudioPipelines(pipelines) {
5762
5790
  const ids = /* @__PURE__ */ new Set();
5763
5791
  return pipelines.map((pipeline) => {
5764
5792
  const id = uniqueAgentId(pipeline.id || "pipeline", ids);
5765
- return {
5793
+ const studioPipeline = {
5766
5794
  id,
5767
- pipeline,
5768
- ...compact({ name: pipeline.name }),
5769
- ...compact({ description: pipeline.description }),
5770
- ...compact({ metadata: pipeline.metadata })
5795
+ pipeline
5771
5796
  };
5797
+ if (pipeline.name !== void 0) studioPipeline.name = pipeline.name;
5798
+ if (pipeline.description !== void 0) studioPipeline.description = pipeline.description;
5799
+ if (pipeline.metadata !== void 0) studioPipeline.metadata = pipeline.metadata;
5800
+ return studioPipeline;
5772
5801
  });
5773
5802
  }
5774
5803
  function uniqueAgentId(baseId, ids) {
@@ -5782,8 +5811,7 @@ function uniqueAgentId(baseId, ids) {
5782
5811
  return id;
5783
5812
  }
5784
5813
  function agentMetadata(agent) {
5785
- return {
5786
- ...compact({ defaultMaxTurns: agent.defaultMaxTurns }),
5814
+ const metadata = {
5787
5815
  staticContextCount: agent.staticContext.length,
5788
5816
  dynamicContextCount: agent.dynamicContexts.length,
5789
5817
  dynamicToolCount: agent.dynamicTools.length,
@@ -5792,6 +5820,8 @@ function agentMetadata(agent) {
5792
5820
  observerCount: agent.observers.length,
5793
5821
  approvalToolCount: agent.toolSet.values().filter((tool) => tool.approval !== void 0).length
5794
5822
  };
5823
+ if (agent.defaultMaxTurns !== void 0) metadata.defaultMaxTurns = agent.defaultMaxTurns;
5824
+ return metadata;
5795
5825
  }
5796
5826
  function createStudioApp(options) {
5797
5827
  const observabilityHub = new StudioObservabilityHub();
@@ -5852,16 +5882,16 @@ function createStudioApp(options) {
5852
5882
  evals: options.evals,
5853
5883
  evalMap
5854
5884
  });
5855
- registerKnowledgeRoutes(app, {
5856
- agents,
5857
- ...compact({ traceStore: stores.traces })
5858
- });
5859
- registerPipelineRoutes(app, {
5885
+ const knowledgeOptions = { agents };
5886
+ if (stores.traces !== void 0) knowledgeOptions.traceStore = stores.traces;
5887
+ registerKnowledgeRoutes(app, knowledgeOptions);
5888
+ const pipelineOptions = {
5860
5889
  pipelines,
5861
- pipelineMap,
5862
- ...compact({ logStore: stores.pipelineLogs }),
5863
- ...compact({ runStore: stores.pipelineRuns })
5864
- });
5890
+ pipelineMap
5891
+ };
5892
+ if (stores.pipelineLogs !== void 0) pipelineOptions.logStore = stores.pipelineLogs;
5893
+ if (stores.pipelineRuns !== void 0) pipelineOptions.runStore = stores.pipelineRuns;
5894
+ registerPipelineRoutes(app, pipelineOptions);
5865
5895
  registerAgentRunRoute(app, {
5866
5896
  agentMap,
5867
5897
  stores,
@@ -5873,11 +5903,12 @@ function createStudioApp(options) {
5873
5903
  registerMemoryRoutes(app, {
5874
5904
  sessionStore: stores.sessions
5875
5905
  });
5876
- registerSessionRoutes(app, {
5906
+ const sessionOptions = {
5877
5907
  agentMap,
5878
- sessionStore: stores.sessions,
5879
- ...compact({ traceStore: stores.traces })
5880
- });
5908
+ sessionStore: stores.sessions
5909
+ };
5910
+ if (stores.traces !== void 0) sessionOptions.traceStore = stores.traces;
5911
+ registerSessionRoutes(app, sessionOptions);
5881
5912
  }
5882
5913
  if (stores.traces !== void 0) {
5883
5914
  registerTraceRoutes(app, stores.traces);
@@ -5886,7 +5917,7 @@ function createStudioApp(options) {
5886
5917
  app.all(`/${capability}`, (c) => unsupportedCapability(c, capability));
5887
5918
  app.all(`/${capability}/*`, (c) => unsupportedCapability(c, capability));
5888
5919
  }
5889
- return {
5920
+ const studio = {
5890
5921
  app,
5891
5922
  fetch(request) {
5892
5923
  return app.fetch(request);
@@ -5895,10 +5926,11 @@ function createStudioApp(options) {
5895
5926
  return buildConfig(options, agents, pipelines, stores);
5896
5927
  },
5897
5928
  close() {
5898
- },
5899
- ...compact({ sessionStore: stores.sessions }),
5900
- ...compact({ traceStore: stores.traces })
5929
+ }
5901
5930
  };
5931
+ if (stores.sessions !== void 0) Object.assign(studio, { sessionStore: stores.sessions });
5932
+ if (stores.traces !== void 0) Object.assign(studio, { traceStore: stores.traces });
5933
+ return studio;
5902
5934
  }
5903
5935
  function withStudioTraceObserver(studioAgent, traceStore) {
5904
5936
  if (traceStore === void 0 || hasStudioTraceObserver(studioAgent.agent)) {
@@ -5973,15 +6005,16 @@ var SqliteSessionStore = class {
5973
6005
  $metadata: input.metadata === void 0 ? null : JSON.stringify(input.metadata),
5974
6006
  $now: now
5975
6007
  });
5976
- return {
6008
+ const session = {
5977
6009
  id: input.id,
5978
6010
  agentId: input.agentId,
5979
- ...compact({ title: input.title }),
5980
6011
  createdAt: now,
5981
6012
  updatedAt: now,
5982
- messageCount: 0,
5983
- ...compact({ metadata: input.metadata })
6013
+ messageCount: 0
5984
6014
  };
6015
+ if (input.title !== void 0) session.title = input.title;
6016
+ if (input.metadata !== void 0) session.metadata = input.metadata;
6017
+ return session;
5985
6018
  }
5986
6019
  getSession(id) {
5987
6020
  const row = this.getSessionRow(id);
@@ -6166,15 +6199,15 @@ var SqliteSessionStore = class {
6166
6199
  const entry = {
6167
6200
  id: globalThis.crypto.randomUUID(),
6168
6201
  sessionId: input.sessionId,
6169
- ...compact({ runId: input.runId }),
6170
6202
  sequence,
6171
6203
  timestamp: now,
6172
6204
  level: input.level,
6173
6205
  category: input.category,
6174
6206
  event: input.event,
6175
- message: input.message,
6176
- ...compact({ metadata: input.metadata })
6207
+ message: input.message
6177
6208
  };
6209
+ if (input.runId !== void 0) entry.runId = input.runId;
6210
+ if (input.metadata !== void 0) entry.metadata = input.metadata;
6178
6211
  db.prepare(
6179
6212
  `INSERT INTO anvia_studio_session_logs (
6180
6213
  id,
@@ -6247,15 +6280,15 @@ var SqliteSessionStore = class {
6247
6280
  const entry = {
6248
6281
  id: globalThis.crypto.randomUUID(),
6249
6282
  pipelineId: input.pipelineId,
6250
- ...compact({ runId: input.runId }),
6251
6283
  sequence,
6252
6284
  timestamp: now,
6253
6285
  level: input.level,
6254
6286
  category: input.category,
6255
6287
  event: input.event,
6256
- message: input.message,
6257
- ...compact({ metadata: input.metadata })
6288
+ message: input.message
6258
6289
  };
6290
+ if (input.runId !== void 0) entry.runId = input.runId;
6291
+ if (input.metadata !== void 0) entry.metadata = input.metadata;
6259
6292
  db.prepare(
6260
6293
  `INSERT INTO anvia_studio_pipeline_logs (
6261
6294
  id,
@@ -6367,18 +6400,19 @@ var SqliteSessionStore = class {
6367
6400
  $endedAt: input.endedAt ?? null,
6368
6401
  $durationMs: input.durationMs ?? null
6369
6402
  });
6370
- return {
6403
+ const record = {
6371
6404
  runId: input.runId,
6372
6405
  pipelineId: input.pipelineId,
6373
6406
  status: input.status,
6374
6407
  input: input.input,
6375
- ...compact({ output: input.output }),
6376
- ...compact({ error: input.error }),
6377
- ...compact({ metadata: input.metadata }),
6378
- startedAt: input.startedAt,
6379
- ...compact({ endedAt: input.endedAt }),
6380
- ...compact({ durationMs: input.durationMs })
6408
+ startedAt: input.startedAt
6381
6409
  };
6410
+ if (input.output !== void 0) record.output = input.output;
6411
+ if (input.error !== void 0) record.error = input.error;
6412
+ if (input.metadata !== void 0) record.metadata = input.metadata;
6413
+ if (input.endedAt !== void 0) record.endedAt = input.endedAt;
6414
+ if (input.durationMs !== void 0) record.durationMs = input.durationMs;
6415
+ return record;
6382
6416
  }
6383
6417
  getPipelineRun(options) {
6384
6418
  const db = this.database();
@@ -6812,62 +6846,66 @@ function toSession(row, messages, runRows = []) {
6812
6846
  }
6813
6847
  function toSessionSummary(row) {
6814
6848
  const metadata = parseJsonValue(row.metadata_json);
6815
- return {
6849
+ const summary = {
6816
6850
  id: row.id,
6817
6851
  agentId: row.agent_id,
6818
- ...compact({ title: row.title ?? void 0 }),
6819
6852
  createdAt: row.created_at,
6820
6853
  updatedAt: row.updated_at,
6821
- messageCount: row.message_count,
6822
- ...compact({ metadata })
6854
+ messageCount: row.message_count
6823
6855
  };
6856
+ if (row.title !== null) summary.title = row.title;
6857
+ if (metadata !== void 0) summary.metadata = metadata;
6858
+ return summary;
6824
6859
  }
6825
6860
  function toSessionLog(row) {
6826
6861
  const metadata = parseJsonValue(row.metadata_json);
6827
- return {
6862
+ const entry = {
6828
6863
  id: row.id,
6829
6864
  sessionId: row.session_id,
6830
- ...compact({ runId: row.run_id ?? void 0 }),
6831
6865
  sequence: row.sequence,
6832
6866
  timestamp: row.timestamp,
6833
6867
  level: row.level,
6834
6868
  category: row.category,
6835
6869
  event: row.event,
6836
- message: row.message,
6837
- ...compact({ metadata })
6870
+ message: row.message
6838
6871
  };
6872
+ if (row.run_id !== null) entry.runId = row.run_id;
6873
+ if (metadata !== void 0) entry.metadata = metadata;
6874
+ return entry;
6839
6875
  }
6840
6876
  function toPipelineLog(row) {
6841
6877
  const metadata = parseJsonValue(row.metadata_json);
6842
- return {
6878
+ const entry = {
6843
6879
  id: row.id,
6844
6880
  pipelineId: row.pipeline_id,
6845
- ...compact({ runId: row.run_id ?? void 0 }),
6846
6881
  sequence: row.sequence,
6847
6882
  timestamp: row.timestamp,
6848
6883
  level: row.level,
6849
6884
  category: row.category,
6850
6885
  event: row.event,
6851
- message: row.message,
6852
- ...compact({ metadata })
6886
+ message: row.message
6853
6887
  };
6888
+ if (row.run_id !== null) entry.runId = row.run_id;
6889
+ if (metadata !== void 0) entry.metadata = metadata;
6890
+ return entry;
6854
6891
  }
6855
6892
  function toPipelineRun(row) {
6856
6893
  const output = parseJsonValue(row.output_json);
6857
6894
  const error = parseJsonValue(row.error_json);
6858
6895
  const metadata = parseJsonValue(row.metadata_json);
6859
- return {
6896
+ const record = {
6860
6897
  runId: row.run_id,
6861
6898
  pipelineId: row.pipeline_id,
6862
6899
  status: row.status,
6863
6900
  input: JSON.parse(row.input_json),
6864
- ...compact({ output }),
6865
- ...compact({ error }),
6866
- ...compact({ metadata }),
6867
- startedAt: row.started_at,
6868
- ...compact({ endedAt: row.ended_at ?? void 0 }),
6869
- ...compact({ durationMs: row.duration_ms ?? void 0 })
6901
+ startedAt: row.started_at
6870
6902
  };
6903
+ if (output !== void 0) record.output = output;
6904
+ if (error !== void 0) record.error = error;
6905
+ if (metadata !== void 0) record.metadata = metadata;
6906
+ if (row.ended_at !== null) record.endedAt = row.ended_at;
6907
+ if (row.duration_ms !== null) record.durationMs = row.duration_ms;
6908
+ return record;
6871
6909
  }
6872
6910
  function messageParts(message) {
6873
6911
  if (message.role === "system") {
@@ -6884,31 +6922,38 @@ function messageFromRows(row, partRows) {
6884
6922
  if (metadata !== void 0 && !isJsonValue2(metadata)) {
6885
6923
  throw new TypeError("Stored Studio message metadata is not a strict JSON value.");
6886
6924
  }
6887
- const metadataProperties = compact({ metadata });
6888
6925
  if (row.role === "system") {
6889
- return { role: "system", content: systemContentFromParts(parts), ...metadataProperties };
6926
+ const message = {
6927
+ role: "system",
6928
+ content: systemContentFromParts(parts)
6929
+ };
6930
+ if (metadata !== void 0) message.metadata = metadata;
6931
+ return message;
6890
6932
  }
6891
6933
  if (row.role === "user") {
6892
- return {
6934
+ const message = {
6893
6935
  role: "user",
6894
- content: parts,
6895
- ...metadataProperties
6936
+ content: parts
6896
6937
  };
6938
+ if (metadata !== void 0) message.metadata = metadata;
6939
+ return message;
6897
6940
  }
6898
6941
  if (row.role === "assistant") {
6899
- return {
6942
+ const message = {
6900
6943
  role: "assistant",
6901
- ...compact({ id: row.message_id ?? void 0 }),
6902
- content: parts,
6903
- ...metadataProperties
6944
+ content: parts
6904
6945
  };
6946
+ if (row.message_id !== null) message.id = row.message_id;
6947
+ if (metadata !== void 0) message.metadata = metadata;
6948
+ return message;
6905
6949
  }
6906
6950
  if (row.role === "tool") {
6907
- return {
6951
+ const message = {
6908
6952
  role: "tool",
6909
- content: parts,
6910
- ...metadataProperties
6953
+ content: parts
6911
6954
  };
6955
+ if (metadata !== void 0) message.metadata = metadata;
6956
+ return message;
6912
6957
  }
6913
6958
  throw new Error(`Unsupported stored message role: ${row.role}`);
6914
6959
  }
@@ -6952,32 +6997,34 @@ function loadDatabaseSync() {
6952
6997
  function toTrace(row) {
6953
6998
  const trace = parseJsonValue(row.trace_json);
6954
6999
  const input = parseJsonValue(row.input_json);
6955
- return {
7000
+ const result = {
6956
7001
  ...toTraceSummary(row),
6957
- ...compact({ trace }),
6958
- ...compact({ input }),
6959
7002
  observations: parseJsonArray(row.observations_json)
6960
7003
  };
7004
+ if (trace !== void 0) result.trace = trace;
7005
+ if (input !== void 0) result.input = input;
7006
+ return result;
6961
7007
  }
6962
7008
  function toTraceSummary(row) {
6963
7009
  const observations = parseJsonArray(row.observations_json);
6964
7010
  const error = parseJsonValue(row.error_json);
6965
7011
  const usage = parseJsonValue(row.usage_json);
6966
7012
  const metadata = parseJsonValue(row.metadata_json);
6967
- return {
7013
+ const summary = {
6968
7014
  id: row.id,
6969
7015
  sessionId: row.session_id,
6970
- ...compact({ name: row.name ?? void 0 }),
6971
7016
  status: row.status,
6972
7017
  startedAt: row.started_at,
6973
- ...compact({ endedAt: row.ended_at ?? void 0 }),
6974
- ...compact({ durationMs: row.duration_ms ?? void 0 }),
6975
- ...compact({ output: row.output ?? void 0 }),
6976
- ...compact({ error }),
6977
- ...compact({ usage }),
6978
- ...compact({ metadata }),
6979
7018
  observationCount: observations.length
6980
7019
  };
7020
+ if (row.name !== null) summary.name = row.name;
7021
+ if (row.ended_at !== null) summary.endedAt = row.ended_at;
7022
+ if (row.duration_ms !== null) summary.durationMs = row.duration_ms;
7023
+ if (row.output !== null) summary.output = row.output;
7024
+ if (error !== void 0) summary.error = error;
7025
+ if (usage !== void 0) summary.usage = usage;
7026
+ if (metadata !== void 0) summary.metadata = metadata;
7027
+ return summary;
6981
7028
  }
6982
7029
  function parseJsonArray(value) {
6983
7030
  const parsed = JSON.parse(value);
@@ -7005,29 +7052,11 @@ function serializeJsonError2(error) {
7005
7052
  }
7006
7053
  return String(error);
7007
7054
  }
7008
-
7009
- // src/types.ts
7010
- function traceSummary3(trace) {
7011
- return compact({
7012
- id: trace.id,
7013
- sessionId: trace.sessionId,
7014
- name: trace.name,
7015
- status: trace.status,
7016
- startedAt: trace.startedAt,
7017
- endedAt: trace.endedAt,
7018
- durationMs: trace.durationMs,
7019
- output: trace.output,
7020
- error: trace.error,
7021
- usage: trace.usage,
7022
- metadata: trace.metadata,
7023
- observationCount: trace.observations.length
7024
- });
7025
- }
7026
7055
  export {
7027
7056
  Studio,
7028
7057
  StudioTraceObserver,
7029
7058
  createInMemoryStudioStore,
7030
7059
  createSqliteSessionStore,
7031
- traceSummary3 as traceSummary
7060
+ traceSummary
7032
7061
  };
7033
7062
  //# sourceMappingURL=index.js.map