@superdurable/dex-agents 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +1981 -2
  3. package/dist/src/agent-built-in-tools.d.ts +81 -0
  4. package/dist/src/agent-built-in-tools.js +246 -0
  5. package/dist/src/agent-built-in-tools.js.map +1 -0
  6. package/dist/src/agent-context-compaction.d.ts +108 -0
  7. package/dist/src/agent-context-compaction.js +39 -0
  8. package/dist/src/agent-context-compaction.js.map +1 -0
  9. package/dist/src/agent-event-writer.d.ts +26 -0
  10. package/dist/src/agent-event-writer.js +110 -0
  11. package/dist/src/agent-event-writer.js.map +1 -0
  12. package/dist/src/agent-framework-runner.d.ts +808 -0
  13. package/dist/src/agent-framework-runner.js +82 -0
  14. package/dist/src/agent-framework-runner.js.map +1 -0
  15. package/dist/src/agent-plans.d.ts +48 -0
  16. package/dist/src/agent-plans.js +86 -0
  17. package/dist/src/agent-plans.js.map +1 -0
  18. package/dist/src/agent-session-cancellation-steps.d.ts +28 -0
  19. package/dist/src/agent-session-cancellation-steps.js +154 -0
  20. package/dist/src/agent-session-cancellation-steps.js.map +1 -0
  21. package/dist/src/agent-session-codecs.d.ts +105 -0
  22. package/dist/src/agent-session-codecs.js +689 -0
  23. package/dist/src/agent-session-codecs.js.map +1 -0
  24. package/dist/src/agent-session-flow.d.ts +416 -0
  25. package/dist/src/agent-session-flow.js +623 -0
  26. package/dist/src/agent-session-flow.js.map +1 -0
  27. package/dist/src/agent-session-persistence.d.ts +133 -0
  28. package/dist/src/agent-session-persistence.js +74 -0
  29. package/dist/src/agent-session-persistence.js.map +1 -0
  30. package/dist/src/agent-session-settings.d.ts +58 -0
  31. package/dist/src/agent-session-settings.js +81 -0
  32. package/dist/src/agent-session-settings.js.map +1 -0
  33. package/dist/src/agent-session-step-options.d.ts +27 -0
  34. package/dist/src/agent-session-step-options.js +39 -0
  35. package/dist/src/agent-session-step-options.js.map +1 -0
  36. package/dist/src/agent-session-step-types.d.ts +20 -0
  37. package/dist/src/agent-session-step-types.js +28 -0
  38. package/dist/src/agent-session-step-types.js.map +1 -0
  39. package/dist/src/agent-session-steps.d.ts +179 -0
  40. package/dist/src/agent-session-steps.js +1272 -0
  41. package/dist/src/agent-session-steps.js.map +1 -0
  42. package/dist/src/agent-session-tracer.d.ts +61 -0
  43. package/dist/src/agent-session-tracer.js +608 -0
  44. package/dist/src/agent-session-tracer.js.map +1 -0
  45. package/dist/src/agent-session-transitions.d.ts +224 -0
  46. package/dist/src/agent-session-transitions.js +850 -0
  47. package/dist/src/agent-session-transitions.js.map +1 -0
  48. package/dist/src/agent-session-values.d.ts +998 -0
  49. package/dist/src/agent-session-values.js +162 -0
  50. package/dist/src/agent-session-values.js.map +1 -0
  51. package/dist/src/agent-session-wait-steps.d.ts +53 -0
  52. package/dist/src/agent-session-wait-steps.js +389 -0
  53. package/dist/src/agent-session-wait-steps.js.map +1 -0
  54. package/dist/src/agent-tracing-options.d.ts +107 -0
  55. package/dist/src/agent-tracing-options.js +20 -0
  56. package/dist/src/agent-tracing-options.js.map +1 -0
  57. package/dist/src/ai-sdk/ai-sdk-model-client.d.ts +40 -0
  58. package/dist/src/ai-sdk/ai-sdk-model-client.js +235 -0
  59. package/dist/src/ai-sdk/ai-sdk-model-client.js.map +1 -0
  60. package/dist/src/ai-sdk/index.d.ts +1 -0
  61. package/dist/src/ai-sdk/index.js +9 -0
  62. package/dist/src/ai-sdk/index.js.map +1 -0
  63. package/dist/src/index.d.ts +10 -0
  64. package/dist/src/index.js +17 -0
  65. package/dist/src/index.js.map +1 -0
  66. package/dist/src/mcp/index.d.ts +3 -0
  67. package/dist/src/mcp/index.js +10 -0
  68. package/dist/src/mcp/index.js.map +1 -0
  69. package/dist/src/mcp/mcp-resource-and-prompt-tools.d.ts +29 -0
  70. package/dist/src/mcp/mcp-resource-and-prompt-tools.js +185 -0
  71. package/dist/src/mcp/mcp-resource-and-prompt-tools.js.map +1 -0
  72. package/dist/src/mcp/mcp-server-config.d.ts +86 -0
  73. package/dist/src/mcp/mcp-server-config.js +38 -0
  74. package/dist/src/mcp/mcp-server-config.js.map +1 -0
  75. package/dist/src/mcp/mcp-tool-source.d.ts +470 -0
  76. package/dist/src/mcp/mcp-tool-source.js +1204 -0
  77. package/dist/src/mcp/mcp-tool-source.js.map +1 -0
  78. package/dist/src/stepwise/agent-definition.d.ts +158 -0
  79. package/dist/src/stepwise/agent-definition.js +9 -0
  80. package/dist/src/stepwise/agent-definition.js.map +1 -0
  81. package/dist/src/stepwise/function-tool.d.ts +130 -0
  82. package/dist/src/stepwise/function-tool.js +75 -0
  83. package/dist/src/stepwise/function-tool.js.map +1 -0
  84. package/dist/src/stepwise/index.d.ts +7 -0
  85. package/dist/src/stepwise/index.js +12 -0
  86. package/dist/src/stepwise/index.js.map +1 -0
  87. package/dist/src/stepwise/json-schema-validation.d.ts +9 -0
  88. package/dist/src/stepwise/json-schema-validation.js +141 -0
  89. package/dist/src/stepwise/json-schema-validation.js.map +1 -0
  90. package/dist/src/stepwise/model-client.d.ts +194 -0
  91. package/dist/src/stepwise/model-client.js +9 -0
  92. package/dist/src/stepwise/model-client.js.map +1 -0
  93. package/dist/src/stepwise/scripted-model-client.d.ts +99 -0
  94. package/dist/src/stepwise/scripted-model-client.js +156 -0
  95. package/dist/src/stepwise/scripted-model-client.js.map +1 -0
  96. package/dist/src/stepwise/stepwise-agent-runner.d.ts +189 -0
  97. package/dist/src/stepwise/stepwise-agent-runner.js +804 -0
  98. package/dist/src/stepwise/stepwise-agent-runner.js.map +1 -0
  99. package/dist/src/stepwise/stepwise-agent-session-flow.d.ts +35 -0
  100. package/dist/src/stepwise/stepwise-agent-session-flow.js +56 -0
  101. package/dist/src/stepwise/stepwise-agent-session-flow.js.map +1 -0
  102. package/dist/src/stepwise/stepwise-input-items.d.ts +12 -0
  103. package/dist/src/stepwise/stepwise-input-items.js +172 -0
  104. package/dist/src/stepwise/stepwise-input-items.js.map +1 -0
  105. package/dist/src/stepwise/tool-source.d.ts +103 -0
  106. package/dist/src/stepwise/tool-source.js +9 -0
  107. package/dist/src/stepwise/tool-source.js.map +1 -0
  108. package/dist/src/testing/agent-session-test-client.d.ts +205 -0
  109. package/dist/src/testing/agent-session-test-client.js +290 -0
  110. package/dist/src/testing/agent-session-test-client.js.map +1 -0
  111. package/dist/src/testing/agent-test-environment.d.ts +52 -0
  112. package/dist/src/testing/agent-test-environment.js +86 -0
  113. package/dist/src/testing/agent-test-environment.js.map +1 -0
  114. package/dist/src/testing/agent-worker-process.d.ts +91 -0
  115. package/dist/src/testing/agent-worker-process.js +150 -0
  116. package/dist/src/testing/agent-worker-process.js.map +1 -0
  117. package/dist/src/testing/child-process-group.d.ts +33 -0
  118. package/dist/src/testing/child-process-group.js +164 -0
  119. package/dist/src/testing/child-process-group.js.map +1 -0
  120. package/dist/src/testing/coordination.d.ts +99 -0
  121. package/dist/src/testing/coordination.js +155 -0
  122. package/dist/src/testing/coordination.js.map +1 -0
  123. package/dist/src/testing/index.d.ts +8 -0
  124. package/dist/src/testing/index.js +16 -0
  125. package/dist/src/testing/index.js.map +1 -0
  126. package/dist/src/testing/polling.d.ts +31 -0
  127. package/dist/src/testing/polling.js +51 -0
  128. package/dist/src/testing/polling.js.map +1 -0
  129. package/dist/src/testing/private-dex-engine.d.ts +101 -0
  130. package/dist/src/testing/private-dex-engine.js +223 -0
  131. package/dist/src/testing/private-dex-engine.js.map +1 -0
  132. package/dist/src/testing/scripted-model-client.d.ts +1 -0
  133. package/dist/src/testing/scripted-model-client.js +10 -0
  134. package/dist/src/testing/scripted-model-client.js.map +1 -0
  135. package/dist/src/testing/step-history.d.ts +40 -0
  136. package/dist/src/testing/step-history.js +59 -0
  137. package/dist/src/testing/step-history.js.map +1 -0
  138. package/dist/src/ui-stream/agent-event-json.d.ts +30 -0
  139. package/dist/src/ui-stream/agent-event-json.js +64 -0
  140. package/dist/src/ui-stream/agent-event-json.js.map +1 -0
  141. package/dist/src/ui-stream/agent-event-sse.d.ts +154 -0
  142. package/dist/src/ui-stream/agent-event-sse.js +159 -0
  143. package/dist/src/ui-stream/agent-event-sse.js.map +1 -0
  144. package/dist/src/ui-stream/agent-event-stream-positions.d.ts +42 -0
  145. package/dist/src/ui-stream/agent-event-stream-positions.js +153 -0
  146. package/dist/src/ui-stream/agent-event-stream-positions.js.map +1 -0
  147. package/dist/src/ui-stream/agent-session-record-reader.d.ts +72 -0
  148. package/dist/src/ui-stream/agent-session-record-reader.js +241 -0
  149. package/dist/src/ui-stream/agent-session-record-reader.js.map +1 -0
  150. package/dist/src/ui-stream/agent-ui-message-stream-responses.d.ts +219 -0
  151. package/dist/src/ui-stream/agent-ui-message-stream-responses.js +440 -0
  152. package/dist/src/ui-stream/agent-ui-message-stream-responses.js.map +1 -0
  153. package/dist/src/ui-stream/agent-ui-message-stream.d.ts +138 -0
  154. package/dist/src/ui-stream/agent-ui-message-stream.js +681 -0
  155. package/dist/src/ui-stream/agent-ui-message-stream.js.map +1 -0
  156. package/dist/src/ui-stream/agent-ui-message-types.d.ts +238 -0
  157. package/dist/src/ui-stream/agent-ui-message-types.js +57 -0
  158. package/dist/src/ui-stream/agent-ui-message-types.js.map +1 -0
  159. package/dist/src/ui-stream/agent-ui-messages.d.ts +66 -0
  160. package/dist/src/ui-stream/agent-ui-messages.js +220 -0
  161. package/dist/src/ui-stream/agent-ui-messages.js.map +1 -0
  162. package/dist/src/ui-stream/agent-ui-stream-cursor.d.ts +64 -0
  163. package/dist/src/ui-stream/agent-ui-stream-cursor.js +186 -0
  164. package/dist/src/ui-stream/agent-ui-stream-cursor.js.map +1 -0
  165. package/dist/src/ui-stream/index.d.ts +14 -0
  166. package/dist/src/ui-stream/index.js +22 -0
  167. package/dist/src/ui-stream/index.js.map +1 -0
  168. package/dist/src/ui-stream/server-sent-event-responses.d.ts +6 -0
  169. package/dist/src/ui-stream/server-sent-event-responses.js +34 -0
  170. package/dist/src/ui-stream/server-sent-event-responses.js.map +1 -0
  171. package/package.json +86 -4
@@ -0,0 +1,623 @@
1
+ // Copyright (c) 2026 Super Durable, Inc.
2
+ //
3
+ // Licensed under the Sustainable Use License 1.0.
4
+ // You may not use this file except in compliance with the License.
5
+ // See the LICENSE file in the repository root.
6
+ //
7
+ // SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
8
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
9
+ var useValue = arguments.length > 2;
10
+ for (var i = 0; i < initializers.length; i++) {
11
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
12
+ }
13
+ return useValue ? value : void 0;
14
+ };
15
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
16
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
17
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
18
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
19
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
20
+ var _, done = false;
21
+ for (var i = decorators.length - 1; i >= 0; i--) {
22
+ var context = {};
23
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
24
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
25
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
26
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
27
+ if (kind === "accessor") {
28
+ if (result === void 0) continue;
29
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
30
+ if (_ = accept(result.get)) descriptor.get = _;
31
+ if (_ = accept(result.set)) descriptor.set = _;
32
+ if (_ = accept(result.init)) initializers.unshift(_);
33
+ }
34
+ else if (_ = accept(result)) {
35
+ if (kind === "field") initializers.unshift(_);
36
+ else descriptor[key] = _;
37
+ }
38
+ }
39
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
40
+ done = true;
41
+ };
42
+ import { StepList, StepRef, booleanCodec, rpc, } from "@superdurable/dex";
43
+ import { builtInToolNames, isBlankText } from "./agent-built-in-tools.js";
44
+ import { isContextCompactionRunner, resolveCompactionPolicy, } from "./agent-context-compaction.js";
45
+ import { agentMessagesPageCodec, agentSnapshotCodec, agentUserMessageCodec, answerQuestionRequestCodec, cancelTurnRequestCodec, deleteQueuedMessageRequestCodec, executePlanRequestCodec, listAgentMessagesInputCodec, resolveInterruptInputCodec, steerUserMessageRequestCodec, updateSessionSettingsRequestCodec, } from "./agent-session-codecs.js";
46
+ import { createAgentSessionPersistence, defaultAgentEventsCapacityBytes, planExecutionKey, } from "./agent-session-persistence.js";
47
+ import { checkStoredSessionSettings } from "./agent-session-settings.js";
48
+ import { ApplyTurnControlStep, AwaitToolApprovalStep, AwaitUserMessageStep, CompactContextStep, isExecutablePlanStatus, RecordTurnFailureStep, ResumeTurnStep, RunModelStep, StartAgentSessionStep, ToolCallFailureRecordingStep, ToolCallStep, } from "./agent-session-steps.js";
49
+ import { AgentSessionTracer } from "./agent-session-tracer.js";
50
+ import { CancelToolTaskStep, FinishTurnCancellationStep } from "./agent-session-cancellation-steps.js";
51
+ import { AwaitQuestionAnswerStep, AwaitTimerStep, PollToolTaskStep } from "./agent-session-wait-steps.js";
52
+ import { AgentSessionTransitions, agentSessionStepTypes, finishTurnCancellationMovement, messageRolloverMaxBytesPerCommit, messageRolloverMaxChunksPerCommit, } from "./agent-session-transitions.js";
53
+ import { genAISemanticConventionsSchemaUrls, } from "./agent-tracing-options.js";
54
+ export const snapshotMessageLimit = 200;
55
+ export const defaultMaxDurableWaitMs = 365 * 24 * 60 * 60 * 1_000;
56
+ export const messagePageLimit = 200;
57
+ /** Default {@link AgentSessionOptions.messageWindowSize}. */
58
+ export const defaultMessageWindowSize = 64;
59
+ /** Default {@link AgentSessionOptions.messageChunkSize}. */
60
+ export const defaultMessageChunkSize = 32;
61
+ /** Default {@link AgentSessionOptions.messageChunkMaxBytes}: 1 MiB. */
62
+ export const defaultMessageChunkMaxBytes = 1_048_576;
63
+ /** Default {@link AgentSessionOptions.retainedMessageLimit}. */
64
+ export const defaultRetainedMessageLimit = 1_000;
65
+ export { messageRolloverMaxBytesPerCommit, messageRolloverMaxChunksPerCommit };
66
+ const toolEffects = [
67
+ "read",
68
+ "idempotent_write",
69
+ "non_idempotent_write",
70
+ "unclassified",
71
+ ];
72
+ /**
73
+ * Creates the shared agent session Flow for one agent and its framework runner.
74
+ *
75
+ * Construct it once per agent at application startup and pass the same object to the Registry and
76
+ * every Client call. Each call creates a distinct Flow with its own Step instances, persistence
77
+ * definitions, and RPC methods, so one Registry can hold several agents under different Flow types.
78
+ * Adapter packages wrap this function; applications usually call the adapter's factory instead.
79
+ *
80
+ * It is a function rather than a class because the Dex Client identifies an RPC by its method
81
+ * function, and two Flows of one class would share their RPC methods.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * const triage = createAgentSessionFlow(triageRunner, "TriageAgent", {
86
+ * toolPolicies: { lookup_customer: { effect: "read" } },
87
+ * interruptDeadlineMs: 24 * 60 * 60 * 1000,
88
+ * });
89
+ * const billing = createAgentSessionFlow(billingRunner, "BillingAgent");
90
+ * const registry = new Registry([triage, billing]);
91
+ * ```
92
+ * @typeParam Runner - Type of the runner, kept as the Flow's `runner` property type.
93
+ * @param runner - Framework runner; the Flow owns no other dependency.
94
+ * @param flowType - Flow type, unique within the Registry, such as `"TriageAgent"`. Keep it stable:
95
+ * running sessions resume by it.
96
+ * @param options - Tool policies, Stream capacity, approval deadline, and tracing. Defaults to all
97
+ * defaults.
98
+ * @returns A new Flow to register in one Registry.
99
+ * @throws {TypeError} When `flowType` is blank, the runner is incomplete, an effect or built-in tool is
100
+ * unknown, a tool policy names an enabled built-in tool, a tracing option is invalid, `planModeEnabled`
101
+ * is set without `write_todos` or for a runner without {@link AgentFrameworkRunner.supportsPlanMode}, or
102
+ * `compaction` is set for a runner without the compaction methods.
103
+ * @throws {RangeError} When `eventStreamCapacityBytes` or `interruptDeadlineMs` is not positive,
104
+ * `maxDurableWaitMs` is not a positive whole number of seconds, or the compaction policy is out of range.
105
+ */
106
+ export function createAgentSessionFlow(runner, flowType, options = {}) {
107
+ const config = resolveAgentSessionConfig(runner, flowType, options);
108
+ const persistence = createAgentSessionPersistence(config.eventStreamCapacityBytes);
109
+ const transitions = new AgentSessionTransitions(persistence, runner, config, new AgentSessionTracer(config.tracing, persistence));
110
+ const resolvedOptions = Object.freeze({
111
+ toolPolicies: config.toolPolicies,
112
+ defaultToolEffect: config.defaultToolEffect,
113
+ eventStreamCapacityBytes: config.eventStreamCapacityBytes,
114
+ interruptDeadlineMs: config.interruptDeadlineMs,
115
+ tracing: config.tracing,
116
+ builtInTools: Object.freeze(builtInToolNames.filter((name) => config.builtInTools.has(name))),
117
+ maxDurableWaitMs: config.maxDurableWaitMs,
118
+ planModeEnabled: config.planModeEnabled,
119
+ ...(config.compaction === undefined ? {} : { compaction: config.compaction }),
120
+ messageWindowSize: config.messageWindowSize,
121
+ messageChunkSize: config.messageChunkSize,
122
+ messageChunkMaxBytes: config.messageChunkMaxBytes,
123
+ retainedMessageLimit: config.retainedMessageLimit,
124
+ });
125
+ // A class per Flow gives each Flow its own RPC methods, which the Dex Client identifies by function.
126
+ let AgentSessionFlowDefinition = (() => {
127
+ let _instanceExtraInitializers = [];
128
+ let _sendUserMessage_decorators;
129
+ let _executePlan_decorators;
130
+ let _steerUserMessage_decorators;
131
+ let _deleteQueuedMessage_decorators;
132
+ let _cancelTurn_decorators;
133
+ let _updateSessionSettings_decorators;
134
+ let _resolveInterrupt_decorators;
135
+ let _answerQuestion_decorators;
136
+ let _getAgentSnapshot_decorators;
137
+ let _listAgentMessages_decorators;
138
+ return class AgentSessionFlowDefinition {
139
+ static {
140
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
141
+ _sendUserMessage_decorators = [rpc({
142
+ name: "send_user_message",
143
+ inputCodec: agentUserMessageCodec,
144
+ outputCodec: booleanCodec,
145
+ isTransactional: true,
146
+ })];
147
+ _executePlan_decorators = [rpc({
148
+ name: "execute_plan",
149
+ inputCodec: executePlanRequestCodec,
150
+ outputCodec: booleanCodec,
151
+ lockAttributes: [persistence.pendingPlanExecution.lock()],
152
+ })];
153
+ _steerUserMessage_decorators = [rpc({
154
+ name: "steer_user_message",
155
+ inputCodec: steerUserMessageRequestCodec,
156
+ outputCodec: booleanCodec,
157
+ isTransactional: true,
158
+ loadChannels: [persistence.queuedUserMessages],
159
+ })];
160
+ _deleteQueuedMessage_decorators = [rpc({
161
+ name: "delete_queued_message",
162
+ inputCodec: deleteQueuedMessageRequestCodec,
163
+ outputCodec: booleanCodec,
164
+ isTransactional: true,
165
+ loadChannels: [persistence.queuedUserMessages],
166
+ })];
167
+ _cancelTurn_decorators = [rpc({
168
+ name: "cancel_turn",
169
+ inputCodec: cancelTurnRequestCodec,
170
+ outputCodec: booleanCodec,
171
+ lockAttributes: [persistence.turnCancellationRequest.lock(), persistence.pendingInterrupts.lock()],
172
+ })];
173
+ _updateSessionSettings_decorators = [rpc({
174
+ name: "update_session_settings",
175
+ inputCodec: updateSessionSettingsRequestCodec,
176
+ outputCodec: booleanCodec,
177
+ isTransactional: true,
178
+ })];
179
+ _resolveInterrupt_decorators = [rpc({
180
+ name: "resolve_interrupt",
181
+ inputCodec: resolveInterruptInputCodec,
182
+ outputCodec: booleanCodec,
183
+ lockAttributes: [persistence.pendingInterrupts.lock()],
184
+ })];
185
+ _answerQuestion_decorators = [rpc({
186
+ name: "answer_question",
187
+ inputCodec: answerQuestionRequestCodec,
188
+ outputCodec: booleanCodec,
189
+ lockAttributes: [persistence.pendingInterrupts.lock()],
190
+ })];
191
+ _getAgentSnapshot_decorators = [rpc({
192
+ name: "get_agent_snapshot",
193
+ outputCodec: agentSnapshotCodec,
194
+ loadAttributeMaps: [persistence.agentMessages, persistence.agentMessageChunks, persistence.agentToolCalls],
195
+ loadChannels: [persistence.queuedUserMessages, persistence.steeredUserMessages],
196
+ })];
197
+ _listAgentMessages_decorators = [rpc({
198
+ name: "list_agent_messages",
199
+ inputCodec: listAgentMessagesInputCodec,
200
+ outputCodec: agentMessagesPageCodec,
201
+ loadAttributeMaps: [persistence.agentMessages, persistence.agentMessageChunks],
202
+ })];
203
+ __esDecorate(this, null, _sendUserMessage_decorators, { kind: "method", name: "sendUserMessage", static: false, private: false, access: { has: obj => "sendUserMessage" in obj, get: obj => obj.sendUserMessage }, metadata: _metadata }, null, _instanceExtraInitializers);
204
+ __esDecorate(this, null, _executePlan_decorators, { kind: "method", name: "executePlan", static: false, private: false, access: { has: obj => "executePlan" in obj, get: obj => obj.executePlan }, metadata: _metadata }, null, _instanceExtraInitializers);
205
+ __esDecorate(this, null, _steerUserMessage_decorators, { kind: "method", name: "steerUserMessage", static: false, private: false, access: { has: obj => "steerUserMessage" in obj, get: obj => obj.steerUserMessage }, metadata: _metadata }, null, _instanceExtraInitializers);
206
+ __esDecorate(this, null, _deleteQueuedMessage_decorators, { kind: "method", name: "deleteQueuedMessage", static: false, private: false, access: { has: obj => "deleteQueuedMessage" in obj, get: obj => obj.deleteQueuedMessage }, metadata: _metadata }, null, _instanceExtraInitializers);
207
+ __esDecorate(this, null, _cancelTurn_decorators, { kind: "method", name: "cancelTurn", static: false, private: false, access: { has: obj => "cancelTurn" in obj, get: obj => obj.cancelTurn }, metadata: _metadata }, null, _instanceExtraInitializers);
208
+ __esDecorate(this, null, _updateSessionSettings_decorators, { kind: "method", name: "updateSessionSettings", static: false, private: false, access: { has: obj => "updateSessionSettings" in obj, get: obj => obj.updateSessionSettings }, metadata: _metadata }, null, _instanceExtraInitializers);
209
+ __esDecorate(this, null, _resolveInterrupt_decorators, { kind: "method", name: "resolveInterrupt", static: false, private: false, access: { has: obj => "resolveInterrupt" in obj, get: obj => obj.resolveInterrupt }, metadata: _metadata }, null, _instanceExtraInitializers);
210
+ __esDecorate(this, null, _answerQuestion_decorators, { kind: "method", name: "answerQuestion", static: false, private: false, access: { has: obj => "answerQuestion" in obj, get: obj => obj.answerQuestion }, metadata: _metadata }, null, _instanceExtraInitializers);
211
+ __esDecorate(this, null, _getAgentSnapshot_decorators, { kind: "method", name: "getAgentSnapshot", static: false, private: false, access: { has: obj => "getAgentSnapshot" in obj, get: obj => obj.getAgentSnapshot }, metadata: _metadata }, null, _instanceExtraInitializers);
212
+ __esDecorate(this, null, _listAgentMessages_decorators, { kind: "method", name: "listAgentMessages", static: false, private: false, access: { has: obj => "listAgentMessages" in obj, get: obj => obj.listAgentMessages }, metadata: _metadata }, null, _instanceExtraInitializers);
213
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
214
+ }
215
+ runner = (__runInitializers(this, _instanceExtraInitializers), runner);
216
+ options = resolvedOptions;
217
+ agentState = persistence.agentState;
218
+ agentMessages = persistence.agentMessages;
219
+ agentMessageChunks = persistence.agentMessageChunks;
220
+ agentMessageIndex = persistence.agentMessageIndex;
221
+ frameworkRunState = persistence.frameworkRunState;
222
+ agentToolCalls = persistence.agentToolCalls;
223
+ pendingInterrupts = persistence.pendingInterrupts;
224
+ agentUsage = persistence.agentUsage;
225
+ queuedUserMessages = persistence.queuedUserMessages;
226
+ interruptResolutions = persistence.interruptResolutions;
227
+ toolCallResults = persistence.toolCallResults;
228
+ steeredUserMessages = persistence.steeredUserMessages;
229
+ turnControlRequests = persistence.turnControlRequests;
230
+ turnCancellationRequest = persistence.turnCancellationRequest;
231
+ toolCallCancellations = persistence.toolCallCancellations;
232
+ agentEvents = persistence.agentEvents;
233
+ agentTraceContext = persistence.agentTraceContext;
234
+ agentPlan = persistence.agentPlan;
235
+ planExecutions = persistence.planExecutions;
236
+ pendingPlanExecution = persistence.pendingPlanExecution;
237
+ contextSummary = persistence.contextSummary;
238
+ sessionSettings = persistence.sessionSettings;
239
+ turnSessionSettings = persistence.turnSessionSettings;
240
+ /** The `TurnReplySequence` Attribute; see {@link AgentSessionPersistence.turnReplySequence}. */
241
+ turnReplySequence = persistence.turnReplySequence;
242
+ steps = StepList.startStep(new StartAgentSessionStep(transitions)).otherSteps(new AwaitUserMessageStep(transitions), new RunModelStep(transitions), new CompactContextStep(transitions), new AwaitToolApprovalStep(transitions), new AwaitQuestionAnswerStep(transitions), new AwaitTimerStep(transitions), new ToolCallStep(transitions, agentSessionStepTypes.callTool), new ToolCallStep(transitions, agentSessionStepTypes.callSingleAttemptTool), new PollToolTaskStep(transitions), new ToolCallFailureRecordingStep(transitions, agentSessionStepTypes.recordToolFailure, true), new ToolCallFailureRecordingStep(transitions, agentSessionStepTypes.recordToolOutcomeUnknown, false), new ResumeTurnStep(transitions), new ApplyTurnControlStep(transitions), new RecordTurnFailureStep(transitions), new FinishTurnCancellationStep(transitions), new CancelToolTaskStep(transitions));
243
+ getFlowType() {
244
+ return config.flowType;
245
+ }
246
+ getSteps() {
247
+ return this.steps;
248
+ }
249
+ // AgentTraceContext and ContextSummary are always registered, so Workers with and without tracing or
250
+ // compaction serve one Flow type.
251
+ getPersistenceSchema() {
252
+ return {
253
+ attributes: [
254
+ persistence.agentState,
255
+ persistence.agentMessages,
256
+ persistence.agentMessageChunks,
257
+ persistence.agentMessageIndex,
258
+ persistence.frameworkRunState,
259
+ persistence.agentToolCalls,
260
+ persistence.pendingInterrupts,
261
+ persistence.agentUsage,
262
+ persistence.turnCancellationRequest,
263
+ persistence.agentTraceContext,
264
+ persistence.agentPlan,
265
+ persistence.pendingPlanExecution,
266
+ persistence.contextSummary,
267
+ persistence.sessionSettings,
268
+ persistence.turnSessionSettings,
269
+ persistence.turnReplySequence,
270
+ ],
271
+ channels: [
272
+ persistence.queuedUserMessages,
273
+ persistence.interruptResolutions,
274
+ persistence.toolCallResults,
275
+ persistence.planExecutions,
276
+ persistence.steeredUserMessages,
277
+ persistence.turnControlRequests,
278
+ persistence.toolCallCancellations,
279
+ ],
280
+ streams: [persistence.agentEvents],
281
+ };
282
+ }
283
+ sendUserMessage(context, message) {
284
+ const planMode = message.planMode ?? false;
285
+ if (isBlankText(message.text) || (planMode && !config.planModeEnabled)) {
286
+ return { output: false };
287
+ }
288
+ persistence.queuedUserMessages.publish(context, { text: message.text, planMode });
289
+ return { output: true };
290
+ }
291
+ executePlan(context, input) {
292
+ const state = transitions.readOptionalAgentState(context);
293
+ const plan = transitions.readOptionalAgentPlan(context);
294
+ const pending = persistence.pendingPlanExecution.get(context);
295
+ if (state === null ||
296
+ state.status !== "waiting_for_user_message" ||
297
+ state.activeTurnId !== null ||
298
+ plan === null ||
299
+ plan.revision !== input.revision ||
300
+ !isExecutablePlanStatus(plan.status) ||
301
+ (pending !== undefined && pending.revision === plan.revision) ||
302
+ context.channelSize(persistence.queuedUserMessages) > 0 ||
303
+ context.channelSize(persistence.steeredUserMessages) > 0 ||
304
+ transitions.readPendingInterrupts(context).length > 0) {
305
+ return { output: false };
306
+ }
307
+ const request = { revision: plan.revision };
308
+ persistence.pendingPlanExecution.set(context, request);
309
+ persistence.planExecutions.publish(context, planExecutionKey(plan.revision), request);
310
+ return { output: true };
311
+ }
312
+ steerUserMessage(context, input) {
313
+ if ((input.messageId === null) === (input.text === null)) {
314
+ return { output: false };
315
+ }
316
+ const state = transitions.readOptionalAgentState(context);
317
+ if (state?.activeTurnId == null) {
318
+ // Any Worker version waits for queued messages while idle; a steer might wait forever.
319
+ if (input.text === null) {
320
+ return { output: findQueuedMessage(context, persistence, input.messageId ?? "") !== undefined };
321
+ }
322
+ return this.sendUserMessage(context, { text: input.text });
323
+ }
324
+ if (state.acceptsTurnControl !== true) {
325
+ return { output: false };
326
+ }
327
+ let steered;
328
+ if (input.text !== null) {
329
+ if (isBlankText(input.text)) {
330
+ return { output: false };
331
+ }
332
+ steered = { text: input.text };
333
+ }
334
+ else {
335
+ const queued = findQueuedMessage(context, persistence, input.messageId ?? "");
336
+ if (queued === undefined) {
337
+ return { output: false };
338
+ }
339
+ persistence.queuedUserMessages.delete(context, queued.messageId);
340
+ steered = queued.message;
341
+ }
342
+ persistence.steeredUserMessages.publish(context, steered);
343
+ persistence.turnControlRequests.publish(context, { kind: "steer" });
344
+ return { output: true };
345
+ }
346
+ deleteQueuedMessage(context, input) {
347
+ const queued = findQueuedMessage(context, persistence, input.messageId);
348
+ if (queued === undefined) {
349
+ return { output: false };
350
+ }
351
+ persistence.queuedUserMessages.delete(context, queued.messageId);
352
+ return { output: true };
353
+ }
354
+ // PendingInterrupts orders it with ResumeTurn, and TurnCancellationRequest with turn starts.
355
+ cancelTurn(context, input) {
356
+ const state = transitions.readOptionalAgentState(context);
357
+ const activeTurnId = state?.activeTurnId ?? null;
358
+ if (activeTurnId === null ||
359
+ state?.acceptsTurnControl !== true ||
360
+ (input.turnId !== null && input.turnId !== activeTurnId)) {
361
+ return { output: false };
362
+ }
363
+ if (transitions.isTurnCancelled(context, activeTurnId)) {
364
+ return { output: true };
365
+ }
366
+ persistence.turnCancellationRequest.set(context, {
367
+ turnId: activeTurnId,
368
+ requestedAt: new Date().toISOString(),
369
+ });
370
+ // Each cancelled Step has no outside effect or only waits; the model call's answer is lost.
371
+ return {
372
+ output: true,
373
+ nextSteps: [finishTurnCancellationMovement(activeTurnId)],
374
+ cancelingSteps: [
375
+ agentSessionStepTypes.runModel,
376
+ agentSessionStepTypes.compactContext,
377
+ agentSessionStepTypes.recordTurnFailure,
378
+ agentSessionStepTypes.awaitToolApproval,
379
+ agentSessionStepTypes.awaitQuestionAnswer,
380
+ agentSessionStepTypes.awaitTimer,
381
+ agentSessionStepTypes.pollToolTask,
382
+ ].map((stepType) => new StepRef(stepType)),
383
+ };
384
+ }
385
+ updateSessionSettings(context, input) {
386
+ const sessionSettings = input.sessionSettings;
387
+ if (transitions.readOptionalAgentState(context) === null || sessionSettings === null) {
388
+ return { output: false };
389
+ }
390
+ try {
391
+ checkStoredSessionSettings(sessionSettings);
392
+ }
393
+ catch {
394
+ return { output: false };
395
+ }
396
+ if (Object.keys(sessionSettings).length > 0) {
397
+ persistence.sessionSettings.set(context, sessionSettings);
398
+ }
399
+ else if (transitions.readSessionSettings(context) !== null) {
400
+ persistence.sessionSettings.delete(context);
401
+ }
402
+ return { output: true };
403
+ }
404
+ resolveInterrupt(context, input) {
405
+ const pendingInterrupts = transitions.readPendingInterrupts(context);
406
+ const interrupt = pendingInterrupts.find((pending) => pending.interruptId === input.interruptId);
407
+ // After the deadline, AwaitToolApproval rejects the call; a late answer must not win.
408
+ if (interrupt === undefined ||
409
+ (interrupt.deadline !== null && Date.parse(interrupt.deadline) <= Date.now()) ||
410
+ (interrupt.kind === "question" && input.approved)) {
411
+ return { output: false };
412
+ }
413
+ persistence.pendingInterrupts.set(context, pendingInterrupts.filter((interrupt) => interrupt.interruptId !== input.interruptId));
414
+ persistence.interruptResolutions.publish(context, input.interruptId, {
415
+ approved: input.approved,
416
+ rejectionMessage: input.approved ? null : input.rejectionMessage,
417
+ answer: null,
418
+ });
419
+ return { output: true };
420
+ }
421
+ answerQuestion(context, input) {
422
+ const pendingInterrupts = transitions.readPendingInterrupts(context);
423
+ const interrupt = pendingInterrupts.find((pending) => pending.interruptId === input.interruptId);
424
+ if (interrupt === undefined ||
425
+ interrupt.kind !== "question" ||
426
+ (interrupt.deadline !== null && Date.parse(interrupt.deadline) <= Date.now()) ||
427
+ isBlankText(input.answer) ||
428
+ isAnswerOutsideChoices(interrupt.choices ?? [], interrupt.allowsFreeText ?? true, input.answer)) {
429
+ return { output: false };
430
+ }
431
+ persistence.pendingInterrupts.set(context, pendingInterrupts.filter((pending) => pending.interruptId !== input.interruptId));
432
+ persistence.interruptResolutions.publish(context, input.interruptId, {
433
+ approved: true,
434
+ rejectionMessage: null,
435
+ answer: input.answer,
436
+ });
437
+ return { output: true };
438
+ }
439
+ getAgentSnapshot(context) {
440
+ const state = transitions.readOptionalAgentState(context);
441
+ if (state === null) {
442
+ return {
443
+ output: {
444
+ state: null,
445
+ messages: [],
446
+ pendingInterrupts: [],
447
+ toolCalls: [],
448
+ usage: transitions.readAgentUsage(context),
449
+ queuedMessageCount: 0,
450
+ plan: null,
451
+ queuedMessages: [],
452
+ steeredMessages: [],
453
+ contextSummary: null,
454
+ sessionSettings: null,
455
+ },
456
+ };
457
+ }
458
+ const end = state.nextMessageSequence;
459
+ return {
460
+ output: {
461
+ state,
462
+ messages: transitions.readMessages(context, end - snapshotMessageLimit, end),
463
+ pendingInterrupts: transitions.readPendingInterrupts(context),
464
+ toolCalls: transitions.readTurnToolCalls(context, state.activeTurnId),
465
+ usage: transitions.readAgentUsage(context),
466
+ queuedMessageCount: context.channelSize(persistence.queuedUserMessages),
467
+ plan: transitions.readOptionalAgentPlan(context),
468
+ queuedMessages: readPendingUserMessages(context, persistence.queuedUserMessages),
469
+ steeredMessages: readPendingUserMessages(context, persistence.steeredUserMessages),
470
+ contextSummary: transitions.readContextSummary(context),
471
+ sessionSettings: transitions.readSessionSettings(context),
472
+ },
473
+ };
474
+ }
475
+ listAgentMessages(context, input) {
476
+ const state = transitions.readOptionalAgentState(context);
477
+ if (state === null) {
478
+ return { output: { messages: [], nextBeforeSequence: null, deletedBeforeSequence: null } };
479
+ }
480
+ const limit = Math.max(1, Math.min(input.limit, messagePageLimit));
481
+ const firstSequence = transitions.readFirstStoredSequence(context);
482
+ let end = state.nextMessageSequence;
483
+ if (input.beforeSequence !== null) {
484
+ end = Math.max(firstSequence, Math.min(input.beforeSequence, end));
485
+ }
486
+ const start = Math.max(firstSequence, end - limit);
487
+ return {
488
+ output: {
489
+ messages: transitions.readMessages(context, start, end),
490
+ nextBeforeSequence: start > firstSequence ? start : null,
491
+ deletedBeforeSequence: firstSequence > 1 ? firstSequence : null,
492
+ },
493
+ };
494
+ }
495
+ };
496
+ })();
497
+ return new AgentSessionFlowDefinition();
498
+ }
499
+ function resolveAgentSessionConfig(runner, flowType, options) {
500
+ if (typeof runner?.buildUserMessage !== "function" ||
501
+ typeof runner.runModelStep !== "function" ||
502
+ typeof runner.executeDeferredToolCall !== "function") {
503
+ throw new TypeError("createAgentSessionFlow requires an AgentFrameworkRunner");
504
+ }
505
+ if (typeof flowType !== "string" || flowType.trim() === "") {
506
+ throw new TypeError("flowType must be a non-blank string");
507
+ }
508
+ const defaultToolEffect = options.defaultToolEffect ?? "unclassified";
509
+ requireToolEffect(defaultToolEffect, "defaultToolEffect");
510
+ const toolPolicies = {};
511
+ for (const [toolName, policy] of Object.entries(options.toolPolicies ?? {})) {
512
+ requireToolEffect(policy.effect, `tool policy ${toolName}`);
513
+ toolPolicies[toolName] = Object.freeze({ ...policy });
514
+ }
515
+ const eventStreamCapacityBytes = options.eventStreamCapacityBytes ?? defaultAgentEventsCapacityBytes;
516
+ if (!Number.isSafeInteger(eventStreamCapacityBytes) || eventStreamCapacityBytes <= 0) {
517
+ throw new RangeError("eventStreamCapacityBytes must be a positive integer");
518
+ }
519
+ const interruptDeadlineMs = options.interruptDeadlineMs;
520
+ if (interruptDeadlineMs !== undefined &&
521
+ (!Number.isFinite(interruptDeadlineMs) || interruptDeadlineMs <= 0)) {
522
+ throw new RangeError("interruptDeadlineMs must be positive");
523
+ }
524
+ const builtInTools = new Set();
525
+ for (const builtInTool of options.builtInTools ?? []) {
526
+ if (!builtInToolNames.includes(builtInTool)) {
527
+ throw new TypeError(`builtInTools has unknown built-in tool ${String(builtInTool)}`);
528
+ }
529
+ builtInTools.add(builtInTool);
530
+ }
531
+ for (const toolName of Object.keys(toolPolicies)) {
532
+ if (builtInTools.has(toolName)) {
533
+ throw new TypeError(`tool policy ${toolName} names an enabled built-in tool, whose policy is fixed`);
534
+ }
535
+ }
536
+ const planModeEnabled = options.planModeEnabled ?? false;
537
+ if (planModeEnabled && !builtInTools.has("write_todos")) {
538
+ throw new TypeError("planModeEnabled requires the write_todos built-in tool");
539
+ }
540
+ if (planModeEnabled && runner.supportsPlanMode !== true) {
541
+ throw new TypeError("planModeEnabled requires a runner that supports plan mode");
542
+ }
543
+ const maxDurableWaitMs = options.maxDurableWaitMs ?? defaultMaxDurableWaitMs;
544
+ if (!Number.isSafeInteger(maxDurableWaitMs) || maxDurableWaitMs < 1_000 || maxDurableWaitMs % 1_000 !== 0) {
545
+ throw new RangeError("maxDurableWaitMs must be a positive whole number of seconds, in milliseconds");
546
+ }
547
+ const compaction = options.compaction === undefined ? undefined : resolveCompactionPolicy(options.compaction);
548
+ if (compaction !== undefined && !isContextCompactionRunner(runner)) {
549
+ throw new TypeError("compaction needs a runner that implements estimateInputTokens, selectCompactionCutoff, and summarizeContext");
550
+ }
551
+ const messageChunkSize = options.messageChunkSize ?? defaultMessageChunkSize;
552
+ if (!Number.isSafeInteger(messageChunkSize) || messageChunkSize <= 0) {
553
+ throw new RangeError("messageChunkSize must be positive");
554
+ }
555
+ const messageWindowSize = options.messageWindowSize ?? defaultMessageWindowSize;
556
+ if (!Number.isSafeInteger(messageWindowSize) || messageWindowSize < messageChunkSize) {
557
+ throw new RangeError("messageWindowSize must be at least messageChunkSize");
558
+ }
559
+ const messageChunkMaxBytes = options.messageChunkMaxBytes ?? defaultMessageChunkMaxBytes;
560
+ if (!Number.isSafeInteger(messageChunkMaxBytes) ||
561
+ messageChunkMaxBytes < 1 ||
562
+ messageChunkMaxBytes > messageRolloverMaxBytesPerCommit) {
563
+ throw new RangeError(`messageChunkMaxBytes must be between 1 and ${messageRolloverMaxBytesPerCommit}`);
564
+ }
565
+ const retainedMessageLimit = options.retainedMessageLimit === undefined ? defaultRetainedMessageLimit : options.retainedMessageLimit;
566
+ if (retainedMessageLimit !== null && (!Number.isSafeInteger(retainedMessageLimit) || retainedMessageLimit < 0)) {
567
+ throw new RangeError("retainedMessageLimit must not be negative");
568
+ }
569
+ return {
570
+ flowType,
571
+ toolPolicies: Object.freeze(toolPolicies),
572
+ defaultToolEffect,
573
+ eventStreamCapacityBytes,
574
+ interruptDeadlineMs,
575
+ tracing: resolveAgentTracingOptions(flowType, options.tracing ?? {}),
576
+ builtInTools,
577
+ maxDurableWaitMs,
578
+ planModeEnabled,
579
+ compaction,
580
+ messageWindowSize,
581
+ messageChunkSize,
582
+ messageChunkMaxBytes,
583
+ retainedMessageLimit,
584
+ };
585
+ }
586
+ function resolveAgentTracingOptions(flowType, tracing) {
587
+ const agentName = tracing.agentName ?? flowType;
588
+ if (typeof agentName !== "string" || agentName.trim() === "") {
589
+ throw new TypeError("tracing.agentName must be a non-blank string");
590
+ }
591
+ const semanticConventionsVersion = tracing.semanticConventionsVersion ?? "1.42.0-dev";
592
+ if (!Object.hasOwn(genAISemanticConventionsSchemaUrls, semanticConventionsVersion)) {
593
+ throw new TypeError(`tracing.semanticConventionsVersion ${String(semanticConventionsVersion)} is unknown`);
594
+ }
595
+ const tracerProvider = tracing.tracerProvider;
596
+ if (tracerProvider !== undefined && typeof tracerProvider?.getTracer !== "function") {
597
+ throw new TypeError("tracing.tracerProvider must be an OpenTelemetry TracerProvider");
598
+ }
599
+ return Object.freeze({
600
+ isEnabled: tracing.isEnabled ?? true,
601
+ tracerProvider,
602
+ agentName,
603
+ shouldCaptureMessageContent: tracing.shouldCaptureMessageContent ?? false,
604
+ semanticConventionsVersion,
605
+ });
606
+ }
607
+ function readPendingUserMessages(context, channel) {
608
+ return channel
609
+ .pendingMessages(context)
610
+ .map((pending) => ({ messageId: pending.messageId, message: pending.value }));
611
+ }
612
+ function findQueuedMessage(context, persistence, messageId) {
613
+ return readPendingUserMessages(context, persistence.queuedUserMessages).find((queued) => queued.messageId === messageId);
614
+ }
615
+ function isAnswerOutsideChoices(choices, allowsFreeText, answer) {
616
+ return choices.length > 0 && !allowsFreeText && !choices.includes(answer);
617
+ }
618
+ function requireToolEffect(effect, description) {
619
+ if (!toolEffects.includes(effect)) {
620
+ throw new TypeError(`${description} has unknown tool effect ${String(effect)}`);
621
+ }
622
+ }
623
+ //# sourceMappingURL=agent-session-flow.js.map