@relayfx/sdk 0.7.3 → 0.7.4

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.
@@ -17,7 +17,7 @@ import {
17
17
  exports_tool_executor,
18
18
  exports_tool_output,
19
19
  exports_turn_policy
20
- } from "./index-qa93yf6j.js";
20
+ } from "./index-etc2cnk2.js";
21
21
  import {
22
22
  ClientError,
23
23
  EventLogCursorNotFound,
@@ -47,7 +47,7 @@ import {
47
47
  exports_workflow_schema,
48
48
  exports_workspace_schema,
49
49
  followExecutionFrom
50
- } from "./index-syx9q5v3.js";
50
+ } from "./index-nb078xsy.js";
51
51
  import {
52
52
  __export
53
53
  } from "./index-nb39b5ae.js";
@@ -1685,6 +1685,7 @@ __export(exports_child_fan_out_repository, {
1685
1685
  recordTerminal: () => recordTerminal,
1686
1686
  memoryLayer: () => memoryLayer10,
1687
1687
  listNonTerminal: () => listNonTerminal,
1688
+ listByParent: () => listByParent,
1688
1689
  layer: () => layer12,
1689
1690
  get: () => get4,
1690
1691
  create: () => create2,
@@ -1885,7 +1886,18 @@ var layer12 = Layer16.effect(Service18, Effect17.gen(function* () {
1885
1886
  }
1886
1887
  return states;
1887
1888
  });
1888
- return Service18.of({ create: create2, get: get4, claimAdmissions, recordTerminal, cancel, listNonTerminal });
1889
+ const listByParent = Effect17.fn("ChildFanOutRepository.listByParent")(function* (parentExecutionId) {
1890
+ const tenantId = yield* current();
1891
+ const rows = yield* sql`SELECT id FROM relay_child_fan_outs WHERE tenant_id = ${tenantId} AND parent_execution_id = ${parentExecutionId} ORDER BY created_at ASC, id ASC`.pipe(Effect17.mapError(repositoryError));
1892
+ const states = [];
1893
+ for (const row of rows) {
1894
+ const state = yield* load(tenantId, exports_ids_schema.ChildFanOutId.make(String(row.id))).pipe(Effect17.mapError(repositoryError));
1895
+ if (state !== undefined)
1896
+ states.push(state);
1897
+ }
1898
+ return states;
1899
+ });
1900
+ return Service18.of({ create: create2, get: get4, claimAdmissions, recordTerminal, cancel, listNonTerminal, listByParent });
1889
1901
  }));
1890
1902
  var memoryLayer10 = Layer16.effect(Service18, Effect17.gen(function* () {
1891
1903
  const records = new Map;
@@ -1978,7 +1990,8 @@ var memoryLayer10 = Layer16.effect(Service18, Effect17.gen(function* () {
1978
1990
  return { fanOut: globalThis.structuredClone(fanOut), transitioned, activeChildExecutionIds };
1979
1991
  })));
1980
1992
  const listNonTerminal = Effect17.fn("ChildFanOutRepository.memory.listNonTerminal")((parentExecutionId) => Effect17.sync(() => [...records.values()].filter((state) => state.state === "joining" && (parentExecutionId === undefined || state.parent_execution_id === parentExecutionId)).toSorted((left, right) => left.created_at - right.created_at || left.fan_out_id.localeCompare(right.fan_out_id)).map((state) => globalThis.structuredClone(state))));
1981
- return Service18.of({ create: create2, get: get4, claimAdmissions, recordTerminal, cancel, listNonTerminal });
1993
+ const listByParent = Effect17.fn("ChildFanOutRepository.memory.listByParent")((parentExecutionId) => Effect17.sync(() => [...records.values()].filter((state) => state.parent_execution_id === parentExecutionId).toSorted((left, right) => left.created_at - right.created_at || left.fan_out_id.localeCompare(right.fan_out_id)).map((state) => globalThis.structuredClone(state))));
1994
+ return Service18.of({ create: create2, get: get4, claimAdmissions, recordTerminal, cancel, listNonTerminal, listByParent });
1982
1995
  }));
1983
1996
  var create2 = Effect17.fn("ChildFanOutRepository.create.call")(function* (definition) {
1984
1997
  const repository = yield* Service18;
@@ -2004,6 +2017,10 @@ var listNonTerminal = Effect17.fn("ChildFanOutRepository.listNonTerminal.call")(
2004
2017
  const repository = yield* Service18;
2005
2018
  return yield* repository.listNonTerminal(parentExecutionId);
2006
2019
  });
2020
+ var listByParent = Effect17.fn("ChildFanOutRepository.listByParent.call")(function* (parentExecutionId) {
2021
+ const repository = yield* Service18;
2022
+ return yield* repository.listByParent(parentExecutionId);
2023
+ });
2007
2024
  // ../store-sql/src/cluster/cluster-registry-repository.ts
2008
2025
  var exports_cluster_registry_repository = {};
2009
2026
  __export(exports_cluster_registry_repository, {
@@ -6880,6 +6897,9 @@ var makeSessionRepository = (errors) => Effect40.gen(function* () {
6880
6897
  });
6881
6898
  const appendCheckpoint = Effect40.fn("SessionRepository.appendCheckpoint")(function* (input) {
6882
6899
  const tenantId = yield* current();
6900
+ if (input.compactionCommit !== undefined && input.compactionCommit.checkpointId !== input.id) {
6901
+ return yield* conflict4("checkpoint-id-reused", "Compaction commit checkpoint does not match entry");
6902
+ }
6883
6903
  return yield* mapRepositoryError(sql.withTransaction(Effect40.gen(function* () {
6884
6904
  yield* lockSession(tenantId, input.sessionId);
6885
6905
  const session = yield* requireSession(tenantId, input.sessionId);
@@ -7157,6 +7177,9 @@ var memoryLayer26 = Layer35.sync(Service35, () => {
7157
7177
  return cloneEntry(desired);
7158
7178
  }),
7159
7179
  appendCheckpoint: Effect41.fn("SessionRepository.memory.appendCheckpoint")(function* (input) {
7180
+ if (input.compactionCommit !== undefined && input.compactionCommit.checkpointId !== input.id) {
7181
+ return yield* conflict4("checkpoint-id-reused", "Compaction commit checkpoint does not match entry");
7182
+ }
7160
7183
  const session = sessions.get(input.sessionId);
7161
7184
  if (session === undefined)
7162
7185
  return yield* missingSession(input.sessionId);
@@ -11655,7 +11678,7 @@ var listRevisions3 = Effect61.fn("AgentRegistry.listRevisions.call")(function* (
11655
11678
  });
11656
11679
 
11657
11680
  // ../runtime/src/agent/agent-loop-service.ts
11658
- import { Cause as Cause2, Config as Config4, Context as Context64, Crypto as Crypto3, Effect as Effect93, HashSet as HashSet7, Layer as Layer75, Option as Option24, Ref as Ref19, Schema as Schema85, Stream as Stream13 } from "effect";
11681
+ import { Cause as Cause2, Clock as Clock17, Config as Config4, Context as Context64, Crypto as Crypto3, Effect as Effect93, HashSet as HashSet7, Layer as Layer75, Option as Option24, Ref as Ref19, Schema as Schema85, Stream as Stream13 } from "effect";
11659
11682
  import { AiError as AiError3, Chat, LanguageModel, Prompt as Prompt7, Tokenizer, Tool as AiTool2, Toolkit as Toolkit2 } from "effect/unstable/ai";
11660
11683
 
11661
11684
  // ../runtime/src/child/child-run-service.ts
@@ -11977,6 +12000,7 @@ var childDefinition = Function12.dual(2, (parentDefinition, context) => context.
11977
12000
  child_run_presets: {},
11978
12001
  ...context.compactionPolicy === undefined ? {} : { compaction_policy: context.compactionPolicy },
11979
12002
  ...parentDefinition.turn_policy === undefined ? {} : { turn_policy: parentDefinition.turn_policy },
12003
+ ...parentDefinition.tool_execution === undefined ? {} : { tool_execution: parentDefinition.tool_execution },
11980
12004
  ...parentDefinition.max_tool_turns === undefined ? {} : { max_tool_turns: parentDefinition.max_tool_turns },
11981
12005
  ...parentDefinition.max_wait_turns === undefined ? {} : { max_wait_turns: parentDefinition.max_wait_turns },
11982
12006
  ...parentDefinition.token_budget === undefined ? {} : { token_budget: parentDefinition.token_budget },
@@ -12143,6 +12167,7 @@ var createJoinWait = Effect64.fn("SpawnChildRunTool.createJoinWait")(function* (
12143
12167
  var dispatchChild = Effect64.fn("SpawnChildRunTool.dispatchChild")(function* (config, input, id, definition, waitId2) {
12144
12168
  yield* config.dispatch({
12145
12169
  executionId: exports_ids_schema.ExecutionId.make(id),
12170
+ ...config.origin === undefined ? {} : { origin: config.origin },
12146
12171
  rootAddressId: input.address_id,
12147
12172
  sessionId: exports_execution_schema.childSessionId(id),
12148
12173
  input: input.input ?? [],
@@ -12156,7 +12181,9 @@ var dispatchChild = Effect64.fn("SpawnChildRunTool.dispatchChild")(function* (co
12156
12181
  metadata: {
12157
12182
  parent_execution_id: input.execution_id,
12158
12183
  child_execution_id: id,
12159
- parent_wait_id: waitId2
12184
+ parent_wait_id: waitId2,
12185
+ child_purpose: "child-run",
12186
+ ...input.preset_name === undefined ? {} : { child_profile: input.preset_name }
12160
12187
  }
12161
12188
  }).pipe(Effect64.mapError((error5) => ToolRuntimeError.make({ message: String(error5) })));
12162
12189
  });
@@ -13530,14 +13557,20 @@ var cancelledEvent = (input) => ({
13530
13557
  created_at: input.cancelledAt
13531
13558
  });
13532
13559
  var updateStatus2 = Effect74.fn("ExecutionService.updateStatus")(function* (repository, id, status, updatedAt, metadata11) {
13560
+ const current2 = yield* repository.get(id);
13561
+ const origin = current2?.metadata[exports_execution_schema.executionOriginMetadataKey];
13562
+ const nextMetadata = metadata11 === undefined ? undefined : {
13563
+ ...metadata11,
13564
+ ...origin === undefined ? {} : { [exports_execution_schema.executionOriginMetadataKey]: origin }
13565
+ };
13533
13566
  const record2 = yield* repository.transition({
13534
13567
  id,
13535
13568
  status,
13536
13569
  updatedAt,
13537
- ...metadata11 === undefined ? {} : { metadata: metadata11 }
13538
- }).pipe(Effect74.mapError(mapRepositoryError7));
13570
+ ...nextMetadata === undefined ? {} : { metadata: nextMetadata }
13571
+ });
13539
13572
  return toExecution(record2);
13540
- });
13573
+ }, Effect74.mapError(mapRepositoryError7));
13541
13574
  var layer46 = Layer61.effect(Service56, Effect74.gen(function* () {
13542
13575
  const repository = yield* exports_execution_repository.Service;
13543
13576
  const eventLog = yield* Service41;
@@ -14124,6 +14157,7 @@ var StartInput = Schema74.Struct({
14124
14157
  wait_id: Schema74.optionalKey(exports_ids_schema.WaitId),
14125
14158
  resume_suspension: Schema74.optionalKey(exports_agent_event.AgentSuspended),
14126
14159
  workflow_generation: Schema74.optionalKey(Schema74.Int.check(Schema74.isGreaterThanOrEqualTo(0))),
14160
+ origin: Schema74.optionalKey(exports_execution_schema.ExecutionOrigin),
14127
14161
  metadata: Schema74.optionalKey(exports_shared_schema.Metadata)
14128
14162
  }).annotate({ identifier: "Relay.ExecutionWorkflow.StartInput" });
14129
14163
  var WaitSignalState = Schema74.Literals(["resolved", "timed_out", "cancelled"]).annotate({
@@ -14277,7 +14311,12 @@ var acceptExecution = (input) => Activity.make({
14277
14311
  ...input.agent_revision === undefined ? {} : { agentRevision: input.agent_revision },
14278
14312
  ...input.agent_snapshot === undefined ? {} : { agentSnapshot: input.agent_snapshot },
14279
14313
  ...input.agent_tool_input_schema_digests === undefined ? {} : { agentToolInputSchemaDigests: input.agent_tool_input_schema_digests },
14280
- ...input.metadata === undefined ? {} : { metadata: input.metadata }
14314
+ ...input.metadata === undefined && input.origin === undefined ? {} : {
14315
+ metadata: {
14316
+ ...Object.fromEntries(Object.entries(input.metadata ?? {}).filter(([key4]) => key4 !== exports_execution_schema.executionOriginMetadataKey)),
14317
+ ...input.origin === undefined ? {} : { [exports_execution_schema.executionOriginMetadataKey]: input.origin }
14318
+ }
14319
+ }
14281
14320
  }).pipe(Effect79.mapError(mapExecutionError));
14282
14321
  const skillDefinitionIds = input.agent_snapshot?.skill_definition_ids ?? [];
14283
14322
  if (skillDefinitionIds.length > 0) {
@@ -14565,6 +14604,7 @@ var completeExecution = (input, waitId2, waitState, workspaceRuntimeLayer, turn,
14565
14604
  const skillDefinitionIds = input.agent_snapshot.skill_definition_ids ?? [];
14566
14605
  const loopProgram = agentLoop.run({
14567
14606
  executionId: input.execution_id,
14607
+ ...input.origin === undefined ? {} : { origin: input.origin },
14568
14608
  ...input.session_id === undefined ? {} : {
14569
14609
  sessionId: input.session_id,
14570
14610
  sessionEntryScope: sessionEntryScope(input, turn)
@@ -14593,6 +14633,7 @@ var completeExecution = (input, waitId2, waitState, workspaceRuntimeLayer, turn,
14593
14633
  agent_revision: child.agentRevision,
14594
14634
  agent_snapshot: child.agentSnapshot,
14595
14635
  ...child.agentToolInputSchemaDigests === undefined ? {} : { agent_tool_input_schema_digests: child.agentToolInputSchemaDigests },
14636
+ ...child.origin === undefined ? {} : { origin: child.origin },
14596
14637
  metadata: child.metadata
14597
14638
  }, { discard: true }).pipe(Effect79.provideService(WorkflowEngine.WorkflowEngine, workflowEngine), Effect79.asVoid)
14598
14639
  });
@@ -15987,12 +16028,169 @@ var modelMetadata = (agent) => ({
15987
16028
  model: agent.model.model,
15988
16029
  ...agent.model.registration_key === undefined ? {} : { registration_key: agent.model.registration_key }
15989
16030
  });
15990
- var serviceTier = (part) => {
15991
- const openai = part.metadata.openai;
15992
- if (openai === null || typeof openai !== "object" || Array.isArray(openai))
15993
- return;
15994
- const value = openai.serviceTier;
15995
- return typeof value === "string" ? value : undefined;
16031
+ var usage = (value) => ({
16032
+ input_tokens: value.inputTokens.total ?? null,
16033
+ input_tokens_uncached: value.inputTokens.uncached ?? null,
16034
+ input_tokens_cache_read: value.inputTokens.cacheRead ?? null,
16035
+ input_tokens_cache_write: value.inputTokens.cacheWrite ?? null,
16036
+ output_tokens: value.outputTokens.total ?? null,
16037
+ output_tokens_reasoning: value.outputTokens.reasoning ?? null,
16038
+ output_tokens_text: value.outputTokens.text ?? null
16039
+ });
16040
+ var legacyTelemetryIdentity = (event) => {
16041
+ switch (event._tag) {
16042
+ case "ModelAttemptStarted":
16043
+ case "ModelAttemptCompleted":
16044
+ case "ModelAttemptFailed":
16045
+ return event.modelAttemptId;
16046
+ case "ModelAttemptFirstOutput":
16047
+ return `${event.modelAttemptId}:${event.kind}`;
16048
+ case "ModelRetryScheduled":
16049
+ return `${event.modelCallId}:${event.attempt}`;
16050
+ case "CompactionStarted":
16051
+ case "CompactionCompleted":
16052
+ case "CompactionFailed":
16053
+ return event.compactionId;
16054
+ default:
16055
+ return event.modelCallId;
16056
+ }
16057
+ };
16058
+ var legacyTelemetryCursor = (input, event) => `${input.executionId}:telemetry:${event._tag}:${legacyTelemetryIdentity(event)}`;
16059
+ var legacyUsageCursor = (input, event) => `${input.executionId}:model-usage:${event.modelCallId}:${event.modelAttemptId}`;
16060
+ var telemetryEvent = (input, sessionId, event, sequence, createdAt) => {
16061
+ const type = {
16062
+ ModelCallStarted: "model.call.started",
16063
+ ModelAttemptStarted: "model.attempt.started",
16064
+ ModelAttemptFirstOutput: "model.attempt.first_output",
16065
+ ModelAttemptCompleted: "model.attempt.completed",
16066
+ ModelAttemptFailed: "model.attempt.failed",
16067
+ ModelRetryScheduled: "model.retry.scheduled",
16068
+ ModelCallCompleted: "model.call.completed",
16069
+ ModelCallFailed: "model.call.failed",
16070
+ CompactionStarted: "agent.compaction.started",
16071
+ CompactionCompleted: "agent.compaction.completed",
16072
+ CompactionFailed: "agent.compaction.failed"
16073
+ }[event._tag];
16074
+ const common = "modelCallId" in event ? {
16075
+ turn: event.turn,
16076
+ model_call_id: event.modelCallId,
16077
+ telemetry_session_id: sessionId,
16078
+ delivery_id: event.deliveryId
16079
+ } : {
16080
+ turn: event.turn,
16081
+ compaction_id: event.compactionId,
16082
+ telemetry_session_id: sessionId,
16083
+ delivery_id: event.deliveryId
16084
+ };
16085
+ let data;
16086
+ switch (event._tag) {
16087
+ case "ModelCallStarted":
16088
+ data = {
16089
+ ...common,
16090
+ purpose: event.purpose,
16091
+ started_at: event.startedAt,
16092
+ ...event.provider === undefined ? {} : { provider: event.provider },
16093
+ ...event.model === undefined ? {} : { model: event.model },
16094
+ ...event.compactionId === undefined ? {} : { compaction_id: event.compactionId }
16095
+ };
16096
+ break;
16097
+ case "ModelAttemptStarted":
16098
+ data = { ...common, model_attempt_id: event.modelAttemptId, attempt: event.attempt, started_at: event.startedAt };
16099
+ break;
16100
+ case "ModelAttemptFirstOutput":
16101
+ data = {
16102
+ ...common,
16103
+ model_attempt_id: event.modelAttemptId,
16104
+ attempt: event.attempt,
16105
+ kind: event.kind,
16106
+ at: event.at
16107
+ };
16108
+ break;
16109
+ case "ModelAttemptCompleted":
16110
+ data = {
16111
+ ...common,
16112
+ model_attempt_id: event.modelAttemptId,
16113
+ attempt: event.attempt,
16114
+ completed_at: event.completedAt,
16115
+ ...event.usage === undefined ? {} : { usage: usage(event.usage) },
16116
+ ...event.usageAt === undefined ? {} : { usage_at: event.usageAt },
16117
+ ...event.finishReason === undefined ? {} : { finish_reason: event.finishReason },
16118
+ ...event.requestId === undefined ? {} : { request_id: event.requestId },
16119
+ ...event.responseModel === undefined ? {} : { response_model: event.responseModel },
16120
+ ...event.serviceTier === undefined ? {} : { service_tier: event.serviceTier },
16121
+ ...event.cost === undefined ? {} : { cost: event.cost }
16122
+ };
16123
+ break;
16124
+ case "ModelAttemptFailed":
16125
+ data = {
16126
+ ...common,
16127
+ model_attempt_id: event.modelAttemptId,
16128
+ attempt: event.attempt,
16129
+ failed_at: event.failedAt,
16130
+ category: event.category,
16131
+ classification: event.classification
16132
+ };
16133
+ break;
16134
+ case "ModelRetryScheduled":
16135
+ data = {
16136
+ ...common,
16137
+ attempt: event.attempt,
16138
+ reason: event.reason,
16139
+ category: event.category,
16140
+ delay_millis: event.delayMillis,
16141
+ at: event.at
16142
+ };
16143
+ break;
16144
+ case "ModelCallCompleted":
16145
+ data = {
16146
+ ...common,
16147
+ purpose: event.purpose,
16148
+ attempts: event.attempts,
16149
+ completed_at: event.completedAt,
16150
+ ...event.usage === undefined ? {} : { usage: usage(event.usage) },
16151
+ ...event.finishReason === undefined ? {} : { finish_reason: event.finishReason }
16152
+ };
16153
+ break;
16154
+ case "ModelCallFailed":
16155
+ data = {
16156
+ ...common,
16157
+ purpose: event.purpose,
16158
+ attempts: event.attempts,
16159
+ failed_at: event.failedAt,
16160
+ category: event.category
16161
+ };
16162
+ break;
16163
+ case "CompactionStarted":
16164
+ data = {
16165
+ ...common,
16166
+ trigger: event.trigger,
16167
+ started_at: event.startedAt,
16168
+ ...event.contextTokensBefore === undefined ? {} : { context_tokens_before: event.contextTokensBefore },
16169
+ ...event.entriesBefore === undefined ? {} : { entries_before: event.entriesBefore }
16170
+ };
16171
+ break;
16172
+ case "CompactionCompleted":
16173
+ data = {
16174
+ ...common,
16175
+ kind: event.kind,
16176
+ completed_at: event.completedAt,
16177
+ ...event.summaryModelCallId === undefined ? {} : { summary_model_call_id: event.summaryModelCallId }
16178
+ };
16179
+ break;
16180
+ case "CompactionFailed":
16181
+ data = { ...common, failed_at: event.failedAt };
16182
+ break;
16183
+ }
16184
+ const cursor = `${input.executionId}:telemetry:${sessionId}:${event.deliveryId}`;
16185
+ return {
16186
+ id: exports_ids_schema.EventId.make(`event:${cursor}`),
16187
+ execution_id: input.executionId,
16188
+ type,
16189
+ sequence,
16190
+ cursor,
16191
+ data,
16192
+ created_at: createdAt
16193
+ };
15996
16194
  };
15997
16195
  var inputPreparedEvent = (input, definitions2) => ({
15998
16196
  id: exports_ids_schema.EventId.make(`event:${input.executionId}:model:${input.eventSequence}:input-prepared`),
@@ -16009,28 +16207,31 @@ var inputPreparedEvent = (input, definitions2) => ({
16009
16207
  },
16010
16208
  created_at: input.startedAt
16011
16209
  });
16012
- var usageReportedEvent = (input, part, modelSnapshot, sequence) => {
16013
- const tier = serviceTier(part);
16210
+ var usageReportedEvent = (input, sessionId, event, sequence, createdAt) => {
16211
+ const cursor = `${input.executionId}:model-usage:${sessionId}:${event.deliveryId}`;
16212
+ const reported = event.usage;
16014
16213
  return {
16015
- id: exports_ids_schema.EventId.make(`event:${input.executionId}:model:${sequence}:usage`),
16214
+ id: exports_ids_schema.EventId.make(`event:${cursor}`),
16016
16215
  execution_id: input.executionId,
16017
16216
  type: "model.usage.reported",
16018
16217
  sequence,
16019
- cursor: `${input.executionId}:model:${sequence}:usage`,
16218
+ cursor,
16020
16219
  data: {
16220
+ turn: event.turn,
16221
+ model_call_id: event.modelCallId,
16222
+ model_attempt_id: event.modelAttemptId,
16223
+ attempt: event.attempt,
16224
+ telemetry_session_id: sessionId,
16225
+ delivery_id: event.deliveryId,
16021
16226
  provider: input.agent.model.provider,
16022
16227
  model: input.agent.model.model,
16023
- ...modelSnapshot === undefined ? {} : { model_snapshot: modelSnapshot },
16024
- ...tier === undefined ? {} : { service_tier: tier },
16025
- finish_reason: part.reason,
16026
- input_tokens: part.usage.inputTokens.total ?? null,
16027
- input_tokens_uncached: part.usage.inputTokens.uncached ?? null,
16028
- input_tokens_cache_read: part.usage.inputTokens.cacheRead ?? null,
16029
- input_tokens_cache_write: part.usage.inputTokens.cacheWrite ?? null,
16030
- output_tokens: part.usage.outputTokens.total ?? null,
16031
- output_tokens_reasoning: part.usage.outputTokens.reasoning ?? null
16228
+ ...event.responseModel === undefined ? {} : { model_snapshot: event.responseModel },
16229
+ ...event.serviceTier === undefined ? {} : { service_tier: event.serviceTier },
16230
+ ...event.finishReason === undefined ? {} : { finish_reason: event.finishReason },
16231
+ usage_at: event.usageAt ?? event.completedAt,
16232
+ ...usage(reported)
16032
16233
  },
16033
- created_at: input.startedAt + (sequence - input.eventSequence)
16234
+ created_at: createdAt
16034
16235
  };
16035
16236
  };
16036
16237
  var budgetExceededEvent = (input, tokensUsed, tokenBudget, sequence) => ({
@@ -16049,7 +16250,7 @@ var budgetExceededEvent = (input, tokensUsed, tokenBudget, sequence) => ({
16049
16250
  created_at: input.startedAt + (sequence - input.eventSequence)
16050
16251
  });
16051
16252
  var outputCompletedCursor = (input, sequence) => `${input.executionId}:model:${sequence}:output-completed`;
16052
- var outputDeltaEvent = (input, part, deltaIndex) => {
16253
+ var outputDeltaEvent = (input, modelPart, part, deltaIndex, createdAt) => {
16053
16254
  const sequence = input.eventSequence + 1 + deltaIndex;
16054
16255
  return {
16055
16256
  id: exports_ids_schema.EventId.make(`event:${input.executionId}:model:${sequence}:output-delta:${deltaIndex}`),
@@ -16058,12 +16259,19 @@ var outputDeltaEvent = (input, part, deltaIndex) => {
16058
16259
  sequence,
16059
16260
  cursor: `${input.executionId}:model:${sequence}:output-delta:${deltaIndex}`,
16060
16261
  content: [exports_content_schema.text(part.delta)],
16061
- data: { delta: part.delta, delta_index: deltaIndex, part_id: part.id },
16062
- created_at: input.startedAt + deltaIndex + 1
16262
+ data: {
16263
+ delta: part.delta,
16264
+ delta_index: deltaIndex,
16265
+ part_id: part.id,
16266
+ model_call_id: modelPart.modelCallId,
16267
+ model_attempt_id: modelPart.modelAttemptId,
16268
+ attempt: modelPart.attempt
16269
+ },
16270
+ created_at: createdAt
16063
16271
  };
16064
16272
  };
16065
16273
  var reasoningText = (part) => part.type === "reasoning" ? part.text : part.delta;
16066
- var reasoningDeltaEvent = (input, part, deltaIndex) => {
16274
+ var reasoningDeltaEvent = (input, modelPart, part, deltaIndex, createdAt) => {
16067
16275
  const sequence = input.eventSequence + 1 + deltaIndex;
16068
16276
  const delta = reasoningText(part);
16069
16277
  return {
@@ -16076,12 +16284,15 @@ var reasoningDeltaEvent = (input, part, deltaIndex) => {
16076
16284
  data: {
16077
16285
  delta,
16078
16286
  delta_index: deltaIndex,
16079
- ...part.type === "reasoning-delta" ? { part_id: part.id } : {}
16287
+ ...part.type === "reasoning-delta" ? { part_id: part.id } : {},
16288
+ model_call_id: modelPart.modelCallId,
16289
+ model_attempt_id: modelPart.modelAttemptId,
16290
+ attempt: modelPart.attempt
16080
16291
  },
16081
- created_at: input.startedAt + deltaIndex + 1
16292
+ created_at: createdAt
16082
16293
  };
16083
16294
  };
16084
- var toolCallDeltaEvent = (input, part, toolCallName, sequence, deltaIndex) => ({
16295
+ var toolCallDeltaEvent = (input, modelPart, part, toolCallName, sequence, deltaIndex, createdAt) => ({
16085
16296
  id: exports_ids_schema.EventId.make(`event:${input.executionId}:model:${sequence}:toolcall-delta:${part.id}:${deltaIndex}`),
16086
16297
  execution_id: input.executionId,
16087
16298
  type: "model.toolcall.delta",
@@ -16091,11 +16302,14 @@ var toolCallDeltaEvent = (input, part, toolCallName, sequence, deltaIndex) => ({
16091
16302
  tool_call_id: part.id,
16092
16303
  ...toolCallName === undefined ? {} : { tool_name: toolCallName },
16093
16304
  delta: part.delta,
16094
- delta_index: deltaIndex
16305
+ delta_index: deltaIndex,
16306
+ model_call_id: modelPart.modelCallId,
16307
+ model_attempt_id: modelPart.modelAttemptId,
16308
+ attempt: modelPart.attempt
16095
16309
  },
16096
- created_at: input.startedAt + (sequence - input.eventSequence)
16310
+ created_at: createdAt
16097
16311
  });
16098
- var outputCompletedEvent = (input, content, outputText, sequence, structuredOutput) => ({
16312
+ var outputCompletedEvent = (input, content, outputText, sequence, structuredOutput, structuredIdentity) => ({
16099
16313
  id: exports_ids_schema.EventId.make(`event:${input.executionId}:model:${sequence}:output-completed`),
16100
16314
  execution_id: input.executionId,
16101
16315
  type: "model.output.completed",
@@ -16104,7 +16318,12 @@ var outputCompletedEvent = (input, content, outputText, sequence, structuredOutp
16104
16318
  content,
16105
16319
  data: {
16106
16320
  model_output: outputText,
16107
- ...structuredOutput === undefined ? {} : { structured_output: structuredOutput }
16321
+ ...structuredOutput === undefined ? {} : { structured_output: structuredOutput },
16322
+ ...structuredIdentity === undefined ? {} : {
16323
+ structured_output_model_call_id: structuredIdentity.modelCallId,
16324
+ structured_output_model_attempt_id: structuredIdentity.modelAttemptId,
16325
+ structured_output_attempt: structuredIdentity.attempt
16326
+ }
16108
16327
  },
16109
16328
  created_at: input.completedAt
16110
16329
  });
@@ -16121,11 +16340,14 @@ var AgentLoopEvents = {
16121
16340
  budgetExceededEvent,
16122
16341
  completedContent,
16123
16342
  inputPreparedEvent,
16343
+ legacyTelemetryCursor,
16344
+ legacyUsageCursor,
16124
16345
  modelOutputMetadata,
16125
16346
  outputCompletedEvent,
16126
16347
  outputDeltaEvent,
16127
16348
  reasoningDeltaEvent,
16128
16349
  toolCallDeltaEvent,
16350
+ telemetryEvent,
16129
16351
  usageReportedEvent
16130
16352
  };
16131
16353
 
@@ -16134,11 +16356,14 @@ var {
16134
16356
  budgetExceededEvent: budgetExceededEvent2,
16135
16357
  completedContent: completedContent2,
16136
16358
  inputPreparedEvent: inputPreparedEvent2,
16359
+ legacyTelemetryCursor: legacyTelemetryCursor2,
16360
+ legacyUsageCursor: legacyUsageCursor2,
16137
16361
  modelOutputMetadata: modelOutputMetadata2,
16138
16362
  outputCompletedEvent: outputCompletedEvent2,
16139
16363
  outputDeltaEvent: outputDeltaEvent2,
16140
16364
  reasoningDeltaEvent: reasoningDeltaEvent2,
16141
16365
  toolCallDeltaEvent: toolCallDeltaEvent2,
16366
+ telemetryEvent: telemetryEvent2,
16142
16367
  usageReportedEvent: usageReportedEvent2
16143
16368
  } = AgentLoopEvents;
16144
16369
 
@@ -16212,6 +16437,7 @@ var childRunCoreTools = (input, childRuns, eventLog, waits) => {
16212
16437
  return Effect93.succeed([
16213
16438
  registeredTool({
16214
16439
  agent: input.agent,
16440
+ ...input.origin === undefined ? {} : { origin: input.origin },
16215
16441
  agentId: input.agentId,
16216
16442
  agentRevision: input.agentRevision,
16217
16443
  ...input.agentToolInputSchemaDigests === undefined ? {} : { agentToolInputSchemaDigests: input.agentToolInputSchemaDigests },
@@ -16222,6 +16448,7 @@ var childRunCoreTools = (input, childRuns, eventLog, waits) => {
16222
16448
  }),
16223
16449
  ...transferTools({
16224
16450
  agent: input.agent,
16451
+ ...input.origin === undefined ? {} : { origin: input.origin },
16225
16452
  agentId: input.agentId,
16226
16453
  agentRevision: input.agentRevision,
16227
16454
  ...input.agentToolInputSchemaDigests === undefined ? {} : { agentToolInputSchemaDigests: input.agentToolInputSchemaDigests },
@@ -16238,59 +16465,79 @@ var existingOutput = (eventLog, input) => eventLog.findFirstByTypeAfterSequence(
16238
16465
  afterSequence: input.eventSequence
16239
16466
  }).pipe(Effect93.map(Option24.getOrUndefined), Effect93.mapError((error5) => loopError(error5, input.eventSequence + 2)));
16240
16467
  var STRUCTURED_TURN_PROMPT = "Return the final structured output for the task above.";
16241
- var runStructuredTurn = Effect93.fn("AgentLoop.runStructuredTurn")(function* (languageModels, schemas, chat, input, schemaRef, sequence) {
16242
- const registration = yield* schemas.resolve(schemaRef).pipe(Effect93.mapError((error5) => loopError(error5, sequence)));
16243
- const response = yield* languageModels.provideForAgent(input.agent, chat.generateObject({
16244
- prompt: STRUCTURED_TURN_PROMPT,
16245
- schema: registration.schema,
16246
- objectName: "output"
16247
- })).pipe(Effect93.mapError((error5) => Schema85.is(AgentLoopError)(error5) ? error5 : loopError(error5, sequence)));
16248
- return jsonValue6(response.value);
16249
- });
16250
16468
  var loopError = (error5, nextEventSequence5) => AgentLoopError.make({
16251
16469
  message: error5 instanceof Error ? `${error5.name}: ${error5.message}` : String(error5),
16252
16470
  next_event_sequence: nextEventSequence5
16253
16471
  });
16254
16472
  var appendEvent = (eventLog, allocator, event, nextEventSequence5) => appendIdempotentTo(eventLog, event).pipe(Effect93.tap((appended) => allocator.advanceTo(appended.sequence + 1)), Effect93.mapError((error5) => loopError(error5, nextEventSequence5)));
16255
- var compactionCommittedCursor = (executionId, checkpointId2) => `execution:${executionId}:agent-compaction:${checkpointId2}:committed`;
16256
- var appendCompactionStartedEvent = Effect93.fn("AgentLoop.appendCompactionStartedEvent")(function* (eventLog, allocator, input, info) {
16257
- const cursor = `execution:${input.executionId}:agent-compaction:turn:${info.turn}:started`;
16258
- const existing = yield* eventLog.findByCursor({ executionId: input.executionId, cursor }).pipe(Effect93.mapError((error5) => loopError(error5, input.eventSequence + 1)));
16259
- if (Option24.isSome(existing))
16260
- return;
16261
- const sequence = yield* allocator.allocate(1);
16262
- const data = { turn: info.turn, overflow: info.overflow };
16263
- yield* appendEvent(eventLog, allocator, {
16264
- id: exports_ids_schema.EventId.make(`event:${input.executionId}:agent-compaction:turn:${info.turn}:started`),
16265
- execution_id: input.executionId,
16266
- type: "agent.compaction.started",
16267
- sequence,
16268
- cursor,
16269
- data,
16270
- created_at: input.startedAt + (sequence - input.eventSequence)
16271
- }, sequence + 1);
16473
+ var deliverTelemetry = Effect93.fn("AgentLoop.deliverTelemetry")(function* (eventLog, allocator, input, batch) {
16474
+ for (const event of batch.events) {
16475
+ const createdAt = yield* Clock17.currentTimeMillis;
16476
+ const candidate = telemetryEvent2(input, batch.sessionId, event, 0, createdAt);
16477
+ const existing = yield* eventLog.findByCursor({ executionId: input.executionId, cursor: candidate.cursor });
16478
+ const legacy = yield* eventLog.findByCursor({
16479
+ executionId: input.executionId,
16480
+ cursor: legacyTelemetryCursor2(input, event)
16481
+ });
16482
+ if (Option24.isNone(existing) && Option24.isNone(legacy)) {
16483
+ const sequence = yield* allocator.allocate(1);
16484
+ yield* appendEvent(eventLog, allocator, { ...candidate, sequence }, sequence + 1);
16485
+ }
16486
+ if (event._tag === "ModelAttemptCompleted" && event.usage !== undefined) {
16487
+ const usageCreatedAt = yield* Clock17.currentTimeMillis;
16488
+ const usageCandidate = usageReportedEvent2(input, batch.sessionId, event, 0, usageCreatedAt);
16489
+ const existingUsage = yield* eventLog.findByCursor({
16490
+ executionId: input.executionId,
16491
+ cursor: usageCandidate.cursor
16492
+ });
16493
+ const legacyUsage = yield* eventLog.findByCursor({
16494
+ executionId: input.executionId,
16495
+ cursor: legacyUsageCursor2(input, event)
16496
+ });
16497
+ if (Option24.isNone(existingUsage) && Option24.isNone(legacyUsage)) {
16498
+ const sequence = yield* allocator.allocate(1);
16499
+ yield* appendEvent(eventLog, allocator, { ...usageCandidate, sequence }, sequence + 1);
16500
+ }
16501
+ }
16502
+ }
16503
+ });
16504
+ var telemetryDelivery = (eventLog, allocator, input) => exports_model_telemetry.Delivery.of({
16505
+ deliver: (batch) => deliverTelemetry(eventLog, allocator, input, batch).pipe(Effect93.mapError((error5) => exports_model_telemetry.DeliveryFailed.make({
16506
+ message: "Relay could not durably project model telemetry",
16507
+ cause: error5
16508
+ })))
16272
16509
  });
16510
+ var compactionCommittedCursor = (executionId, checkpointId2) => `execution:${executionId}:agent-compaction-commit:v2:${checkpointId2}`;
16273
16511
  var appendCompactionCommittedEvent = Effect93.fn("AgentLoop.appendCompactionCommittedEvent")(function* (eventLog, allocator, input, checkpoint) {
16274
16512
  if (input.sessionId === undefined)
16275
16513
  return;
16276
- const cursor = compactionCommittedCursor(input.executionId, checkpoint.id);
16514
+ const commit = checkpoint.compactionCommit;
16515
+ if (commit === undefined)
16516
+ return;
16517
+ const cursor = compactionCommittedCursor(input.executionId, exports_ids_schema.SessionEntryId.make(commit.checkpointId));
16277
16518
  const existing = yield* eventLog.findByCursor({ executionId: input.executionId, cursor }).pipe(Effect93.mapError((error5) => loopError(error5, input.eventSequence + 1)));
16278
16519
  if (Option24.isSome(existing))
16279
16520
  return;
16280
16521
  const sequence = yield* allocator.allocate(1);
16522
+ const createdAt = yield* Clock17.currentTimeMillis;
16281
16523
  const data = {
16282
- checkpoint_id: exports_ids_schema.SessionEntryId.make(checkpoint.id),
16524
+ checkpoint_id: exports_ids_schema.SessionEntryId.make(commit.checkpointId),
16283
16525
  session_id: input.sessionId,
16284
- summary_present: checkpoint.summary !== undefined
16526
+ compaction_id: commit.compactionId,
16527
+ ...commit.summaryModelCallId === undefined ? {} : { summary_model_call_id: commit.summaryModelCallId },
16528
+ ...commit.contextTokensBefore === undefined ? {} : { context_tokens_before: commit.contextTokensBefore },
16529
+ ...commit.contextTokensAfter === undefined ? {} : { context_tokens_after: commit.contextTokensAfter },
16530
+ ...commit.entriesBefore === undefined ? {} : { entries_before: commit.entriesBefore },
16531
+ ...commit.entriesAfter === undefined ? {} : { entries_after: commit.entriesAfter }
16285
16532
  };
16286
16533
  yield* appendEvent(eventLog, allocator, {
16287
- id: exports_ids_schema.EventId.make(`event:${input.executionId}:agent-compaction:${checkpoint.id}:committed`),
16534
+ id: exports_ids_schema.EventId.make(`event:${input.executionId}:agent-compaction-commit:v2:${commit.checkpointId}`),
16288
16535
  execution_id: input.executionId,
16289
16536
  type: "agent.compaction.committed",
16290
16537
  sequence,
16291
16538
  cursor,
16292
16539
  data,
16293
- created_at: input.startedAt + (sequence - input.eventSequence)
16540
+ created_at: createdAt
16294
16541
  }, sequence + 1);
16295
16542
  });
16296
16543
  var toolFromDefinition = (definition) => AiTool2.dynamic(definition.name, {
@@ -16327,7 +16574,7 @@ var restoreHistory = Effect93.fn("AgentLoop.restoreHistory")(function* (chats, i
16327
16574
  return history;
16328
16575
  });
16329
16576
  var promptEquivalence = Schema85.toEquivalence(Prompt7.Prompt);
16330
- var reconcileCompactionCheckpoint = Effect93.fn("AgentLoop.reconcileCompactionCheckpoint")(function* (sessions, chats, input, restoredHistory, onCheckpointCommitted, failOnMismatch = false) {
16577
+ var reconcileCompactionCheckpoint = Effect93.fn("AgentLoop.reconcileCompactionCheckpoint")(function* (sessions, chats, eventLog, allocator, input, restoredHistory, onCheckpointCommitted, failOnMismatch = false) {
16331
16578
  if (input.sessionId === undefined)
16332
16579
  return restoredHistory;
16333
16580
  const path2 = yield* sessions.path({ sessionId: input.sessionId }).pipe(Effect93.mapError((error5) => loopError(error5, input.eventSequence + 1)));
@@ -16342,6 +16589,10 @@ var reconcileCompactionCheckpoint = Effect93.fn("AgentLoop.reconcileCompactionCh
16342
16589
  checkpoint,
16343
16590
  leafId: checkpoint.id
16344
16591
  };
16592
+ yield* deliverTelemetry(eventLog, allocator, input, {
16593
+ sessionId: input.sessionId,
16594
+ events: checkpoint.telemetry
16595
+ }).pipe(Effect93.mapError((error5) => loopError(error5, input.eventSequence + 1)));
16345
16596
  const repaired = exports_session.buildContext(path2);
16346
16597
  if (restoredHistory === undefined) {
16347
16598
  yield* persistTranscript(chats, input, repaired);
@@ -16603,7 +16854,7 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16603
16854
  };
16604
16855
  const storedHistory = resumeToolCall === undefined ? yield* loadStoredHistory(chats, input) : yield* restoreHistory(chats, input);
16605
16856
  const onCheckpointCommitted = (result) => appendCompactionCommittedEvent(eventLog, allocator, input, result.checkpoint).pipe(Effect93.andThen(layerOptions?.onCheckpointCommitted?.(result) ?? Effect93.void));
16606
- const durableHistory = Option24.isNone(sessionRepository) ? storedHistory : yield* reconcileCompactionCheckpoint(sessionRepository.value, chats, input, storedHistory, onCheckpointCommitted, resumeSuspension === undefined);
16857
+ const durableHistory = Option24.isNone(sessionRepository) ? storedHistory : yield* reconcileCompactionCheckpoint(sessionRepository.value, chats, eventLog, allocator, input, storedHistory, onCheckpointCommitted, resumeSuspension === undefined);
16607
16858
  const continuingDurableHistory = durableHistory !== undefined;
16608
16859
  const permissionsLayer = input.agent.permission_rules === undefined ? Layer75.empty : Option24.isNone(permissionRules) || Option24.isNone(waits) ? yield* AgentLoopError.make({
16609
16860
  message: "Execution permission rules require PermissionRuleRepository and WaitService in context",
@@ -16693,11 +16944,20 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16693
16944
  next_event_sequence: input.eventSequence + 1
16694
16945
  });
16695
16946
  }
16947
+ const schemaRef = input.agent.output_schema_ref;
16948
+ const structuredRegistration = schemaRef === undefined ? undefined : yield* schemas.resolve(schemaRef).pipe(Effect93.mapError((error5) => loopError(error5, input.eventSequence + 1)));
16696
16949
  const batonCompaction = compactionPolicy === undefined ? undefined : { contextWindow: compactionPolicy.context_window };
16697
16950
  const batonOptions = {
16698
16951
  ...options,
16699
16952
  ...toolOutputMaxBytes === undefined ? {} : { toolOutputMaxBytes },
16700
- ...batonCompaction === undefined ? {} : { compaction: batonCompaction }
16953
+ ...batonCompaction === undefined ? {} : { compaction: batonCompaction },
16954
+ ...structuredRegistration === undefined ? {} : {
16955
+ output: {
16956
+ schema: structuredRegistration.schema,
16957
+ name: "output",
16958
+ prompt: STRUCTURED_TURN_PROMPT
16959
+ }
16960
+ }
16701
16961
  };
16702
16962
  const batonMemory = memory === undefined || Option24.isNone(durableMemory) ? undefined : recallOnlyMemory(durableMemory.value);
16703
16963
  const executorLayer = layer56({
@@ -16717,8 +16977,7 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16717
16977
  const compactionService = activeCompactionOptions === undefined ? undefined : exports_compaction.Compaction.of(make8({
16718
16978
  executionId: input.executionId,
16719
16979
  repository: activeCompactionRepository,
16720
- options: activeCompactionOptions,
16721
- onSummarizeStarted: (info) => appendCompactionStartedEvent(eventLog, allocator, input, info).pipe(Effect93.mapError((error5) => exports_compaction.CompactionError.make({ message: error5.message, cause: error5 })))
16980
+ options: activeCompactionOptions
16722
16981
  }));
16723
16982
  if (memory !== undefined && Option24.isNone(durableMemory)) {
16724
16983
  return yield* AgentLoopError.make({
@@ -16738,18 +16997,55 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16738
16997
  });
16739
16998
  const foldEvent = (state, event) => Effect93.gen(function* () {
16740
16999
  switch (event._tag) {
17000
+ case "ModelCallStarted":
17001
+ case "ModelAttemptStarted":
17002
+ case "ModelAttemptFirstOutput":
17003
+ case "ModelAttemptCompleted":
17004
+ case "ModelAttemptFailed":
17005
+ case "ModelRetryScheduled":
17006
+ case "ModelCallCompleted":
17007
+ case "ModelCallFailed":
17008
+ case "CompactionStarted":
17009
+ case "CompactionCompleted":
17010
+ case "CompactionFailed": {
17011
+ const createdAt = yield* Clock17.currentTimeMillis;
17012
+ const candidate = telemetryEvent2(input, input.sessionId ?? input.executionId, event, 0, createdAt);
17013
+ const existingTelemetry = yield* eventLog.findByCursor({
17014
+ executionId: input.executionId,
17015
+ cursor: candidate.cursor
17016
+ });
17017
+ if (Option24.isNone(existingTelemetry)) {
17018
+ const sequence = yield* allocator.allocate(1);
17019
+ yield* appendEvent(eventLog, allocator, { ...candidate, sequence }, sequence + 1);
17020
+ }
17021
+ if (event._tag === "ModelAttemptCompleted" && event.usage !== undefined) {
17022
+ const usageCreatedAt = yield* Clock17.currentTimeMillis;
17023
+ const usageCandidate = usageReportedEvent2(input, input.sessionId ?? input.executionId, event, 0, usageCreatedAt);
17024
+ const existingUsage = yield* eventLog.findByCursor({
17025
+ executionId: input.executionId,
17026
+ cursor: usageCandidate.cursor
17027
+ });
17028
+ if (Option24.isNone(existingUsage)) {
17029
+ const usageSequence = yield* allocator.allocate(1);
17030
+ yield* appendEvent(eventLog, allocator, { ...usageCandidate, sequence: usageSequence }, usageSequence + 1);
17031
+ }
17032
+ }
17033
+ return state;
17034
+ }
16741
17035
  case "ModelPart": {
16742
17036
  const part = event.part;
16743
17037
  if (part.type === "text-delta") {
16744
17038
  const sequence = yield* allocator.allocate(1);
16745
17039
  const deltaIndex = sequence - input.eventSequence - 1;
16746
- yield* appendEvent(eventLog, allocator, outputDeltaEvent2(input, part, deltaIndex), sequence + 1);
17040
+ const createdAt = yield* Clock17.currentTimeMillis;
17041
+ yield* appendEvent(eventLog, allocator, outputDeltaEvent2(input, event, part, deltaIndex, createdAt), sequence + 1);
16747
17042
  return { ...state, text: `${state.text}${part.delta}` };
16748
17043
  }
16749
17044
  if (part.type === "reasoning" || part.type === "reasoning-delta") {
16750
17045
  const sequence = yield* allocator.allocate(1);
16751
17046
  const deltaIndex = sequence - input.eventSequence - 1;
16752
- yield* appendEvent(eventLog, allocator, reasoningDeltaEvent2(input, part, deltaIndex), sequence + 1);
17047
+ const createdAt = yield* Clock17.currentTimeMillis;
17048
+ yield* appendEvent(eventLog, allocator, reasoningDeltaEvent2(input, event, part, deltaIndex, createdAt), sequence + 1);
16753
17049
  return state;
16754
17050
  }
16755
17051
  if (part.type === "tool-params-start") {
@@ -16760,7 +17056,8 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16760
17056
  if (part.type === "tool-params-delta") {
16761
17057
  const sequence = yield* allocator.allocate(1);
16762
17058
  const deltaIndex = state.toolCallDeltaIndexes[part.id] ?? 0;
16763
- yield* appendEvent(eventLog, allocator, toolCallDeltaEvent2(input, part, state.toolCallNames[part.id], sequence, deltaIndex), sequence + 1);
17059
+ const createdAt = yield* Clock17.currentTimeMillis;
17060
+ yield* appendEvent(eventLog, allocator, toolCallDeltaEvent2(input, event, part, state.toolCallNames[part.id], sequence, deltaIndex, createdAt), sequence + 1);
16764
17061
  return {
16765
17062
  ...state,
16766
17063
  toolCallDeltaIndexes: { ...state.toolCallDeltaIndexes, [part.id]: deltaIndex + 1 }
@@ -16768,8 +17065,6 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16768
17065
  }
16769
17066
  if (part.type === "finish") {
16770
17067
  const finish = part;
16771
- const sequence = yield* allocator.allocate(1);
16772
- yield* appendEvent(eventLog, allocator, usageReportedEvent2(input, finish, state.modelId, sequence), sequence + 1);
16773
17068
  yield* recordModelUsage({
16774
17069
  provider: input.agent.model.provider,
16775
17070
  model: input.agent.model.model,
@@ -16798,6 +17093,17 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16798
17093
  case "Completed": {
16799
17094
  return { ...state, text: event.text, transcript: event.transcript, turn: event.turns - 1 };
16800
17095
  }
17096
+ case "StructuredOutput": {
17097
+ return {
17098
+ ...state,
17099
+ structuredOutput: jsonValue6(event.value),
17100
+ structuredIdentity: {
17101
+ modelCallId: event.modelCallId,
17102
+ modelAttemptId: event.modelAttemptId,
17103
+ attempt: event.attempt
17104
+ }
17105
+ };
17106
+ }
16801
17107
  default:
16802
17108
  return state;
16803
17109
  }
@@ -16809,7 +17115,7 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16809
17115
  onCheckpointCommitted: (result) => onCheckpointCommitted(result).pipe(Effect93.orDie),
16810
17116
  ...sessionWriter === undefined ? {} : { writer: sessionWriter }
16811
17117
  }).pipe(Effect93.provideService(exports_session_repository.Service, sessionRepository.value)) : undefined;
16812
- const foldContext = yield* Layer75.build(Layer75.mergeAll(executorLayer, handlerLayer, approvalsLayer, exports_model_middleware.layerIdentity, instructionsLayer, permissionsLayer, steeringLayer));
17118
+ const foldContext = yield* Layer75.build(Layer75.mergeAll(executorLayer, handlerLayer, approvalsLayer, exports_model_middleware.layerIdentity, instructionsLayer, permissionsLayer, steeringLayer, Layer75.succeed(exports_model_telemetry.Delivery, telemetryDelivery(eventLog, allocator, input))));
16813
17119
  const folded = exports_agent.stream(agent, batonOptions).pipe(Stream13.runFoldEffect(() => ({
16814
17120
  text: "",
16815
17121
  transcript: undefined,
@@ -16837,10 +17143,9 @@ var make12 = (layerOptions) => Effect93.gen(function* () {
16837
17143
  yield* durableMemory.value.remember({ key: memory.key, turn: finalState.turn ?? 0, transcript, terminal: true }).pipe(Effect93.mapError((error5) => loopError(error5, completedSequence + 1)));
16838
17144
  }
16839
17145
  }
16840
- const schemaRef = input.agent.output_schema_ref;
16841
- const structuredOutput = schemaRef === undefined || finalState.transcript === undefined ? undefined : yield* Chat.fromPrompt(finalState.transcript).pipe(Effect93.flatMap((chat) => runStructuredTurn(languageModels, schemas, chat, input, schemaRef, completedSequence + 1)));
17146
+ const structuredOutput = finalState.structuredOutput;
16842
17147
  const structuredPart = structuredOutput === undefined || schemaRef === undefined ? [] : [{ type: "structured", value: structuredOutput, schema_ref: schemaRef }];
16843
- yield* appendEvent(eventLog, allocator, outputCompletedEvent2(input, [...completedContent2(finalState.text), ...structuredPart], finalState.text, completedSequence, structuredOutput), completedSequence + 1);
17148
+ yield* appendEvent(eventLog, allocator, outputCompletedEvent2(input, [...completedContent2(finalState.text), ...structuredPart], finalState.text, completedSequence, structuredOutput, finalState.structuredIdentity), completedSequence + 1);
16844
17149
  return {
16845
17150
  metadata: {
16846
17151
  model_output: finalState.text,
@@ -17145,7 +17450,7 @@ var layerFromServices2 = Layer79.effect(Service68, Effect97.gen(function* () {
17145
17450
  }));
17146
17451
 
17147
17452
  // ../runtime/src/schedule/scheduler-service.ts
17148
- import { Clock as Clock17, Config as Config7, Context as Context69, Cron, DateTime as DateTime2, Duration as Duration6, Effect as Effect98, Layer as Layer80, Option as Option25, Random as Random3, Result as Result3, Schema as Schema91 } from "effect";
17453
+ import { Clock as Clock18, Config as Config7, Context as Context69, Cron, DateTime as DateTime2, Duration as Duration6, Effect as Effect98, Layer as Layer80, Option as Option25, Random as Random3, Result as Result3, Schema as Schema91 } from "effect";
17149
17454
  class SchedulerError extends Schema91.TaggedErrorClass()("SchedulerError", {
17150
17455
  message: Schema91.String
17151
17456
  }) {
@@ -17270,7 +17575,7 @@ var make13 = Effect98.gen(function* () {
17270
17575
  const runOnce2 = Effect98.gen(function* () {
17271
17576
  let dispatched = 0;
17272
17577
  while (true) {
17273
- const now = yield* Clock17.currentTimeMillis;
17578
+ const now = yield* Clock18.currentTimeMillis;
17274
17579
  const claimed = yield* schedules.claimDue({ workerId, now, claimExpiresAt: now + claimTtlMillis }).pipe(Effect98.mapError(toSchedulerError));
17275
17580
  if (claimed === undefined)
17276
17581
  return dispatched;
@@ -17671,7 +17976,7 @@ var check = Effect99.fn("RunnerRuntime.check.call")(function* () {
17671
17976
  });
17672
17977
 
17673
17978
  // ../runtime/src/workflow/definition-runtime.ts
17674
- import { Cause as Cause3, Clock as Clock18, Context as Context71, Effect as Effect100, Exit as Exit2, FiberMap as FiberMap2, Layer as Layer82, Option as Option27, Schema as Schema93 } from "effect";
17979
+ import { Cause as Cause3, Clock as Clock19, Context as Context71, Effect as Effect100, Exit as Exit2, FiberMap as FiberMap2, Layer as Layer82, Option as Option27, Schema as Schema93 } from "effect";
17675
17980
  import { dual as dual2 } from "effect/Function";
17676
17981
 
17677
17982
  class UnsupportedOperation extends Schema93.TaggedErrorClass()("UnsupportedWorkflowOperation", { operation_id: exports_ids_schema.WorkflowOperationId, kind: Schema93.String }) {
@@ -17736,7 +18041,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17736
18041
  yield* repository.appendLifecycle({
17737
18042
  execution_id: executionId,
17738
18043
  type: "workflow.started",
17739
- created_at: yield* Clock18.currentTimeMillis
18044
+ created_at: yield* Clock19.currentTimeMillis
17740
18045
  });
17741
18046
  const byId = new Map(revision.definition.operations.map((operation) => [operation.id, operation]));
17742
18047
  const execute = (id) => Effect100.gen(function* () {
@@ -17749,7 +18054,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17749
18054
  const operation = byId.get(id);
17750
18055
  if (operation === undefined)
17751
18056
  return yield* Effect100.die(new Error(`validated workflow operation missing: ${id}`));
17752
- const startedAt = persisted?.started_at ?? (yield* Clock18.currentTimeMillis);
18057
+ const startedAt = persisted?.started_at ?? (yield* Clock19.currentTimeMillis);
17753
18058
  const sideEffectContext = {
17754
18059
  execution_id: executionId,
17755
18060
  operation_id: id,
@@ -17791,7 +18096,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17791
18096
  return yield* UnsupportedOperation.make({ operation_id: operation.id, kind: operation.kind });
17792
18097
  const fanOutId = persisted?.fan_out_id ?? fanOutIdFor(executionId, operation.fan_out_key);
17793
18098
  if (persisted?.fan_out_id === undefined) {
17794
- const now = yield* Clock18.currentTimeMillis;
18099
+ const now = yield* Clock19.currentTimeMillis;
17795
18100
  yield* repository.putOperation({
17796
18101
  execution_id: executionId,
17797
18102
  operation_id: id,
@@ -17849,7 +18154,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17849
18154
  return yield* Effect100.die(new Error(`workflow fan-out state missing: ${operation.parallel_operation}`));
17850
18155
  const fanOut = yield* handlers.inspectChildFanOut(parallelState.fan_out_id);
17851
18156
  if (fanOut === undefined || fanOut.state === "joining") {
17852
- const now = yield* Clock18.currentTimeMillis;
18157
+ const now = yield* Clock19.currentTimeMillis;
17853
18158
  yield* repository.putOperation({
17854
18159
  execution_id: executionId,
17855
18160
  operation_id: id,
@@ -17892,7 +18197,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17892
18197
  break;
17893
18198
  case "branch": {
17894
18199
  const decision = persisted?.decision ?? (yield* handlers.branch(executionId, operation, sideEffectContext));
17895
- const now = yield* Clock18.currentTimeMillis;
18200
+ const now = yield* Clock19.currentTimeMillis;
17896
18201
  yield* repository.putOperation({
17897
18202
  execution_id: executionId,
17898
18203
  operation_id: id,
@@ -17911,7 +18216,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17911
18216
  let attempt = persisted?.attempt ?? 0;
17912
18217
  while (attempt < operation.max_attempts) {
17913
18218
  if (persisted?.backoff_until !== undefined) {
17914
- const remaining = persisted.backoff_until - (yield* Clock18.currentTimeMillis);
18219
+ const remaining = persisted.backoff_until - (yield* Clock19.currentTimeMillis);
17915
18220
  if (remaining > 0)
17916
18221
  yield* Effect100.sleep(`${remaining} millis`);
17917
18222
  }
@@ -17923,7 +18228,7 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17923
18228
  attempt += 1;
17924
18229
  if (attempt >= operation.max_attempts)
17925
18230
  return yield* result2;
17926
- const now = yield* Clock18.currentTimeMillis;
18231
+ const now = yield* Clock19.currentTimeMillis;
17927
18232
  const backoffUntil = now + attempt * 1000;
17928
18233
  yield* repository.putOperation({
17929
18234
  execution_id: executionId,
@@ -17946,9 +18251,9 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17946
18251
  }
17947
18252
  case "budget": {
17948
18253
  const states = yield* repository.listOperations(executionId);
17949
- const used = operation.unit === "milliseconds" ? (yield* Clock18.currentTimeMillis) - startedAt : states.filter((state) => state.status === "completed").length;
18254
+ const used = operation.unit === "milliseconds" ? (yield* Clock19.currentTimeMillis) - startedAt : states.filter((state) => state.status === "completed").length;
17950
18255
  if (used >= operation.limit) {
17951
- const now = yield* Clock18.currentTimeMillis;
18256
+ const now = yield* Clock19.currentTimeMillis;
17952
18257
  yield* repository.appendLifecycle({
17953
18258
  execution_id: executionId,
17954
18259
  operation_id: id,
@@ -17973,18 +18278,18 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
17973
18278
  ...output2 === undefined ? {} : { output: output2 },
17974
18279
  compensation_operation_id: operation.compensate_with,
17975
18280
  started_at: startedAt,
17976
- updated_at: yield* Clock18.currentTimeMillis
18281
+ updated_at: yield* Clock19.currentTimeMillis
17977
18282
  });
17978
18283
  yield* repository.appendLifecycle({
17979
18284
  execution_id: executionId,
17980
18285
  operation_id: id,
17981
18286
  type: "compensation.recorded",
17982
18287
  data: { compensate_with: operation.compensate_with },
17983
- created_at: yield* Clock18.currentTimeMillis
18288
+ created_at: yield* Clock19.currentTimeMillis
17984
18289
  });
17985
18290
  break;
17986
18291
  }
17987
- const completedAt = yield* Clock18.currentTimeMillis;
18292
+ const completedAt = yield* Clock19.currentTimeMillis;
17988
18293
  const current2 = yield* repository.getOperation(executionId, id);
17989
18294
  yield* repository.putOperation({
17990
18295
  execution_id: executionId,
@@ -18020,15 +18325,15 @@ var run6 = Effect100.fn("WorkflowDefinitionRuntime.run")(function* (executionId)
18020
18325
  for (const state of compensationStack) {
18021
18326
  if (state.compensation_operation_id === undefined || state.status === "compensated")
18022
18327
  continue;
18023
- yield* repository.putOperation({ ...state, status: "compensating", updated_at: yield* Clock18.currentTimeMillis });
18328
+ yield* repository.putOperation({ ...state, status: "compensating", updated_at: yield* Clock19.currentTimeMillis });
18024
18329
  yield* repository.appendLifecycle({
18025
18330
  execution_id: executionId,
18026
18331
  operation_id: state.operation_id,
18027
18332
  type: "compensation.started",
18028
- created_at: yield* Clock18.currentTimeMillis
18333
+ created_at: yield* Clock19.currentTimeMillis
18029
18334
  });
18030
18335
  yield* execute(state.compensation_operation_id);
18031
- const completedAt = yield* Clock18.currentTimeMillis;
18336
+ const completedAt = yield* Clock19.currentTimeMillis;
18032
18337
  yield* repository.putOperation({
18033
18338
  ...state,
18034
18339
  status: "compensated",
@@ -18080,7 +18385,7 @@ var layerFromRuntime2 = Layer82.effect(Service71, Effect100.gen(function* () {
18080
18385
  }));
18081
18386
 
18082
18387
  // src/runtime.ts
18083
- import { Cause as Cause5, Context as Context74, Effect as Effect112, Layer as Layer86, Option as Option31, Schema as Schema101 } from "effect";
18388
+ import { Cause as Cause5, Context as Context74, Effect as Effect112, Layer as Layer86, Option as Option32, Schema as Schema103 } from "effect";
18084
18389
  import { SqlClient as SqlClient31 } from "effect/unstable/sql/SqlClient";
18085
18390
 
18086
18391
  // src/runtime-acquisition-error.ts
@@ -18162,7 +18467,7 @@ var renderConfigurationError = (error5) => {
18162
18467
  return `Runtime configuration error [${error5.category}/${error5.scope}]: ${remediation}; causes=${reasons}${error5.cause.truncated ? ",truncated" : ""}`;
18163
18468
  };
18164
18469
  // src/internal-client.ts
18165
- import { Clock as Clock19, Effect as Effect109, Layer as Layer84, Option as Option30, Random as Random4, Schema as Schema100, Stream as Stream17 } from "effect";
18470
+ import { Clock as Clock20, Effect as Effect109, Layer as Layer84, Option as Option31, Random as Random4, Schema as Schema102, Stream as Stream17 } from "effect";
18166
18471
  import { EntityId, ShardId, Sharding as Sharding2, ShardingConfig as ShardingConfig3 } from "effect/unstable/cluster";
18167
18472
 
18168
18473
  // src/runtime-capability-policy.ts
@@ -18302,7 +18607,7 @@ var registerAgentPayload = Effect102.fn("Client.agents.registerPayload")(functio
18302
18607
  });
18303
18608
 
18304
18609
  // src/client-child-runs.ts
18305
- import { Effect as Effect104, Option as Option29 } from "effect";
18610
+ import { Effect as Effect104, Option as Option29, Schema as Schema98 } from "effect";
18306
18611
 
18307
18612
  // src/client-event-sequence.ts
18308
18613
  import { Effect as Effect103 } from "effect";
@@ -18418,7 +18723,8 @@ var parentDefinitionPin = Effect104.fn("Client.parentDefinitionPin")(function* (
18418
18723
  agentId: record2.agentId,
18419
18724
  agentRevision: record2.agentRevision,
18420
18725
  agentSnapshot: record2.agentSnapshot,
18421
- ...record2.agentToolInputSchemaDigests === undefined ? {} : { agentToolInputSchemaDigests: record2.agentToolInputSchemaDigests }
18726
+ ...record2.agentToolInputSchemaDigests === undefined ? {} : { agentToolInputSchemaDigests: record2.agentToolInputSchemaDigests },
18727
+ ...Schema98.decodeUnknownOption(exports_execution_schema.ExecutionOrigin)(record2.metadata[exports_execution_schema.executionOriginMetadataKey]).pipe(Option29.match({ onNone: () => ({}), onSome: (origin) => ({ origin }) }))
18422
18728
  };
18423
18729
  });
18424
18730
  var childStartInput = (input, accepted2, pin, definition, createdAt, parentWaitId) => ({
@@ -18433,21 +18739,27 @@ var childStartInput = (input, accepted2, pin, definition, createdAt, parentWaitI
18433
18739
  agent_revision: pin.agentRevision,
18434
18740
  agent_snapshot: definition,
18435
18741
  ...pin.agentToolInputSchemaDigests === undefined ? {} : { agent_tool_input_schema_digests: pin.agentToolInputSchemaDigests },
18742
+ ...pin.origin === undefined ? {} : { origin: pin.origin },
18436
18743
  metadata: {
18744
+ ...input.metadata,
18437
18745
  parent_execution_id: input.execution_id,
18438
18746
  child_execution_id: accepted2.child_execution_id,
18747
+ child_purpose: "child-run",
18748
+ ...input.preset_name === undefined ? {} : { child_profile: input.preset_name },
18749
+ ...pin.origin === undefined ? {} : { [exports_execution_schema.executionOriginMetadataKey]: pin.origin },
18439
18750
  ...parentWaitId === undefined ? {} : { parent_wait_id: parentWaitId }
18440
18751
  }
18441
18752
  });
18442
18753
  var childRunInternals = { childStartInput, internalSpawnChildRunInput };
18443
18754
 
18444
18755
  // src/client-execution-payloads.ts
18445
- import { Effect as Effect105, Schema as Schema98 } from "effect";
18446
- var encodeExecutionCursor = (cursor) => Schema98.encodeEffect(exports_pagination_schema.ExecutionCursorCodec)({ id: cursor.id, at: cursor.updatedAt }).pipe(Effect105.mapError(toClientError));
18756
+ import { Effect as Effect105, Schema as Schema99 } from "effect";
18757
+ var encodeExecutionCursor = (cursor) => Schema99.encodeEffect(exports_pagination_schema.ExecutionCursorCodec)({ id: cursor.id, at: cursor.updatedAt }).pipe(Effect105.mapError(toClientError));
18447
18758
  var executionIdFromIdempotencyKey = (idempotencyKey) => exports_ids_schema.ExecutionId.make(`execution:${idempotencyKey}`);
18448
- var metadataWithIdempotencyKey = (metadata11, idempotencyKey) => ({
18759
+ var metadataWithIdempotencyKey = (metadata11, idempotencyKey, origin) => ({
18449
18760
  ...metadata11,
18450
- idempotency_key: idempotencyKey
18761
+ idempotency_key: idempotencyKey,
18762
+ ...origin === undefined ? {} : { [exports_execution_schema.executionOriginMetadataKey]: origin }
18451
18763
  });
18452
18764
  var startExecutionByAddressPayload = (input) => ({
18453
18765
  execution_id: input.execution_id ?? executionIdFromIdempotencyKey(input.idempotency_key),
@@ -18458,7 +18770,8 @@ var startExecutionByAddressPayload = (input) => ({
18458
18770
  started_at: input.started_at,
18459
18771
  completed_at: input.completed_at,
18460
18772
  ...input.wait_id === undefined ? {} : { wait_id: input.wait_id },
18461
- metadata: metadataWithIdempotencyKey(input.metadata, input.idempotency_key)
18773
+ ...input.origin === undefined ? {} : { origin: input.origin },
18774
+ metadata: metadataWithIdempotencyKey(input.metadata, input.idempotency_key, input.origin)
18462
18775
  });
18463
18776
  var startExecutionByAgentDefinitionPayload = (input, definition) => ({
18464
18777
  execution_id: input.execution_id ?? executionIdFromIdempotencyKey(input.idempotency_key),
@@ -18473,7 +18786,8 @@ var startExecutionByAgentDefinitionPayload = (input, definition) => ({
18473
18786
  agent_snapshot: definition.definition,
18474
18787
  ...definition.tool_input_schema_digests === undefined ? {} : { agent_tool_input_schema_digests: definition.tool_input_schema_digests },
18475
18788
  ...input.wait_id === undefined ? {} : { wait_id: input.wait_id },
18476
- metadata: metadataWithIdempotencyKey(input.metadata, input.idempotency_key)
18789
+ ...input.origin === undefined ? {} : { origin: input.origin },
18790
+ metadata: metadataWithIdempotencyKey(input.metadata, input.idempotency_key, input.origin)
18477
18791
  });
18478
18792
  var executionPayloadInternals = { startExecutionByAgentDefinitionPayload };
18479
18793
 
@@ -18560,9 +18874,9 @@ var wakeRuntime = Effect107.fn("Client.waits.wakeRuntime")(function* (waits, eve
18560
18874
  var runtimeWakeInternals = { wakeRuntime };
18561
18875
 
18562
18876
  // src/client-tool-outcome.ts
18563
- import { Effect as Effect108, Schema as Schema99 } from "effect";
18877
+ import { Effect as Effect108, Schema as Schema100 } from "effect";
18564
18878
  var toolWaitId = (executionId, callId) => Identifiers.waitId("tool", executionId, callId);
18565
- var acceptedWaitOutcome = (wait) => Schema99.decodeUnknownEffect(exports_tool_schema.ExternalOutcome)(wait.metadata.external_outcome).pipe(Effect108.mapError(toClientError));
18879
+ var acceptedWaitOutcome = (wait) => Schema100.decodeUnknownEffect(exports_tool_schema.ExternalOutcome)(wait.metadata.external_outcome).pipe(Effect108.mapError(toClientError));
18566
18880
  var resolveToolOutcomeWait = Effect108.fn("Client.resolveToolOutcomeWait")(function* (waits, eventLog, call, outcome, completedAt) {
18567
18881
  const waitId2 = call.waitId ?? toolWaitId(call.executionId, call.call.id);
18568
18882
  const wait = yield* waits.get(waitId2).pipe(Effect108.mapError(toClientError));
@@ -18608,6 +18922,7 @@ var signalToolOutcome = Effect108.fn("Client.signalToolOutcome")(function* (exec
18608
18922
  var toolOutcomeInternals = { signalToolOutcome };
18609
18923
 
18610
18924
  // src/client-view-mappers.ts
18925
+ import { Option as Option30, Schema as Schema101 } from "effect";
18611
18926
  var conversationKind = (metadata11) => metadata11.kind === "agent-agent" ? "agent-agent" : "user-agent";
18612
18927
  var toConversationSummary = (record2) => ({
18613
18928
  execution_id: record2.id,
@@ -18629,6 +18944,7 @@ var toExecutionView = (record2) => ({
18629
18944
  ...record2.agentRevision === undefined ? {} : { agent_revision: record2.agentRevision },
18630
18945
  ...record2.agentSnapshot === undefined ? {} : { agent_snapshot: record2.agentSnapshot },
18631
18946
  ...record2.agentToolInputSchemaDigests === undefined ? {} : { agent_tool_input_schema_digests: record2.agentToolInputSchemaDigests },
18947
+ ...Schema101.decodeUnknownOption(exports_execution_schema.ExecutionOrigin)(record2.metadata[exports_execution_schema.executionOriginMetadataKey]).pipe(Option30.match({ onNone: () => ({}), onSome: (origin) => ({ origin }) })),
18632
18948
  metadata: record2.metadata,
18633
18949
  created_at: record2.createdAt,
18634
18950
  updated_at: record2.updatedAt
@@ -18836,14 +19152,14 @@ var groupImplementation = (implementation) => ({
18836
19152
  var rejectReserved = (id, prefix) => id.startsWith(prefix) ? Effect109.fail(ResidentNamespaceReserved.make({ id, message: "start residents via Client.residents.spawn" })) : Effect109.void;
18837
19153
  var replyValueFrom = (content) => {
18838
19154
  if (content === undefined || content.length === 0)
18839
- return Option30.none();
19155
+ return Option31.none();
18840
19156
  const structured = content.find((part) => part.type === "structured");
18841
19157
  if (structured !== undefined)
18842
- return Option30.some(structured.value);
19158
+ return Option31.some(structured.value);
18843
19159
  const text = content.filter((part) => part.type === "text").map((part) => part.text).join("");
18844
19160
  if (text.length === 0)
18845
- return Option30.none();
18846
- return Schema100.decodeUnknownOption(Schema100.UnknownFromJsonString)(text);
19161
+ return Option31.none();
19162
+ return Schema102.decodeUnknownOption(Schema102.UnknownFromJsonString)(text);
18847
19163
  };
18848
19164
  var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
18849
19165
  const makeExecutionClient = yield* client;
@@ -18882,7 +19198,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
18882
19198
  const coordinateToolTransition = (effect) => toolTransitions.coordinate(effect).pipe(Effect109.mapError(toClientError));
18883
19199
  const coordinateChildSpawn = (effect) => toolTransitions.coordinate(effect).pipe(Effect109.mapError(toClientError));
18884
19200
  const cancelFanOut = Effect109.fn("Client.runtime.cancelFanOut")(function* (input) {
18885
- if (Option30.isSome(childFanOutRuntime)) {
19201
+ if (Option31.isSome(childFanOutRuntime)) {
18886
19202
  const fanOut = yield* childFanOutRuntime.value.cancel(input.fan_out_id, input.cancelled_at, input.reason ?? "child fan-out cancelled").pipe(Effect109.mapError(toClientError));
18887
19203
  if (fanOut === undefined)
18888
19204
  return yield* ClientError.make({ message: `Child fan-out not found: ${input.fan_out_id}` });
@@ -18914,7 +19230,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
18914
19230
  const identity2 = input.idempotency_key ?? input.correlation_key ?? `${input.from}:${input.to}`;
18915
19231
  const executionId = exports_ids_schema.ExecutionId.make(input.correlation_key ?? `execution:send:${identity2}`);
18916
19232
  const envelopeId = exports_ids_schema.EnvelopeId.make(`${executionId}:envelope:${identity2}`);
18917
- const createdAt = yield* Clock19.currentTimeMillis;
19233
+ const createdAt = yield* Clock20.currentTimeMillis;
18918
19234
  const execution = yield* executionRepository.get(executionId).pipe(Effect109.mapError(toClientError));
18919
19235
  if (execution === undefined) {
18920
19236
  yield* executionRepository.create({
@@ -18923,7 +19239,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
18923
19239
  status: "queued",
18924
19240
  metadata: { operation: "envelope-send" },
18925
19241
  createdAt
18926
- }).pipe(Effect109.catchIf(Schema100.is(exports_execution_repository.DuplicateExecution), () => Effect109.void), Effect109.mapError(toClientError));
19242
+ }).pipe(Effect109.catchIf(Schema102.is(exports_execution_repository.DuplicateExecution), () => Effect109.void), Effect109.mapError(toClientError));
18927
19243
  }
18928
19244
  const maxSequence3 = yield* eventLog.maxSequence(executionId).pipe(Effect109.mapError(toClientError));
18929
19245
  return yield* envelopes.send({
@@ -18970,18 +19286,73 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
18970
19286
  const execution = yield* executionRepository.get(executionId).pipe(Effect109.mapError(toClientError));
18971
19287
  if (execution === undefined)
18972
19288
  return yield* ExecutionNotFound.make({ execution_id: executionId });
18973
- const openWaits = yield* envelopeReady.listAllWaits({ executionId, state: "open" }).pipe(Effect109.mapError(toClientError));
19289
+ const waitRecords = yield* envelopeReady.listAllWaits({ executionId }).pipe(Effect109.mapError(toClientError));
19290
+ const openWaits = waitRecords.filter((wait) => wait.state === "open");
18974
19291
  const calls = yield* toolCalls2.listCalls(executionId).pipe(Effect109.mapError(toClientError));
19292
+ const attemptsByCall = yield* Effect109.forEach(calls, (call) => toolCalls2.listAttempts(executionId, call.call.id).pipe(Effect109.mapError(toClientError), Effect109.map((attempts) => ({ call, attempts }))));
18975
19293
  const pendingChunks = yield* Effect109.forEach(calls, (call) => toolCalls2.getResult(call.executionId, call.call.id).pipe(Effect109.mapError(toClientError), Effect109.map((result) => result === undefined ? [toToolCallSummary(call)] : [])));
18976
19294
  const children = yield* childExecutions.listByExecution(executionId).pipe(Effect109.mapError(toClientError));
19295
+ const childTree = [];
19296
+ const queue = [{ executionId, depth: 1 }];
19297
+ const expanded = new Set;
19298
+ const edges = new Set;
19299
+ while (queue.length > 0) {
19300
+ const parent = queue.shift();
19301
+ if (expanded.has(parent.executionId))
19302
+ continue;
19303
+ expanded.add(parent.executionId);
19304
+ const descendants = yield* childExecutions.listByExecution(parent.executionId).pipe(Effect109.mapError(toClientError));
19305
+ for (const child of descendants) {
19306
+ const edge = `${parent.executionId}:${child.id}`;
19307
+ if (edges.has(edge))
19308
+ continue;
19309
+ edges.add(edge);
19310
+ if (edges.size > 1000) {
19311
+ return yield* ClientError.make({ message: "Execution child tree exceeds the 1000 edge inspection limit" });
19312
+ }
19313
+ childTree.push({
19314
+ parent_execution_id: parent.executionId,
19315
+ child_execution_id: child.id,
19316
+ address_id: child.addressId,
19317
+ depth: parent.depth,
19318
+ status: child.status,
19319
+ metadata: child.metadata,
19320
+ created_at: child.createdAt,
19321
+ updated_at: child.updatedAt
19322
+ });
19323
+ const childExecutionId3 = exports_ids_schema.ExecutionId.make(child.id);
19324
+ if (!expanded.has(childExecutionId3))
19325
+ queue.push({ executionId: childExecutionId3, depth: parent.depth + 1 });
19326
+ }
19327
+ }
19328
+ const fanOuts = yield* childFanOuts.listByParent(executionId).pipe(Effect109.mapError(toClientError));
18977
19329
  const maxSequence3 = yield* eventLog.maxSequence(executionId).pipe(Effect109.mapError(toClientError));
18978
- const lastEvent = maxSequence3 === undefined ? undefined : yield* eventLog.findBySequence({ executionId, sequence: maxSequence3 }).pipe(Effect109.mapError(toClientError), Effect109.map(Option30.getOrUndefined));
19330
+ const lastEvent = maxSequence3 === undefined ? undefined : yield* eventLog.findBySequence({ executionId, sequence: maxSequence3 }).pipe(Effect109.mapError(toClientError), Effect109.map(Option31.getOrUndefined));
18979
19331
  return {
18980
19332
  execution_id: execution.id,
18981
19333
  status: execution.status,
18982
19334
  waiting_on: openWaits.map(toWaitView),
19335
+ waits: waitRecords.map(toWaitView),
18983
19336
  pending_tool_calls: pendingChunks.flat(),
19337
+ tool_attempts: attemptsByCall.flatMap(({ attempts }) => attempts.map(toToolAttempt)),
19338
+ tool_invocations: attemptsByCall.flatMap(({ call, attempts }) => call.placement.kind !== "local" && call.placement.kind !== "mcp" ? [] : attempts.map((attempt) => ({
19339
+ invocation_id: `tool-invocation:${executionId}:${call.call.id}:${attempt.id}`,
19340
+ tool_call_id: call.call.id,
19341
+ attempt_id: attempt.id,
19342
+ placement: call.placement.kind,
19343
+ state: attempt.state,
19344
+ ...attempt.state === "completed" ? { outcome: "success" } : attempt.state === "failed" ? {
19345
+ outcome: "failure",
19346
+ failure_category: "handler"
19347
+ } : attempt.state === "abandoned" ? { outcome: "abandoned", failure_category: "abandoned" } : {},
19348
+ started_at: attempt.createdAt,
19349
+ ...attempt.completedAt === undefined ? {} : { completed_at: attempt.completedAt },
19350
+ ...attempt.claimExpiresAt === undefined ? {} : { claim_expires_at: attempt.claimExpiresAt },
19351
+ ...call.placement.kind !== "remote" || attempt.workerId === undefined ? {} : { worker_id: exports_tool_schema.WorkerId.make(attempt.workerId) }
19352
+ }))),
18984
19353
  child_runs: children.map(toChildRunSummary),
19354
+ child_tree: childTree,
19355
+ fan_outs: fanOuts,
18985
19356
  ...lastEvent === undefined ? {} : { last_event_cursor: lastEvent.cursor }
18986
19357
  };
18987
19358
  });
@@ -19017,27 +19388,27 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19017
19388
  return { records: yield* workflows.list(id).pipe(Effect109.mapError(toClientError)) };
19018
19389
  }),
19019
19390
  startWorkflowRun: Effect109.fn("Client.runtime.startWorkflowRun")(function* (input) {
19020
- if (Option30.isSome(runtimeCapabilityPolicy))
19391
+ if (Option31.isSome(runtimeCapabilityPolicy))
19021
19392
  yield* runtimeCapabilityPolicy.value.admit("workflow-definition");
19022
- return yield* Option30.match(workflowRuntime, {
19393
+ return yield* Option31.match(workflowRuntime, {
19023
19394
  onNone: () => workflows.start(input),
19024
19395
  onSome: (runtime) => runtime.start(input)
19025
19396
  }).pipe(Effect109.mapError(toClientError));
19026
19397
  }),
19027
19398
  inspectWorkflowRun: Effect109.fn("Client.runtime.inspectWorkflowRun")(function* (id) {
19028
- return yield* Option30.match(workflowRuntime, {
19399
+ return yield* Option31.match(workflowRuntime, {
19029
19400
  onNone: () => workflows.inspect(id),
19030
19401
  onSome: (runtime) => runtime.inspect(id)
19031
19402
  }).pipe(Effect109.mapError(toClientError));
19032
19403
  }),
19033
19404
  replayWorkflowRun: Effect109.fn("Client.runtime.replayWorkflowRun")(function* (id) {
19034
- return yield* Option30.match(workflowRuntime, {
19405
+ return yield* Option31.match(workflowRuntime, {
19035
19406
  onNone: () => workflows.listLifecycle(id),
19036
19407
  onSome: (runtime) => runtime.replay(id)
19037
19408
  }).pipe(Effect109.mapError(toClientError));
19038
19409
  }),
19039
19410
  cancelWorkflowRun: Effect109.fn("Client.runtime.cancelWorkflowRun")(function* (id) {
19040
- return yield* Option30.match(workflowRuntime, {
19411
+ return yield* Option31.match(workflowRuntime, {
19041
19412
  onNone: () => workflows.cancel(id).pipe(Effect109.map((result) => result.record)),
19042
19413
  onSome: (runtime) => runtime.cancel(id)
19043
19414
  }).pipe(Effect109.mapError(toClientError));
@@ -19169,7 +19540,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19169
19540
  return records.map(toWaitView);
19170
19541
  }),
19171
19542
  listExecutions: Effect109.fn("Client.runtime.listExecutions")(function* (input) {
19172
- const cursor = input.cursor === undefined ? undefined : yield* Schema100.decodeEffect(exports_pagination_schema.ExecutionCursorCodec)(input.cursor).pipe(Effect109.map(({ id, at }) => ({ id, updatedAt: at })));
19543
+ const cursor = input.cursor === undefined ? undefined : yield* Schema102.decodeEffect(exports_pagination_schema.ExecutionCursorCodec)(input.cursor).pipe(Effect109.map(({ id, at }) => ({ id, updatedAt: at })));
19173
19544
  const result = yield* executionRepository.list({
19174
19545
  ...input.root_address_id === undefined ? {} : { rootAddressId: input.root_address_id },
19175
19546
  ...input.status === undefined ? {} : { status: input.status },
@@ -19219,13 +19590,13 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19219
19590
  }).pipe(Effect109.mapError(toClientError));
19220
19591
  }),
19221
19592
  listSessions: Effect109.fn("Client.runtime.listSessions")(function* (input) {
19222
- const cursor = input.cursor === undefined ? undefined : yield* Schema100.decodeEffect(exports_pagination_schema.SessionCursorCodec)(input.cursor).pipe(Effect109.map(({ id, at }) => ({ id, updatedAt: at })));
19593
+ const cursor = input.cursor === undefined ? undefined : yield* Schema102.decodeEffect(exports_pagination_schema.SessionCursorCodec)(input.cursor).pipe(Effect109.map(({ id, at }) => ({ id, updatedAt: at })));
19223
19594
  const result = yield* sessionRepository.list({
19224
19595
  ...input.root_address_id === undefined ? {} : { rootAddressId: input.root_address_id },
19225
19596
  ...input.limit === undefined ? {} : { limit: input.limit },
19226
19597
  ...cursor === undefined ? {} : { cursor }
19227
19598
  });
19228
- const nextCursor = result.nextCursor === undefined ? undefined : yield* Schema100.encodeEffect(exports_pagination_schema.SessionCursorCodec)({
19599
+ const nextCursor = result.nextCursor === undefined ? undefined : yield* Schema102.encodeEffect(exports_pagination_schema.SessionCursorCodec)({
19229
19600
  id: result.nextCursor.id,
19230
19601
  at: result.nextCursor.updatedAt
19231
19602
  });
@@ -19238,7 +19609,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19238
19609
  const session = yield* sessionRepository.get(input.session_id).pipe(Effect109.mapError(toClientError));
19239
19610
  if (session === undefined)
19240
19611
  return yield* ClientError.make({ message: `Session not found: ${input.session_id}` });
19241
- const cursor = input.cursor === undefined ? undefined : yield* Schema100.decodeEffect(exports_pagination_schema.ExecutionCursorCodec)(input.cursor).pipe(Effect109.map(({ id, at }) => ({ id, updatedAt: at })), Effect109.mapError(toClientError));
19612
+ const cursor = input.cursor === undefined ? undefined : yield* Schema102.decodeEffect(exports_pagination_schema.ExecutionCursorCodec)(input.cursor).pipe(Effect109.map(({ id, at }) => ({ id, updatedAt: at })), Effect109.mapError(toClientError));
19242
19613
  const result = yield* executionRepository.list({
19243
19614
  sessionId: input.session_id,
19244
19615
  ...input.limit === undefined ? {} : { limit: input.limit },
@@ -19295,12 +19666,12 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19295
19666
  const shard = ShardId.toString(sharding.getShardId(EntityId.make(executionId), "execution"));
19296
19667
  const owner = yield* clusterRegistry.lockOwner(shard).pipe(Effect109.mapError(toClientError));
19297
19668
  const runnerAddress = owner ?? null;
19298
- const self = Option30.map(shardingConfig2.runnerAddress, (address) => `${address.host}:${address.port}`);
19669
+ const self = Option31.map(shardingConfig2.runnerAddress, (address) => `${address.host}:${address.port}`);
19299
19670
  return {
19300
19671
  execution_id: executionId,
19301
19672
  shard,
19302
19673
  runner_address: runnerAddress,
19303
- owned: runnerAddress !== null && Option30.getOrNull(self) === runnerAddress
19674
+ owned: runnerAddress !== null && Option31.getOrNull(self) === runnerAddress
19304
19675
  };
19305
19676
  }),
19306
19677
  send: sendEnvelope,
@@ -19309,10 +19680,10 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19309
19680
  if (instance === undefined || instance.status === "destroyed") {
19310
19681
  return yield* ResidentNotFound.make({ kind: input.kind, key: input.key });
19311
19682
  }
19312
- const encoded = yield* Schema100.encodeUnknownEffect(input.command.input)(input.input).pipe(Effect109.mapError(toClientError));
19683
+ const encoded = yield* Schema102.encodeUnknownEffect(input.command.input)(input.input).pipe(Effect109.mapError(toClientError));
19313
19684
  const inputRef = inputSchemaRef(input.command.name);
19314
19685
  const outputRef = outputSchemaRef(input.command.name);
19315
- if (Option30.isSome(schemaRegistry)) {
19686
+ if (Option31.isSome(schemaRegistry)) {
19316
19687
  yield* schemaRegistry.value.register({ ref: inputRef, schema: input.command.input });
19317
19688
  yield* schemaRegistry.value.register({ ref: outputRef, schema: input.command.output });
19318
19689
  }
@@ -19356,7 +19727,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19356
19727
  message: "reply carried no decodable content"
19357
19728
  });
19358
19729
  }
19359
- return yield* Schema100.decodeUnknownEffect(input.command.output)(replyValue.value).pipe(Effect109.mapError((issue) => CommandReplyInvalid.make({
19730
+ return yield* Schema102.decodeUnknownEffect(input.command.output)(replyValue.value).pipe(Effect109.mapError((issue) => CommandReplyInvalid.make({
19360
19731
  command: input.command.name,
19361
19732
  wait_id: outcome.wait_id,
19362
19733
  message: errorMessage2(issue)
@@ -19397,14 +19768,14 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19397
19768
  ...input.expected_version === undefined ? {} : { expectedVersion: input.expected_version },
19398
19769
  ...input.idempotency_key === undefined ? {} : { idempotencyKey: input.idempotency_key },
19399
19770
  updatedAt: input.updated_at
19400
- }).pipe(Effect109.mapError((error5) => Schema100.is(StateVersionConflict3)(error5) ? StateVersionConflict.make(error5) : toClientError(error5)))),
19771
+ }).pipe(Effect109.mapError((error5) => Schema102.is(StateVersionConflict3)(error5) ? StateVersionConflict.make(error5) : toClientError(error5)))),
19401
19772
  deleteResidentState: Effect109.fn("Client.runtime.deleteResidentState")((input) => executionState.remove({
19402
19773
  executionId: input.execution_id,
19403
19774
  key: input.key,
19404
19775
  ...input.expected_version === undefined ? {} : { expectedVersion: input.expected_version },
19405
19776
  ...input.idempotency_key === undefined ? {} : { idempotencyKey: input.idempotency_key },
19406
19777
  removedAt: input.removed_at
19407
- }).pipe(Effect109.mapError((error5) => Schema100.is(StateVersionConflict3)(error5) ? StateVersionConflict.make(error5) : toClientError(error5)))),
19778
+ }).pipe(Effect109.mapError((error5) => Schema102.is(StateVersionConflict3)(error5) ? StateVersionConflict.make(error5) : toClientError(error5)))),
19408
19779
  listResidentState: Effect109.fn("Client.runtime.listResidentState")((input) => executionState.list({
19409
19780
  executionId: input.execution_id,
19410
19781
  ...input.prefix === undefined ? {} : { prefix: input.prefix },
@@ -19527,7 +19898,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19527
19898
  }),
19528
19899
  spawnChildRun: Effect109.fn("Client.runtime.spawnChildRun")(function* (input) {
19529
19900
  const pin = yield* parentDefinitionPin(executionRepository, input.execution_id);
19530
- const createdAt = yield* Clock19.currentTimeMillis;
19901
+ const createdAt = yield* Clock20.currentTimeMillis;
19531
19902
  const internal = childRunInternals.internalSpawnChildRunInput(input, pin, createdAt);
19532
19903
  const context = yield* resolveForDispatch(internal).pipe(Effect109.mapError((error5) => ClientError.make({ message: error5._tag })));
19533
19904
  const definition = yield* childDefinition(pin.agentSnapshot, context).pipe(Effect109.mapError((error5) => ClientError.make({ message: error5._tag })));
@@ -19545,9 +19916,9 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19545
19916
  return coordinated.accepted;
19546
19917
  }),
19547
19918
  createChildFanOut: Effect109.fn("Client.runtime.createChildFanOut")(function* (input) {
19548
- if (Option30.isSome(runtimeCapabilityPolicy))
19919
+ if (Option31.isSome(runtimeCapabilityPolicy))
19549
19920
  yield* runtimeCapabilityPolicy.value.admit("fan-out");
19550
- if (Option30.isNone(childFanOutRuntime)) {
19921
+ if (Option31.isNone(childFanOutRuntime)) {
19551
19922
  return yield* ClientError.make({
19552
19923
  message: "Child fan-out runtime unavailable"
19553
19924
  });
@@ -19558,7 +19929,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19558
19929
  return yield* cancelFanOut(input);
19559
19930
  }),
19560
19931
  inspectChildFanOut: Effect109.fn("Client.runtime.inspectChildFanOut")(function* (input) {
19561
- const fanOut = yield* Option30.match(childFanOutRuntime, {
19932
+ const fanOut = yield* Option31.match(childFanOutRuntime, {
19562
19933
  onNone: () => childFanOuts.get(input.fan_out_id),
19563
19934
  onSome: (runtime) => runtime.inspect(input.fan_out_id)
19564
19935
  }).pipe(Effect109.mapError(toClientError));
@@ -19600,7 +19971,7 @@ var layerFromRuntime3 = Layer84.effect(Service, Effect109.gen(function* () {
19600
19971
  if (input.cron_expr !== undefined) {
19601
19972
  yield* parseCron(input.cron_expr).pipe(Effect109.mapError(toClientError));
19602
19973
  }
19603
- const createdAt = yield* Clock19.currentTimeMillis;
19974
+ const createdAt = yield* Clock20.currentTimeMillis;
19604
19975
  const schedule = yield* schedules.create({
19605
19976
  id: input.schedule_id,
19606
19977
  kind: input.kind,
@@ -19663,77 +20034,77 @@ import { Effect as Effect111 } from "effect";
19663
20034
  var recoverPersistedFanOut = (recover) => recover().pipe(Effect111.mapError((error5) => WorkflowRuntimeError.make({ message: error5._tag })), Effect111.asVoid);
19664
20035
 
19665
20036
  // src/runtime.ts
19666
- var Dialect2 = Schema101.Literals(["pg", "mysql", "sqlite"]);
20037
+ var Dialect2 = Schema103.Literals(["pg", "mysql", "sqlite"]);
19667
20038
 
19668
- class NotificationFailure extends Schema101.TaggedErrorClass()("NotificationFailure", {
19669
- reason: Schema101.String
20039
+ class NotificationFailure extends Schema103.TaggedErrorClass()("NotificationFailure", {
20040
+ reason: Schema103.String
19670
20041
  }) {
19671
20042
  }
19672
20043
 
19673
- class ClusterFailure extends Schema101.TaggedErrorClass()("ClusterFailure", {
19674
- reason: Schema101.String
20044
+ class ClusterFailure extends Schema103.TaggedErrorClass()("ClusterFailure", {
20045
+ reason: Schema103.String
19675
20046
  }) {
19676
20047
  }
19677
20048
 
19678
- class SqlFailure extends Schema101.TaggedErrorClass()("SqlFailure", {
19679
- category: Schema101.Literals(["connection", "statement", "unknown"]),
19680
- operation: Schema101.Literals(["acquire", "migrate", "verify", "notify", "readiness"]),
19681
- retryable: Schema101.Boolean
20049
+ class SqlFailure extends Schema103.TaggedErrorClass()("SqlFailure", {
20050
+ category: Schema103.Literals(["connection", "statement", "unknown"]),
20051
+ operation: Schema103.Literals(["acquire", "migrate", "verify", "notify", "readiness"]),
20052
+ retryable: Schema103.Boolean
19682
20053
  }) {
19683
20054
  }
19684
- var SqlDialect = Schema101.Literals(["sqlite", "pg", "mysql", "mssql", "clickhouse"]);
20055
+ var SqlDialect = Schema103.Literals(["sqlite", "pg", "mysql", "mssql", "clickhouse"]);
19685
20056
 
19686
- class DatabaseDialectMismatch extends Schema101.TaggedErrorClass()("DatabaseDialectMismatch", { expected: Dialect2, actual: SqlDialect }) {
20057
+ class DatabaseDialectMismatch extends Schema103.TaggedErrorClass()("DatabaseDialectMismatch", { expected: Dialect2, actual: SqlDialect }) {
19687
20058
  }
19688
20059
 
19689
- class DatabaseAlreadyOwned extends Schema101.TaggedErrorClass()("DatabaseAlreadyOwned", {
20060
+ class DatabaseAlreadyOwned extends Schema103.TaggedErrorClass()("DatabaseAlreadyOwned", {
19690
20061
  databaseIdentity: DatabaseIdentity
19691
20062
  }) {
19692
20063
  }
19693
20064
 
19694
- class UnsupportedTopology extends Schema101.TaggedErrorClass()("UnsupportedTopology", {
19695
- reason: Schema101.String
20065
+ class UnsupportedTopology extends Schema103.TaggedErrorClass()("UnsupportedTopology", {
20066
+ reason: Schema103.String
19696
20067
  }) {
19697
20068
  }
19698
20069
 
19699
- class MigratorError extends Schema101.TaggedErrorClass()("MigratorError", {
19700
- reason: Schema101.String
20070
+ class MigratorError extends Schema103.TaggedErrorClass()("MigratorError", {
20071
+ reason: Schema103.String
19701
20072
  }) {
19702
20073
  }
19703
20074
 
19704
- class SchemaHeadMismatch extends Schema101.TaggedErrorClass()("SchemaHeadMismatch", {
19705
- expected: Schema101.String,
19706
- actual: Schema101.String
20075
+ class SchemaHeadMismatch extends Schema103.TaggedErrorClass()("SchemaHeadMismatch", {
20076
+ expected: Schema103.String,
20077
+ actual: Schema103.String
19707
20078
  }) {
19708
20079
  }
19709
20080
 
19710
- class HostUnavailable extends Schema101.TaggedErrorClass()("HostUnavailable", {
19711
- host: Schema101.String,
19712
- reason: Schema101.String
20081
+ class HostUnavailable extends Schema103.TaggedErrorClass()("HostUnavailable", {
20082
+ host: Schema103.String,
20083
+ reason: Schema103.String
19713
20084
  }) {
19714
20085
  }
19715
- var RuntimeTopologyCause = Schema101.Union([
20086
+ var RuntimeTopologyCause = Schema103.Union([
19716
20087
  ClusterFailure,
19717
20088
  DatabaseDialectMismatch,
19718
20089
  DatabaseAlreadyOwned,
19719
20090
  UnsupportedTopology
19720
20091
  ]);
19721
- var RuntimeMigrationCause = Schema101.Union([
20092
+ var RuntimeMigrationCause = Schema103.Union([
19722
20093
  SqlFailure,
19723
20094
  MigratorError,
19724
20095
  SchemaHeadMismatch
19725
20096
  ]);
19726
- var RuntimeReadinessCause = Schema101.Union([
20097
+ var RuntimeReadinessCause = Schema103.Union([
19727
20098
  SqlFailure,
19728
20099
  NotificationFailure,
19729
20100
  ClusterFailure,
19730
20101
  HostUnavailable
19731
20102
  ]);
19732
20103
 
19733
- class RuntimeTopologyError extends Schema101.TaggedErrorClass()("RuntimeTopologyError", {
20104
+ class RuntimeTopologyError extends Schema103.TaggedErrorClass()("RuntimeTopologyError", {
19734
20105
  dialect: Dialect2,
19735
- role: Schema101.Literals(["embedded", "runner", "client"]),
19736
- nextAction: Schema101.Literals([
20106
+ role: Schema103.Literals(["embedded", "runner", "client"]),
20107
+ nextAction: Schema103.Literals([
19737
20108
  "use-embedded",
19738
20109
  "use-postgres-or-mysql",
19739
20110
  "use-client-constructor",
@@ -19744,39 +20115,39 @@ class RuntimeTopologyError extends Schema101.TaggedErrorClass()("RuntimeTopology
19744
20115
  }) {
19745
20116
  }
19746
20117
 
19747
- class RuntimeMigrationError extends Schema101.TaggedErrorClass()("RuntimeMigrationError", {
20118
+ class RuntimeMigrationError extends Schema103.TaggedErrorClass()("RuntimeMigrationError", {
19748
20119
  dialect: Dialect2,
19749
- phase: Schema101.Literals(["apply", "verify"]),
19750
- nextAction: Schema101.Literals(["retry", "inspect-schema", "run-compatible-release"]),
20120
+ phase: Schema103.Literals(["apply", "verify"]),
20121
+ nextAction: Schema103.Literals(["retry", "inspect-schema", "run-compatible-release"]),
19751
20122
  cause: RuntimeMigrationCause
19752
20123
  }) {
19753
20124
  }
19754
20125
 
19755
- class RuntimeReadinessError extends Schema101.TaggedErrorClass()("RuntimeReadinessError", {
19756
- phase: Schema101.Literals(["database", "notification", "cluster", "hosts"]),
20126
+ class RuntimeReadinessError extends Schema103.TaggedErrorClass()("RuntimeReadinessError", {
20127
+ phase: Schema103.Literals(["database", "notification", "cluster", "hosts"]),
19757
20128
  cause: RuntimeReadinessCause
19758
20129
  }) {
19759
20130
  }
19760
- var RuntimeCapabilityStatus = Schema101.Union([
19761
- Schema101.Struct({
19762
- enabled: Schema101.Literal(false),
19763
- source: Schema101.Literals(["local-host", "role-unavailable"]),
19764
- health: Schema101.Literal("not-applicable")
20131
+ var RuntimeCapabilityStatus = Schema103.Union([
20132
+ Schema103.Struct({
20133
+ enabled: Schema103.Literal(false),
20134
+ source: Schema103.Literals(["local-host", "role-unavailable"]),
20135
+ health: Schema103.Literal("not-applicable")
19765
20136
  }),
19766
- Schema101.Struct({
19767
- enabled: Schema101.Literal(true),
19768
- source: Schema101.Literal("local-host"),
19769
- health: Schema101.Literals(["healthy", "unhealthy"])
20137
+ Schema103.Struct({
20138
+ enabled: Schema103.Literal(true),
20139
+ source: Schema103.Literal("local-host"),
20140
+ health: Schema103.Literals(["healthy", "unhealthy"])
19770
20141
  })
19771
20142
  ]);
19772
- var ReadinessStatus2 = Schema101.Struct({
19773
- ready: Schema101.Literal(true),
19774
- role: Schema101.Literals(["embedded", "runner", "client"]),
20143
+ var ReadinessStatus2 = Schema103.Struct({
20144
+ ready: Schema103.Literal(true),
20145
+ role: Schema103.Literals(["embedded", "runner", "client"]),
19775
20146
  dialect: Dialect2,
19776
20147
  databaseIdentity: DatabaseIdentity,
19777
- schemaHead: Schema101.String,
19778
- notification: Schema101.Literals(["pg-listen-notify", "polling", "in-process"]),
19779
- capabilities: Schema101.Struct({
20148
+ schemaHead: Schema103.String,
20149
+ notification: Schema103.Literals(["pg-listen-notify", "polling", "in-process"]),
20150
+ capabilities: Schema103.Struct({
19780
20151
  fanOut: RuntimeCapabilityStatus,
19781
20152
  workflowDefinition: RuntimeCapabilityStatus
19782
20153
  })
@@ -19790,7 +20161,7 @@ var normalizeHost = (layer65, _role, _dialect) => layer65.pipe(Layer86.catchCaus
19790
20161
  role: _role,
19791
20162
  nextAction: _role === "embedded" ? "use-embedded" : "use-different-database",
19792
20163
  cause: ClusterFailure.make({ reason: "cluster configuration is incompatible" })
19793
- }) : error5), "host-layer", (error5) => Schema101.is(RuntimeConfigurationError)(error5) || Schema101.is(RuntimeTopologyError)(error5) || Schema101.is(RuntimeMigrationError)(error5))))));
20164
+ }) : error5), "host-layer", (error5) => Schema103.is(RuntimeConfigurationError)(error5) || Schema103.is(RuntimeTopologyError)(error5) || Schema103.is(RuntimeMigrationError)(error5))))));
19794
20165
  var actualDialect = (sql) => sql.onDialectOrElse({
19795
20166
  sqlite: () => "sqlite",
19796
20167
  pg: () => "pg",
@@ -19883,7 +20254,7 @@ var withHosts = (runner, options) => {
19883
20254
  const childFanOut = yield* Effect112.serviceOption(Service44);
19884
20255
  const mapError2 = (effect) => effect.pipe(Effect112.mapError((error5) => WorkflowRuntimeError.make({ message: error5.message })));
19885
20256
  return HandlerService2.of({
19886
- ...Option31.isNone(childFanOut) ? {} : {
20257
+ ...Option32.isNone(childFanOut) ? {} : {
19887
20258
  createChildFanOut: (definition) => childFanOut.value.create(definition).pipe(Effect112.mapError((error5) => WorkflowRuntimeError.make({ message: error5._tag }))),
19888
20259
  admitChildFanOut: () => recoverPersistedFanOut(childFanOut.value.recover),
19889
20260
  inspectChildFanOut: (fanOutId) => childFanOut.value.inspect(fanOutId).pipe(Effect112.mapError((error5) => WorkflowRuntimeError.make({ message: error5._tag })))