@anvia/studio 0.7.28 → 0.7.30

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 +994 -970
  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 +5 -5
  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;
@@ -951,20 +944,17 @@ function serializeError(error) {
951
944
  }
952
945
 
953
946
  // src/runtime/type-guards.ts
947
+ import {
948
+ isJsonValue as isCoreJsonValue
949
+ } from "@anvia/core/completion";
954
950
  function isObject(value) {
955
951
  return typeof value === "object" && value !== null && !Array.isArray(value);
956
952
  }
957
953
  function isJsonObject(value) {
958
- return isObject(value) && Object.values(value).every(isJsonValue);
954
+ return isObject(value) && isCoreJsonValue(value);
959
955
  }
960
956
  function isJsonValue(value) {
961
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
962
- return true;
963
- }
964
- if (Array.isArray(value)) {
965
- return value.every(isJsonValue);
966
- }
967
- return isJsonObject(value);
957
+ return isCoreJsonValue(value);
968
958
  }
969
959
  function isMessageInput(value) {
970
960
  return typeof value === "string" || isMessage(value);
@@ -1049,23 +1039,25 @@ function createStudioModelRegistry(config) {
1049
1039
  }
1050
1040
  staticModels.set(modelId, { ...model, id: modelId });
1051
1041
  }
1052
- providers.set(id, {
1042
+ const runtimeProvider = {
1053
1043
  ...provider,
1054
1044
  id,
1055
- ...compact({
1056
- defaultModel: provider.defaultModel !== void 0 ? normalizeModelId(provider.defaultModel) : void 0
1057
- }),
1058
1045
  staticModels
1059
- });
1046
+ };
1047
+ if (provider.defaultModel !== void 0) {
1048
+ runtimeProvider.defaultModel = normalizeModelId(provider.defaultModel);
1049
+ }
1050
+ providers.set(id, runtimeProvider);
1060
1051
  }
1061
- return {
1062
- ...compact({
1063
- defaultModel: config.default !== void 0 ? normalizeModelRef(config.default) : void 0
1064
- }),
1052
+ const registry = {
1065
1053
  providers,
1066
1054
  agentPolicies: normalizeAgentPolicies(config.agents ?? {}),
1067
1055
  modelCache: /* @__PURE__ */ new Map()
1068
1056
  };
1057
+ if (config.default !== void 0) {
1058
+ Object.assign(registry, { defaultModel: normalizeModelRef(config.default) });
1059
+ }
1060
+ return registry;
1069
1061
  }
1070
1062
  function studioModelsConfig(registry, agents) {
1071
1063
  if (registry === void 0) {
@@ -1075,25 +1067,25 @@ function studioModelsConfig(registry, agents) {
1075
1067
  const models = [...provider.staticModels.values()].map(
1076
1068
  (model) => modelSummary(provider, model.id, model)
1077
1069
  );
1078
- return {
1070
+ const config2 = {
1079
1071
  id: provider.id,
1080
- ...compact({
1081
- name: provider.name,
1082
- defaultModel: provider.defaultModel,
1083
- metadata: provider.metadata
1084
- }),
1085
1072
  models
1086
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;
1087
1078
  });
1088
1079
  const agentIds = new Set(agents.map((agent) => agent.id));
1089
1080
  const agentsConfig = Object.fromEntries(
1090
1081
  [...registry.agentPolicies.entries()].filter(([agentId]) => agentIds.has(agentId)).map(([agentId, policy]) => [agentId, publicPolicy(policy)])
1091
1082
  );
1092
- return {
1083
+ const config = {
1093
1084
  providers,
1094
- ...compact({ default: registry.defaultModel }),
1095
1085
  agents: agentsConfig
1096
1086
  };
1087
+ if (registry.defaultModel !== void 0) config.default = registry.defaultModel;
1088
+ return config;
1097
1089
  }
1098
1090
  function registerModelRoutes(app, props) {
1099
1091
  app.get("/models", async (c) => {
@@ -1103,10 +1095,13 @@ function registerModelRoutes(app, props) {
1103
1095
  const providers = await Promise.all(
1104
1096
  [...props.registry.providers.values()].map((provider) => providerCatalog(provider))
1105
1097
  );
1106
- return c.json({
1107
- providers,
1108
- ...compact({ defaultModel: props.registry.defaultModel })
1109
- });
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);
1110
1105
  });
1111
1106
  app.get("/models/:providerId", async (c) => {
1112
1107
  if (props.registry === void 0) {
@@ -1216,12 +1211,13 @@ async function agentModelsCatalog(registry, agent) {
1216
1211
  }
1217
1212
  });
1218
1213
  const defaultModel = policy?.default ?? registry.defaultModel;
1219
- return {
1214
+ const summary = {
1220
1215
  agentId: agent.id,
1221
- ...compact({ defaultModel }),
1222
- models: [...models, ...exactPolicyModels],
1223
- ...compact({ warnings: warnings.length === 0 ? void 0 : warnings })
1216
+ models: [...models, ...exactPolicyModels]
1224
1217
  };
1218
+ if (defaultModel !== void 0) summary.defaultModel = defaultModel;
1219
+ if (warnings.length > 0) summary.warnings = warnings;
1220
+ return summary;
1225
1221
  }
1226
1222
  async function providerCatalog(provider) {
1227
1223
  const models = /* @__PURE__ */ new Map();
@@ -1234,48 +1230,43 @@ async function providerCatalog(provider) {
1234
1230
  const listed = await provider.listModels();
1235
1231
  for (const model of listed.data) {
1236
1232
  const staticModel = provider.staticModels.get(model.id);
1237
- models.set(
1238
- model.id,
1239
- modelSummary(provider, model.id, {
1240
- id: model.id,
1241
- ...compact({ name: model.name, description: model.description }),
1242
- ...staticModel ?? {},
1243
- metadata: {
1244
- ...compact({
1245
- type: model.type,
1246
- createdAt: model.createdAt,
1247
- ownedBy: model.ownedBy,
1248
- contextLength: model.contextLength
1249
- }),
1250
- ...staticModel?.metadata ?? {}
1251
- }
1252
- })
1253
- );
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));
1254
1245
  }
1255
1246
  } catch (error) {
1256
1247
  const serialized = serializeError(error);
1257
1248
  warning = typeof serialized === "object" && serialized !== null && "message" in serialized ? String(serialized.message) : String(error);
1258
1249
  }
1259
1250
  }
1260
- return {
1251
+ const catalog = {
1261
1252
  id: provider.id,
1262
- ...compact({
1263
- name: provider.name,
1264
- defaultModel: provider.defaultModel,
1265
- metadata: provider.metadata,
1266
- warning
1267
- }),
1268
1253
  models: [...models.values()].sort((left, right) => left.ref.localeCompare(right.ref))
1269
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;
1270
1260
  }
1271
1261
  function modelSummary(provider, modelId, model) {
1272
- return {
1262
+ const summary = {
1273
1263
  ...model,
1274
1264
  id: modelId,
1275
1265
  ref: `${provider.id}:${modelId}`,
1276
- providerId: provider.id,
1277
- ...compact({ providerName: provider.name })
1266
+ providerId: provider.id
1278
1267
  };
1268
+ if (provider.name !== void 0) summary.providerName = provider.name;
1269
+ return summary;
1279
1270
  }
1280
1271
  function ensureModelAllowed(registry, agentId, ref) {
1281
1272
  const { providerId } = parseModelRef(ref);
@@ -1294,21 +1285,23 @@ function allowedByPolicy(allowed, ref) {
1294
1285
  }
1295
1286
  function normalizeAgentPolicies(policies) {
1296
1287
  return new Map(
1297
- Object.entries(policies).map(([agentId, policy]) => [
1298
- agentId.trim(),
1299
- {
1300
- ...compact({
1301
- default: policy.default !== void 0 ? normalizeModelRef(policy.default) : void 0,
1302
- allowed: policy.allowed?.map(
1303
- (entry) => typeof entry === "string" && entry.trim().endsWith(":*") ? `${normalizeProviderId(entry.trim().slice(0, -2))}:*` : normalizeModelRef(entry)
1304
- )
1305
- })
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
+ );
1306
1295
  }
1307
- ])
1296
+ return [agentId.trim(), normalized];
1297
+ })
1308
1298
  );
1309
1299
  }
1310
1300
  function publicPolicy(policy) {
1311
- 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;
1312
1305
  }
1313
1306
  function modelWarnings(ref, model, request) {
1314
1307
  const warnings = [];
@@ -1428,20 +1421,21 @@ function studioStreamError(error) {
1428
1421
 
1429
1422
  // src/runtime/trace-summary.ts
1430
1423
  function traceSummary(trace) {
1431
- return compact({
1424
+ const summary = {
1432
1425
  id: trace.id,
1433
1426
  sessionId: trace.sessionId,
1434
- name: trace.name,
1435
1427
  status: trace.status,
1436
1428
  startedAt: trace.startedAt,
1437
- endedAt: trace.endedAt,
1438
- durationMs: trace.durationMs,
1439
- output: trace.output,
1440
- error: trace.error,
1441
- usage: trace.usage,
1442
- metadata: trace.metadata,
1443
1429
  observationCount: trace.observations.length
1444
- });
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;
1445
1439
  }
1446
1440
 
1447
1441
  // src/runtime/observability.ts
@@ -1468,14 +1462,13 @@ var StudioObservabilityHub = class {
1468
1462
  }
1469
1463
  };
1470
1464
  function observeStores(stores, hub) {
1471
- return {
1472
- ...stores,
1473
- ...compact({
1474
- sessions: stores.sessions !== void 0 ? observeSessionStore(stores.sessions, hub) : void 0,
1475
- traces: stores.traces !== void 0 ? observeTraceStore(stores.traces, hub) : void 0,
1476
- pipelineLogs: stores.pipelineLogs !== void 0 ? observePipelineLogStore(stores.pipelineLogs, hub) : void 0
1477
- })
1478
- };
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;
1479
1472
  }
1480
1473
  function registerObservabilityRoutes(app, hub) {
1481
1474
  app.get("/observability/events", (c) => {
@@ -1495,7 +1488,9 @@ function registerObservabilityRoutes(app, hub) {
1495
1488
  });
1496
1489
  }
1497
1490
  function observabilityEvents(hub, types) {
1498
- const subscription = hub.subscribe(compact({ types }));
1491
+ const options = {};
1492
+ if (types !== void 0) options.types = types;
1493
+ const subscription = hub.subscribe(options);
1499
1494
  return {
1500
1495
  [Symbol.asyncIterator]() {
1501
1496
  return {
@@ -1639,15 +1634,14 @@ function transcriptFromMessages(messages) {
1639
1634
  let textEntryAdded = false;
1640
1635
  for (const content of message.content) {
1641
1636
  if (content.type === "text") {
1642
- transcript.push(
1643
- compact({
1644
- entryId: transcript.length,
1645
- kind: "message",
1646
- role: "user",
1647
- text: content.text,
1648
- attachments: attachments.length === 0 ? void 0 : attachments
1649
- })
1650
- );
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);
1651
1645
  textEntryAdded = true;
1652
1646
  }
1653
1647
  }
@@ -1681,14 +1675,13 @@ function transcriptFromMessages(messages) {
1681
1675
  if (content.type === "text") {
1682
1676
  appendAssistantTranscriptText(transcript, content.text);
1683
1677
  } else if (content.type === "reasoning") {
1684
- transcript.push(
1685
- compact({
1686
- entryId: transcript.length,
1687
- kind: "reasoning",
1688
- reasoningId: content.id,
1689
- text: content.text
1690
- })
1691
- );
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);
1692
1685
  } else if (content.type === "tool_call") {
1693
1686
  transcript.push({
1694
1687
  entryId: transcript.length,
@@ -1708,23 +1701,22 @@ function attachmentsFromMessage(message) {
1708
1701
  }
1709
1702
  return message.content.flatMap((content) => {
1710
1703
  if (content.type === "image") {
1711
- return [
1712
- {
1713
- kind: "image",
1714
- ...content.source.type === "base64" ? { data: content.source.data, mediaType: content.source.mediaType } : { url: content.source.url }
1715
- }
1716
- ];
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];
1717
1712
  }
1718
1713
  if (content.type === "document") {
1719
- return [
1720
- compact({
1721
- kind: "document",
1722
- name: content.source.filename,
1723
- mediaType: content.source.mediaType,
1724
- data: content.source.type === "base64" ? content.source.data : void 0,
1725
- url: content.source.type === "url" ? content.source.url : void 0
1726
- })
1727
- ];
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];
1728
1720
  }
1729
1721
  return [];
1730
1722
  });
@@ -1820,15 +1812,15 @@ function streamAgentRunEvents(_c, events) {
1820
1812
  return streamStudioJsonl(events);
1821
1813
  }
1822
1814
  function traceForRun(trace, agentId, session) {
1823
- const metadata = {
1824
- ...trace?.metadata ?? {},
1825
- agentId
1826
- };
1827
- return {
1828
- ...trace ?? {},
1829
- metadata,
1830
- ...trace?.sessionId !== void 0 ? { sessionId: trace.sessionId } : session === void 0 ? {} : { sessionId: session.id }
1831
- };
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;
1832
1824
  }
1833
1825
  async function* persistStreamingSessionTranscript(props) {
1834
1826
  const transcript = [messageToTranscriptEntry(props.message, 0)];
@@ -1843,14 +1835,15 @@ async function* persistStreamingSessionTranscript(props) {
1843
1835
  try {
1844
1836
  for await (const event of props.stream) {
1845
1837
  acceptTranscriptStreamEvent(transcript, event);
1846
- const nextSession = await props.store.saveSessionRunTranscript({
1838
+ const saveInput = {
1847
1839
  id: props.session.id,
1848
1840
  runId: props.runId,
1849
1841
  ...title,
1850
1842
  transcript,
1851
- status: event.type === "final" ? "success" : event.type === "error" ? "error" : "running",
1852
- ...event.type === "error" ? { error: serializeError(event.error) } : {}
1853
- });
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);
1854
1847
  if (nextSession === void 0) {
1855
1848
  throw new Error("Session not found");
1856
1849
  }
@@ -1897,17 +1890,16 @@ function acceptTranscriptStreamEvent(transcript, event) {
1897
1890
  if (event.type === "tool_result") {
1898
1891
  const matched = findTranscriptToolEntry(transcript, event.toolName, event.toolCallId);
1899
1892
  if (matched === void 0) {
1900
- transcript.push(
1901
- compact({
1902
- entryId: transcript.length,
1903
- kind: "tool",
1904
- toolName: event.toolName,
1905
- callId: event.toolCallId,
1906
- args: event.args,
1907
- result: event.result,
1908
- structuredResult: event.structuredResult
1909
- })
1910
- );
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);
1911
1903
  return;
1912
1904
  }
1913
1905
  matched.args = matched.args ?? event.args;
@@ -1919,17 +1911,16 @@ function acceptTranscriptStreamEvent(transcript, event) {
1919
1911
  if (event.type === "agent_tool_event") {
1920
1912
  const matched = findTranscriptToolEntry(transcript, event.toolName, event.toolCallId);
1921
1913
  if (matched === void 0) {
1922
- transcript.push(
1923
- compact({
1924
- entryId: transcript.length,
1925
- kind: "tool",
1926
- toolName: event.toolName,
1927
- callId: event.toolCallId,
1928
- childEvents: [childAgentTranscriptEvent(event)].filter(
1929
- (childEvent) => childEvent !== void 0
1930
- )
1931
- })
1932
- );
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);
1933
1924
  return;
1934
1925
  }
1935
1926
  appendChildAgentTranscriptEvent(matched, event);
@@ -1955,13 +1946,14 @@ function acceptTranscriptStreamEvent(transcript, event) {
1955
1946
  approvalCallId(event.approval)
1956
1947
  );
1957
1948
  if (matched !== void 0) {
1958
- matched.approval = compact({
1949
+ const approval = {
1959
1950
  id: event.approval.id,
1960
1951
  status: event.approval.status,
1961
- requestedAt: event.approval.requestedAt,
1962
- resolvedAt: event.approval.resolvedAt,
1963
- reason: event.approval.reason
1964
- });
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;
1965
1957
  }
1966
1958
  }
1967
1959
  if (event.type === "tool_question_request") {
@@ -1986,14 +1978,15 @@ function acceptTranscriptStreamEvent(transcript, event) {
1986
1978
  questionCallId(event.question)
1987
1979
  );
1988
1980
  if (matched !== void 0) {
1989
- matched.question = compact({
1981
+ const question = {
1990
1982
  id: event.question.id,
1991
1983
  status: event.question.status,
1992
1984
  requestedAt: event.question.requestedAt,
1993
- answeredAt: event.question.answeredAt,
1994
- questions: event.question.questions,
1995
- answers: event.question.answers
1996
- });
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;
1997
1990
  }
1998
1991
  }
1999
1992
  if (event.type === "final" && event.trace?.traceId !== void 0) {
@@ -2047,51 +2040,56 @@ function appendChildAgentTranscriptEvent(entry, event) {
2047
2040
  function childAgentTranscriptEvent(event) {
2048
2041
  const child = event.event;
2049
2042
  if (child.type === "text_delta") {
2050
- return compact({
2043
+ const entry = {
2051
2044
  kind: "message",
2052
2045
  agentId: event.agentId,
2053
- agentName: event.agentName,
2054
2046
  text: child.delta
2055
- });
2047
+ };
2048
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2049
+ return entry;
2056
2050
  }
2057
2051
  if (child.type === "reasoning_delta") {
2058
- return compact({
2052
+ const entry = {
2059
2053
  kind: "reasoning",
2060
2054
  agentId: event.agentId,
2061
- agentName: event.agentName,
2062
- reasoningId: child.id,
2063
2055
  text: child.delta
2064
- });
2056
+ };
2057
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2058
+ if (child.id !== void 0) entry.reasoningId = child.id;
2059
+ return entry;
2065
2060
  }
2066
2061
  if (child.type === "tool_call") {
2067
- return compact({
2062
+ const entry = {
2068
2063
  kind: "tool",
2069
2064
  agentId: event.agentId,
2070
- agentName: event.agentName,
2071
2065
  toolName: child.toolCall.function.name,
2072
2066
  callId: child.toolCall.callId ?? child.toolCall.id,
2073
2067
  args: formatJson(child.toolCall.function.arguments)
2074
- });
2068
+ };
2069
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2070
+ return entry;
2075
2071
  }
2076
2072
  if (child.type === "tool_result") {
2077
- return compact({
2073
+ const entry = {
2078
2074
  kind: "tool",
2079
2075
  agentId: event.agentId,
2080
- agentName: event.agentName,
2081
- toolName: child.toolName,
2082
- callId: child.toolCallId,
2083
- args: child.args,
2084
- result: child.result,
2085
- structuredResult: child.structuredResult
2086
- });
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;
2087
2084
  }
2088
2085
  if (child.type === "error") {
2089
- return compact({
2086
+ const entry = {
2090
2087
  kind: "message",
2091
2088
  agentId: event.agentId,
2092
- agentName: event.agentName,
2093
2089
  text: `Error: ${errorText(child.error)}`
2094
- });
2090
+ };
2091
+ if (event.agentName !== void 0) entry.agentName = event.agentName;
2092
+ return entry;
2095
2093
  }
2096
2094
  return void 0;
2097
2095
  }
@@ -2115,13 +2113,14 @@ function findChildAgentToolEvent(childEvents, event) {
2115
2113
  }
2116
2114
  function messageToTranscriptEntry(message, entryId) {
2117
2115
  const role = typeof message === "string" || message.role !== "assistant" ? "user" : "assistant";
2118
- return {
2116
+ const entry = {
2119
2117
  entryId,
2120
2118
  kind: "message",
2121
2119
  role,
2122
- text: extractMessageText(message),
2123
- ...role === "user" ? optionalTranscriptAttachments(message) : {}
2120
+ text: extractMessageText(message)
2124
2121
  };
2122
+ if (role === "user") Object.assign(entry, optionalTranscriptAttachments(message));
2123
+ return entry;
2125
2124
  }
2126
2125
  function appendTranscriptAssistantText(transcript, delta) {
2127
2126
  const last = transcript.at(-1);
@@ -2164,14 +2163,13 @@ function appendTranscriptReasoningText(transcript, delta, reasoningId) {
2164
2163
  last.text = `${last.text}${delta}`;
2165
2164
  return;
2166
2165
  }
2167
- transcript.push(
2168
- compact({
2169
- entryId: transcript.length,
2170
- kind: "reasoning",
2171
- reasoningId,
2172
- text: delta
2173
- })
2174
- );
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);
2175
2173
  }
2176
2174
  function findTranscriptToolEntry(transcript, toolName, callId) {
2177
2175
  for (let index = transcript.length - 1; index >= 0; index -= 1) {
@@ -2224,23 +2222,22 @@ function optionalTranscriptAttachments(message) {
2224
2222
  }
2225
2223
  const attachments = message.content.flatMap((content) => {
2226
2224
  if (content.type === "image") {
2227
- return [
2228
- {
2229
- kind: "image",
2230
- ...content.source.type === "base64" ? { data: content.source.data, mediaType: content.source.mediaType } : { url: content.source.url }
2231
- }
2232
- ];
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];
2233
2233
  }
2234
2234
  if (content.type === "document") {
2235
- return [
2236
- compact({
2237
- kind: "document",
2238
- name: content.source.filename,
2239
- mediaType: content.source.mediaType,
2240
- data: content.source.type === "base64" ? content.source.data : void 0,
2241
- url: content.source.type === "url" ? content.source.url : void 0
2242
- })
2243
- ];
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];
2244
2241
  }
2245
2242
  return [];
2246
2243
  });
@@ -2298,10 +2295,9 @@ function parseUiRunRequestBody(c, body) {
2298
2295
  };
2299
2296
  }
2300
2297
  const history = messages.slice(0, -1);
2301
- return {
2302
- message,
2303
- ...history.length === 0 ? {} : { history }
2304
- };
2298
+ const request = { message };
2299
+ if (history.length > 0) request.history = history;
2300
+ return request;
2305
2301
  }
2306
2302
  function parseRunRequestOptions(c, body, request) {
2307
2303
  if ("sessionId" in body) {
@@ -2407,14 +2403,23 @@ function sessionCreatedLog(session) {
2407
2403
  category: "session",
2408
2404
  event: "session.created",
2409
2405
  message: "Session created",
2410
- metadata: compact({
2406
+ metadata: {
2411
2407
  agentId: session.agentId,
2412
2408
  hasTitle: session.title !== void 0,
2413
2409
  titleLength: session.title?.length ?? 0
2414
- })
2410
+ }
2415
2411
  };
2416
2412
  }
2417
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;
2418
2423
  return {
2419
2424
  sessionId: props.sessionId,
2420
2425
  runId: props.runId,
@@ -2422,15 +2427,7 @@ function runReceivedLog(props) {
2422
2427
  category: "api",
2423
2428
  event: "run.received",
2424
2429
  message: "Run request received",
2425
- metadata: compact({
2426
- agentId: props.agentId,
2427
- stream: props.stream,
2428
- message: messageSummary(props.message),
2429
- maxTurns: props.maxTurns,
2430
- toolConcurrency: props.toolConcurrency,
2431
- hasTrace: props.hasTrace,
2432
- metadataKeys: Object.keys(props.metadata ?? {})
2433
- })
2430
+ metadata
2434
2431
  };
2435
2432
  }
2436
2433
  function runStartedLog(session, runId) {
@@ -2441,10 +2438,10 @@ function runStartedLog(session, runId) {
2441
2438
  category: "run",
2442
2439
  event: "run.started",
2443
2440
  message: "Run started",
2444
- metadata: compact({
2441
+ metadata: {
2445
2442
  agentId: session.agentId,
2446
2443
  existingMessageCount: session.messageCount
2447
- })
2444
+ }
2448
2445
  };
2449
2446
  }
2450
2447
  function memoryLoadedLog(session, runId) {
@@ -2455,13 +2452,20 @@ function memoryLoadedLog(session, runId) {
2455
2452
  category: "memory",
2456
2453
  event: "memory.loaded",
2457
2454
  message: "Session memory loaded",
2458
- metadata: compact({
2455
+ metadata: {
2459
2456
  messageCount: session.messageCount,
2460
2457
  transcriptEntries: session.transcript.length
2461
- })
2458
+ }
2462
2459
  };
2463
2460
  }
2464
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;
2465
2469
  return {
2466
2470
  sessionId: props.sessionId,
2467
2471
  runId: props.runId,
@@ -2469,15 +2473,12 @@ function runCompletedLog(props) {
2469
2473
  category: "run",
2470
2474
  event: "run.completed",
2471
2475
  message: "Run completed",
2472
- metadata: compact({
2473
- durationMs: props.durationMs,
2474
- usage: usageSummary(props.usage),
2475
- outputBytes: byteLength2(props.output),
2476
- messageCount: props.messageCount
2477
- })
2476
+ metadata
2478
2477
  };
2479
2478
  }
2480
2479
  function memorySavedLog(props) {
2480
+ const metadata = {};
2481
+ if (props.messageCount !== void 0) metadata.messageCount = props.messageCount;
2481
2482
  return {
2482
2483
  sessionId: props.sessionId,
2483
2484
  runId: props.runId,
@@ -2485,9 +2486,7 @@ function memorySavedLog(props) {
2485
2486
  category: "memory",
2486
2487
  event: "memory.saved",
2487
2488
  message: "Session memory saved",
2488
- metadata: compact({
2489
- messageCount: props.messageCount
2490
- })
2489
+ metadata
2491
2490
  };
2492
2491
  }
2493
2492
  function runFailedLog(sessionId, runId, error, startedAt) {
@@ -2498,10 +2497,10 @@ function runFailedLog(sessionId, runId, error, startedAt) {
2498
2497
  category: "run",
2499
2498
  event: "run.failed",
2500
2499
  message: "Run failed",
2501
- metadata: compact({
2500
+ metadata: {
2502
2501
  durationMs: Date.now() - startedAt,
2503
2502
  error: serializeError(error)
2504
- })
2503
+ }
2505
2504
  };
2506
2505
  }
2507
2506
  function logsFromStreamEvent(props) {
@@ -2515,11 +2514,11 @@ function logsFromStreamEvent(props) {
2515
2514
  category: "prompt",
2516
2515
  event: "prompt.prepared",
2517
2516
  message: `Turn ${event.turn} prompt prepared`,
2518
- metadata: compact({
2517
+ metadata: {
2519
2518
  turn: event.turn,
2520
2519
  prompt: messageSummary(event.prompt),
2521
2520
  historyCount: event.history.length
2522
- })
2521
+ }
2523
2522
  }
2524
2523
  ];
2525
2524
  }
@@ -2532,16 +2531,27 @@ function logsFromStreamEvent(props) {
2532
2531
  category: "tool",
2533
2532
  event: "tool.called",
2534
2533
  message: `Tool ${event.toolCall.function.name} called`,
2535
- metadata: compact({
2534
+ metadata: {
2536
2535
  turn: event.turn,
2537
2536
  toolName: event.toolCall.function.name,
2538
2537
  callId: event.toolCall.callId ?? event.toolCall.id,
2539
2538
  argumentBytes: byteLength2(formatUnknown(event.toolCall.function.arguments))
2540
- })
2539
+ }
2541
2540
  }
2542
2541
  ];
2543
2542
  }
2544
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
+ }
2545
2555
  return [
2546
2556
  {
2547
2557
  sessionId,
@@ -2550,19 +2560,17 @@ function logsFromStreamEvent(props) {
2550
2560
  category: "tool",
2551
2561
  event: "tool.completed",
2552
2562
  message: `Tool ${event.toolName} completed`,
2553
- metadata: compact({
2554
- turn: event.turn,
2555
- toolName: event.toolName,
2556
- callId: event.toolCallId,
2557
- internalCallId: event.internalCallId,
2558
- argumentBytes: byteLength2(event.args),
2559
- resultBytes: byteLength2(event.result),
2560
- structuredResultBytes: event.structuredResult === void 0 ? void 0 : byteLength2(JSON.stringify(event.structuredResult))
2561
- })
2563
+ metadata
2562
2564
  }
2563
2565
  ];
2564
2566
  }
2565
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;
2566
2574
  return [
2567
2575
  {
2568
2576
  sessionId,
@@ -2571,11 +2579,7 @@ function logsFromStreamEvent(props) {
2571
2579
  category: "model",
2572
2580
  event: "model.turn.completed",
2573
2581
  message: `Model turn ${event.turn} completed`,
2574
- metadata: compact({
2575
- turn: event.turn,
2576
- contentCount: event.response.choice.length,
2577
- usage: usageSummary(event.response.usage)
2578
- })
2582
+ metadata
2579
2583
  }
2580
2584
  ];
2581
2585
  }
@@ -2596,6 +2600,14 @@ function logsFromStreamEvent(props) {
2596
2600
  return [runFailedLog(sessionId, runId, event.error, props.startedAt)];
2597
2601
  }
2598
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;
2599
2611
  return [
2600
2612
  {
2601
2613
  sessionId,
@@ -2604,18 +2616,18 @@ function logsFromStreamEvent(props) {
2604
2616
  category: "approval",
2605
2617
  event: "approval.requested",
2606
2618
  message: `Approval requested for ${event.approval.toolName}`,
2607
- metadata: compact({
2608
- approvalId: event.approval.id,
2609
- toolName: event.approval.toolName,
2610
- callId: event.approval.callId,
2611
- status: event.approval.status,
2612
- hasReason: event.approval.reason !== void 0,
2613
- argumentBytes: byteLength2(event.approval.args)
2614
- })
2619
+ metadata
2615
2620
  }
2616
2621
  ];
2617
2622
  }
2618
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;
2619
2631
  return [
2620
2632
  {
2621
2633
  sessionId,
@@ -2624,17 +2636,19 @@ function logsFromStreamEvent(props) {
2624
2636
  category: "approval",
2625
2637
  event: "approval.resolved",
2626
2638
  message: `Approval ${event.approval.status} for ${event.approval.toolName}`,
2627
- metadata: compact({
2628
- approvalId: event.approval.id,
2629
- toolName: event.approval.toolName,
2630
- callId: event.approval.callId,
2631
- status: event.approval.status,
2632
- hasReason: event.approval.reason !== void 0
2633
- })
2639
+ metadata
2634
2640
  }
2635
2641
  ];
2636
2642
  }
2637
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;
2638
2652
  return [
2639
2653
  {
2640
2654
  sessionId,
@@ -2643,18 +2657,20 @@ function logsFromStreamEvent(props) {
2643
2657
  category: "question",
2644
2658
  event: "question.requested",
2645
2659
  message: `Question requested by ${event.question.toolName}`,
2646
- metadata: compact({
2647
- questionId: event.question.id,
2648
- toolName: event.question.toolName,
2649
- callId: event.question.callId,
2650
- status: event.question.status,
2651
- questionCount: event.question.questions.length,
2652
- argumentBytes: byteLength2(event.question.args)
2653
- })
2660
+ metadata
2654
2661
  }
2655
2662
  ];
2656
2663
  }
2657
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;
2658
2674
  return [
2659
2675
  {
2660
2676
  sessionId,
@@ -2663,13 +2679,7 @@ function logsFromStreamEvent(props) {
2663
2679
  category: "question",
2664
2680
  event: "question.answered",
2665
2681
  message: `Question answered for ${event.question.toolName}`,
2666
- metadata: compact({
2667
- questionId: event.question.id,
2668
- toolName: event.question.toolName,
2669
- callId: event.question.callId,
2670
- status: event.question.status,
2671
- answerCount: event.question.answers?.length ?? 0
2672
- })
2682
+ metadata
2673
2683
  }
2674
2684
  ];
2675
2685
  }
@@ -2695,7 +2705,7 @@ function childAgentLog(event, sessionId, runId) {
2695
2705
  category: "tool",
2696
2706
  event: "child_tool.called",
2697
2707
  message: `Child agent ${event.agentName ?? event.agentId} called ${child.toolCall.function.name}`,
2698
- metadata: compact({
2708
+ metadata: {
2699
2709
  parentToolName: event.toolName,
2700
2710
  agentId: event.agentId,
2701
2711
  hasAgentName: event.agentName !== void 0,
@@ -2704,11 +2714,24 @@ function childAgentLog(event, sessionId, runId) {
2704
2714
  toolName: child.toolCall.function.name,
2705
2715
  callId: child.toolCall.callId ?? child.toolCall.id,
2706
2716
  argumentBytes: byteLength2(formatUnknown(child.toolCall.function.arguments))
2707
- })
2717
+ }
2708
2718
  }
2709
2719
  ];
2710
2720
  }
2711
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
+ }
2712
2735
  return [
2713
2736
  {
2714
2737
  sessionId,
@@ -2717,17 +2740,7 @@ function childAgentLog(event, sessionId, runId) {
2717
2740
  category: "tool",
2718
2741
  event: "child_tool.completed",
2719
2742
  message: `Child agent ${event.agentName ?? event.agentId} completed ${child.toolName}`,
2720
- metadata: compact({
2721
- parentToolName: event.toolName,
2722
- agentId: event.agentId,
2723
- hasAgentName: event.agentName !== void 0,
2724
- turn: event.turn,
2725
- childTurn: child.turn,
2726
- toolName: child.toolName,
2727
- callId: child.toolCallId,
2728
- resultBytes: byteLength2(child.result),
2729
- structuredResultBytes: child.structuredResult === void 0 ? void 0 : byteLength2(JSON.stringify(child.structuredResult))
2730
- })
2743
+ metadata
2731
2744
  }
2732
2745
  ];
2733
2746
  }
@@ -2740,17 +2753,26 @@ function childAgentLog(event, sessionId, runId) {
2740
2753
  category: "run",
2741
2754
  event: "child_agent.turn_started",
2742
2755
  message: `Child agent ${event.agentName ?? event.agentId} turn ${child.turn} started`,
2743
- metadata: compact({
2756
+ metadata: {
2744
2757
  parentToolName: event.toolName,
2745
2758
  agentId: event.agentId,
2746
2759
  hasAgentName: event.agentName !== void 0,
2747
2760
  childTurn: child.turn,
2748
2761
  historyCount: child.history.length
2749
- })
2762
+ }
2750
2763
  }
2751
2764
  ];
2752
2765
  }
2753
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;
2754
2776
  return [
2755
2777
  {
2756
2778
  sessionId,
@@ -2759,14 +2781,7 @@ function childAgentLog(event, sessionId, runId) {
2759
2781
  category: "run",
2760
2782
  event: "child_agent.completed",
2761
2783
  message: `Child agent ${event.agentName ?? event.agentId} completed`,
2762
- metadata: compact({
2763
- parentToolName: event.toolName,
2764
- agentId: event.agentId,
2765
- hasAgentName: event.agentName !== void 0,
2766
- usage: usageSummary(child.usage),
2767
- outputBytes: byteLength2(child.output),
2768
- messageCount: child.messages.length
2769
- })
2784
+ metadata
2770
2785
  }
2771
2786
  ];
2772
2787
  }
@@ -2779,12 +2794,12 @@ function childAgentLog(event, sessionId, runId) {
2779
2794
  category: "run",
2780
2795
  event: "child_agent.failed",
2781
2796
  message: `Child agent ${event.agentName ?? event.agentId} failed`,
2782
- metadata: compact({
2797
+ metadata: {
2783
2798
  parentToolName: event.toolName,
2784
2799
  agentId: event.agentId,
2785
2800
  hasAgentName: event.agentName !== void 0,
2786
2801
  error: serializeError(child.error)
2787
- })
2802
+ }
2788
2803
  }
2789
2804
  ];
2790
2805
  }
@@ -2810,13 +2825,20 @@ function usageSummary(value) {
2810
2825
  return void 0;
2811
2826
  }
2812
2827
  const record = value;
2813
- return compact({
2814
- inputTokens: numericValue(record.inputTokens),
2815
- outputTokens: numericValue(record.outputTokens),
2816
- totalTokens: numericValue(record.totalTokens),
2817
- cachedInputTokens: numericValue(record.cachedInputTokens),
2818
- cacheCreationInputTokens: numericValue(record.cacheCreationInputTokens)
2819
- });
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;
2820
2842
  }
2821
2843
  function numericValue(value) {
2822
2844
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
@@ -2940,25 +2962,27 @@ async function recordRunReceived(props) {
2940
2962
  if (props.session === void 0) {
2941
2963
  return;
2942
2964
  }
2943
- await appendSessionLog(
2944
- props.store,
2945
- runReceivedLog({
2946
- sessionId: props.session.id,
2947
- runId: props.runId,
2948
- agentId: props.agentId,
2949
- message: props.body.message,
2950
- stream: props.body.stream === true,
2951
- ...compact({ maxTurns: props.body.maxTurns }),
2952
- ...compact({ toolConcurrency: props.body.toolConcurrency }),
2953
- hasTrace: props.body.trace !== void 0,
2954
- ...props.body.metadata === void 0 && props.selectedModel.ref === void 0 ? {} : {
2955
- metadata: {
2956
- ...props.body.metadata ?? {},
2957
- ...props.selectedModel.ref === void 0 ? {} : { [STUDIO_MODEL_METADATA_KEY]: props.selectedModel.ref }
2958
- }
2959
- }
2960
- })
2961
- );
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));
2962
2986
  }
2963
2987
  async function recordSelectedModelWarnings(props) {
2964
2988
  if (props.session === void 0 || props.selectedModel.ref === void 0) {
@@ -2976,19 +3000,18 @@ async function recordSelectedModelWarnings(props) {
2976
3000
  });
2977
3001
  }
2978
3002
  if (sessionModelRef(props.session.metadata) !== props.selectedModel.ref) {
2979
- await props.store?.updateSessionMetadata?.(props.session.id, {
2980
- ...props.session.metadata ?? {},
2981
- [STUDIO_MODEL_METADATA_KEY]: props.selectedModel.ref
2982
- });
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);
2983
3007
  }
2984
3008
  }
2985
3009
  function runMemoryMetadata(agentId, body, selectedModel, runId) {
2986
- return {
2987
- agentId,
2988
- ...body.metadata ?? {},
2989
- ...selectedModel.ref === void 0 ? {} : { [STUDIO_MODEL_METADATA_KEY]: selectedModel.ref },
2990
- studioRunId: runId
2991
- };
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;
2992
3015
  }
2993
3016
  function createRunRequest(props) {
2994
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(
@@ -3009,24 +3032,24 @@ function createRunRequest(props) {
3009
3032
  }
3010
3033
  function handleStreamingAgentRun(c, run, props) {
3011
3034
  const runtimeEvents = new AsyncEventQueue();
3012
- run.request.approvals(
3013
- props.approvalRuntime.createApprovals({
3014
- runId: run.runId,
3015
- agentId: run.agentId,
3016
- ...compact({ sessionId: run.session?.id }),
3017
- ...compact({ metadata: run.body.metadata }),
3018
- emit: (event) => runtimeEvents.push(event)
3019
- })
3020
- );
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;
3021
3050
  const effectiveHook = composeHooks(
3022
3051
  run.runAgent.hook,
3023
- props.questionRuntime.createHook({
3024
- runId: run.runId,
3025
- agentId: run.agentId,
3026
- ...compact({ sessionId: run.session?.id }),
3027
- ...compact({ metadata: run.body.metadata }),
3028
- emit: (event) => runtimeEvents.push(event)
3029
- })
3052
+ props.questionRuntime.createHook(questionContext)
3030
3053
  );
3031
3054
  if (effectiveHook !== void 0) {
3032
3055
  run.request.requestHook(effectiveHook);
@@ -3064,23 +3087,23 @@ async function startBufferedSessionRun(run, props) {
3064
3087
  await appendSessionLog(run.sessionStore, runStartedLog(run.session, run.runId));
3065
3088
  await appendSessionLog(run.sessionStore, memoryLoadedLog(run.session, run.runId));
3066
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;
3067
3096
  const effectiveHook = composeHooks(
3068
3097
  run.runAgent.hook,
3069
- props.questionRuntime.createHook({
3070
- runId: run.runId,
3071
- agentId: run.agentId,
3072
- ...compact({ sessionId: run.session?.id }),
3073
- ...compact({ metadata: run.body.metadata })
3074
- })
3075
- );
3076
- run.request.approvals(
3077
- props.approvalRuntime.createApprovals({
3078
- runId: run.runId,
3079
- agentId: run.agentId,
3080
- ...compact({ sessionId: run.session?.id }),
3081
- ...compact({ metadata: run.body.metadata })
3082
- })
3098
+ props.questionRuntime.createHook(questionContext)
3083
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));
3084
3107
  if (effectiveHook !== void 0) {
3085
3108
  run.request.requestHook(effectiveHook);
3086
3109
  }
@@ -3254,10 +3277,8 @@ async function parseApprovalDecisionRequest(c) {
3254
3277
  if ("reason" in body && typeof body.reason !== "string") {
3255
3278
  return { error: errorResponse(c, 400, "bad_request", "reason must be a string") };
3256
3279
  }
3257
- return compact({
3258
- approved: body.approved,
3259
- reason: typeof body.reason === "string" && body.reason.trim().length > 0 ? body.reason.trim() : void 0
3260
- });
3280
+ const reason = typeof body.reason === "string" && body.reason.trim().length > 0 ? body.reason.trim() : void 0;
3281
+ return approvalDecision(body.approved, reason);
3261
3282
  }
3262
3283
  function createApprovalRuntime() {
3263
3284
  const approvals = /* @__PURE__ */ new Map();
@@ -3266,19 +3287,18 @@ function createApprovalRuntime() {
3266
3287
  createApprovals(context) {
3267
3288
  return {
3268
3289
  async handler(request) {
3269
- const decision = await requestApproval(
3270
- approvals,
3271
- context,
3272
- compact({
3273
- toolName: request.toolName,
3274
- toolCallId: request.toolCallId,
3275
- internalCallId: request.internalCallId,
3276
- args: request.rawArgs,
3277
- reason: request.reason,
3278
- rejectMessage: request.rejectMessage
3279
- })
3280
- );
3281
- 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);
3282
3302
  }
3283
3303
  };
3284
3304
  },
@@ -3314,16 +3334,11 @@ function createApprovalRuntime() {
3314
3334
  const resolved = resolveApproval(
3315
3335
  approval,
3316
3336
  decision.approved ? "approved" : "rejected",
3317
- compact({ reason })
3337
+ reason === void 0 ? {} : { reason }
3318
3338
  );
3319
3339
  approvals.set(id, resolved);
3320
3340
  approval.emit?.({ type: "tool_approval_result", approval: resolved });
3321
- approval.resolve(
3322
- compact({
3323
- approved: decision.approved,
3324
- reason
3325
- })
3326
- );
3341
+ approval.resolve(approvalDecision(decision.approved, reason));
3327
3342
  return publicApproval(resolved);
3328
3343
  }
3329
3344
  };
@@ -3331,35 +3346,28 @@ function createApprovalRuntime() {
3331
3346
  async function requestApproval(approvals, context, request) {
3332
3347
  const id = globalThis.crypto.randomUUID();
3333
3348
  const approval = {
3334
- ...compact({
3335
- id,
3336
- runId: context.runId,
3337
- agentId: context.agentId,
3338
- sessionId: context.sessionId,
3339
- toolName: request.toolName,
3340
- callId: request.toolCallId,
3341
- internalCallId: request.internalCallId,
3342
- args: request.args,
3343
- status: "pending",
3344
- requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
3345
- reason: request.reason,
3346
- rejectMessage: request.rejectMessage,
3347
- emit: context.emit
3348
- }),
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(),
3349
3357
  resolve: () => {
3350
3358
  }
3351
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;
3352
3365
  const decision = new Promise((resolve2) => {
3353
3366
  approval.resolve = (decision2) => {
3354
3367
  const current = approvals.get(id);
3355
3368
  if (!isPendingApproval(current)) {
3356
3369
  if (current !== void 0) {
3357
- resolve2(
3358
- compact({
3359
- approved: current.status === "approved",
3360
- reason: current.reason
3361
- })
3362
- );
3370
+ resolve2(approvalDecision(current.status === "approved", current.reason));
3363
3371
  }
3364
3372
  return;
3365
3373
  }
@@ -3367,16 +3375,11 @@ async function requestApproval(approvals, context, request) {
3367
3375
  const resolved = resolveApproval(
3368
3376
  current,
3369
3377
  decision2.approved ? "approved" : "rejected",
3370
- compact({ reason })
3378
+ reason === void 0 ? {} : { reason }
3371
3379
  );
3372
3380
  approvals.set(id, resolved);
3373
3381
  context.emit?.({ type: "tool_approval_result", approval: resolved });
3374
- resolve2(
3375
- compact({
3376
- approved: decision2.approved,
3377
- reason
3378
- })
3379
- );
3382
+ resolve2(approvalDecision(decision2.approved, reason));
3380
3383
  };
3381
3384
  });
3382
3385
  approvals.set(id, approval);
@@ -3387,14 +3390,18 @@ function isPendingApproval(approval) {
3387
3390
  return approval !== void 0 && approval.status === "pending" && "resolve" in approval;
3388
3391
  }
3389
3392
  function resolveApproval(approval, status, options = {}) {
3390
- return publicApproval({
3393
+ const resolved = {
3391
3394
  ...approval,
3392
- ...compact({
3393
- status,
3394
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString(),
3395
- reason: options.reason
3396
- })
3397
- });
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;
3398
3405
  }
3399
3406
  function publicApproval(approval) {
3400
3407
  const { emit, rejectMessage, resolve: resolve2, ...rest } = approval;
@@ -3410,18 +3417,19 @@ var PREVIEW_VALUE_MAX_LENGTH = 500;
3410
3417
  function evalConfig(suite) {
3411
3418
  const casePreviews = suite.cases.slice(0, CASE_PREVIEW_LIMIT).map(casePreview);
3412
3419
  const metricSummaries = suite.metrics.map(metricSummary);
3413
- return compact({
3420
+ const config = {
3414
3421
  id: suite.id ?? suite.name,
3415
3422
  name: suite.name,
3416
- description: suite.description,
3417
3423
  caseCount: suite.cases.length,
3418
3424
  metricNames: suite.metrics.map((metric) => metric.name),
3419
3425
  casePreviewCount: casePreviews.length,
3420
3426
  casePreviews,
3421
- metricSummaries,
3422
- concurrency: suite.concurrency,
3423
- metadata: suite.metadata
3424
- });
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;
3425
3433
  }
3426
3434
  function casePreview(testCase, index) {
3427
3435
  if (!isRecord2(testCase)) {
@@ -3430,24 +3438,29 @@ function casePreview(testCase, index) {
3430
3438
  input: previewValue(testCase)
3431
3439
  };
3432
3440
  }
3433
- return compact({
3434
- id: typeof testCase.id === "string" && testCase.id.length > 0 ? testCase.id : `case-${index + 1}`,
3435
- input: "input" in testCase ? previewValue(testCase.input) : void 0,
3436
- expected: "expected" in testCase ? previewValue(testCase.expected) : void 0,
3437
- metadataKeys: metadataKeys(testCase.metadata)
3438
- });
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;
3439
3449
  }
3440
3450
  function metricSummary(metric, index) {
3441
3451
  if (!isRecord2(metric)) {
3442
3452
  return { name: `metric-${index + 1}` };
3443
3453
  }
3444
- return compact({
3445
- name: typeof metric.name === "string" && metric.name.length > 0 ? metric.name : `metric-${index + 1}`,
3446
- dataType: metricDataType(metric.dataType),
3447
- configId: typeof metric.configId === "string" ? metric.configId : void 0,
3448
- scoreConfigId: typeof metric.scoreConfigId === "string" ? metric.scoreConfigId : void 0,
3449
- metadataKeys: metadataKeys(metric.metadata)
3450
- });
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;
3451
3464
  }
3452
3465
  function previewValue(value) {
3453
3466
  const jsonValue = toJsonValue(value);
@@ -3492,11 +3505,10 @@ function approvalMetadata(tool) {
3492
3505
  return { required: false };
3493
3506
  }
3494
3507
  const policy = approval;
3495
- return {
3496
- required: true,
3497
- ...typeof policy.reason === "string" ? { reason: policy.reason } : {},
3498
- ...typeof policy.rejectMessage === "string" ? { rejectMessage: policy.rejectMessage } : {}
3499
- };
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;
3500
3512
  }
3501
3513
  function mcpServerName(tool) {
3502
3514
  const metadata = tool[MCP_TOOL_METADATA_KEY];
@@ -3517,22 +3529,21 @@ function runnerId(options) {
3517
3529
  function agentConfig(agent) {
3518
3530
  const name = agent.name ?? agent.agent.name;
3519
3531
  const description = agent.description ?? agent.agent.description;
3520
- return compact({
3532
+ const config = {
3521
3533
  id: agent.id,
3522
- name,
3523
- description,
3524
- quickPrompts: agent.quickPrompts ?? [],
3525
- metadata: agent.metadata
3526
- });
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;
3527
3540
  }
3528
3541
  function agentRuntimeSummary(agent) {
3529
3542
  const tools = agentToolItems(agent);
3530
3543
  const name = agent.name ?? agent.agent.name;
3531
3544
  const description = agent.description ?? agent.agent.description;
3532
- return compact({
3545
+ const summary = {
3533
3546
  id: agent.id,
3534
- name,
3535
- description,
3536
3547
  model: toJsonValue2(agent.agent.model),
3537
3548
  toolCount: tools.length,
3538
3549
  staticToolCount: tools.filter((item) => item.source === "static").length,
@@ -3544,35 +3555,37 @@ function agentRuntimeSummary(agent) {
3544
3555
  observerCount: agent.agent.observers.length,
3545
3556
  hasMemory: agent.agent.memory !== void 0,
3546
3557
  hasHook: agent.agent.hook !== void 0,
3547
- hasOutputSchema: agent.agent.outputSchema !== void 0,
3548
- defaultMaxTurns: agent.agent.defaultMaxTurns,
3549
- metadata: agent.metadata
3550
- });
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;
3551
3567
  }
3552
3568
  function pipelineConfig(pipeline) {
3553
3569
  const graph = pipeline.pipeline.graph();
3554
3570
  const stageNodes = graph.nodes.filter((node) => node.kind !== "input" && node.kind !== "output");
3555
- return compact({
3571
+ const config = {
3556
3572
  id: pipeline.id,
3557
- name: pipeline.name,
3558
- description: pipeline.description,
3559
- metadata: pipeline.metadata,
3560
3573
  stageCount: stageNodes.length,
3561
3574
  edgeCount: graph.edges.length,
3562
3575
  hasParallelStages: graph.nodes.some((node) => node.kind === "parallel"),
3563
3576
  agentCount: graph.nodes.filter((node) => node.kind === "agent").length,
3564
3577
  extractorCount: graph.nodes.filter((node) => node.kind === "extractor").length
3565
- });
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;
3566
3583
  }
3567
3584
  function buildConfig(options, agents, pipelines, stores) {
3568
3585
  const models = options.models === void 0 ? void 0 : studioModelsConfig(createStudioModelRegistry(options.models), agents);
3569
- return compact({
3586
+ const config = {
3570
3587
  id: runnerId(options),
3571
- name: options.name,
3572
- description: options.description,
3573
- version: options.version,
3574
3588
  agents: agents.map(agentConfig),
3575
- models,
3576
3589
  pipelines: pipelines.map(pipelineConfig),
3577
3590
  evals: options.evals.map(evalConfig),
3578
3591
  chat: {
@@ -3580,7 +3593,12 @@ function buildConfig(options, agents, pipelines, stores) {
3580
3593
  },
3581
3594
  capabilities: capabilityConfig(options, agents, pipelines, stores),
3582
3595
  unsupportedCapabilities: unsupportedCapabilities(stores)
3583
- });
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;
3584
3602
  }
3585
3603
  function capabilityConfig(_options, agents, pipelines, stores) {
3586
3604
  const capabilities = {
@@ -3622,10 +3640,10 @@ function capabilityConfig(_options, agents, pipelines, stores) {
3622
3640
  return capabilities;
3623
3641
  }
3624
3642
  function unsupportedCapabilities(stores) {
3625
- return [
3626
- ...stores.sessions === void 0 ? ["sessions"] : [],
3627
- ...stores.traces === void 0 ? ["traces"] : []
3628
- ];
3643
+ const capabilities = [];
3644
+ if (stores.sessions === void 0) capabilities.push("sessions");
3645
+ if (stores.traces === void 0) capabilities.push("traces");
3646
+ return capabilities;
3629
3647
  }
3630
3648
  function toJsonValue2(value) {
3631
3649
  return serializeUnknown(value);
@@ -3658,10 +3676,9 @@ function registerEvalRoutes(app, props) {
3658
3676
  }
3659
3677
  const runId = globalThis.crypto.randomUUID();
3660
3678
  const startedAt = Date.now();
3661
- const result = await runEvalSuite({
3662
- ...suite,
3663
- ...compact({ concurrency: body.concurrency })
3664
- });
3679
+ const runOptions = { ...suite };
3680
+ if (body.concurrency !== void 0) runOptions.concurrency = body.concurrency;
3681
+ const result = await runEvalSuite(runOptions);
3665
3682
  const endedAt = Date.now();
3666
3683
  const jsonResult = toJsonValue(result);
3667
3684
  const response = {
@@ -3736,18 +3753,19 @@ function registerKnowledgeRoutes(app, props) {
3736
3753
  }
3737
3754
  async function agentKnowledgeConfig(agent) {
3738
3755
  const agentName = agent.name ?? agent.agent.name;
3739
- return {
3756
+ const config = {
3740
3757
  agentId: agent.id,
3741
- ...compact({ agentName }),
3742
3758
  sources: await knowledgeSources(agent),
3743
- staticContext: agent.agent.staticContext.map((document) => ({
3744
- id: document.id,
3745
- text: document.text,
3746
- ...compact({
3747
- additionalProps: document.additionalProps !== void 0 ? jsonObjectFromRecord(document.additionalProps) : void 0
3748
- })
3749
- }))
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
+ })
3750
3766
  };
3767
+ if (agentName !== void 0) config.agentName = agentName;
3768
+ return config;
3751
3769
  }
3752
3770
  async function knowledgeSources(agent) {
3753
3771
  const sources = [
@@ -3764,34 +3782,40 @@ async function knowledgeSources(agent) {
3764
3782
  agent.agent.dynamicContexts.map(async (registration, index) => {
3765
3783
  const inspect = inspectFn(registration.index);
3766
3784
  const count = await inspectableCount(inspect, registration.options.filter);
3767
- return {
3785
+ const source = {
3768
3786
  sourceId: dynamicContextSourceId(index),
3769
3787
  kind: "dynamic_context",
3770
3788
  label: `Dynamic context ${index + 1}`,
3771
3789
  count: 1,
3772
3790
  registrationIndex: index,
3773
3791
  topK: registration.options.topK,
3774
- ...compact({ threshold: registration.options.threshold }),
3775
- inspectable: inspect !== void 0,
3776
- ...compact({ itemCount: count })
3792
+ inspectable: inspect !== void 0
3777
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;
3778
3799
  })
3779
3800
  );
3780
3801
  const dynamicToolSources = await Promise.all(
3781
3802
  agent.agent.dynamicTools.map(async (registration, index) => {
3782
3803
  const inspect = inspectFn(registration.index);
3783
3804
  const count = await inspectableCount(inspect, registration.options.filter);
3784
- return {
3805
+ const source = {
3785
3806
  sourceId: dynamicToolsSourceId(index),
3786
3807
  kind: "dynamic_tools",
3787
3808
  label: `Dynamic tools ${index + 1}`,
3788
3809
  count: 1,
3789
3810
  registrationIndex: index,
3790
3811
  topK: registration.options.topK,
3791
- ...compact({ threshold: registration.options.threshold }),
3792
- inspectable: inspect !== void 0,
3793
- ...compact({ itemCount: count })
3812
+ inspectable: inspect !== void 0
3794
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;
3795
3819
  })
3796
3820
  );
3797
3821
  return [...sources, ...dynamicContextSources, ...dynamicToolSources];
@@ -3822,14 +3846,16 @@ async function knowledgeItemsPage(agent, sourceId, request) {
3822
3846
  cursor: request.cursor,
3823
3847
  filter: registration.options.filter
3824
3848
  });
3825
- return {
3849
+ const result = {
3826
3850
  agentId: agent.id,
3827
3851
  sourceId,
3828
3852
  kind: "dynamic_context",
3829
3853
  inspectable: true,
3830
- items: page.items.map((item) => dynamicContextItem(item)),
3831
- ...compact({ nextCursor: page.nextCursor, totalCount: page.totalCount })
3854
+ items: page.items.map((item) => dynamicContextItem(item))
3832
3855
  };
3856
+ if (page.nextCursor !== void 0) result.nextCursor = page.nextCursor;
3857
+ if (page.totalCount !== void 0) result.totalCount = page.totalCount;
3858
+ return result;
3833
3859
  }
3834
3860
  const dynamicToolsIndex = dynamicSourceIndex(sourceId, "dynamic_tools");
3835
3861
  if (dynamicToolsIndex !== void 0) {
@@ -3846,14 +3872,16 @@ async function knowledgeItemsPage(agent, sourceId, request) {
3846
3872
  cursor: request.cursor,
3847
3873
  filter: registration.options.filter
3848
3874
  });
3849
- return {
3875
+ const result = {
3850
3876
  agentId: agent.id,
3851
3877
  sourceId,
3852
3878
  kind: "dynamic_tools",
3853
3879
  inspectable: true,
3854
- items: page.items.map((item) => dynamicToolItem(item)),
3855
- ...compact({ nextCursor: page.nextCursor, totalCount: page.totalCount })
3880
+ items: page.items.map((item) => dynamicToolItem(item))
3856
3881
  };
3882
+ if (page.nextCursor !== void 0) result.nextCursor = page.nextCursor;
3883
+ if (page.totalCount !== void 0) result.totalCount = page.totalCount;
3884
+ return result;
3857
3885
  }
3858
3886
  return void 0;
3859
3887
  }
@@ -3868,24 +3896,26 @@ function staticKnowledgeItemsPage(agent, request) {
3868
3896
  const start = Math.max(0, Math.trunc(Number(request.cursor ?? "0")));
3869
3897
  const page = agent.agent.staticContext.slice(start, start + request.limit);
3870
3898
  const nextOffset = start + page.length;
3871
- return {
3899
+ const result = {
3872
3900
  agentId: agent.id,
3873
3901
  sourceId: staticSourceId(),
3874
3902
  kind: "static_context",
3875
3903
  inspectable: true,
3876
- items: page.map((document) => ({
3877
- id: document.id,
3878
- kind: "static_context",
3879
- text: document.text,
3880
- ...compact({
3881
- metadata: document.additionalProps !== void 0 ? jsonObjectFromRecord(document.additionalProps) : void 0
3882
- })
3883
- })),
3884
- ...compact({
3885
- 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;
3886
3914
  }),
3887
3915
  totalCount: agent.agent.staticContext.length
3888
3916
  };
3917
+ if (nextOffset < agent.agent.staticContext.length) result.nextCursor = String(nextOffset);
3918
+ return result;
3889
3919
  }
3890
3920
  function nonInspectablePage(agentId, sourceId, kind) {
3891
3921
  return {
@@ -3899,31 +3929,30 @@ function nonInspectablePage(agentId, sourceId, kind) {
3899
3929
  }
3900
3930
  function dynamicContextItem(item) {
3901
3931
  const text = isRecord3(item.document) && typeof item.document.text === "string" ? item.document.text : typeof item.document === "string" ? item.document : void 0;
3902
- return {
3932
+ const result = {
3903
3933
  id: item.id,
3904
- kind: "dynamic_context",
3905
- ...text === void 0 ? { document: toJsonValue(item.document) } : { text },
3906
- ...compact({
3907
- metadata: item.metadata !== void 0 ? jsonObjectFromRecord(item.metadata) : void 0
3908
- })
3934
+ kind: "dynamic_context"
3909
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;
3910
3940
  }
3911
3941
  function dynamicToolItem(item) {
3912
3942
  const document = isRecord3(item.document) ? item.document : {};
3913
3943
  const definition = isRecord3(document.definition) ? document.definition : {};
3914
3944
  const toolName = typeof document.toolName === "string" ? document.toolName : typeof definition.name === "string" ? definition.name : item.id;
3915
3945
  const description = typeof definition.description === "string" ? definition.description : "";
3916
- return {
3946
+ const result = {
3917
3947
  id: item.id,
3918
3948
  kind: "dynamic_tool",
3919
3949
  toolName,
3920
3950
  description,
3921
3951
  parameterKeys: parameterKeys(definition.parameters),
3922
- document: toJsonValue(item.document),
3923
- ...compact({
3924
- metadata: item.metadata !== void 0 ? jsonObjectFromRecord(item.metadata) : void 0
3925
- })
3952
+ document: toJsonValue(item.document)
3926
3953
  };
3954
+ if (item.metadata !== void 0) result.metadata = jsonObjectFromRecord(item.metadata);
3955
+ return result;
3927
3956
  }
3928
3957
  function parameterKeys(parameters) {
3929
3958
  if (!isRecord3(parameters) || !isRecord3(parameters.properties)) {
@@ -3976,21 +4005,20 @@ function evidenceFromTrace(trace) {
3976
4005
  return [];
3977
4006
  }
3978
4007
  const query = queryFromGenerationInput(observation.input);
3979
- return [
3980
- {
3981
- traceId: trace.id,
3982
- sessionId: trace.sessionId,
3983
- observationId: observation.id,
3984
- observationName: observation.name,
3985
- turn: observation.turn,
3986
- startedAt: observation.startedAt,
3987
- ...compact({ query }),
3988
- documentCount: documents.length,
3989
- toolCount: tools.length,
3990
- documents,
3991
- tools
3992
- }
3993
- ];
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];
3994
4022
  });
3995
4023
  }
3996
4024
  function queryFromGenerationInput(value) {
@@ -4056,7 +4084,11 @@ function evidenceDocument(value) {
4056
4084
  if (id === void 0 && text === void 0 && additionalProps === void 0) {
4057
4085
  return [];
4058
4086
  }
4059
- 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];
4060
4092
  }
4061
4093
  function evidenceToolName(value) {
4062
4094
  if (!isRecord3(value) || typeof value.name !== "string") {
@@ -4167,10 +4199,9 @@ function registerMemoryRoutes(app, props) {
4167
4199
  }
4168
4200
  const agentId = optionalQueryString(c.req.query("agentId"));
4169
4201
  const userId = optionalQueryString(c.req.query("userId"));
4170
- const sessions = await props.sessionStore.listSessions({
4171
- ...compact({ agentId }),
4172
- limit: 100
4173
- });
4202
+ const listInput = { limit: 100 };
4203
+ if (agentId !== void 0) listInput.agentId = agentId;
4204
+ const sessions = await props.sessionStore.listSessions(listInput);
4174
4205
  const conversations = sessions.map(memoryConversationSummary).filter((session) => userId === void 0 || session.userId === userId).slice(0, limit);
4175
4206
  return c.json({
4176
4207
  conversations,
@@ -4200,16 +4231,17 @@ function registerMemoryRoutes(app, props) {
4200
4231
  });
4201
4232
  }
4202
4233
  function memoryConversationSummary(session) {
4203
- return compact({
4234
+ const summary = {
4204
4235
  id: session.id,
4205
4236
  userId: sessionUserId(session),
4206
4237
  agentId: session.agentId,
4207
- title: session.title,
4208
4238
  createdAt: session.createdAt,
4209
4239
  updatedAt: session.updatedAt,
4210
- messageCount: session.messageCount,
4211
- metadata: session.metadata
4212
- });
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;
4213
4245
  }
4214
4246
  function sessionUserId(session) {
4215
4247
  const userId = session.metadata?.userId;
@@ -4227,6 +4259,12 @@ async function* emitPipelineLog(store, input) {
4227
4259
  }
4228
4260
  }
4229
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;
4230
4268
  return {
4231
4269
  pipelineId: props.pipeline.id,
4232
4270
  runId: props.runId,
@@ -4234,11 +4272,7 @@ function pipelineRunReceivedLog(props) {
4234
4272
  category: "api",
4235
4273
  event: "pipeline.run_received",
4236
4274
  message: "Pipeline run request received",
4237
- metadata: compact({
4238
- stream: props.stream,
4239
- inputBytes: byteLength3(formatUnknown(props.input)),
4240
- metadataKeys: Object.keys(props.metadata ?? {})
4241
- })
4275
+ metadata
4242
4276
  };
4243
4277
  }
4244
4278
  function pipelineRunStartedLog(pipeline, runId) {
@@ -4250,13 +4284,16 @@ function pipelineRunStartedLog(pipeline, runId) {
4250
4284
  category: "run",
4251
4285
  event: "pipeline.run_started",
4252
4286
  message: "Pipeline run started",
4253
- metadata: compact({
4287
+ metadata: {
4254
4288
  stageCount: graph.nodes.filter((node) => node.kind !== "input" && node.kind !== "output").length,
4255
4289
  edgeCount: graph.edges.length
4256
- })
4290
+ }
4257
4291
  };
4258
4292
  }
4259
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;
4260
4297
  return {
4261
4298
  pipelineId: props.pipelineId,
4262
4299
  runId: props.runId,
@@ -4264,10 +4301,7 @@ function pipelineRunCompletedLog(props) {
4264
4301
  category: "run",
4265
4302
  event: "pipeline.run_completed",
4266
4303
  message: "Pipeline run completed",
4267
- metadata: compact({
4268
- durationMs: props.durationMs,
4269
- outputBytes: byteLength3(formatUnknown(props.output))
4270
- })
4304
+ metadata
4271
4305
  };
4272
4306
  }
4273
4307
  function pipelineRunFailedLog(pipelineId, runId, error, startedAt) {
@@ -4278,10 +4312,10 @@ function pipelineRunFailedLog(pipelineId, runId, error, startedAt) {
4278
4312
  category: "run",
4279
4313
  event: "pipeline.run_failed",
4280
4314
  message: "Pipeline run failed",
4281
- metadata: compact({
4315
+ metadata: {
4282
4316
  durationMs: Date.now() - startedAt,
4283
4317
  error: serializeError(error)
4284
- })
4318
+ }
4285
4319
  };
4286
4320
  }
4287
4321
  function pipelineStageLog(pipelineId, runId, event) {
@@ -4305,10 +4339,10 @@ function pipelineStageLog(pipelineId, runId, event) {
4305
4339
  category,
4306
4340
  event: `${event.node.kind}.completed`,
4307
4341
  message: `${event.node.label} completed`,
4308
- metadata: compact({
4342
+ metadata: {
4309
4343
  ...nodeMetadata(event.node),
4310
4344
  durationMs: event.durationMs
4311
- })
4345
+ }
4312
4346
  };
4313
4347
  }
4314
4348
  return {
@@ -4318,11 +4352,11 @@ function pipelineStageLog(pipelineId, runId, event) {
4318
4352
  category,
4319
4353
  event: `${event.node.kind}.failed`,
4320
4354
  message: `${event.node.label} failed`,
4321
- metadata: compact({
4355
+ metadata: {
4322
4356
  ...nodeMetadata(event.node),
4323
4357
  durationMs: event.durationMs,
4324
4358
  error: serializeError(event.error)
4325
- })
4359
+ }
4326
4360
  };
4327
4361
  }
4328
4362
  function stageCategory(node) {
@@ -4338,14 +4372,15 @@ function stageCategory(node) {
4338
4372
  return "stage";
4339
4373
  }
4340
4374
  function nodeMetadata(node) {
4341
- return compact({
4375
+ const metadata = {
4342
4376
  nodeId: node.id,
4343
4377
  kind: node.kind,
4344
- label: node.label,
4345
- agentId: node.agentId,
4346
- pipelineId: node.pipelineId,
4347
- branchKey: node.branchKey
4348
- });
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;
4349
4384
  }
4350
4385
  function byteLength3(value) {
4351
4386
  return value === void 0 ? void 0 : new TextEncoder().encode(value).length;
@@ -4388,16 +4423,16 @@ function registerPipelineRoutes(app, props) {
4388
4423
  if (after === false) {
4389
4424
  return errorResponse(c, 400, "bad_request", "after must be a non-negative integer");
4390
4425
  }
4391
- const logs = await props.logStore.listPipelineLogs({
4426
+ const listInput = {
4392
4427
  pipelineId,
4393
- limit,
4394
- ...compact({ after })
4395
- });
4428
+ limit
4429
+ };
4430
+ if (after !== void 0) listInput.after = after;
4431
+ const logs = await props.logStore.listPipelineLogs(listInput);
4396
4432
  const last = logs.at(-1);
4397
- return c.json({
4398
- logs,
4399
- ...logs.length === limit && last !== void 0 ? { nextCursor: last.sequence } : {}
4400
- });
4433
+ const response = { logs };
4434
+ if (logs.length === limit && last !== void 0) response.nextCursor = last.sequence;
4435
+ return c.json(response);
4401
4436
  });
4402
4437
  app.get("/pipelines/:pipelineId/runs", async (c) => {
4403
4438
  const pipelineId = c.req.param("pipelineId");
@@ -4460,45 +4495,47 @@ function registerPipelineRoutes(app, props) {
4460
4495
  if (sourceRun.status === "running") {
4461
4496
  return errorResponse(c, 409, "conflict", "Cannot replay a running pipeline run");
4462
4497
  }
4463
- return executePipelineRun(c, props, pipeline, {
4498
+ const replayRequest = {
4464
4499
  input: sourceRun.input,
4465
- ...compact({ stream: body.stream }),
4466
4500
  metadata: replayMetadata(sourceRun.metadata, body.metadata, sourceRun.runId)
4467
- });
4501
+ };
4502
+ if (body.stream !== void 0) replayRequest.stream = body.stream;
4503
+ return executePipelineRun(c, props, pipeline, replayRequest);
4468
4504
  });
4469
4505
  }
4470
4506
  async function executePipelineRun(c, props, pipeline, body) {
4471
4507
  const runId = globalThis.crypto.randomUUID();
4472
4508
  const startedAt = Date.now();
4473
4509
  const startedAtIso = new Date(startedAt).toISOString();
4474
- await appendPipelineLog(
4475
- props.logStore,
4476
- pipelineRunReceivedLog({
4477
- pipeline,
4478
- runId,
4479
- stream: body.stream === true,
4480
- input: body.input,
4481
- ...compact({ metadata: body.metadata })
4482
- })
4483
- );
4484
- 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 = {
4485
4519
  runId,
4486
4520
  pipelineId: pipeline.id,
4487
4521
  status: "running",
4488
4522
  input: body.input,
4489
- ...compact({ metadata: body.metadata }),
4490
4523
  startedAt: startedAtIso
4491
- });
4524
+ };
4525
+ if (body.metadata !== void 0) runningRecord.metadata = body.metadata;
4526
+ await savePipelineRun(props.runStore, runningRecord);
4492
4527
  if (body.stream === true) {
4493
- return streamPipelineRun(c, {
4528
+ const streamOptions = {
4494
4529
  pipeline,
4495
4530
  runId,
4496
4531
  input: body.input,
4497
4532
  startedAt,
4498
- startedAtIso,
4499
- ...compact({ metadata: body.metadata }),
4500
- ...compact({ logStore: props.logStore, runStore: props.runStore })
4501
- });
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);
4502
4539
  }
4503
4540
  try {
4504
4541
  await appendPipelineLog(props.logStore, pipelineRunStartedLog(pipeline, runId));
@@ -4511,17 +4548,18 @@ async function executePipelineRun(c, props, pipeline, body) {
4511
4548
  });
4512
4549
  const jsonOutput = toJsonValue(output);
4513
4550
  const endedAt = Date.now();
4514
- await savePipelineRun(props.runStore, {
4551
+ const successRecord = {
4515
4552
  runId,
4516
4553
  pipelineId: pipeline.id,
4517
4554
  status: "success",
4518
4555
  input: body.input,
4519
4556
  output: jsonOutput,
4520
- ...compact({ metadata: body.metadata }),
4521
4557
  startedAt: startedAtIso,
4522
4558
  endedAt: new Date(endedAt).toISOString(),
4523
4559
  durationMs: endedAt - startedAt
4524
- });
4560
+ };
4561
+ if (body.metadata !== void 0) successRecord.metadata = body.metadata;
4562
+ await savePipelineRun(props.runStore, successRecord);
4525
4563
  await appendPipelineLog(
4526
4564
  props.logStore,
4527
4565
  pipelineRunCompletedLog({
@@ -4539,17 +4577,18 @@ async function executePipelineRun(c, props, pipeline, body) {
4539
4577
  return c.json(response);
4540
4578
  } catch (error) {
4541
4579
  const endedAt = Date.now();
4542
- await savePipelineRun(props.runStore, {
4580
+ const errorRecord = {
4543
4581
  runId,
4544
4582
  pipelineId: pipeline.id,
4545
4583
  status: "error",
4546
4584
  input: body.input,
4547
4585
  error: serializeError(error),
4548
- ...compact({ metadata: body.metadata }),
4549
4586
  startedAt: startedAtIso,
4550
4587
  endedAt: new Date(endedAt).toISOString(),
4551
4588
  durationMs: endedAt - startedAt
4552
- });
4589
+ };
4590
+ if (body.metadata !== void 0) errorRecord.metadata = body.metadata;
4591
+ await savePipelineRun(props.runStore, errorRecord);
4553
4592
  await appendPipelineLog(
4554
4593
  props.logStore,
4555
4594
  pipelineRunFailedLog(pipeline.id, runId, error, startedAt)
@@ -4586,17 +4625,18 @@ async function* pipelineRunEvents(props) {
4586
4625
  }).then(async (output) => {
4587
4626
  const jsonOutput = toJsonValue(output);
4588
4627
  const endedAt = Date.now();
4589
- await savePipelineRun(props.runStore, {
4628
+ const successRecord = {
4590
4629
  runId: props.runId,
4591
4630
  pipelineId: props.pipeline.id,
4592
4631
  status: "success",
4593
4632
  input: props.input,
4594
4633
  output: jsonOutput,
4595
- ...compact({ metadata: props.metadata }),
4596
4634
  startedAt: props.startedAtIso,
4597
4635
  endedAt: new Date(endedAt).toISOString(),
4598
4636
  durationMs: endedAt - props.startedAt
4599
- });
4637
+ };
4638
+ if (props.metadata !== void 0) successRecord.metadata = props.metadata;
4639
+ await savePipelineRun(props.runStore, successRecord);
4600
4640
  const log = await appendPipelineLog(
4601
4641
  props.logStore,
4602
4642
  pipelineRunCompletedLog({
@@ -4617,17 +4657,18 @@ async function* pipelineRunEvents(props) {
4617
4657
  });
4618
4658
  }).catch(async (error) => {
4619
4659
  const endedAt = Date.now();
4620
- await savePipelineRun(props.runStore, {
4660
+ const errorRecord = {
4621
4661
  runId: props.runId,
4622
4662
  pipelineId: props.pipeline.id,
4623
4663
  status: "error",
4624
4664
  input: props.input,
4625
4665
  error: serializeError(error),
4626
- ...compact({ metadata: props.metadata }),
4627
4666
  startedAt: props.startedAtIso,
4628
4667
  endedAt: new Date(endedAt).toISOString(),
4629
4668
  durationMs: endedAt - props.startedAt
4630
- });
4669
+ };
4670
+ if (props.metadata !== void 0) errorRecord.metadata = props.metadata;
4671
+ await savePipelineRun(props.runStore, errorRecord);
4631
4672
  const log = await appendPipelineLog(
4632
4673
  props.logStore,
4633
4674
  pipelineRunFailedLog(props.pipeline.id, props.runId, error, props.startedAt)
@@ -4662,7 +4703,7 @@ async function parsePipelineRunRequest(c) {
4662
4703
  if (!isObject(body)) {
4663
4704
  return { error: errorResponse(c, 400, "bad_request", "Request body must be an object") };
4664
4705
  }
4665
- if (!("input" in body) || !isJsonValue2(body.input)) {
4706
+ if (!("input" in body) || !isJsonValue(body.input)) {
4666
4707
  return { error: errorResponse(c, 400, "bad_request", "input must be JSON-compatible") };
4667
4708
  }
4668
4709
  const request = {
@@ -4708,11 +4749,10 @@ async function parsePipelineReplayRequest(c) {
4708
4749
  return request;
4709
4750
  }
4710
4751
  function replayMetadata(sourceMetadata, requestMetadata, sourceRunId) {
4711
- return {
4712
- ...sourceMetadata ?? {},
4713
- ...requestMetadata ?? {},
4714
- replayOf: sourceRunId
4715
- };
4752
+ const metadata = {};
4753
+ Object.assign(metadata, sourceMetadata, requestMetadata);
4754
+ metadata.replayOf = sourceRunId;
4755
+ return metadata;
4716
4756
  }
4717
4757
  function parsePipelineLogLimit(value) {
4718
4758
  if (value === void 0 || value.trim().length === 0) {
@@ -4734,18 +4774,6 @@ function parsePipelineLogAfter(value) {
4734
4774
  }
4735
4775
  return after;
4736
4776
  }
4737
- function isJsonValue2(value) {
4738
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
4739
- return Number.isFinite(value) || typeof value !== "number";
4740
- }
4741
- if (Array.isArray(value)) {
4742
- return value.every(isJsonValue2);
4743
- }
4744
- if (isObject(value)) {
4745
- return Object.values(value).every((item) => item === void 0 || isJsonValue2(item));
4746
- }
4747
- return false;
4748
- }
4749
4777
 
4750
4778
  // src/runtime/questions.ts
4751
4779
  import { createHook as createHook2 } from "@anvia/core/hooks";
@@ -4826,14 +4854,13 @@ async function parseQuestionAnswerRequest(c) {
4826
4854
  if ("custom" in answer && typeof answer.custom !== "boolean") {
4827
4855
  return { error: errorResponse(c, 400, "bad_request", "custom must be a boolean") };
4828
4856
  }
4829
- answers.push(
4830
- compact({
4831
- questionId: answer.questionId.trim(),
4832
- answer: answer.answer.trim(),
4833
- choice: typeof answer.choice === "string" ? answer.choice : void 0,
4834
- custom: typeof answer.custom === "boolean" ? answer.custom : void 0
4835
- })
4836
- );
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);
4837
4864
  }
4838
4865
  return { answers };
4839
4866
  }
@@ -4851,17 +4878,14 @@ function createQuestionRuntime() {
4851
4878
  if ("error" in prompts) {
4852
4879
  return control.skip(prompts.error);
4853
4880
  }
4854
- const answers = await requestQuestion(
4855
- questions,
4856
- context,
4857
- compact({
4858
- toolName,
4859
- toolCallId,
4860
- internalCallId,
4861
- args,
4862
- questions: prompts.questions
4863
- })
4864
- );
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);
4865
4889
  return control.skip(JSON.stringify({ answers }));
4866
4890
  }
4867
4891
  });
@@ -4905,23 +4929,21 @@ function createQuestionRuntime() {
4905
4929
  async function requestQuestion(questions, context, request) {
4906
4930
  const id = globalThis.crypto.randomUUID();
4907
4931
  const question = {
4908
- ...compact({
4909
- id,
4910
- runId: context.runId,
4911
- agentId: context.agentId,
4912
- sessionId: context.sessionId,
4913
- toolName: request.toolName,
4914
- callId: request.toolCallId,
4915
- internalCallId: request.internalCallId,
4916
- args: request.args,
4917
- questions: request.questions,
4918
- status: "pending",
4919
- requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
4920
- emit: context.emit
4921
- }),
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(),
4922
4941
  resolve: () => {
4923
4942
  }
4924
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;
4925
4947
  const answer = new Promise((resolve2) => {
4926
4948
  question.resolve = (answers) => {
4927
4949
  resolve2(answers);
@@ -5006,10 +5028,9 @@ function registerSessionRoutes(app, props) {
5006
5028
  if (limit === void 0) {
5007
5029
  return errorResponse(c, 400, "bad_request", "limit must be a positive integer");
5008
5030
  }
5009
- const sessions = await props.sessionStore.listSessions({
5010
- ...compact({ agentId }),
5011
- limit
5012
- });
5031
+ const listInput = { limit };
5032
+ if (agentId !== void 0) listInput.agentId = agentId;
5033
+ const sessions = await props.sessionStore.listSessions(listInput);
5013
5034
  return c.json({ sessions });
5014
5035
  });
5015
5036
  app.post("/sessions", async (c) => {
@@ -5020,11 +5041,13 @@ function registerSessionRoutes(app, props) {
5020
5041
  if (!props.agentMap.has(body.agentId)) {
5021
5042
  return errorResponse(c, 404, "not_found", "Agent not found");
5022
5043
  }
5023
- const session = await props.sessionStore.createSession({
5044
+ const createInput = {
5024
5045
  id: globalThis.crypto.randomUUID(),
5025
- agentId: body.agentId,
5026
- ...compact({ title: body.title, metadata: body.metadata })
5027
- });
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);
5028
5051
  await appendSessionLog(props.sessionStore, sessionCreatedLog(session));
5029
5052
  return c.json(session, 201);
5030
5053
  });
@@ -5058,16 +5081,16 @@ function registerSessionRoutes(app, props) {
5058
5081
  if (after === false) {
5059
5082
  return errorResponse(c, 400, "bad_request", "after must be a non-negative integer");
5060
5083
  }
5061
- const logs = await props.sessionStore.listSessionLogs({
5084
+ const listInput = {
5062
5085
  sessionId,
5063
- limit,
5064
- ...compact({ after })
5065
- });
5086
+ limit
5087
+ };
5088
+ if (after !== void 0) listInput.after = after;
5089
+ const logs = await props.sessionStore.listSessionLogs(listInput);
5066
5090
  const last = logs.at(-1);
5067
- return c.json({
5068
- logs,
5069
- ...logs.length === limit && last !== void 0 ? { nextCursor: last.sequence } : {}
5070
- });
5091
+ const response = { logs };
5092
+ if (logs.length === limit && last !== void 0) response.nextCursor = last.sequence;
5093
+ return c.json(response);
5071
5094
  });
5072
5095
  app.delete("/sessions/:sessionId", async (c) => {
5073
5096
  if (props.sessionStore.deleteSession === void 0) {
@@ -5152,19 +5175,17 @@ var InMemoryStudioStore = class {
5152
5175
  createSession(input) {
5153
5176
  const now = (/* @__PURE__ */ new Date()).toISOString();
5154
5177
  const session = {
5155
- ...compact({
5156
- id: input.id,
5157
- agentId: input.agentId,
5158
- title: input.title,
5159
- createdAt: now,
5160
- updatedAt: now,
5161
- messageCount: 0,
5162
- metadata: input.metadata
5163
- }),
5178
+ id: input.id,
5179
+ agentId: input.agentId,
5180
+ createdAt: now,
5181
+ updatedAt: now,
5182
+ messageCount: 0,
5164
5183
  messages: [],
5165
5184
  runs: [],
5166
5185
  logs: []
5167
5186
  };
5187
+ if (input.title !== void 0) session.title = input.title;
5188
+ if (input.metadata !== void 0) session.metadata = input.metadata;
5168
5189
  this.sessions.set(input.id, session);
5169
5190
  return sessionSummary(session);
5170
5191
  }
@@ -5240,18 +5261,18 @@ var InMemoryStudioStore = class {
5240
5261
  appendSessionLog(input) {
5241
5262
  const session = this.sessions.get(input.sessionId);
5242
5263
  const logs = session?.logs ?? [];
5243
- const entry = compact({
5264
+ const entry = {
5244
5265
  id: globalThis.crypto.randomUUID(),
5245
5266
  sessionId: input.sessionId,
5246
- runId: input.runId,
5247
5267
  sequence: logs.length,
5248
5268
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5249
5269
  level: input.level,
5250
5270
  category: input.category,
5251
5271
  event: input.event,
5252
- message: input.message,
5253
- metadata: input.metadata
5254
- });
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;
5255
5276
  if (session !== void 0) {
5256
5277
  session.logs.push(entry);
5257
5278
  session.updatedAt = entry.timestamp;
@@ -5270,7 +5291,7 @@ var InMemoryStudioStore = class {
5270
5291
  return this.sessions.delete(id);
5271
5292
  }
5272
5293
  listTraces(options) {
5273
- 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);
5274
5295
  }
5275
5296
  listSessionTraces(options) {
5276
5297
  return this.listTraces({ sessionId: options.sessionId, limit: options.limit });
@@ -5284,18 +5305,18 @@ var InMemoryStudioStore = class {
5284
5305
  }
5285
5306
  appendPipelineLog(input) {
5286
5307
  const logs = this.pipelineLogs.get(input.pipelineId) ?? [];
5287
- const entry = compact({
5308
+ const entry = {
5288
5309
  id: globalThis.crypto.randomUUID(),
5289
5310
  pipelineId: input.pipelineId,
5290
- runId: input.runId,
5291
5311
  sequence: logs.length,
5292
5312
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5293
5313
  level: input.level,
5294
5314
  category: input.category,
5295
5315
  event: input.event,
5296
- message: input.message,
5297
- metadata: input.metadata
5298
- });
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;
5299
5320
  this.pipelineLogs.set(input.pipelineId, [...logs, entry]);
5300
5321
  return entry;
5301
5322
  }
@@ -5303,18 +5324,18 @@ var InMemoryStudioStore = class {
5303
5324
  return (this.pipelineLogs.get(options.pipelineId) ?? []).filter((log) => options.after === void 0 || log.sequence > options.after).slice(0, options.limit);
5304
5325
  }
5305
5326
  savePipelineRun(input) {
5306
- const record = compact({
5327
+ const record = {
5307
5328
  runId: input.runId,
5308
5329
  pipelineId: input.pipelineId,
5309
5330
  status: input.status,
5310
5331
  input: input.input,
5311
- output: input.output,
5312
- error: input.error,
5313
- metadata: input.metadata,
5314
- startedAt: input.startedAt,
5315
- endedAt: input.endedAt,
5316
- durationMs: input.durationMs
5317
- });
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;
5318
5339
  this.pipelineRuns.set(input.runId, record);
5319
5340
  return record;
5320
5341
  }
@@ -5327,15 +5348,16 @@ var InMemoryStudioStore = class {
5327
5348
  }
5328
5349
  };
5329
5350
  function sessionSummary(session) {
5330
- return compact({
5351
+ const summary = {
5331
5352
  id: session.id,
5332
5353
  agentId: session.agentId,
5333
- title: session.title,
5334
5354
  createdAt: session.createdAt,
5335
5355
  updatedAt: session.updatedAt,
5336
- messageCount: session.messages.length,
5337
- metadata: session.metadata
5338
- });
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;
5339
5361
  }
5340
5362
  function materializeSession(session) {
5341
5363
  return {
@@ -5344,25 +5366,9 @@ function materializeSession(session) {
5344
5366
  transcript: renumberTranscript(session.runs.flatMap((run) => run.transcript))
5345
5367
  };
5346
5368
  }
5347
- function traceSummary2(trace) {
5348
- return compact({
5349
- id: trace.id,
5350
- sessionId: trace.sessionId,
5351
- name: trace.name,
5352
- status: trace.status,
5353
- startedAt: trace.startedAt,
5354
- endedAt: trace.endedAt,
5355
- durationMs: trace.durationMs,
5356
- output: trace.output,
5357
- error: trace.error,
5358
- usage: trace.usage,
5359
- metadata: trace.metadata,
5360
- observationCount: trace.observations.length
5361
- });
5362
- }
5363
5369
  function traceAgentId(trace) {
5364
5370
  const nestedMetadata = trace.metadata?.metadata;
5365
- return isJsonObject2(nestedMetadata) && typeof nestedMetadata.agentId === "string" ? nestedMetadata.agentId : void 0;
5371
+ return isJsonObject(nestedMetadata) && typeof nestedMetadata.agentId === "string" ? nestedMetadata.agentId : void 0;
5366
5372
  }
5367
5373
  function studioRunId(context) {
5368
5374
  const value = context.metadata?.studioRunId;
@@ -5375,19 +5381,7 @@ function serializeJsonError(error) {
5375
5381
  message: error.message
5376
5382
  };
5377
5383
  }
5378
- return isJsonValue3(error) ? error : String(error);
5379
- }
5380
- function isJsonObject2(value) {
5381
- return typeof value === "object" && value !== null && !Array.isArray(value);
5382
- }
5383
- function isJsonValue3(value) {
5384
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
5385
- return true;
5386
- }
5387
- if (Array.isArray(value)) {
5388
- return value.every(isJsonValue3);
5389
- }
5390
- return isJsonObject2(value) && Object.values(value).every(isJsonValue3);
5384
+ return isJsonValue(error) ? error : String(error);
5391
5385
  }
5392
5386
 
5393
5387
  // src/runtime/shared.ts
@@ -5397,12 +5391,12 @@ function resolveStores(options) {
5397
5391
  const traces = resolveTraceStore(options, sessions, defaultStore);
5398
5392
  const pipelineLogs = resolvePipelineLogStore(options, sessions, defaultStore);
5399
5393
  const pipelineRuns = resolvePipelineRunStore(options, sessions, pipelineLogs, defaultStore);
5400
- return compact({
5401
- sessions,
5402
- traces,
5403
- pipelineLogs,
5404
- pipelineRuns
5405
- });
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;
5406
5400
  }
5407
5401
  function defaultStudioStore() {
5408
5402
  return createInMemoryStudioStore();
@@ -5499,35 +5493,38 @@ function normalizePipelines(pipelines) {
5499
5493
  // src/runtime/status.ts
5500
5494
  function registerStatusRoutes(app, props) {
5501
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
+ }
5502
5524
  const summary = {
5503
- runner: {
5504
- id: runnerId(props.options),
5505
- ...compact({ name: props.options.name, version: props.options.version })
5506
- },
5507
- storage: {
5508
- ...compact({
5509
- sessions: props.stores.sessions?.kind,
5510
- traces: props.stores.traces?.kind,
5511
- pipelineLogs: props.stores.pipelineLogs !== void 0 ? "available" : void 0,
5512
- pipelineRuns: props.stores.pipelineRuns !== void 0 ? "available" : void 0
5513
- })
5514
- },
5515
- counts: {
5516
- agents: props.agents.length,
5517
- pipelines: props.pipelines.length,
5518
- ...compact({
5519
- sessions: props.stores.sessions !== void 0 ? (await props.stores.sessions.listSessions({ limit: 100 })).length : void 0,
5520
- traces: props.stores.traces?.listTraces !== void 0 ? (await props.stores.traces.listTraces({ limit: 100 })).length : void 0,
5521
- pipelineRuns: props.stores.pipelineRuns !== void 0 && props.pipelines.length > 0 ? (await Promise.all(
5522
- props.pipelines.map(
5523
- (pipeline) => props.stores.pipelineRuns?.listPipelineRuns({
5524
- pipelineId: pipeline.id,
5525
- limit: 100
5526
- })
5527
- )
5528
- )).reduce((sum, runs) => sum + (runs?.length ?? 0), 0) : void 0
5529
- })
5530
- },
5525
+ runner,
5526
+ storage,
5527
+ counts,
5531
5528
  capabilities: capabilityConfig(props.options, props.agents, props.pipelines, props.stores),
5532
5529
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
5533
5530
  };
@@ -5637,15 +5634,16 @@ async function agentToolMetadata(agent) {
5637
5634
  seen.add(key);
5638
5635
  const definition = await tool.definition("");
5639
5636
  const serverName = mcpServerName(tool);
5640
- metadata.push({
5637
+ const item = {
5641
5638
  agentId: agent.id,
5642
5639
  name: definition.name,
5643
5640
  description: definition.description,
5644
5641
  parameters: definition.parameters,
5645
5642
  source,
5646
- ...serverName === void 0 ? {} : { mcpServerName: serverName },
5647
5643
  approval: approvalMetadata(tool)
5648
- });
5644
+ };
5645
+ if (serverName !== void 0) item.mcpServerName = serverName;
5646
+ metadata.push(item);
5649
5647
  }
5650
5648
  return metadata.sort((left, right) => {
5651
5649
  if (left.source !== right.source) {
@@ -5677,10 +5675,11 @@ function registerTraceRoutes(app, traceStore) {
5677
5675
  }
5678
5676
  const agentId = optionalQueryString(c.req.query("agentId"));
5679
5677
  const sessionId = optionalQueryString(c.req.query("sessionId"));
5680
- const traces = await traceStore.listTraces({
5681
- limit,
5682
- ...compact({ agentId, sessionId, status })
5683
- });
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);
5684
5683
  if (c.req.query("include") === "detail") {
5685
5684
  const detailed = await Promise.all(
5686
5685
  traces.map((trace) => Promise.resolve(traceStore.getTrace(trace.id)))
@@ -5726,11 +5725,12 @@ var Studio = class {
5726
5725
  this.close();
5727
5726
  this.studio = createStudioApp(this.options);
5728
5727
  const port = serveOptions.port ?? Number(process.env.RUNNER_PORT ?? 4021);
5729
- this.server = serve({
5728
+ const serverOptions = {
5730
5729
  fetch: (request) => this.fetch(request),
5731
- ...compact({ hostname: serveOptions.hostname }),
5732
5730
  port
5733
- });
5731
+ };
5732
+ if (serveOptions.hostname !== void 0) serverOptions.hostname = serveOptions.hostname;
5733
+ this.server = serve(serverOptions);
5734
5734
  const log = serveOptions.log ?? true;
5735
5735
  if (log) {
5736
5736
  const host = serveOptions.hostname ?? "localhost";
@@ -5764,14 +5764,15 @@ function studioOptionsFromTargets(targets, options) {
5764
5764
  // biome-ignore lint/suspicious/noExplicitAny: Studio accepts heterogeneous user pipelines.
5765
5765
  (target) => target instanceof Pipeline
5766
5766
  );
5767
- return {
5767
+ const runtimeOptions = {
5768
5768
  agents: inferStudioAgents(agents, options.quickPrompts ?? {}),
5769
5769
  pipelines: inferStudioPipelines(pipelines),
5770
- evals: options.evals ?? [],
5771
- ...compact({ models: options.models }),
5772
- ...compact({ stores: options.stores }),
5773
- ...compact({ ui: options.ui })
5770
+ evals: options.evals ?? []
5774
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;
5775
5776
  }
5776
5777
  function inferStudioAgents(agents, quickPrompts) {
5777
5778
  const ids = /* @__PURE__ */ new Set();
@@ -5789,13 +5790,14 @@ function inferStudioPipelines(pipelines) {
5789
5790
  const ids = /* @__PURE__ */ new Set();
5790
5791
  return pipelines.map((pipeline) => {
5791
5792
  const id = uniqueAgentId(pipeline.id || "pipeline", ids);
5792
- return {
5793
+ const studioPipeline = {
5793
5794
  id,
5794
- pipeline,
5795
- ...compact({ name: pipeline.name }),
5796
- ...compact({ description: pipeline.description }),
5797
- ...compact({ metadata: pipeline.metadata })
5795
+ pipeline
5798
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;
5799
5801
  });
5800
5802
  }
5801
5803
  function uniqueAgentId(baseId, ids) {
@@ -5809,8 +5811,7 @@ function uniqueAgentId(baseId, ids) {
5809
5811
  return id;
5810
5812
  }
5811
5813
  function agentMetadata(agent) {
5812
- return {
5813
- ...compact({ defaultMaxTurns: agent.defaultMaxTurns }),
5814
+ const metadata = {
5814
5815
  staticContextCount: agent.staticContext.length,
5815
5816
  dynamicContextCount: agent.dynamicContexts.length,
5816
5817
  dynamicToolCount: agent.dynamicTools.length,
@@ -5819,6 +5820,8 @@ function agentMetadata(agent) {
5819
5820
  observerCount: agent.observers.length,
5820
5821
  approvalToolCount: agent.toolSet.values().filter((tool) => tool.approval !== void 0).length
5821
5822
  };
5823
+ if (agent.defaultMaxTurns !== void 0) metadata.defaultMaxTurns = agent.defaultMaxTurns;
5824
+ return metadata;
5822
5825
  }
5823
5826
  function createStudioApp(options) {
5824
5827
  const observabilityHub = new StudioObservabilityHub();
@@ -5879,16 +5882,16 @@ function createStudioApp(options) {
5879
5882
  evals: options.evals,
5880
5883
  evalMap
5881
5884
  });
5882
- registerKnowledgeRoutes(app, {
5883
- agents,
5884
- ...compact({ traceStore: stores.traces })
5885
- });
5886
- registerPipelineRoutes(app, {
5885
+ const knowledgeOptions = { agents };
5886
+ if (stores.traces !== void 0) knowledgeOptions.traceStore = stores.traces;
5887
+ registerKnowledgeRoutes(app, knowledgeOptions);
5888
+ const pipelineOptions = {
5887
5889
  pipelines,
5888
- pipelineMap,
5889
- ...compact({ logStore: stores.pipelineLogs }),
5890
- ...compact({ runStore: stores.pipelineRuns })
5891
- });
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);
5892
5895
  registerAgentRunRoute(app, {
5893
5896
  agentMap,
5894
5897
  stores,
@@ -5900,11 +5903,12 @@ function createStudioApp(options) {
5900
5903
  registerMemoryRoutes(app, {
5901
5904
  sessionStore: stores.sessions
5902
5905
  });
5903
- registerSessionRoutes(app, {
5906
+ const sessionOptions = {
5904
5907
  agentMap,
5905
- sessionStore: stores.sessions,
5906
- ...compact({ traceStore: stores.traces })
5907
- });
5908
+ sessionStore: stores.sessions
5909
+ };
5910
+ if (stores.traces !== void 0) sessionOptions.traceStore = stores.traces;
5911
+ registerSessionRoutes(app, sessionOptions);
5908
5912
  }
5909
5913
  if (stores.traces !== void 0) {
5910
5914
  registerTraceRoutes(app, stores.traces);
@@ -5913,7 +5917,7 @@ function createStudioApp(options) {
5913
5917
  app.all(`/${capability}`, (c) => unsupportedCapability(c, capability));
5914
5918
  app.all(`/${capability}/*`, (c) => unsupportedCapability(c, capability));
5915
5919
  }
5916
- return {
5920
+ const studio = {
5917
5921
  app,
5918
5922
  fetch(request) {
5919
5923
  return app.fetch(request);
@@ -5922,10 +5926,11 @@ function createStudioApp(options) {
5922
5926
  return buildConfig(options, agents, pipelines, stores);
5923
5927
  },
5924
5928
  close() {
5925
- },
5926
- ...compact({ sessionStore: stores.sessions }),
5927
- ...compact({ traceStore: stores.traces })
5929
+ }
5928
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;
5929
5934
  }
5930
5935
  function withStudioTraceObserver(studioAgent, traceStore) {
5931
5936
  if (traceStore === void 0 || hasStudioTraceObserver(studioAgent.agent)) {
@@ -5951,6 +5956,7 @@ function hasStudioTraceObserver(agent) {
5951
5956
  import { mkdirSync } from "fs";
5952
5957
  import { createRequire } from "module";
5953
5958
  import { dirname, resolve } from "path";
5959
+ import { isJsonValue as isJsonValue2 } from "@anvia/core/completion";
5954
5960
  var DatabaseSync;
5955
5961
  function createSqliteSessionStore(options = {}) {
5956
5962
  return new SqliteSessionStore(options.path ?? ":memory:");
@@ -5999,15 +6005,16 @@ var SqliteSessionStore = class {
5999
6005
  $metadata: input.metadata === void 0 ? null : JSON.stringify(input.metadata),
6000
6006
  $now: now
6001
6007
  });
6002
- return {
6008
+ const session = {
6003
6009
  id: input.id,
6004
6010
  agentId: input.agentId,
6005
- ...compact({ title: input.title }),
6006
6011
  createdAt: now,
6007
6012
  updatedAt: now,
6008
- messageCount: 0,
6009
- ...compact({ metadata: input.metadata })
6013
+ messageCount: 0
6010
6014
  };
6015
+ if (input.title !== void 0) session.title = input.title;
6016
+ if (input.metadata !== void 0) session.metadata = input.metadata;
6017
+ return session;
6011
6018
  }
6012
6019
  getSession(id) {
6013
6020
  const row = this.getSessionRow(id);
@@ -6192,15 +6199,15 @@ var SqliteSessionStore = class {
6192
6199
  const entry = {
6193
6200
  id: globalThis.crypto.randomUUID(),
6194
6201
  sessionId: input.sessionId,
6195
- ...compact({ runId: input.runId }),
6196
6202
  sequence,
6197
6203
  timestamp: now,
6198
6204
  level: input.level,
6199
6205
  category: input.category,
6200
6206
  event: input.event,
6201
- message: input.message,
6202
- ...compact({ metadata: input.metadata })
6207
+ message: input.message
6203
6208
  };
6209
+ if (input.runId !== void 0) entry.runId = input.runId;
6210
+ if (input.metadata !== void 0) entry.metadata = input.metadata;
6204
6211
  db.prepare(
6205
6212
  `INSERT INTO anvia_studio_session_logs (
6206
6213
  id,
@@ -6273,15 +6280,15 @@ var SqliteSessionStore = class {
6273
6280
  const entry = {
6274
6281
  id: globalThis.crypto.randomUUID(),
6275
6282
  pipelineId: input.pipelineId,
6276
- ...compact({ runId: input.runId }),
6277
6283
  sequence,
6278
6284
  timestamp: now,
6279
6285
  level: input.level,
6280
6286
  category: input.category,
6281
6287
  event: input.event,
6282
- message: input.message,
6283
- ...compact({ metadata: input.metadata })
6288
+ message: input.message
6284
6289
  };
6290
+ if (input.runId !== void 0) entry.runId = input.runId;
6291
+ if (input.metadata !== void 0) entry.metadata = input.metadata;
6285
6292
  db.prepare(
6286
6293
  `INSERT INTO anvia_studio_pipeline_logs (
6287
6294
  id,
@@ -6393,18 +6400,19 @@ var SqliteSessionStore = class {
6393
6400
  $endedAt: input.endedAt ?? null,
6394
6401
  $durationMs: input.durationMs ?? null
6395
6402
  });
6396
- return {
6403
+ const record = {
6397
6404
  runId: input.runId,
6398
6405
  pipelineId: input.pipelineId,
6399
6406
  status: input.status,
6400
6407
  input: input.input,
6401
- ...compact({ output: input.output }),
6402
- ...compact({ error: input.error }),
6403
- ...compact({ metadata: input.metadata }),
6404
- startedAt: input.startedAt,
6405
- ...compact({ endedAt: input.endedAt }),
6406
- ...compact({ durationMs: input.durationMs })
6408
+ startedAt: input.startedAt
6407
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;
6408
6416
  }
6409
6417
  getPipelineRun(options) {
6410
6418
  const db = this.database();
@@ -6607,6 +6615,7 @@ var SqliteSessionStore = class {
6607
6615
  message_index INTEGER NOT NULL,
6608
6616
  role TEXT NOT NULL,
6609
6617
  message_id TEXT,
6618
+ metadata_json TEXT,
6610
6619
  created_at TEXT NOT NULL,
6611
6620
  PRIMARY KEY(session_id, message_index),
6612
6621
  FOREIGN KEY(session_id) REFERENCES anvia_studio_sessions(id) ON DELETE CASCADE
@@ -6701,6 +6710,7 @@ var SqliteSessionStore = class {
6701
6710
  CREATE INDEX IF NOT EXISTS anvia_studio_traces_session_started_idx
6702
6711
  ON anvia_studio_traces(session_id, started_at DESC);
6703
6712
  `);
6713
+ ensureMessageMetadataColumn(db);
6704
6714
  this.db = db;
6705
6715
  return db;
6706
6716
  }
@@ -6745,7 +6755,7 @@ var SqliteSessionStore = class {
6745
6755
  listSessionMessages(sessionId) {
6746
6756
  const db = this.database();
6747
6757
  const messageRows = db.prepare(
6748
- `SELECT session_id, message_index, role, message_id, created_at
6758
+ `SELECT session_id, message_index, role, message_id, metadata_json, created_at
6749
6759
  FROM anvia_studio_session_messages
6750
6760
  WHERE session_id = $sessionId
6751
6761
  ORDER BY message_index ASC`
@@ -6785,8 +6795,9 @@ var SqliteSessionStore = class {
6785
6795
  message_index,
6786
6796
  role,
6787
6797
  message_id,
6798
+ metadata_json,
6788
6799
  created_at
6789
- ) VALUES ($sessionId, $messageIndex, $role, $messageId, $createdAt)`
6800
+ ) VALUES ($sessionId, $messageIndex, $role, $messageId, $metadata, $createdAt)`
6790
6801
  );
6791
6802
  const insertPart = db.prepare(
6792
6803
  `INSERT INTO anvia_studio_session_message_parts (
@@ -6799,11 +6810,15 @@ var SqliteSessionStore = class {
6799
6810
  );
6800
6811
  messages.forEach((message, messageOffset) => {
6801
6812
  const messageIndex = startIndex + messageOffset;
6813
+ if (message.metadata !== void 0 && !isJsonValue2(message.metadata)) {
6814
+ throw new TypeError("Studio message metadata must be a strict JSON value.");
6815
+ }
6802
6816
  insertMessage.run({
6803
6817
  $sessionId: sessionId,
6804
6818
  $messageIndex: messageIndex,
6805
6819
  $role: message.role,
6806
6820
  $messageId: message.role === "assistant" ? message.id ?? null : null,
6821
+ $metadata: message.metadata === void 0 ? null : JSON.stringify(message.metadata),
6807
6822
  $createdAt: createdAt
6808
6823
  });
6809
6824
  messageParts(message).forEach((part, partIndex) => {
@@ -6831,62 +6846,66 @@ function toSession(row, messages, runRows = []) {
6831
6846
  }
6832
6847
  function toSessionSummary(row) {
6833
6848
  const metadata = parseJsonValue(row.metadata_json);
6834
- return {
6849
+ const summary = {
6835
6850
  id: row.id,
6836
6851
  agentId: row.agent_id,
6837
- ...compact({ title: row.title ?? void 0 }),
6838
6852
  createdAt: row.created_at,
6839
6853
  updatedAt: row.updated_at,
6840
- messageCount: row.message_count,
6841
- ...compact({ metadata })
6854
+ messageCount: row.message_count
6842
6855
  };
6856
+ if (row.title !== null) summary.title = row.title;
6857
+ if (metadata !== void 0) summary.metadata = metadata;
6858
+ return summary;
6843
6859
  }
6844
6860
  function toSessionLog(row) {
6845
6861
  const metadata = parseJsonValue(row.metadata_json);
6846
- return {
6862
+ const entry = {
6847
6863
  id: row.id,
6848
6864
  sessionId: row.session_id,
6849
- ...compact({ runId: row.run_id ?? void 0 }),
6850
6865
  sequence: row.sequence,
6851
6866
  timestamp: row.timestamp,
6852
6867
  level: row.level,
6853
6868
  category: row.category,
6854
6869
  event: row.event,
6855
- message: row.message,
6856
- ...compact({ metadata })
6870
+ message: row.message
6857
6871
  };
6872
+ if (row.run_id !== null) entry.runId = row.run_id;
6873
+ if (metadata !== void 0) entry.metadata = metadata;
6874
+ return entry;
6858
6875
  }
6859
6876
  function toPipelineLog(row) {
6860
6877
  const metadata = parseJsonValue(row.metadata_json);
6861
- return {
6878
+ const entry = {
6862
6879
  id: row.id,
6863
6880
  pipelineId: row.pipeline_id,
6864
- ...compact({ runId: row.run_id ?? void 0 }),
6865
6881
  sequence: row.sequence,
6866
6882
  timestamp: row.timestamp,
6867
6883
  level: row.level,
6868
6884
  category: row.category,
6869
6885
  event: row.event,
6870
- message: row.message,
6871
- ...compact({ metadata })
6886
+ message: row.message
6872
6887
  };
6888
+ if (row.run_id !== null) entry.runId = row.run_id;
6889
+ if (metadata !== void 0) entry.metadata = metadata;
6890
+ return entry;
6873
6891
  }
6874
6892
  function toPipelineRun(row) {
6875
6893
  const output = parseJsonValue(row.output_json);
6876
6894
  const error = parseJsonValue(row.error_json);
6877
6895
  const metadata = parseJsonValue(row.metadata_json);
6878
- return {
6896
+ const record = {
6879
6897
  runId: row.run_id,
6880
6898
  pipelineId: row.pipeline_id,
6881
6899
  status: row.status,
6882
6900
  input: JSON.parse(row.input_json),
6883
- ...compact({ output }),
6884
- ...compact({ error }),
6885
- ...compact({ metadata }),
6886
- startedAt: row.started_at,
6887
- ...compact({ endedAt: row.ended_at ?? void 0 }),
6888
- ...compact({ durationMs: row.duration_ms ?? void 0 })
6901
+ startedAt: row.started_at
6889
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;
6890
6909
  }
6891
6910
  function messageParts(message) {
6892
6911
  if (message.role === "system") {
@@ -6899,27 +6918,42 @@ function messageParts(message) {
6899
6918
  }
6900
6919
  function messageFromRows(row, partRows) {
6901
6920
  const parts = partRows.map((partRow) => JSON.parse(partRow.part_json));
6921
+ const metadata = parseJsonValue(row.metadata_json);
6922
+ if (metadata !== void 0 && !isJsonValue2(metadata)) {
6923
+ throw new TypeError("Stored Studio message metadata is not a strict JSON value.");
6924
+ }
6902
6925
  if (row.role === "system") {
6903
- return { role: "system", content: systemContentFromParts(parts) };
6926
+ const message = {
6927
+ role: "system",
6928
+ content: systemContentFromParts(parts)
6929
+ };
6930
+ if (metadata !== void 0) message.metadata = metadata;
6931
+ return message;
6904
6932
  }
6905
6933
  if (row.role === "user") {
6906
- return {
6934
+ const message = {
6907
6935
  role: "user",
6908
6936
  content: parts
6909
6937
  };
6938
+ if (metadata !== void 0) message.metadata = metadata;
6939
+ return message;
6910
6940
  }
6911
6941
  if (row.role === "assistant") {
6912
- return {
6942
+ const message = {
6913
6943
  role: "assistant",
6914
- ...compact({ id: row.message_id ?? void 0 }),
6915
6944
  content: parts
6916
6945
  };
6946
+ if (row.message_id !== null) message.id = row.message_id;
6947
+ if (metadata !== void 0) message.metadata = metadata;
6948
+ return message;
6917
6949
  }
6918
6950
  if (row.role === "tool") {
6919
- return {
6951
+ const message = {
6920
6952
  role: "tool",
6921
6953
  content: parts
6922
6954
  };
6955
+ if (metadata !== void 0) message.metadata = metadata;
6956
+ return message;
6923
6957
  }
6924
6958
  throw new Error(`Unsupported stored message role: ${row.role}`);
6925
6959
  }
@@ -6938,6 +6972,12 @@ function guardAgainstLegacySessionSchema(db) {
6938
6972
  );
6939
6973
  }
6940
6974
  }
6975
+ function ensureMessageMetadataColumn(db) {
6976
+ const columns = db.prepare("PRAGMA table_info('anvia_studio_session_messages')").all();
6977
+ if (!columns.some((column) => column.name === "metadata_json")) {
6978
+ db.exec("ALTER TABLE anvia_studio_session_messages ADD COLUMN metadata_json TEXT");
6979
+ }
6980
+ }
6941
6981
  function loadDatabaseSync() {
6942
6982
  if (DatabaseSync !== void 0) {
6943
6983
  return DatabaseSync;
@@ -6957,32 +6997,34 @@ function loadDatabaseSync() {
6957
6997
  function toTrace(row) {
6958
6998
  const trace = parseJsonValue(row.trace_json);
6959
6999
  const input = parseJsonValue(row.input_json);
6960
- return {
7000
+ const result = {
6961
7001
  ...toTraceSummary(row),
6962
- ...compact({ trace }),
6963
- ...compact({ input }),
6964
7002
  observations: parseJsonArray(row.observations_json)
6965
7003
  };
7004
+ if (trace !== void 0) result.trace = trace;
7005
+ if (input !== void 0) result.input = input;
7006
+ return result;
6966
7007
  }
6967
7008
  function toTraceSummary(row) {
6968
7009
  const observations = parseJsonArray(row.observations_json);
6969
7010
  const error = parseJsonValue(row.error_json);
6970
7011
  const usage = parseJsonValue(row.usage_json);
6971
7012
  const metadata = parseJsonValue(row.metadata_json);
6972
- return {
7013
+ const summary = {
6973
7014
  id: row.id,
6974
7015
  sessionId: row.session_id,
6975
- ...compact({ name: row.name ?? void 0 }),
6976
7016
  status: row.status,
6977
7017
  startedAt: row.started_at,
6978
- ...compact({ endedAt: row.ended_at ?? void 0 }),
6979
- ...compact({ durationMs: row.duration_ms ?? void 0 }),
6980
- ...compact({ output: row.output ?? void 0 }),
6981
- ...compact({ error }),
6982
- ...compact({ usage }),
6983
- ...compact({ metadata }),
6984
7018
  observationCount: observations.length
6985
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;
6986
7028
  }
6987
7029
  function parseJsonArray(value) {
6988
7030
  const parsed = JSON.parse(value);
@@ -7010,29 +7052,11 @@ function serializeJsonError2(error) {
7010
7052
  }
7011
7053
  return String(error);
7012
7054
  }
7013
-
7014
- // src/types.ts
7015
- function traceSummary3(trace) {
7016
- return compact({
7017
- id: trace.id,
7018
- sessionId: trace.sessionId,
7019
- name: trace.name,
7020
- status: trace.status,
7021
- startedAt: trace.startedAt,
7022
- endedAt: trace.endedAt,
7023
- durationMs: trace.durationMs,
7024
- output: trace.output,
7025
- error: trace.error,
7026
- usage: trace.usage,
7027
- metadata: trace.metadata,
7028
- observationCount: trace.observations.length
7029
- });
7030
- }
7031
7055
  export {
7032
7056
  Studio,
7033
7057
  StudioTraceObserver,
7034
7058
  createInMemoryStudioStore,
7035
7059
  createSqliteSessionStore,
7036
- traceSummary3 as traceSummary
7060
+ traceSummary
7037
7061
  };
7038
7062
  //# sourceMappingURL=index.js.map