@kuralle-agents/core 0.12.0 → 0.14.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 (210) hide show
  1. package/README.md +89 -4
  2. package/dist/ai-sdk/uiMessageStream.d.ts +2 -2
  3. package/dist/ai-sdk/uiMessageStream.js +42 -29
  4. package/dist/capabilities/LivePromptAssembler.d.ts +1 -1
  5. package/dist/capabilities/LivePromptAssembler.js +2 -1
  6. package/dist/capabilities/index.d.ts +1 -1
  7. package/dist/eval/EvalRunner.js +4 -4
  8. package/dist/eval/simulation.js +4 -3
  9. package/dist/events/TurnHandle.d.ts +3 -3
  10. package/dist/flow/collectDigression.d.ts +5 -2
  11. package/dist/flow/collectDigression.js +48 -10
  12. package/dist/flow/collectUntilComplete.js +13 -5
  13. package/dist/flow/degrade.js +8 -4
  14. package/dist/flow/emitInteractive.d.ts +2 -2
  15. package/dist/flow/emitInteractive.js +6 -3
  16. package/dist/flow/extraction.d.ts +3 -2
  17. package/dist/flow/extraction.js +14 -4
  18. package/dist/flow/reduceTransition.d.ts +2 -2
  19. package/dist/flow/reduceTransition.js +7 -3
  20. package/dist/flow/runFlow.js +97 -17
  21. package/dist/foundation/AgentStateController.d.ts +1 -1
  22. package/dist/foundation/ToolExecutor.d.ts +2 -2
  23. package/dist/foundation/index.d.ts +0 -11
  24. package/dist/foundation/index.js +0 -5
  25. package/dist/index.d.ts +15 -15
  26. package/dist/index.js +9 -6
  27. package/dist/outcomes/streamPart.d.ts +2 -2
  28. package/dist/outcomes/streamPart.js +2 -3
  29. package/dist/prompts/PromptBuilder.d.ts +3 -3
  30. package/dist/prompts/PromptBuilder.js +13 -6
  31. package/dist/prompts/index.d.ts +1 -1
  32. package/dist/prompts/types.d.ts +9 -2
  33. package/dist/runtime/InMemoryRetrievalCache.d.ts +25 -0
  34. package/dist/runtime/InMemoryRetrievalCache.js +59 -0
  35. package/dist/runtime/KnowledgeProvider.d.ts +3 -2
  36. package/dist/runtime/KnowledgeProvider.js +60 -31
  37. package/dist/runtime/Runtime.d.ts +47 -1
  38. package/dist/runtime/Runtime.js +273 -36
  39. package/dist/runtime/TokenAccumulator.d.ts +7 -0
  40. package/dist/runtime/TokenAccumulator.js +7 -0
  41. package/dist/runtime/TraceRecorder.d.ts +51 -0
  42. package/dist/runtime/TraceRecorder.js +326 -0
  43. package/dist/runtime/buildAgentToolSurface.js +1 -1
  44. package/dist/runtime/channels/TextDriver.js +57 -31
  45. package/dist/runtime/channels/executeModelTool.d.ts +14 -1
  46. package/dist/runtime/channels/executeModelTool.js +132 -3
  47. package/dist/runtime/channels/extractionTurn.js +1 -1
  48. package/dist/runtime/channels/index.d.ts +0 -3
  49. package/dist/runtime/channels/index.js +0 -6
  50. package/dist/runtime/channels/inputBuffer.d.ts +1 -0
  51. package/dist/runtime/channels/inputBuffer.js +9 -0
  52. package/dist/runtime/channels/streaming/hostControlSpeak.js +5 -1
  53. package/dist/runtime/channels/streaming/speakGated.js +24 -12
  54. package/dist/runtime/citations/index.d.ts +3 -3
  55. package/dist/runtime/closeRun.js +14 -10
  56. package/dist/runtime/compaction.d.ts +2 -0
  57. package/dist/runtime/compaction.js +3 -2
  58. package/dist/runtime/controlFlowSignal.d.ts +24 -0
  59. package/dist/runtime/controlFlowSignal.js +29 -0
  60. package/dist/runtime/ctx.d.ts +3 -4
  61. package/dist/runtime/ctx.js +147 -60
  62. package/dist/runtime/durable/RunStore.d.ts +16 -0
  63. package/dist/runtime/durable/RunStore.js +7 -1
  64. package/dist/runtime/durable/SessionRunStore.d.ts +7 -2
  65. package/dist/runtime/durable/SessionRunStore.js +136 -34
  66. package/dist/runtime/durable/idempotency.d.ts +1 -0
  67. package/dist/runtime/durable/idempotency.js +3 -0
  68. package/dist/runtime/durable/replay.js +7 -2
  69. package/dist/runtime/durable/types.d.ts +11 -0
  70. package/dist/runtime/goals.d.ts +18 -0
  71. package/dist/runtime/goals.js +158 -0
  72. package/dist/runtime/grounding/gather.d.ts +1 -1
  73. package/dist/runtime/grounding/inMemoryKnowledge.d.ts +1 -1
  74. package/dist/runtime/grounding/knowledge.d.ts +1 -1
  75. package/dist/runtime/grounding/knowledge.js +1 -1
  76. package/dist/runtime/handoffContinuation.d.ts +20 -0
  77. package/dist/runtime/handoffContinuation.js +30 -0
  78. package/dist/runtime/handoffOscillation.d.ts +6 -0
  79. package/dist/runtime/handoffOscillation.js +17 -0
  80. package/dist/runtime/hostLoop.js +37 -6
  81. package/dist/runtime/index.d.ts +4 -3
  82. package/dist/runtime/index.js +2 -1
  83. package/dist/runtime/openRun.d.ts +2 -0
  84. package/dist/runtime/openRun.js +46 -17
  85. package/dist/runtime/outcomeMarking.d.ts +2 -2
  86. package/dist/runtime/outcomeMarking.js +2 -1
  87. package/dist/runtime/policies/agentTurn.d.ts +1 -1
  88. package/dist/runtime/policies/limits.d.ts +1 -0
  89. package/dist/runtime/policies/limits.js +3 -0
  90. package/dist/runtime/runHookSafely.d.ts +3 -0
  91. package/dist/runtime/runHookSafely.js +19 -0
  92. package/dist/runtime/select.d.ts +5 -1
  93. package/dist/runtime/select.js +30 -1
  94. package/dist/runtime/turnTokenUsage.d.ts +28 -0
  95. package/dist/runtime/turnTokenUsage.js +70 -0
  96. package/dist/scheduler/index.d.ts +2 -2
  97. package/dist/scheduler/index.js +1 -1
  98. package/dist/services/TracingService.js +2 -3
  99. package/dist/session/SessionStore.d.ts +6 -0
  100. package/dist/session/SessionStore.js +12 -1
  101. package/dist/session/stores/MemoryStore.d.ts +1 -1
  102. package/dist/session/stores/MemoryStore.js +16 -2
  103. package/dist/session/testing.d.ts +6 -1
  104. package/dist/session/testing.js +34 -0
  105. package/dist/session/utils.d.ts +3 -0
  106. package/dist/session/utils.js +23 -0
  107. package/dist/skills/collectSkills.d.ts +11 -3
  108. package/dist/skills/collectSkills.js +51 -8
  109. package/dist/skills/compositeSkillStore.d.ts +26 -0
  110. package/dist/skills/compositeSkillStore.js +54 -0
  111. package/dist/skills/defineSkill.d.ts +21 -0
  112. package/dist/skills/defineSkill.js +26 -0
  113. package/dist/skills/fsSkillStore.d.ts +3 -0
  114. package/dist/skills/fsSkillStore.js +79 -0
  115. package/dist/skills/index.d.ts +4 -0
  116. package/dist/skills/index.js +4 -0
  117. package/dist/skills/parseSkillFrontmatter.d.ts +14 -0
  118. package/dist/skills/parseSkillFrontmatter.js +183 -0
  119. package/dist/skills/wireAgentSkills.d.ts +2 -1
  120. package/dist/skills/wireAgentSkills.js +2 -2
  121. package/dist/testing/mocks.d.ts +3 -3
  122. package/dist/testing/mocks.js +7 -3
  123. package/dist/tools/controlResults.d.ts +14 -0
  124. package/dist/tools/controlResults.js +15 -0
  125. package/dist/tools/effect/ToolExecutor.d.ts +6 -0
  126. package/dist/tools/effect/ToolExecutor.js +75 -36
  127. package/dist/tools/effect/defineTool.d.ts +11 -0
  128. package/dist/tools/effect/defineTool.js +3 -0
  129. package/dist/tools/effect/errors.d.ts +2 -5
  130. package/dist/tools/effect/errors.js +2 -5
  131. package/dist/tools/index.d.ts +0 -1
  132. package/dist/tools/index.js +0 -1
  133. package/dist/tracing/MemoryTraceStore.d.ts +16 -0
  134. package/dist/tracing/MemoryTraceStore.js +56 -0
  135. package/dist/tracing/OtelTraceSink.d.ts +127 -0
  136. package/dist/tracing/OtelTraceSink.js +101 -0
  137. package/dist/tracing/TraceStore.d.ts +19 -0
  138. package/dist/tracing/TraceStore.js +32 -0
  139. package/dist/tracing/index.d.ts +3 -0
  140. package/dist/tracing/index.js +3 -0
  141. package/dist/tracing/testing.d.ts +3 -0
  142. package/dist/tracing/testing.js +45 -0
  143. package/dist/types/agentConfig.d.ts +2 -1
  144. package/dist/types/channel.d.ts +14 -1
  145. package/dist/types/effectTool.d.ts +6 -0
  146. package/dist/types/flow.d.ts +1 -1
  147. package/dist/types/guardrails.d.ts +5 -0
  148. package/dist/types/hooks.d.ts +2 -2
  149. package/dist/types/index.d.ts +25 -15
  150. package/dist/types/index.js +8 -12
  151. package/dist/types/knowledge.d.ts +213 -0
  152. package/dist/types/processors.d.ts +0 -58
  153. package/dist/types/run-context.d.ts +16 -7
  154. package/dist/types/runtime.d.ts +3 -74
  155. package/dist/types/session.d.ts +11 -1
  156. package/dist/types/skills.d.ts +15 -1
  157. package/dist/types/stream.d.ts +138 -68
  158. package/dist/types/stream.js +34 -1
  159. package/dist/types/trace.d.ts +52 -0
  160. package/guides/AGENTS.md +3 -3
  161. package/guides/EXAMPLE_VERIFICATION.md +4 -4
  162. package/guides/FLOWS.md +1 -1
  163. package/guides/GETTING_STARTED.md +1 -1
  164. package/guides/RUNTIME.md +20 -15
  165. package/guides/TOOLS.md +1 -1
  166. package/package.json +13 -14
  167. package/dist/foundation/AgentDefinition.d.ts +0 -17
  168. package/dist/foundation/ConversationEventLog.d.ts +0 -71
  169. package/dist/foundation/ConversationState.d.ts +0 -33
  170. package/dist/foundation/ConversationState.js +0 -1
  171. package/dist/foundation/DefaultConversationEventLog.d.ts +0 -27
  172. package/dist/foundation/DefaultConversationEventLog.js +0 -205
  173. package/dist/foundation/DefaultConversationState.d.ts +0 -36
  174. package/dist/foundation/DefaultConversationState.js +0 -103
  175. package/dist/foundation/DefaultToolExecutor.d.ts +0 -57
  176. package/dist/foundation/DefaultToolExecutor.js +0 -132
  177. package/dist/foundation/createFoundation.d.ts +0 -32
  178. package/dist/foundation/createFoundation.js +0 -33
  179. package/dist/hooks/HookRunner.d.ts +0 -37
  180. package/dist/hooks/HookRunner.js +0 -111
  181. package/dist/hooks/builtin/logging.d.ts +0 -5
  182. package/dist/hooks/builtin/logging.js +0 -98
  183. package/dist/hooks/builtin/metrics.d.ts +0 -7
  184. package/dist/hooks/builtin/metrics.js +0 -60
  185. package/dist/hooks/builtin/observability.d.ts +0 -20
  186. package/dist/hooks/builtin/observability.js +0 -572
  187. package/dist/hooks/helpers.d.ts +0 -22
  188. package/dist/hooks/helpers.js +0 -183
  189. package/dist/hooks/index.d.ts +0 -8
  190. package/dist/hooks/index.js +0 -6
  191. package/dist/realtime/RealtimeAudioClient.d.ts +0 -166
  192. package/dist/realtime/RealtimeAudioClient.js +0 -14
  193. package/dist/realtime/RealtimeSessionHandle.d.ts +0 -6
  194. package/dist/realtime/RealtimeSessionHandle.js +0 -1
  195. package/dist/realtime/index.d.ts +0 -2
  196. package/dist/realtime/index.js +0 -1
  197. package/dist/runtime/channels/VoiceDriver.d.ts +0 -31
  198. package/dist/runtime/channels/VoiceDriver.js +0 -321
  199. package/dist/runtime/channels/voiceTools.d.ts +0 -9
  200. package/dist/runtime/channels/voiceTools.js +0 -51
  201. package/dist/tools/errorHandling.d.ts +0 -35
  202. package/dist/tools/errorHandling.js +0 -145
  203. package/dist/types/voice.d.ts +0 -517
  204. package/dist/types/voice.js +0 -14
  205. package/dist/utils/isRecord.d.ts +0 -1
  206. package/dist/utils/isRecord.js +0 -3
  207. package/dist/utils/messageNormalization.d.ts +0 -2
  208. package/dist/utils/messageNormalization.js +0 -137
  209. /package/dist/{foundation/AgentDefinition.js → types/knowledge.js} +0 -0
  210. /package/dist/{foundation/ConversationEventLog.js → types/trace.js} +0 -0
@@ -6,6 +6,10 @@ function collectDataKey(nodeId) {
6
6
  function collectTurnsKey(nodeId) {
7
7
  return `__collectTurns_${nodeId}`;
8
8
  }
9
+ export function resetCollect(state, nodeId) {
10
+ delete state[collectDataKey(nodeId)];
11
+ delete state[collectTurnsKey(nodeId)];
12
+ }
9
13
  export function getCollectData(state, nodeId) {
10
14
  const raw = state[collectDataKey(nodeId)];
11
15
  if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {
@@ -125,16 +129,22 @@ export function emitExtractionTelemetry(node, state, incoming, emit) {
125
129
  }
126
130
  }
127
131
  emit({
132
+ channel: 'internal',
128
133
  type: 'custom',
129
- name: 'flow.extraction.submission',
130
- data: { node: node.id, fieldsAccepted, fieldsRejected },
134
+ payload: {
135
+ name: 'flow.extraction.submission',
136
+ data: { node: node.id, fieldsAccepted, fieldsRejected },
137
+ },
131
138
  });
132
139
  const collected = getCollectData(state, node.id);
133
140
  const missing = computeMissingFields(node, collected);
134
141
  emit({
142
+ channel: 'internal',
135
143
  type: 'custom',
136
- name: 'flow.extraction.update',
137
- data: { nodeId: node.id, collected, missing },
144
+ payload: {
145
+ name: 'flow.extraction.update',
146
+ data: { nodeId: node.id, collected, missing },
147
+ },
138
148
  });
139
149
  }
140
150
  function fieldPopulated(value) {
@@ -1,7 +1,7 @@
1
1
  import type { LanguageModel } from 'ai';
2
2
  import type { Flow, FlowNode } from '../types/flow.js';
3
3
  import type { RunState } from '../runtime/durable/types.js';
4
- import type { HarnessStreamPart } from '../types/stream.js';
4
+ import type { StreamPart } from '../types/stream.js';
5
5
  export interface ReduceTransitionInput {
6
6
  fromNodeId: string;
7
7
  toNode: FlowNode;
@@ -9,7 +9,7 @@ export interface ReduceTransitionInput {
9
9
  flow: Flow;
10
10
  model: LanguageModel;
11
11
  data?: Record<string, unknown>;
12
- emit: (part: HarnessStreamPart) => void;
12
+ emit: (part: StreamPart) => void;
13
13
  abortSignal?: AbortSignal;
14
14
  }
15
15
  export declare function reduceTransition(input: ReduceTransitionInput): Promise<void>;
@@ -8,9 +8,13 @@ function resolveNodeContext(toNode, flow) {
8
8
  }
9
9
  export async function reduceTransition(input) {
10
10
  const { fromNodeId, toNode, run, flow, model, data, emit, abortSignal } = input;
11
- emit({ type: 'node-exit', nodeName: fromNodeId });
12
- emit({ type: 'flow-transition', from: fromNodeId, to: toNode.id });
13
- emit({ type: 'node-enter', nodeName: toNode.id });
11
+ emit({ channel: 'internal', type: 'node-exit', payload: { nodeName: fromNodeId } });
12
+ emit({
13
+ channel: 'internal',
14
+ type: 'flow-transition',
15
+ payload: { from: fromNodeId, to: toNode.id },
16
+ });
17
+ emit({ channel: 'internal', type: 'node-enter', payload: { nodeName: toNode.id } });
14
18
  emitInteractiveOnNodeEnter(toNode, run.state, emit);
15
19
  await applyContextStrategy({
16
20
  strategy: resolveNodeContext(toNode, flow),
@@ -1,6 +1,6 @@
1
- import { getFlowPark } from './collectDigression.js';
1
+ import { popFlowPark, runCollectDigression } from './collectDigression.js';
2
2
  import { parseConfirmation } from './confirmParse.js';
3
- import { hasPendingUserInput } from '../runtime/channels/inputBuffer.js';
3
+ import { hasPendingUserInput, setPendingUserInput } from '../runtime/channels/inputBuffer.js';
4
4
  import { userInputToText } from '../runtime/userInput.js';
5
5
  import { collectUntilComplete } from './collectUntilComplete.js';
6
6
  import { isActionNode, isCollectNode, isDecideNode, isReplyNode, } from './nodeKinds.js';
@@ -10,8 +10,8 @@ import { resolveReplyNode } from './nodeBuilders.js';
10
10
  import { evaluateReplyControl } from './controlEvaluator.js';
11
11
  import { runNodeVerify, VerifyBlockedError } from './verify.js';
12
12
  import { loadRecordedSteps } from '../runtime/durable/replay.js';
13
- import { SuspendError } from '../runtime/durable/RunStore.js';
14
- import { ToolApprovalDeniedError } from '../tools/effect/errors.js';
13
+ import { persistTurnUsageFromTurn } from '../runtime/turnTokenUsage.js';
14
+ import { isApprovalDenial, isControlFlowSignal } from '../runtime/controlFlowSignal.js';
15
15
  import { emitInteractiveOnNodeEnter } from './emitInteractive.js';
16
16
  import { appendConversationAudit } from '../audit/record.js';
17
17
  import { appendSafeAssistantMessage, degradeFlowError, findEscalateNode, } from './degrade.js';
@@ -68,16 +68,24 @@ async function dispatchConfirmGate(node, run, driver, ctx) {
68
68
  return { kind: 'stay' };
69
69
  }
70
70
  let input = '';
71
+ let rawInput = '';
71
72
  if (hasPendingUserInput(ctx.session)) {
72
73
  const signal = await driver.awaitUser(ctx);
74
+ rawInput = signal.input;
73
75
  input = userInputToText(signal.input);
74
76
  appendUserMessage(run, signal.input);
75
77
  }
76
78
  else {
77
79
  input = latestUserText(run);
80
+ rawInput = input;
78
81
  }
79
- ctx.turnInputConsumed = true;
80
82
  const verdict = parseConfirmation(input);
83
+ if (verdict === 'decline') {
84
+ setPendingUserInput(ctx.session, rawInput);
85
+ }
86
+ else {
87
+ ctx.turnInputConsumed = true;
88
+ }
81
89
  const branch = verdict === 'affirm'
82
90
  ? gate.onConfirm
83
91
  : verdict === 'decline'
@@ -136,7 +144,40 @@ async function dispatchNode(node, run, driver, ctx, agent, flow) {
136
144
  return normalizeTransition(await node.decide(structured, run.state));
137
145
  }
138
146
  if (isReplyNode(node)) {
147
+ // Consume input here ONLY to feed the out-of-band digression check below, and
148
+ // only for input this turn genuinely fresh to THIS reply — gated on both:
149
+ // !turnInputConsumed: a prior node (e.g. a collect) already took the turn's
150
+ // input, so a terminal reply like `done` (next→end) must not re-digress on
151
+ // the leftover — otherwise it returns `stay`, the main loop's stay+pending
152
+ // branch re-dispatches, and completion hangs on a driver clearing the buffer.
153
+ // outOfBandControl: with OOB off there is no digression, so the reply must not
154
+ // swallow input here — it returns its transition (`next: () => 'stay'`) and the
155
+ // main loop's stay-branch owns awaitUser.
156
+ let freshUserInput = false;
157
+ if (hasPendingUserInput(ctx.session) && !ctx.turnInputConsumed && ctx.outOfBandControl) {
158
+ const signal = await driver.awaitUser(ctx);
159
+ appendUserMessage(run, signal.input);
160
+ ctx.turnInputConsumed = true;
161
+ freshUserInput = true;
162
+ }
163
+ if (freshUserInput && agent) {
164
+ const digression = await runCollectDigression({
165
+ agent,
166
+ node,
167
+ activeFlowName: flow.name,
168
+ run,
169
+ driver,
170
+ ctx,
171
+ });
172
+ if (digression.kind === 'transition') {
173
+ return digression.transition;
174
+ }
175
+ if (digression.kind === 'answeredThenResume') {
176
+ return { kind: 'stay' };
177
+ }
178
+ }
139
179
  const turn = await driver.runAgentTurn(resolveReplyNode(node, run.state), ctx);
180
+ await persistTurnUsageFromTurn(ctx, turn);
140
181
  if (ctx.outOfBandControl) {
141
182
  const decision = await evaluateReplyControl({
142
183
  node,
@@ -147,6 +188,23 @@ async function dispatchNode(node, run, driver, ctx, agent, flow) {
147
188
  if (decision.kind === 'redispatch') {
148
189
  const signal = await driver.awaitUser(ctx);
149
190
  appendUserMessage(run, signal.input);
191
+ ctx.turnInputConsumed = true;
192
+ if (agent) {
193
+ const digression = await runCollectDigression({
194
+ agent,
195
+ node,
196
+ activeFlowName: flow.name,
197
+ run,
198
+ driver,
199
+ ctx,
200
+ });
201
+ if (digression.kind === 'transition') {
202
+ return digression.transition;
203
+ }
204
+ if (digression.kind === 'answeredThenResume') {
205
+ return { kind: 'stay' };
206
+ }
207
+ }
150
208
  return dispatchNode(node, run, driver, ctx, agent, flow);
151
209
  }
152
210
  appendAssistantMessage(run, turn.text);
@@ -206,8 +264,8 @@ export async function runFlow(flow, run, driver, ctx, agent) {
206
264
  if (!run.activeNode) {
207
265
  run.activeNode = node.id;
208
266
  run.activeFlow = flow.name;
209
- ctx.emit({ type: 'flow-enter', flow: flow.name });
210
- ctx.emit({ type: 'node-enter', nodeName: node.id });
267
+ ctx.emit({ channel: 'internal', type: 'flow-enter', payload: { flow: flow.name } });
268
+ ctx.emit({ channel: 'internal', type: 'node-enter', payload: { nodeName: node.id } });
211
269
  emitInteractiveOnNodeEnter(node, run.state, ctx.emit);
212
270
  }
213
271
  const edgeCounts = new Map();
@@ -218,11 +276,14 @@ export async function runFlow(flow, run, driver, ctx, agent) {
218
276
  transition = await dispatchNode(node, run, driver, ctx, agent, flow);
219
277
  }
220
278
  catch (error) {
221
- if (error instanceof SuspendError || error instanceof ToolApprovalDeniedError) {
279
+ // Neither is a malfunction, so neither may reach degradeFlowError and be reported to
280
+ // the user as "something went wrong on my side". A suspend resumes later; a denial is
281
+ // the action node author's to handle, since they chose to call the tool.
282
+ if (isControlFlowSignal(error) || isApprovalDenial(error)) {
222
283
  throw error;
223
284
  }
224
285
  const message = error instanceof Error ? error.message : String(error);
225
- ctx.emit({ type: 'error', error: message });
286
+ ctx.emit({ channel: 'client', type: 'error', payload: { error: message } });
226
287
  return degradeFlowError(flow, registry, run, driver, ctx, (n, r, d, c) => dispatchNode(n, r, d, c, agent, flow));
227
288
  }
228
289
  if (transition.kind === 'switchFlow') {
@@ -232,23 +293,34 @@ export async function runFlow(flow, run, driver, ctx, agent) {
232
293
  return runFlow(transition.flow, run, driver, ctx, agent);
233
294
  }
234
295
  if (transition.kind === 'end') {
235
- const park = getFlowPark(run.state);
296
+ const park = popFlowPark(run.state);
236
297
  if (park && agent) {
237
- delete run.state.__flowPark;
238
298
  const parkedFlow = agent.flows?.find((candidate) => candidate.name === park.flow);
239
299
  if (parkedFlow) {
240
300
  run.activeFlow = park.flow;
241
301
  run.activeNode = park.node;
242
302
  await ctx.runStore.putRunState(run);
243
- ctx.emit({ type: 'flow-end', flow: flow.name, reason: transition.reason });
303
+ ctx.emit({
304
+ channel: 'internal',
305
+ type: 'flow-end',
306
+ payload: { flow: flow.name, reason: transition.reason },
307
+ });
244
308
  return runFlow(parkedFlow, run, driver, ctx, agent);
245
309
  }
246
310
  }
247
- ctx.emit({ type: 'flow-end', flow: flow.name, reason: transition.reason });
311
+ ctx.emit({
312
+ channel: 'internal',
313
+ type: 'flow-end',
314
+ payload: { flow: flow.name, reason: transition.reason },
315
+ });
248
316
  return { kind: 'ended', reason: transition.reason };
249
317
  }
250
318
  if (transition.kind === 'handoff') {
251
- ctx.emit({ type: 'handoff', targetAgent: transition.to, reason: transition.reason });
319
+ ctx.emit({
320
+ channel: 'internal',
321
+ type: 'handoff',
322
+ payload: { targetAgent: transition.to, reason: transition.reason },
323
+ });
252
324
  return { kind: 'handoff', to: transition.to, reason: transition.reason };
253
325
  }
254
326
  if (transition.kind === 'escalate') {
@@ -279,14 +351,18 @@ export async function runFlow(flow, run, driver, ctx, agent) {
279
351
  }
280
352
  catch (error) {
281
353
  if (error instanceof VerifyBlockedError) {
282
- ctx.emit({ type: 'error', error: error.message });
354
+ ctx.emit({ channel: 'client', type: 'error', payload: { error: error.message } });
283
355
  return { kind: 'awaitingUser' };
284
356
  }
285
357
  throw error;
286
358
  }
287
359
  const oscillation = bumpOscillation(edgeCounts, node.id, target.id);
288
360
  if (oscillation > maxOscillations) {
289
- ctx.emit({ type: 'error', error: `Flow oscillation blocked: ${node.id} -> ${target.id}` });
361
+ ctx.emit({
362
+ channel: 'client',
363
+ type: 'error',
364
+ payload: { error: `Flow oscillation blocked: ${node.id} -> ${target.id}` },
365
+ });
290
366
  const escalateNode = findEscalateNode(registry);
291
367
  if (escalateNode) {
292
368
  appendSafeAssistantMessage(run, ctx);
@@ -305,7 +381,11 @@ export async function runFlow(flow, run, driver, ctx, agent) {
305
381
  continue;
306
382
  }
307
383
  appendSafeAssistantMessage(run, ctx);
308
- ctx.emit({ type: 'flow-end', flow: flow.name, reason: 'error_degraded' });
384
+ ctx.emit({
385
+ channel: 'internal',
386
+ type: 'flow-end',
387
+ payload: { flow: flow.name, reason: 'error_degraded' },
388
+ });
309
389
  return { kind: 'ended', reason: 'error_degraded' };
310
390
  }
311
391
  await reduceTransition({
@@ -1,7 +1,7 @@
1
1
  import type { Session } from '../types/index.js';
2
2
  /**
3
3
  * Manages active agent resolution, handoff recording, and agent state.
4
- * Shared by Runtime and VoiceEngine.
4
+ * Used by Runtime.
5
5
  */
6
6
  export interface AgentStateController {
7
7
  /** Resolve the active agent ID, falling back to the provided default. */
@@ -1,7 +1,7 @@
1
1
  import type { Session, ToolCallRecord } from '../types/index.js';
2
2
  /**
3
3
  * Minimal tool shape required by the executor.
4
- * Compatible with AI SDK `Tool`, VoiceToolDef, and plain `{ execute }` objects.
4
+ * Compatible with AI SDK `Tool` and plain `{ execute }` objects.
5
5
  */
6
6
  export interface ExecutableTool {
7
7
  execute: (args: unknown, options?: unknown) => Promise<unknown>;
@@ -9,7 +9,7 @@ export interface ExecutableTool {
9
9
  }
10
10
  /**
11
11
  * Encapsulates tool execution with enforcement, idempotency, and context enrichment.
12
- * Shared by Runtime (text path) and VoiceEngine (audio path).
12
+ * Used by Runtime.
13
13
  */
14
14
  export interface ToolExecutor {
15
15
  /**
@@ -1,14 +1,3 @@
1
- export type { AgentDefinition } from './AgentDefinition.js';
2
1
  export type { ToolExecutor, ExecutableTool } from './ToolExecutor.js';
3
- export type { ConversationState } from './ConversationState.js';
4
- export type { ConversationEventLog, ConversationEvent } from './ConversationEventLog.js';
5
2
  export type { AgentStateController } from './AgentStateController.js';
6
- export { DefaultToolExecutor, ToolTimeoutError } from './DefaultToolExecutor.js';
7
- export type { DefaultToolExecutorConfig } from './DefaultToolExecutor.js';
8
- export { DefaultConversationState } from './DefaultConversationState.js';
9
- export type { DefaultConversationStateConfig } from './DefaultConversationState.js';
10
- export { DefaultConversationEventLog } from './DefaultConversationEventLog.js';
11
- export type { DefaultConversationEventLogConfig } from './DefaultConversationEventLog.js';
12
3
  export { DefaultAgentStateController } from './DefaultAgentStateController.js';
13
- export { createFoundation } from './createFoundation.js';
14
- export type { Foundation, FoundationConfig } from './createFoundation.js';
@@ -1,7 +1,2 @@
1
1
  // Default implementations
2
- export { DefaultToolExecutor, ToolTimeoutError } from './DefaultToolExecutor.js';
3
- export { DefaultConversationState } from './DefaultConversationState.js';
4
- export { DefaultConversationEventLog } from './DefaultConversationEventLog.js';
5
2
  export { DefaultAgentStateController } from './DefaultAgentStateController.js';
6
- // Factory
7
- export { createFoundation } from './createFoundation.js';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { createFlowTransition, createFlowTransitionWithNode, isFlowTransition, createFlowUpdate, isFlowUpdate, } from './flows/index.js';
2
2
  export { SessionManager } from './session/SessionManager.js';
3
3
  export type { SessionStore } from './session/SessionStore.js';
4
+ export { StaleWriteError } from './session/SessionStore.js';
4
5
  export { MemoryStore } from './session/stores/MemoryStore.js';
5
6
  export { reviveSession } from './session/utils.js';
6
7
  export { DEFAULT_CHANNEL_POLICIES, applyChannelPolicy, getDefaultChannelPolicy, resolveChannelPolicy, } from './channels/index.js';
@@ -29,12 +30,6 @@ export type { PromptSection, PromptTemplate, ToolGuideline } from './prompts/ind
29
30
  export { BuiltinPersonas, composePersonaPrompt } from './persona/index.js';
30
31
  export { resolvePersonaExperiment } from './persona/index.js';
31
32
  export type { PersonaConfig, PersonaExperimentCohort, PersonaExperimentConfig, PersonaExperimentMetadata, PersonaExperimentResolution, PersonaLanguagePolicy, PersonaRegister, PersonaVoice, } from './persona/index.js';
32
- export { HookRunner, createHookRunner } from './hooks/HookRunner.js';
33
- export { loggingHooks, createLoggingHooks } from './hooks/builtin/logging.js';
34
- export { createMetricsHooks, InMemoryMetrics } from './hooks/builtin/metrics.js';
35
- export type { Metrics } from './hooks/builtin/metrics.js';
36
- export { createObservabilityHooks } from './hooks/builtin/observability.js';
37
- export type { ObservabilityConfig } from './hooks/builtin/observability.js';
38
33
  export type { SessionTrace, TraceStreamEvent } from './types/telemetry.js';
39
34
  export { createPromptInjectionGuard } from './processors/builtin/promptInjectionGuard.js';
40
35
  export type { PromptInjectionGuardOptions } from './processors/builtin/promptInjectionGuard.js';
@@ -75,8 +70,8 @@ export { applyPromptCache, applyAnthropicCacheControl, buildOpenAIResponsesProvi
75
70
  export type { AnthropicCacheTtl, OpenAIResponsesCompactOptions } from './runtime/promptCache.js';
76
71
  export { handoffFilters, removeToolHistory, keepRecentMessages, removeKeys, composeFilters, } from './runtime/handoffFilters.js';
77
72
  export type { HandoffInputFilter, HandoffInputData, HandoffInputResult, } from './runtime/handoffFilters.js';
78
- export { DefaultToolExecutor, DefaultConversationState, DefaultConversationEventLog, DefaultAgentStateController, createFoundation, } from './foundation/index.js';
79
- export type { ToolExecutor, ConversationState, ConversationEventLog, ConversationEvent, AgentStateController, Foundation, FoundationConfig, } from './foundation/index.js';
73
+ export { DefaultAgentStateController } from './foundation/index.js';
74
+ export type { ToolExecutor, AgentStateController, } from './foundation/index.js';
80
75
  export type * from './types/index.js';
81
76
  export { CapabilityHost, ExtractionCapability, GuardrailCapability, AutoRetrieveCapability, PassThroughRefinement, PassThroughValidation, toGeminiDeclarations, toAISDKTools, } from './capabilities/index.js';
82
77
  export type { Capability, CapabilityAction, ExtractionToolResponseEnvelope, FlowReconfigureTransition, ToolDeclaration, PromptSection as CapabilityPromptSection, GeminiFunctionDeclaration, ExtractionCapabilityConfig, RetrieveProvider, AutoRetrieveCapabilityConfig, RefinementCapability, RefineInput, RefineDecision, ValidationCapability, ValidateInput, ValidateDecision, SourceRef, } from './capabilities/index.js';
@@ -86,9 +81,7 @@ export { createInProcessScheduler, createWakeJobRunner, createScheduleFollowupTo
86
81
  export type { Scheduler, ScheduledJob, InjectableTimer, WakeOptions, WakeJobPayload, WakeDelivery, WakeRunnable, } from './scheduler/index.js';
87
82
  export { filterAuditEntries } from './audit/index.js';
88
83
  export type { AuditConfig, AuditEntryBase, AuditEntryType, AuditListOptions, AuditReplayOptions, ConversationAuditEntry, ConversationAuditLog, } from './audit/types.js';
89
- export type { RealtimeAudioClient, RealtimeSessionConfig, RealtimeAudioConfig, RealtimeToolResponse, RealtimeEventMap, RealtimeSessionHandle, } from './realtime/index.js';
90
84
  export type { Hooks } from './types/hooks.js';
91
- export type { HarnessHooks } from './types/runtime.js';
92
85
  export { defineAgent, defineFlow, reply, collect, action, decide, confirmGate, } from './authoring/index.js';
93
86
  export { defineTool } from './types/effectTool.js';
94
87
  export { fsErrorCode } from './types/filesystem.js';
@@ -97,8 +90,8 @@ export type { CreateFsToolOptions, GrepHit } from './tools/fs/createFsTool.js';
97
90
  export { createShellTool } from './tools/fs/createShellTool.js';
98
91
  export type { CreateShellToolOptions } from './tools/fs/createShellTool.js';
99
92
  export type { Shell, ShellResult, ShellExecOptions } from './types/shell.js';
100
- export { SkillsCapability, wireAgentSkills, collectRegisteredNames, validateSkillAllowedTools, prepareSkillStore, isSkillStore, InlineSkillStore, } from './skills/index.js';
101
- export type { WiredAgentSkills, SkillWireAgent } from './skills/index.js';
93
+ export { SkillsCapability, wireAgentSkills, collectRegisteredNames, validateSkillAllowedTools, prepareSkillStore, isSkillStore, InlineSkillStore, CompositeSkillStore, fsSkillStore, defineSkill, parseSkillFrontmatter, } from './skills/index.js';
94
+ export type { WiredAgentSkills, SkillWireAgent, DefineSkillConfig, ParsedSkill, } from './skills/index.js';
102
95
  export { buildToolSet, toolToAiSdk, wrapAiSdkTool, ToolApprovalDeniedError, ToolTimeoutError, } from './tools/effect/index.js';
103
96
  export type { Tool as EffectTool } from './types/effectTool.js';
104
97
  export type { AgentRoute } from './types/processors.js';
@@ -107,8 +100,15 @@ export type { Flow, FlowNode, Transition, CollectNode, DecideNode, ConfirmGate,
107
100
  export { parseConfirmation } from './flow/confirmParse.js';
108
101
  export type { ConfirmVerdict } from './flow/confirmParse.js';
109
102
  export type { Route } from './types/route.js';
110
- export type { TurnHandle } from './types/stream.js';
111
- export type { HarnessStreamPart } from './types/stream.js';
103
+ export { PART_CHANNEL } from './types/stream.js';
104
+ export type { StreamChannel, StreamPartBase, TextStartPayload, TextDeltaPayload, TextEndPayload, TextCancelPayload, ToolCallPayload, ToolResultPayload, FlowEnterPayload, FlowEndPayload, NodeEnterPayload, NodeExitPayload, FlowTransitionPayload, HandoffPayload, InterruptedPayload, PausedPayload, ConversationOutcomePayload, InteractivePayload, TurnEndPayload, PipelineValidationBlockPayload, SafetyBlockedPayload, WakePayload, EscalationPayload, ContextCompactedPayload, CompactionSkippedPayload, ContextOverflowRecoveredPayload, ErrorPayload, CustomPayload, DonePayload, KnowledgeCacheHitPayload, KnowledgeCacheMissPayload, KnowledgeSearchPayload, KnowledgeQualityCheckPayload, KnowledgeReformulationPayload, StreamPart, TurnHandle, } from './types/stream.js';
105
+ export type { AgentSpan, AgentTrace, SpanKind } from './types/trace.js';
106
+ export { MemoryTraceStore, isTraceStore, type MemoryTraceStoreOptions, type TraceListWindow, type TraceSink, type TraceStore, } from './tracing/index.js';
107
+ export { OtelTraceSink, langfuseSink, otelSink, toOtlpPayload, type LangfuseSinkOptions, type OtelTraceSinkOptions, } from './tracing/index.js';
108
+ export { TraceRecorder, runOnce, type TraceRecorderOptions } from './runtime/TraceRecorder.js';
109
+ export { TracingService } from './services/TracingService.js';
110
+ export { InMemoryMetricsService } from './services/MetricsService.js';
111
+ export type { MetricsService } from './services/MetricsService.js';
112
112
  export { harnessToUIMessageStream } from './ai-sdk/uiMessageStream.js';
113
113
  export type { KuralleMetadata, KuralleDataParts, KuralleUIMessage, } from './ai-sdk/uiMessageStream.js';
114
114
  export type { ChoiceOption, ResolvedSelection } from './types/selection.js';
@@ -119,7 +119,7 @@ export type { ChannelDriver, TextDriver } from './runtime/channels/index.js';
119
119
  export type { TurnResult } from './types/channel.js';
120
120
  export type { RunContext, ToolContext, ActionContext } from './types/run-context.js';
121
121
  export type { AnyTool } from './types/effectTool.js';
122
- export { createRuntime, Runtime, type HarnessConfig, type RunOptions, } from './runtime/Runtime.js';
122
+ export { createRuntime, Runtime, type HarnessConfig, type RunOptions, type TracingConfig, } from './runtime/Runtime.js';
123
123
  export type { RuntimeLike } from './runtime/RuntimeLike.js';
124
124
  export { userInputToText, mergeUserInputContents, hasMediaParts, transcribeAudioParts, type UserInputContent, } from './runtime/userInput.js';
125
125
  export { setPendingUserInput, consumePendingUserInput, consumeAllPendingUserInput, peekPendingUserInput, hasPendingUserInput, } from './runtime/channels/inputBuffer.js';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { createFlowTransition, createFlowTransitionWithNode, isFlowTransition, createFlowUpdate, isFlowUpdate, } from './flows/index.js';
2
2
  export { SessionManager } from './session/SessionManager.js';
3
+ export { StaleWriteError } from './session/SessionStore.js';
3
4
  export { MemoryStore } from './session/stores/MemoryStore.js';
4
5
  export { reviveSession } from './session/utils.js';
5
6
  export { DEFAULT_CHANNEL_POLICIES, applyChannelPolicy, getDefaultChannelPolicy, resolveChannelPolicy, } from './channels/index.js';
@@ -17,10 +18,6 @@ export { createLoadMemoryTool } from './tools/memory.js';
17
18
  export { PromptTemplateBuilder, PromptBuilder, createPromptTemplate, SUPPORT_AGENT_TEMPLATE, SALES_AGENT_TEMPLATE, TRIAGE_AGENT_TEMPLATE, createSupportAgentTemplate, DEFAULT_HANDOFF_INSTRUCTION, } from './prompts/index.js';
18
19
  export { BuiltinPersonas, composePersonaPrompt } from './persona/index.js';
19
20
  export { resolvePersonaExperiment } from './persona/index.js';
20
- export { HookRunner, createHookRunner } from './hooks/HookRunner.js';
21
- export { loggingHooks, createLoggingHooks } from './hooks/builtin/logging.js';
22
- export { createMetricsHooks, InMemoryMetrics } from './hooks/builtin/metrics.js';
23
- export { createObservabilityHooks } from './hooks/builtin/observability.js';
24
21
  export { createPromptInjectionGuard } from './processors/builtin/promptInjectionGuard.js';
25
22
  export { createPiiInputGuard, createPiiOutputGuard, redactPii, } from './processors/builtin/piiGuard.js';
26
23
  export { createModerationGuard, createModerationOutputGuard, } from './processors/builtin/moderationGuard.js';
@@ -44,7 +41,7 @@ export { compactMessages, estimateMessagesTokens, DEFAULT_COMPACTION_TRIGGER_TOK
44
41
  export { isContextOverflowError, recoverFromContextOverflow, } from './runtime/contextOverflow.js';
45
42
  export { applyPromptCache, applyAnthropicCacheControl, buildOpenAIResponsesProviderOptions, isAnthropicLanguageModel, isOpenAIResponsesModel, } from './runtime/promptCache.js';
46
43
  export { handoffFilters, removeToolHistory, keepRecentMessages, removeKeys, composeFilters, } from './runtime/handoffFilters.js';
47
- export { DefaultToolExecutor, DefaultConversationState, DefaultConversationEventLog, DefaultAgentStateController, createFoundation, } from './foundation/index.js';
44
+ export { DefaultAgentStateController } from './foundation/index.js';
48
45
  export { CapabilityHost, ExtractionCapability, GuardrailCapability, AutoRetrieveCapability, PassThroughRefinement, PassThroughValidation, toGeminiDeclarations, toAISDKTools, } from './capabilities/index.js';
49
46
  export { buildEscalationRequest, ensureSessionMetadata } from './escalation/escalation.js';
50
47
  export { createInProcessScheduler, createWakeJobRunner, createScheduleFollowupTool, wakeJob, isWakeJob, WAKE_JOB_KIND, } from './scheduler/index.js';
@@ -54,9 +51,15 @@ export { defineTool } from './types/effectTool.js';
54
51
  export { fsErrorCode } from './types/filesystem.js';
55
52
  export { createFsTool } from './tools/fs/createFsTool.js';
56
53
  export { createShellTool } from './tools/fs/createShellTool.js';
57
- export { SkillsCapability, wireAgentSkills, collectRegisteredNames, validateSkillAllowedTools, prepareSkillStore, isSkillStore, InlineSkillStore, } from './skills/index.js';
54
+ export { SkillsCapability, wireAgentSkills, collectRegisteredNames, validateSkillAllowedTools, prepareSkillStore, isSkillStore, InlineSkillStore, CompositeSkillStore, fsSkillStore, defineSkill, parseSkillFrontmatter, } from './skills/index.js';
58
55
  export { buildToolSet, toolToAiSdk, wrapAiSdkTool, ToolApprovalDeniedError, ToolTimeoutError, } from './tools/effect/index.js';
59
56
  export { parseConfirmation } from './flow/confirmParse.js';
57
+ export { PART_CHANNEL } from './types/stream.js';
58
+ export { MemoryTraceStore, isTraceStore, } from './tracing/index.js';
59
+ export { OtelTraceSink, langfuseSink, otelSink, toOtlpPayload, } from './tracing/index.js';
60
+ export { TraceRecorder, runOnce } from './runtime/TraceRecorder.js';
61
+ export { TracingService } from './services/TracingService.js';
62
+ export { InMemoryMetricsService } from './services/MetricsService.js';
60
63
  export { harnessToUIMessageStream } from './ai-sdk/uiMessageStream.js';
61
64
  export { DURABLE_RUNS_KEY } from './runtime/durable/types.js';
62
65
  export { createRuntime, Runtime, } from './runtime/Runtime.js';
@@ -1,3 +1,3 @@
1
- import type { HarnessStreamPart } from '../types/voice.js';
1
+ import type { StreamPart } from '../types/stream.js';
2
2
  import type { ConversationOutcomeRecord } from './types.js';
3
- export declare function toConversationOutcomeStreamPart(record: ConversationOutcomeRecord): HarnessStreamPart;
3
+ export declare function toConversationOutcomeStreamPart(record: ConversationOutcomeRecord): StreamPart;
@@ -1,8 +1,7 @@
1
1
  export function toConversationOutcomeStreamPart(record) {
2
2
  return {
3
+ channel: 'client',
3
4
  type: 'conversation-outcome',
4
- outcome: record.outcome,
5
- ...(record.reason ? { reason: record.reason } : {}),
6
- markedBy: record.markedBy,
5
+ payload: { outcome: record.outcome },
7
6
  };
8
7
  }
@@ -1,5 +1,5 @@
1
1
  import type { ToolSet } from '../tools/Tool.js';
2
- import type { PromptTemplate, PromptBuilderConfig, BrandVoiceConfig, KnowledgeContext, SessionMemory, AgentDefinition, PolicyProfile } from './types.js';
2
+ import type { PromptTemplate, PromptBuilderConfig, BrandVoiceConfig, KnowledgeContext, SessionMemory, AgentIdentity, PolicyProfile } from './types.js';
3
3
  import { type PersonaConfig } from '../persona/index.js';
4
4
  export declare class PromptBuilder {
5
5
  private config;
@@ -10,7 +10,7 @@ export declare class PromptBuilder {
10
10
  */
11
11
  constructor(config?: PromptBuilderConfig | PromptTemplate);
12
12
  withTemplate(template: PromptTemplate): this;
13
- withAgentDefinition(definition: AgentDefinition): this;
13
+ withAgentIdentity(identity: AgentIdentity): this;
14
14
  withBrandVoice(brandVoice: BrandVoiceConfig): this;
15
15
  withPersona(persona: PersonaConfig): this;
16
16
  addPersona(persona: PersonaConfig): this;
@@ -19,7 +19,7 @@ export declare class PromptBuilder {
19
19
  withKnowledgeContext(context: KnowledgeContext): this;
20
20
  withPolicyProfile(profile: PolicyProfile): this;
21
21
  build(): string;
22
- private buildAgentDefinitionSections;
22
+ private buildAgentIdentitySections;
23
23
  private buildPersonaSections;
24
24
  private buildBrandVoiceSections;
25
25
  private buildKnowledgeSections;
@@ -22,8 +22,8 @@ export class PromptBuilder {
22
22
  this.config.template = template;
23
23
  return this;
24
24
  }
25
- withAgentDefinition(definition) {
26
- this.config.agentDefinition = definition;
25
+ withAgentIdentity(identity) {
26
+ this.config.agentIdentity = identity;
27
27
  return this;
28
28
  }
29
29
  withBrandVoice(brandVoice) {
@@ -63,8 +63,8 @@ export class PromptBuilder {
63
63
  immutable: true,
64
64
  });
65
65
  // Layer 1: Agent Definition
66
- if (this.config.agentDefinition) {
67
- sections.push(...this.buildAgentDefinitionSections());
66
+ if (this.config.agentIdentity) {
67
+ sections.push(...this.buildAgentIdentitySections());
68
68
  }
69
69
  if (this.config.persona) {
70
70
  sections.push(...this.buildPersonaSections());
@@ -100,8 +100,8 @@ export class PromptBuilder {
100
100
  const sorted = sections.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
101
101
  return sorted.map(s => this.formatSection(s)).join('\n\n');
102
102
  }
103
- buildAgentDefinitionSections() {
104
- const def = this.config.agentDefinition;
103
+ buildAgentIdentitySections() {
104
+ const def = this.config.agentIdentity;
105
105
  const sections = [];
106
106
  sections.push({
107
107
  type: 'identity',
@@ -235,6 +235,13 @@ export class PromptBuilder {
235
235
  priority: LAYER_PRIORITIES.CONVERSATION_SUMMARY,
236
236
  });
237
237
  }
238
+ if (memory.openGoalsPrompt) {
239
+ sections.push({
240
+ type: 'conversation_summary',
241
+ content: memory.openGoalsPrompt,
242
+ priority: LAYER_PRIORITIES.CONVERSATION_SUMMARY,
243
+ });
244
+ }
238
245
  return sections;
239
246
  }
240
247
  formatSection(section) {
@@ -1,4 +1,4 @@
1
- export type { PromptSection, PromptTemplate, ToolGuideline, PromptTemplateBuilderOptions, PromptSectionType, VoiceRulesConfig, VoiceRules, GlossaryTerm, GlossaryConfig, BrandVoiceConfig, KnowledgeContext, SessionMemory, AgentDefinition, PolicyProfile, PromptBuilderConfig, } from './types.js';
1
+ export type { PromptSection, PromptTemplate, ToolGuideline, PromptTemplateBuilderOptions, PromptSectionType, VoiceRulesConfig, VoiceRules, GlossaryTerm, GlossaryConfig, BrandVoiceConfig, KnowledgeContext, SessionMemory, AgentIdentity, PolicyProfile, PromptBuilderConfig, } from './types.js';
2
2
  export { PromptTemplateBuilder, createPromptTemplate, LAYER_PRIORITIES } from './types.js';
3
3
  export { PromptBuilder, createPrompt } from './PromptBuilder.js';
4
4
  export { SUPPORT_AGENT_TEMPLATE, SALES_AGENT_TEMPLATE, TRIAGE_AGENT_TEMPLATE, createSupportAgentTemplate, BUILTIN_TEMPLATES, DEFAULT_HANDOFF_INSTRUCTION, } from './templates.js';
@@ -49,15 +49,22 @@ export interface SessionMemory {
49
49
  label: string;
50
50
  content: string;
51
51
  }>;
52
+ /** Compact open-thread note projected from session.workingMemory.__goals (G5). */
53
+ openGoalsPrompt?: string;
52
54
  }
53
- export interface AgentDefinition {
55
+ /**
56
+ * Who the agent is, rendered into the `identity` / `role` / `capabilities` prompt
57
+ * sections by `PromptBuilder`. A prompt fragment — not the agent itself, which is
58
+ * `AgentConfig` from `defineAgent`.
59
+ */
60
+ export interface AgentIdentity {
54
61
  identity: string;
55
62
  role: string;
56
63
  capabilities?: string[];
57
64
  }
58
65
  export interface PromptBuilderConfig {
59
66
  template?: PromptTemplate;
60
- agentDefinition?: AgentDefinition;
67
+ agentIdentity?: AgentIdentity;
61
68
  persona?: PersonaConfig;
62
69
  brandVoice?: BrandVoiceConfig;
63
70
  knowledgeContext?: KnowledgeContext;
@@ -0,0 +1,25 @@
1
+ import type { KnowledgeRetrievalResult, RetrievalCacheAdapter } from '../types/knowledge.js';
2
+ /**
3
+ * Zero-config, in-process session retrieval cache (G6). Keyed by the query
4
+ * embedding: a lookup returns the cached results of the most-similar recent
5
+ * query (cosine ≥ threshold, within TTL). LRU-bounded. Needs only the embedder
6
+ * the KnowledgeProvider already requires — no external dependency. Apps that
7
+ * want a shared/vector-backed cache can inject their own `RetrievalCacheAdapter`
8
+ * via the KnowledgeProvider's `cacheFactory` instead.
9
+ */
10
+ export interface InMemoryRetrievalCacheOptions {
11
+ maxEntries?: number;
12
+ ttlMs?: number;
13
+ similarityThreshold?: number;
14
+ }
15
+ export declare class InMemoryRetrievalCache implements RetrievalCacheAdapter {
16
+ /** Ordered oldest → newest (LRU front, MRU back). */
17
+ private entries;
18
+ private readonly maxEntries;
19
+ private readonly ttlMs;
20
+ private readonly threshold;
21
+ constructor(options?: InMemoryRetrievalCacheOptions);
22
+ get size(): number;
23
+ lookup(queryEmbedding: readonly number[], topK?: number): KnowledgeRetrievalResult[];
24
+ populate(results: KnowledgeRetrievalResult[], queryEmbedding?: readonly number[]): void;
25
+ }