melony 0.1.25 → 0.1.28

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.
@@ -102,6 +102,13 @@ var ui = {
102
102
  };
103
103
 
104
104
  // src/runtime.ts
105
+ var RuntimeInterruption = class extends Error {
106
+ constructor(event) {
107
+ super("Runtime interrupted");
108
+ this.event = event;
109
+ this.name = "RuntimeInterruption";
110
+ }
111
+ };
105
112
  var Runtime = class {
106
113
  constructor(config) {
107
114
  this.config = config;
@@ -112,17 +119,31 @@ var Runtime = class {
112
119
  state: input.state ?? {},
113
120
  runId,
114
121
  stepCount: 0,
115
- isDone: false,
116
122
  actions: this.config.actions,
117
123
  ui,
118
- suspend: () => {
119
- context.isDone = true;
124
+ suspend: (event) => {
125
+ throw new RuntimeInterruption(event);
120
126
  }
121
127
  };
122
- let nextAction = void 0;
123
- for (const plugin2 of this.config.plugins || []) {
124
- if (plugin2.onBeforeRun) {
125
- const result = await plugin2.onBeforeRun(
128
+ try {
129
+ let nextAction = void 0;
130
+ for (const plugin2 of this.config.plugins || []) {
131
+ if (plugin2.onBeforeRun) {
132
+ const result = await plugin2.onBeforeRun(
133
+ { event: input.event, runId, state: context.state },
134
+ context
135
+ );
136
+ if (result) {
137
+ if ("type" in result) {
138
+ yield* this.emit(result, context);
139
+ } else {
140
+ nextAction = result;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ if (this.config.hooks?.onBeforeRun) {
146
+ const result = await this.config.hooks.onBeforeRun(
126
147
  { event: input.event, runId, state: context.state },
127
148
  context
128
149
  );
@@ -134,79 +155,72 @@ var Runtime = class {
134
155
  }
135
156
  }
136
157
  }
137
- }
138
- if (this.config.hooks?.onBeforeRun) {
139
- const result = await this.config.hooks.onBeforeRun(
140
- { event: input.event, runId, state: context.state },
158
+ yield* this.emit(
159
+ { type: "run-started", data: { inputEvent: input.event } },
141
160
  context
142
161
  );
143
- if (result) {
144
- if ("type" in result) {
145
- yield* this.emit(result, context);
162
+ if (!nextAction && this.config.brain) {
163
+ nextAction = yield* this.dispatchToBrain(input.event, context);
164
+ }
165
+ while (nextAction) {
166
+ if (context.stepCount++ >= (this.config.safetyMaxSteps ?? 10)) {
167
+ yield* this.emit(
168
+ { type: "error", data: { message: "Max steps exceeded" } },
169
+ context
170
+ );
171
+ break;
172
+ }
173
+ const current = nextAction;
174
+ nextAction = void 0;
175
+ const actionName = current.action ?? Object.keys(this.config.actions)[0];
176
+ const action2 = this.config.actions[actionName];
177
+ if (!action2) {
178
+ yield* this.emit(
179
+ {
180
+ type: "error",
181
+ data: { message: `Action ${actionName} not found` }
182
+ },
183
+ context
184
+ );
185
+ break;
186
+ }
187
+ const result = yield* this.executeAction(action2, current, context);
188
+ if (this.config.brain) {
189
+ nextAction = yield* this.dispatchToBrain(
190
+ {
191
+ type: "action-result",
192
+ data: {
193
+ ...current,
194
+ // Preserve all metadata (like toolCallId)
195
+ action: actionName,
196
+ params: current.params,
197
+ result
198
+ }
199
+ },
200
+ context
201
+ );
146
202
  } else {
147
203
  nextAction = result;
148
204
  }
149
205
  }
150
- }
151
- if (context.isDone) return;
152
- yield* this.emit(
153
- { type: "run-started", data: { inputEvent: input.event } },
154
- context
155
- );
156
- if (!nextAction && this.config.brain) {
157
- nextAction = yield* this.dispatchToBrain(input.event, context);
158
- }
159
- while (nextAction && !context.isDone) {
160
- if (context.stepCount++ >= (this.config.safetyMaxSteps ?? 10)) {
161
- yield* this.emit(
162
- { type: "error", data: { message: "Max steps exceeded" } },
163
- context
164
- );
165
- break;
166
- }
167
- const current = nextAction;
168
- nextAction = void 0;
169
- const actionName = current.action ?? Object.keys(this.config.actions)[0];
170
- const action2 = this.config.actions[actionName];
171
- if (!action2) {
172
- yield* this.emit(
173
- {
174
- type: "error",
175
- data: { message: `Action ${actionName} not found` }
176
- },
177
- context
178
- );
179
- break;
180
- }
181
- const result = yield* this.executeAction(action2, current, context);
182
- if (context.isDone) break;
183
- if (this.config.brain) {
184
- nextAction = yield* this.dispatchToBrain(
185
- {
186
- type: "action-result",
187
- data: {
188
- ...current,
189
- // Preserve all metadata (like toolCallId)
190
- action: actionName,
191
- params: current.params,
192
- result
193
- }
194
- },
195
- context
196
- );
197
- } else {
198
- nextAction = result;
206
+ for (const plugin2 of this.config.plugins || []) {
207
+ if (plugin2.onAfterRun) {
208
+ const extra = await plugin2.onAfterRun(context);
209
+ if (extra) yield* this.emit(extra, context);
210
+ }
199
211
  }
200
- }
201
- for (const plugin2 of this.config.plugins || []) {
202
- if (plugin2.onAfterRun) {
203
- const extra = await plugin2.onAfterRun(context);
212
+ if (this.config.hooks?.onAfterRun) {
213
+ const extra = await this.config.hooks.onAfterRun(context);
204
214
  if (extra) yield* this.emit(extra, context);
205
215
  }
206
- }
207
- if (this.config.hooks?.onAfterRun) {
208
- const extra = await this.config.hooks.onAfterRun(context);
209
- if (extra) yield* this.emit(extra, context);
216
+ } catch (error) {
217
+ if (error instanceof RuntimeInterruption) {
218
+ if (error.event) {
219
+ yield* this.emit(error.event, context);
220
+ }
221
+ return;
222
+ }
223
+ throw error;
210
224
  }
211
225
  }
212
226
  async *dispatchToBrain(event, context) {
@@ -227,7 +241,6 @@ var Runtime = class {
227
241
  );
228
242
  if (hookResult) {
229
243
  yield* this.emit(hookResult, context);
230
- if (context.isDone) return;
231
244
  }
232
245
  }
233
246
  }
@@ -238,7 +251,6 @@ var Runtime = class {
238
251
  );
239
252
  if (hookResult) {
240
253
  yield* this.emit(hookResult, context);
241
- if (context.isDone) return;
242
254
  }
243
255
  }
244
256
  try {
@@ -251,7 +263,6 @@ var Runtime = class {
251
263
  break;
252
264
  }
253
265
  yield* this.emit(value, context);
254
- if (context.isDone) return;
255
266
  }
256
267
  for (const plugin2 of this.config.plugins || []) {
257
268
  if (plugin2.onAfterAction) {
@@ -271,6 +282,7 @@ var Runtime = class {
271
282
  }
272
283
  return result;
273
284
  } catch (error) {
285
+ if (error instanceof RuntimeInterruption) throw error;
274
286
  yield* this.emit(
275
287
  {
276
288
  type: "error",
@@ -321,6 +333,6 @@ var melony = (config) => {
321
333
  var action = (config) => config;
322
334
  var plugin = (config) => config;
323
335
 
324
- export { Runtime, action, melony, plugin, ui };
325
- //# sourceMappingURL=chunk-GTBFMQGD.js.map
326
- //# sourceMappingURL=chunk-GTBFMQGD.js.map
336
+ export { Runtime, RuntimeInterruption, action, melony, plugin, ui };
337
+ //# sourceMappingURL=chunk-LECAXAQJ.js.map
338
+ //# sourceMappingURL=chunk-LECAXAQJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/runtime.ts"],"names":["plugin","action"],"mappings":";;;AAiLO,IAAM,EAAA,GAAK;AAAA,EAChB,IAAA,EAAM,CACJ,KAAA,KACmB;AACnB,IAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,KAAA,EAAO,MAAM,QAAA,EAAS;AAAA,EAC/C,CAAA;AAAA,EACA,GAAA,EAAK,CACH,KAAA,KACkB;AAClB,IAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,MAAM,QAAA,EAAS;AAAA,EAC9C,CAAA;AAAA,EACA,GAAA,EAAK,CACH,KAAA,KACkB;AAClB,IAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,MAAM,QAAA,EAAS;AAAA,EAC9C,CAAA;AAAA,EACA,GAAA,EAAK,CACH,KAAA,KACkB;AAClB,IAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,MAAM,QAAA,EAAS;AAAA,EAC9C,CAAA;A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;AAAA,IACA,GAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,IAAA,CAAK,OAAO;AAAA,GAC/B;AACF;AAKO,IAAM,MAAA,GAAS,CAAwB,MAAA,KAC5C;AAKK,IAAM,MAAA,GAAS,CAAC,MAAA,KAA2B","file":"chunk-LECAXAQJ.js","sourcesContent":["import z from \"zod\";\n\n// ============================================\n// UI Protocol & Contracts\n// ============================================\n\nexport type UISize = \"sm\" | \"md\" | \"lg\";\nexport type UIAlign = \"start\" | \"center\" | \"end\" | \"stretch\";\nexport type UIJustify = \"start\" | \"center\" | \"end\" | \"between\" | \"around\";\nexport type UIWrap = \"nowrap\" | \"wrap\" | \"wrap-reverse\";\nexport type UIOrientation = \"horizontal\" | \"vertical\";\n\nexport type UIColor =\n | \"primary\"\n | \"secondary\"\n | \"success\"\n | \"danger\"\n | \"warning\"\n | \"info\"\n | \"background\"\n | \"foreground\"\n | \"muted\"\n | \"mutedForeground\"\n | \"border\";\n\nexport type UISpacing = \"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | \"xxl\";\n\n/**\n * UI Component Contracts\n * This acts as the source of truth for the SDUI protocol.\n */\nexport interface UIContract {\n card: {\n title?: string;\n subtitle?: string;\n background?: string;\n isLoading?: boolean;\n };\n row: {\n align?: UIAlign;\n justify?: UIJustify;\n wrap?: UIWrap;\n gap?: UISpacing;\n };\n col: {\n align?: UIAlign;\n justify?: UIJustify;\n gap?: UISpacing;\n width?: string | number;\n height?: string | number;\n padding?: UISpacing;\n };\n box: {\n padding?: UISpacing;\n margin?: string | number;\n background?: string;\n border?: boolean;\n borderRadius?: UISpacing;\n width?: string | number;\n height?: string | number;\n };\n spacer: {\n size?: UISpacing;\n direction?: UIOrientation;\n };\n divider: {\n orientation?: UIOrientation;\n color?: UIColor;\n };\n text: {\n value: string;\n size?: UISpacing;\n weight?: \"normal\" | \"medium\" | \"semibold\" | \"bold\";\n color?: UIColor;\n align?: UIAlign;\n };\n heading: {\n value: string;\n level?: 1 | 2 | 3 | 4 | 5 | 6;\n };\n badge: {\n label: string;\n variant?: \"primary\" | \"secondary\" | \"success\" | \"danger\" | \"warning\";\n size?: UISize;\n };\n image: {\n src: string;\n alt?: string;\n size?: UISize;\n };\n icon: {\n name: string;\n size?: UISize;\n color?: UIColor;\n };\n chart: {\n data: Array<{ label: string; value: number; color?: string }>;\n chartType?: \"bar\" | \"line\" | \"area\" | \"pie\";\n title?: string;\n };\n list: {};\n listItem: {\n onClickAction?: Event;\n gap?: UISpacing;\n };\n form: {\n onSubmitAction?: Event;\n };\n input: {\n name: string;\n label?: string;\n placeholder?: string;\n defaultValue?: string;\n inputType?: string;\n onChangeAction?: Event;\n };\n textarea: {\n name: string;\n label?: string;\n placeholder?: string;\n defaultValue?: string;\n rows?: number;\n onChangeAction?: Event;\n };\n select: {\n name: string;\n label?: string;\n options: Array<{ label: string; value: string }>;\n defaultValue?: string;\n placeholder?: string;\n onChangeAction?: Event;\n };\n checkbox: {\n name: string;\n label?: string;\n checked?: boolean;\n onChangeAction?: Event;\n };\n radioGroup: {\n name: string;\n options: Array<{ label: string; value: string; disabled?: boolean }>;\n label?: string;\n defaultValue?: string;\n orientation?: UIOrientation;\n onChangeAction?: Event;\n };\n label: {\n value: string;\n htmlFor?: string;\n required?: boolean;\n };\n button: {\n label: string;\n variant?:\n | \"primary\"\n | \"secondary\"\n | \"success\"\n | \"danger\"\n | \"outline\"\n | \"ghost\"\n | \"link\";\n size?: UISize;\n disabled?: boolean;\n onClickAction?: Event;\n };\n}\n\nexport type UINode<T extends keyof UIContract = keyof UIContract> = {\n type: T;\n props?: UIContract[T];\n children?: UINode<any>[];\n};\n\n/**\n * UI Builder for SDUI.\n * Typed using the UIContract source of truth.\n */\nexport const ui = {\n card: (\n props: UIContract[\"card\"] & { children?: UINode<any>[] }\n ): UINode<\"card\"> => {\n const { children, ...rest } = props;\n return { type: \"card\", props: rest, children };\n },\n row: (\n props: UIContract[\"row\"] & { children?: UINode<any>[] }\n ): UINode<\"row\"> => {\n const { children, ...rest } = props;\n return { type: \"row\", props: rest, children };\n },\n col: (\n props: UIContract[\"col\"] & { children?: UINode<any>[] }\n ): UINode<\"col\"> => {\n const { children, ...rest } = props;\n return { type: \"col\", props: rest, children };\n },\n box: (\n props: UIContract[\"box\"] & { children?: UINode<any>[] }\n ): UINode<\"box\"> => {\n const { children, ...rest } = props;\n return { type: \"box\", props: rest, children };\n },\n spacer: (props: UIContract[\"spacer\"]): UINode<\"spacer\"> => ({\n type: \"spacer\",\n props,\n }),\n divider: (props: UIContract[\"divider\"]): UINode<\"divider\"> => ({\n type: \"divider\",\n props,\n }),\n text: (\n value: string,\n props?: Omit<UIContract[\"text\"], \"value\">\n ): UINode<\"text\"> => ({\n type: \"text\",\n props: { ...props, value },\n }),\n heading: (\n value: string,\n level: UIContract[\"heading\"][\"level\"] = 1\n ): UINode<\"heading\"> => ({\n type: \"heading\",\n props: { value, level },\n }),\n badge: (\n label: string,\n variant: UIContract[\"badge\"][\"variant\"] = \"primary\",\n size: UISize = \"md\"\n ): UINode<\"badge\"> => ({\n type: \"badge\",\n props: { label, variant, size },\n }),\n image: (src: string, alt?: string, size: UISize = \"md\"): UINode<\"image\"> => ({\n type: \"image\",\n props: { src, alt, size },\n }),\n icon: (\n name: string,\n size: UISize = \"md\",\n color?: UIColor\n ): UINode<\"icon\"> => ({\n type: \"icon\",\n props: { name, size, color },\n }),\n chart: (props: UIContract[\"chart\"]): UINode<\"chart\"> => ({\n type: \"chart\",\n props,\n }),\n list: (children: UINode<any>[]): UINode<\"list\"> => ({\n type: \"list\",\n children,\n }),\n listItem: (\n props: UIContract[\"listItem\"] & { children: UINode<any>[] }\n ): UINode<\"listItem\"> => {\n const { children, ...rest } = props;\n return { type: \"listItem\", props: rest, children };\n },\n form: (\n props: UIContract[\"form\"] & { children?: UINode<any>[] }\n ): UINode<\"form\"> => {\n const { children, ...rest } = props;\n return { type: \"form\", props: rest, children };\n },\n input: (props: UIContract[\"input\"]): UINode<\"input\"> => ({\n type: \"input\",\n props,\n }),\n textarea: (props: UIContract[\"textarea\"]): UINode<\"textarea\"> => ({\n type: \"textarea\",\n props,\n }),\n select: (props: UIContract[\"select\"]): UINode<\"select\"> => ({\n type: \"select\",\n props,\n }),\n checkbox: (props: UIContract[\"checkbox\"]): UINode<\"checkbox\"> => ({\n type: \"checkbox\",\n props,\n }),\n radioGroup: (props: UIContract[\"radioGroup\"]): UINode<\"radioGroup\"> => ({\n type: \"radioGroup\",\n props,\n }),\n label: (\n value: string,\n props?: Omit<UIContract[\"label\"], \"value\">\n ): UINode<\"label\"> => ({\n type: \"label\",\n props: { ...props, value },\n }),\n button: (props: UIContract[\"button\"]): UINode<\"button\"> => ({\n type: \"button\",\n props,\n }),\n actions: {\n navigate: (url: string): Event => ({ type: \"client:navigate\", data: { url } }),\n openUrl: (url: string, target = \"_blank\"): Event => ({\n type: \"client:open-url\",\n data: { url, target },\n }),\n copy: (text: string): Event => ({ type: \"client:copy\", data: { text } }),\n reset: (): Event => ({ type: \"client:reset\" }),\n },\n};\n\n// ============================================\n// Events\n// ============================================\n\nexport type Role = \"user\" | \"assistant\" | \"system\";\n\nexport type Event = {\n type: string;\n data?: any;\n ui?: UINode;\n runId?: string;\n threadId?: string;\n timestamp?: number;\n role?: Role;\n state?: any;\n};\n\n// ============================================\n// Runtime & Hooks\n// ============================================\n\nexport interface Action<TParams extends z.ZodSchema = z.ZodObject<any>> {\n name: string;\n description?: string;\n paramsSchema: TParams;\n execute: (\n params: z.infer<TParams>,\n context: RuntimeContext\n ) => AsyncGenerator<Event, NextAction | void, unknown>;\n}\n\nexport interface NextAction {\n action?: string;\n params?: any;\n description?: string;\n [key: string]: any; // Allow metadata like toolCallId\n}\n\nexport interface RuntimeContext<TState = any> {\n state: TState;\n runId: string;\n stepCount: number;\n actions: Record<string, Action<any>>;\n ui: typeof ui;\n /**\n * Immediately interrupts the runtime execution.\n * If an event is provided, it will be emitted before the runtime stops.\n */\n suspend: (event?: Event) => never;\n}\n\n/**\n * Standardized Hook Result for consistent DX.\n */\nexport type HookResult = Promise<Event | void>;\n\nexport interface Hooks {\n /**\n * Called when a run session begins.\n * Can return an Event to be emitted, or a NextAction to jump-start the loop.\n */\n onBeforeRun?: (\n input: { event: Event; runId: string; state: Record<string, any> },\n context: RuntimeContext\n ) => Promise<Event | NextAction | void>;\n\n /**\n * Called when a run session completes.\n */\n onAfterRun?: (context: RuntimeContext) => HookResult;\n\n /**\n * Called whenever an event is yielded by the runtime.\n */\n onEvent?: (event: Event, context: RuntimeContext) => HookResult;\n\n /**\n * Called before an action is executed.\n * Return an event to intercept/suspend the action.\n */\n onBeforeAction?: (\n call: { action: Action<any>; params: any; nextAction: NextAction },\n context: RuntimeContext\n ) => HookResult;\n\n /**\n * Called after an action completes.\n */\n onAfterAction?: (\n result: { action: Action<any>; data: NextAction | void },\n context: RuntimeContext\n ) => HookResult;\n}\n\n/**\n * A plugin is just a named set of hooks.\n */\nexport interface Plugin extends Hooks {\n name: string;\n}\n\nexport interface Config {\n actions: Record<string, Action<any>>;\n /**\n * The central brain for handling incoming events.\n */\n brain?: (\n event: Event,\n context: RuntimeContext\n ) => AsyncGenerator<Event, NextAction | void, unknown>;\n hooks?: Hooks;\n plugins?: Plugin[];\n safetyMaxSteps?: number;\n starterPrompts?: Array<{\n label: string;\n prompt: string;\n icon?: string;\n }>;\n options?: Array<{\n id: string;\n label: string;\n options: Array<{ id: string; label: string; value: any }>;\n type?: \"single\" | \"multiple\";\n defaultSelectedIds?: string[];\n }>;\n fileAttachments?: {\n enabled?: boolean;\n accept?: string; // e.g., \"image/*,.pdf\" for file input accept attribute\n maxFiles?: number; // Maximum number of files allowed\n maxFileSize?: number; // Maximum file size in bytes\n };\n}\n","import {\n Action,\n Event,\n NextAction,\n RuntimeContext,\n Config,\n Plugin,\n ui,\n} from \"./types\";\nimport { generateId } from \"./utils/generate-id\";\nimport { z } from \"zod\";\n\n/**\n * Special error to immediately interrupt the runtime.\n * This is used for Human-In-The-Loop (HITL) or other suspension cases.\n */\nexport class RuntimeInterruption extends Error {\n constructor(public event?: Event) {\n super(\"Runtime interrupted\");\n this.name = \"RuntimeInterruption\";\n }\n}\n\n/**\n * The Slim Runtime.\n * Single Responsibility: Orchestrate Event -> Action -> Event transitions.\n */\nexport class Runtime {\n private config: Config;\n\n constructor(config: Config) {\n this.config = config;\n }\n\n public async *run(input: {\n event: Event;\n runId?: string;\n state?: Record<string, any>;\n }): AsyncGenerator<Event> {\n const runId = input.runId ?? generateId();\n\n const context: RuntimeContext = {\n state: input.state ?? {},\n runId,\n stepCount: 0,\n actions: this.config.actions,\n ui,\n suspend: (event?: Event) => {\n throw new RuntimeInterruption(event);\n },\n };\n\n try {\n let nextAction: NextAction | void = undefined;\n\n // 1. Trigger Plugins: onBeforeRun\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBeforeRun) {\n const result = await plugin.onBeforeRun(\n { event: input.event, runId, state: context.state },\n context\n );\n if (result) {\n if (\"type\" in result) {\n yield* this.emit(result as Event, context);\n } else {\n nextAction = result as NextAction;\n }\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeRun\n if (this.config.hooks?.onBeforeRun) {\n const result = await this.config.hooks.onBeforeRun(\n { event: input.event, runId, state: context.state },\n context\n );\n if (result) {\n if (\"type\" in result) {\n yield* this.emit(result as Event, context);\n } else {\n nextAction = result as NextAction;\n }\n }\n }\n\n yield* this.emit(\n { type: \"run-started\", data: { inputEvent: input.event } },\n context\n );\n\n // Initial dispatch of the incoming event to the agent's brain\n // Only if onBeforeRun didn't already provide a nextAction\n if (!nextAction && this.config.brain) {\n nextAction = yield* this.dispatchToBrain(input.event, context);\n }\n\n // Agentic loop\n while (nextAction) {\n if (context.stepCount++ >= (this.config.safetyMaxSteps ?? 10)) {\n yield* this.emit(\n { type: \"error\", data: { message: \"Max steps exceeded\" } },\n context\n );\n break;\n }\n\n const current: NextAction = nextAction;\n nextAction = undefined; // Reset\n\n // 1. Resolve Action\n const actionName: string =\n current.action ?? Object.keys(this.config.actions)[0];\n const action: Action<any> = this.config.actions[actionName];\n\n if (!action) {\n yield* this.emit(\n {\n type: \"error\",\n data: { message: `Action ${actionName} not found` },\n },\n context\n );\n break;\n }\n\n // 2. Execute Action\n const result = yield* this.executeAction(action, current, context);\n\n // 3. Decide Next Step\n if (this.config.brain) {\n // If we have a brain, feed the result back to it to decide what to do next.\n // This keeps the brain in the loop for multi-step reasoning.\n nextAction = yield* this.dispatchToBrain(\n {\n type: \"action-result\",\n data: {\n ...current, // Preserve all metadata (like toolCallId)\n action: actionName,\n params: current.params,\n result,\n },\n },\n context\n );\n } else {\n // Simple mode: follow the action's own suggestion for the next step.\n nextAction = result;\n }\n }\n\n // 1. Trigger Plugins: onAfterRun\n for (const plugin of this.config.plugins || []) {\n if (plugin.onAfterRun) {\n const extra = await plugin.onAfterRun(context);\n if (extra) yield* this.emit(extra, context);\n }\n }\n\n // 2. Trigger Hook: onAfterRun\n if (this.config.hooks?.onAfterRun) {\n const extra = await this.config.hooks.onAfterRun(context);\n if (extra) yield* this.emit(extra, context);\n }\n } catch (error) {\n if (error instanceof RuntimeInterruption) {\n // If the suspension carried an event, emit it before finishing\n if (error.event) {\n yield* this.emit(error.event, context);\n }\n return;\n }\n throw error;\n }\n }\n\n private async *dispatchToBrain(\n event: Event,\n context: RuntimeContext\n ): AsyncGenerator<Event, NextAction | void> {\n const generator = this.config.brain!(event, context);\n while (true) {\n const { value, done } = await generator.next();\n if (done) return value as NextAction | void;\n yield* this.emit(value as Event, context);\n }\n }\n\n private async *executeAction(\n action: Action,\n nextAction: NextAction,\n context: RuntimeContext\n ): AsyncGenerator<Event, NextAction | void> {\n const params = nextAction.params;\n\n // 1. Trigger Plugins: onBeforeAction\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBeforeAction) {\n const hookResult = await plugin.onBeforeAction(\n { action, params, nextAction },\n context\n );\n if (hookResult) {\n yield* this.emit(hookResult, context);\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeAction\n if (this.config.hooks?.onBeforeAction) {\n const hookResult = await this.config.hooks.onBeforeAction(\n { action, params, nextAction },\n context\n );\n if (hookResult) {\n yield* this.emit(hookResult, context);\n }\n }\n\n try {\n const generator = action.execute(params, context);\n let result: NextAction | void;\n\n while (true) {\n const { value, done } = await generator.next();\n if (done) {\n result = value as NextAction | void;\n break;\n }\n yield* this.emit(value as Event, context);\n }\n\n // 3. Trigger Plugins: onAfterAction\n for (const plugin of this.config.plugins || []) {\n if (plugin.onAfterAction) {\n const extra = await plugin.onAfterAction(\n { action, data: result },\n context\n );\n if (extra) yield* this.emit(extra, context);\n }\n }\n\n // 4. Trigger Hook: onAfterAction\n if (this.config.hooks?.onAfterAction) {\n const extra = await this.config.hooks.onAfterAction(\n { action, data: result },\n context\n );\n if (extra) yield* this.emit(extra, context);\n }\n\n return result;\n } catch (error) {\n if (error instanceof RuntimeInterruption) throw error;\n\n yield* this.emit(\n {\n type: \"error\",\n data: {\n action: action.name,\n error: error instanceof Error ? error.message : String(error),\n },\n },\n context\n );\n }\n }\n\n /**\n * Internal helper to yield an event and trigger the onEvent hook.\n */\n private async *emit(\n event: Event,\n context: RuntimeContext\n ): AsyncGenerator<Event> {\n const finalEvent = {\n ...event,\n runId: context.runId,\n timestamp: event.timestamp ?? Date.now(),\n role: event.role ?? \"assistant\",\n state: context.state,\n };\n\n // Yield the actual event first\n yield finalEvent;\n\n // 1. Trigger Plugins: onEvent\n for (const plugin of this.config.plugins || []) {\n if (plugin.onEvent) {\n const extra = await plugin.onEvent(finalEvent, context);\n if (extra) {\n yield { ...extra, runId: context.runId, timestamp: Date.now() };\n }\n }\n }\n\n // 2. Trigger Hook: onEvent for side-effects or extra events\n if (this.config.hooks?.onEvent) {\n const extra = await this.config.hooks.onEvent(finalEvent, context);\n if (extra) {\n // Yield extra event from hook, ensuring it has required metadata\n yield { ...extra, runId: context.runId, timestamp: Date.now() };\n }\n }\n }\n}\n\nexport const melony = (config: Config) => {\n const runtime = new Runtime(config);\n return {\n config,\n run: runtime.run.bind(runtime),\n };\n};\n\n/**\n * Helper to define an action with full type inference.\n */\nexport const action = <T extends z.ZodSchema>(config: Action<T>): Action<T> =>\n config;\n\n/**\n * Helper to define a plugin.\n */\nexport const plugin = (config: Plugin): Plugin => config;\n"]}
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { E as Event, C as Config } from './types-BggpSdNT.js';
1
+ import { E as Event, C as Config } from './types-CFbiFt1b.js';
2
2
  export { g as generateId } from './generate-id-DU8kwYc2.js';
3
3
  import 'zod';
4
4
 
package/dist/index.d.ts CHANGED
@@ -1,8 +1,16 @@
1
- import { C as Config, E as Event, A as Action, P as Plugin } from './types-BggpSdNT.js';
2
- export { H as HookResult, j as Hooks, N as NextAction, R as Role, i as RuntimeContext, a as UIAlign, e as UIColor, g as UIContract, b as UIJustify, h as UINode, d as UIOrientation, U as UISize, f as UISpacing, c as UIWrap, u as ui } from './types-BggpSdNT.js';
1
+ import { E as Event, C as Config, A as Action, P as Plugin } from './types-CFbiFt1b.js';
2
+ export { H as HookResult, j as Hooks, N as NextAction, R as Role, i as RuntimeContext, a as UIAlign, e as UIColor, g as UIContract, b as UIJustify, h as UINode, d as UIOrientation, U as UISize, f as UISpacing, c as UIWrap, u as ui } from './types-CFbiFt1b.js';
3
3
  import { z } from 'zod';
4
4
  export { g as generateId } from './generate-id-DU8kwYc2.js';
5
5
 
6
+ /**
7
+ * Special error to immediately interrupt the runtime.
8
+ * This is used for Human-In-The-Loop (HITL) or other suspension cases.
9
+ */
10
+ declare class RuntimeInterruption extends Error {
11
+ event?: Event | undefined;
12
+ constructor(event?: Event | undefined);
13
+ }
6
14
  /**
7
15
  * The Slim Runtime.
8
16
  * Single Responsibility: Orchestrate Event -> Action -> Event transitions.
@@ -45,4 +53,4 @@ declare const plugin: (config: Plugin) => Plugin;
45
53
  */
46
54
  declare function createStreamResponse(generator: AsyncGenerator<Event>): Response;
47
55
 
48
- export { Action, Config, Event, Plugin, Runtime, action, createStreamResponse, melony, plugin };
56
+ export { Action, Config, Event, Plugin, Runtime, RuntimeInterruption, action, createStreamResponse, melony, plugin };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createStreamResponse } from './chunk-CFG7FFEZ.js';
2
- export { Runtime, action, melony, plugin, ui } from './chunk-GTBFMQGD.js';
2
+ export { Runtime, RuntimeInterruption, action, melony, plugin, ui } from './chunk-LECAXAQJ.js';
3
3
  export { generateId } from './chunk-WAI5H335.js';
4
4
  //# sourceMappingURL=index.js.map
5
5
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { A as Action, i as RuntimeContext, P as Plugin } from '../types-BggpSdNT.js';
1
+ import { A as Action, i as RuntimeContext, P as Plugin } from '../types-CFbiFt1b.js';
2
2
  import 'zod';
3
3
 
4
4
  interface RequireApprovalOptions {
@@ -1,4 +1,4 @@
1
- import { plugin, ui } from '../chunk-GTBFMQGD.js';
1
+ import { plugin, ui } from '../chunk-LECAXAQJ.js';
2
2
  import '../chunk-WAI5H335.js';
3
3
 
4
4
  // src/plugins/require-approval.ts
@@ -14,8 +14,7 @@ var requireApproval = (options = {}) => {
14
14
  const { action, params, token, approvalId, ...rest } = event.data;
15
15
  const pending = context.state.__pending_approvals?.[approvalId];
16
16
  if (!pending) {
17
- context.suspend();
18
- return {
17
+ context.suspend({
19
18
  role: "assistant",
20
19
  type: "error",
21
20
  data: {
@@ -29,7 +28,7 @@ var requireApproval = (options = {}) => {
29
28
  )
30
29
  ]
31
30
  })
32
- };
31
+ });
33
32
  }
34
33
  delete context.state.__pending_approvals[approvalId];
35
34
  if (event.type === "action-approved") {
@@ -50,13 +49,12 @@ var requireApproval = (options = {}) => {
50
49
  context.state.__approved_action = { action, params };
51
50
  return { action, params, ...rest };
52
51
  }
53
- context.suspend();
54
- return {
52
+ context.suspend({
55
53
  type: "error",
56
54
  data: {
57
55
  message: `Action '${action}' was rejected by the user.`
58
56
  }
59
- };
57
+ });
60
58
  }
61
59
  },
62
60
  /**
@@ -78,7 +76,6 @@ var requireApproval = (options = {}) => {
78
76
  delete context.state.__approved_action;
79
77
  return;
80
78
  }
81
- context.suspend();
82
79
  const approvalId = Math.random().toString(36).substring(2, 15);
83
80
  context.state.__pending_approvals = context.state.__pending_approvals || {};
84
81
  context.state.__pending_approvals[approvalId] = true;
@@ -87,7 +84,7 @@ var requireApproval = (options = {}) => {
87
84
  options.secret
88
85
  ) : void 0;
89
86
  const message = typeof options.message === "function" ? options.message(action.name, params) : options.message || `The agent wants to execute **${action.name}**. Do you approve?`;
90
- return {
87
+ context.suspend({
91
88
  type: "hitl-required",
92
89
  data: { ...nextAction, token, approvalId },
93
90
  ui: ui.card({
@@ -126,7 +123,7 @@ var requireApproval = (options = {}) => {
126
123
  })
127
124
  ]
128
125
  })
129
- };
126
+ });
130
127
  }
131
128
  });
132
129
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/require-approval.ts"],"names":[],"mappings":";;;;AAqCO,IAAM,eAAA,GAAkB,CAAC,OAAA,GAAkC,EAAC,KAAM;AACvE,EAAA,OAAO,MAAA,CAAO;AAAA,IACZ,IAAA,EAAM,kBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMN,WAAA,EAAa,OAAO,EAAE,KAAA,IAAS,OAAA,KAAY;AACzC,MAAA,IACE,KAAA,CAAM,IAAA,KAAS,iBAAA,IACf,KAAA,CAAM,SAAS,iBAAA,EACf;AACA,QAAA,MAAM,EAAE,QAAQ,MAAA,EAAQ,KAAA,EAAO,YAAY,GAAG,IAAA,KAAS,KAAA,CAAM,IAAA;AAG7D,QAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,KAAA,CAAM,mBAAA,GAAsB,UAAU,CAAA;AAC9D,QAAA,IAAI,CAAC,OAAA,EAAS;AACZ,UAAA,OAAA,CAAQ,OAAA,EAAQ;AAChB,UAAA,OAAO;AAAA,YACL,IAAA,EAAM,WAAA;AAAA,YACN,IAAA,EAAM,OAAA;AAAA,YACN,IAAA,EAAM;AAAA,cACJ,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;AAAA,IACF;AAAA,GACD,CAAA;AACH;AAKA,eAAe,WAAA,CAAY,MAAW,MAAA,EAAiC;AACrE,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA;AAC/B,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAChC,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA;AACrC,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,MAAA,CAAO,GAAG,CAAA;AAErC,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,SAAA;AAAA,IAC9B,KAAA;AAAA,IACA,OAAA;AAAA,IACA,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAU;AAAA,IAChC,KAAA;AAAA,IACA,CAAC,MAAM;AAAA,GACT;AAEA,EAAA,MAAM,YAAY,MAAM,MAAA,CAAO,OAAO,IAAA,CAAK,MAAA,EAAQ,KAAK,UAAU,CAAA;AAClE,EAAA,OAAO,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,IAAI,UAAA,CAAW,SAAS,CAAC,CAAC,CAAA;AAC/D","file":"require-approval.js","sourcesContent":["import { plugin } from \"../runtime\";\nimport { ui } from \"../types\";\nimport type { Action, RuntimeContext } from \"../types\";\n\nexport interface RequireApprovalOptions {\n /**\n * List of action names that require explicit approval.\n * If not provided, all actions will require approval.\n */\n actions?: string[];\n\n /**\n * Optional secret to sign the approval payload.\n * If provided, the plugin will verify that the parameters haven't been\n * tampered with between the request and the approval.\n */\n secret?: string;\n\n /**\n * Custom message to show in the approval card.\n */\n message?: string | ((action: string, params: any) => string);\n\n /**\n * Optional condition to check if approval is needed dynamically.\n */\n shouldApprove?: (\n action: Action<any>,\n params: any,\n context: RuntimeContext\n ) => boolean | Promise<boolean>;\n}\n\n/**\n * A plugin that intercepts actions and requires human approval before execution.\n * It uses SDUI to prompt the user and handles the resumption of the agentic loop.\n */\nexport const requireApproval = (options: RequireApprovalOptions = {}) => {\n return plugin({\n name: \"require-approval\",\n\n /**\n * Step 1: Handle the resumption when the user clicks \"Approve\" or \"Cancel\".\n * We verify the one-time-use approvalId to prevent replay attacks or double-clicks.\n */\n onBeforeRun: async ({ event }, context) => {\n if (\n event.type === \"action-approved\" ||\n event.type === \"action-rejected\"\n ) {\n const { action, params, token, approvalId, ...rest } = event.data;\n\n // 1. Check if this specific request exists and hasn't been used\n const pending = context.state.__pending_approvals?.[approvalId];\n if (!pending) {\n context.suspend();\n return {\n role: \"assistant\",\n type: \"error\",\n data: {\n message:\n \"Security Error: This approval request is invalid or has already been used.\",\n },\n ui: ui.card({\n title: \"Security Error\",\n children: [\n ui.text(\n \"This approval request is invalid or has already been used.\"\n ),\n ],\n }),\n };\n }\n\n // 2. Consume the token immediately (Destroy after usage)\n delete context.state.__pending_approvals[approvalId];\n\n if (event.type === \"action-approved\") {\n // 3. Security: Verify the token if a secret was provided\n if (options.secret) {\n const expectedToken = await signPayload(\n { action, params, approvalId },\n options.secret\n );\n if (token !== expectedToken) {\n return {\n type: \"error\",\n data: {\n message:\n \"Security Warning: Approval token mismatch. Execution blocked.\",\n },\n };\n }\n }\n\n // 4. Store approval in ephemeral state for the upcoming action execution\n context.state.__approved_action = { action, params };\n\n // Return the action to jump-start the loop exactly where we left off\n return { action, params, ...rest };\n }\n\n // Handle Rejection\n context.suspend();\n return {\n type: \"error\",\n data: {\n message: `Action '${action}' was rejected by the user.`,\n },\n };\n }\n },\n\n /**\n * Step 2: Intercept actions that require approval.\n */\n onBeforeAction: async ({ action, params, nextAction }, context) => {\n // 1. Check if this action needs approval\n const isTargetAction =\n !options.actions || options.actions.includes(action.name);\n if (!isTargetAction) return;\n\n if (options.shouldApprove) {\n const needsApproval = await options.shouldApprove(\n action,\n params,\n context\n );\n if (!needsApproval) return;\n }\n\n // 2. Check if it was ALREADY approved in this run\n const approval = context.state.__approved_action;\n if (\n approval &&\n approval.action === action.name &&\n JSON.stringify(approval.params) === JSON.stringify(params)\n ) {\n delete context.state.__approved_action;\n return; // Proceed to execution\n }\n\n // 3. Suspend and request approval with a one-time-use nonce\n context.suspend();\n\n const approvalId = Math.random().toString(36).substring(2, 15);\n context.state.__pending_approvals =\n context.state.__pending_approvals || {};\n context.state.__pending_approvals[approvalId] = true;\n\n const token = options.secret\n ? await signPayload(\n { action: action.name, params, approvalId },\n options.secret\n )\n : undefined;\n\n const message =\n typeof options.message === \"function\"\n ? options.message(action.name, params)\n : options.message ||\n `The agent wants to execute **${action.name}**. Do you approve?`;\n\n return {\n type: \"hitl-required\",\n data: { ...nextAction, token, approvalId },\n ui: ui.card({\n title: \"Approval Required\",\n children: [\n ui.text(message),\n ui.box({\n padding: \"md\",\n background: \"muted\",\n children: [\n ui.text(JSON.stringify(params, null, 2), { size: \"xs\" }),\n ],\n }),\n ui.row({\n gap: \"md\",\n children: [\n ui.button({\n label: \"Approve\",\n variant: \"success\",\n onClickAction: {\n role: \"user\",\n type: \"action-approved\",\n data: { ...nextAction, token, approvalId },\n ui: ui.text(\"Approval granted\"),\n },\n }),\n ui.button({\n label: \"Cancel\",\n variant: \"outline\",\n onClickAction: {\n type: \"action-rejected\",\n data: { action: action.name, approvalId },\n },\n }),\n ],\n }),\n ],\n }),\n };\n },\n });\n};\n\n/**\n * Simple HMAC signing using the Web Crypto API (supported in Node 16+ and Browsers).\n */\nasync function signPayload(data: any, secret: string): Promise<string> {\n const msg = JSON.stringify(data);\n const encoder = new TextEncoder();\n const keyData = encoder.encode(secret);\n const dataToSign = encoder.encode(msg);\n\n const key = await crypto.subtle.importKey(\n \"raw\",\n keyData,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n\n const signature = await crypto.subtle.sign(\"HMAC\", key, dataToSign);\n return btoa(String.fromCharCode(...new Uint8Array(signature)));\n}\n"]}
1
+ {"version":3,"sources":["../../src/plugins/require-approval.ts"],"names":[],"mappings":";;;;AAqCO,IAAM,eAAA,GAAk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AClE,EAAA,OAAO,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,IAAI,UAAA,CAAW,SAAS,CAAC,CAAC,CAAA;AAC/D","file":"require-approval.js","sourcesContent":["import { plugin } from \"../runtime\";\nimport { ui } from \"../types\";\nimport type { Action, RuntimeContext } from \"../types\";\n\nexport interface RequireApprovalOptions {\n /**\n * List of action names that require explicit approval.\n * If not provided, all actions will require approval.\n */\n actions?: string[];\n\n /**\n * Optional secret to sign the approval payload.\n * If provided, the plugin will verify that the parameters haven't been\n * tampered with between the request and the approval.\n */\n secret?: string;\n\n /**\n * Custom message to show in the approval card.\n */\n message?: string | ((action: string, params: any) => string);\n\n /**\n * Optional condition to check if approval is needed dynamically.\n */\n shouldApprove?: (\n action: Action<any>,\n params: any,\n context: RuntimeContext\n ) => boolean | Promise<boolean>;\n}\n\n/**\n * A plugin that intercepts actions and requires human approval before execution.\n * It uses SDUI to prompt the user and handles the resumption of the agentic loop.\n */\nexport const requireApproval = (options: RequireApprovalOptions = {}) => {\n return plugin({\n name: \"require-approval\",\n\n /**\n * Step 1: Handle the resumption when the user clicks \"Approve\" or \"Cancel\".\n * We verify the one-time-use approvalId to prevent replay attacks or double-clicks.\n */\n onBeforeRun: async ({ event }, context) => {\n if (\n event.type === \"action-approved\" ||\n event.type === \"action-rejected\"\n ) {\n const { action, params, token, approvalId, ...rest } = event.data;\n\n // 1. Check if this specific request exists and hasn't been used\n const pending = context.state.__pending_approvals?.[approvalId];\n if (!pending) {\n context.suspend({\n role: \"assistant\",\n type: \"error\",\n data: {\n message:\n \"Security Error: This approval request is invalid or has already been used.\",\n },\n ui: ui.card({\n title: \"Security Error\",\n children: [\n ui.text(\n \"This approval request is invalid or has already been used.\"\n ),\n ],\n }),\n });\n }\n\n // 2. Consume the token immediately (Destroy after usage)\n delete context.state.__pending_approvals[approvalId];\n\n if (event.type === \"action-approved\") {\n // 3. Security: Verify the token if a secret was provided\n if (options.secret) {\n const expectedToken = await signPayload(\n { action, params, approvalId },\n options.secret\n );\n if (token !== expectedToken) {\n return {\n type: \"error\",\n data: {\n message:\n \"Security Warning: Approval token mismatch. Execution blocked.\",\n },\n };\n }\n }\n\n // 4. Store approval in ephemeral state for the upcoming action execution\n context.state.__approved_action = { action, params };\n\n // Return the action to jump-start the loop exactly where we left off\n return { action, params, ...rest };\n }\n\n // Handle Rejection\n context.suspend({\n type: \"error\",\n data: {\n message: `Action '${action}' was rejected by the user.`,\n },\n });\n }\n },\n\n /**\n * Step 2: Intercept actions that require approval.\n */\n onBeforeAction: async ({ action, params, nextAction }, context) => {\n // 1. Check if this action needs approval\n const isTargetAction =\n !options.actions || options.actions.includes(action.name);\n if (!isTargetAction) return;\n\n if (options.shouldApprove) {\n const needsApproval = await options.shouldApprove(\n action,\n params,\n context\n );\n if (!needsApproval) return;\n }\n\n // 2. Check if it was ALREADY approved in this run\n const approval = context.state.__approved_action;\n if (\n approval &&\n approval.action === action.name &&\n JSON.stringify(approval.params) === JSON.stringify(params)\n ) {\n delete context.state.__approved_action;\n return; // Proceed to execution\n }\n\n // 3. Suspend and request approval with a one-time-use nonce\n const approvalId = Math.random().toString(36).substring(2, 15);\n context.state.__pending_approvals =\n context.state.__pending_approvals || {};\n context.state.__pending_approvals[approvalId] = true;\n\n const token = options.secret\n ? await signPayload(\n { action: action.name, params, approvalId },\n options.secret\n )\n : undefined;\n\n const message =\n typeof options.message === \"function\"\n ? options.message(action.name, params)\n : options.message ||\n `The agent wants to execute **${action.name}**. Do you approve?`;\n\n context.suspend({\n type: \"hitl-required\",\n data: { ...nextAction, token, approvalId },\n ui: ui.card({\n title: \"Approval Required\",\n children: [\n ui.text(message),\n ui.box({\n padding: \"md\",\n background: \"muted\",\n children: [\n ui.text(JSON.stringify(params, null, 2), { size: \"xs\" }),\n ],\n }),\n ui.row({\n gap: \"md\",\n children: [\n ui.button({\n label: \"Approve\",\n variant: \"success\",\n onClickAction: {\n role: \"user\",\n type: \"action-approved\",\n data: { ...nextAction, token, approvalId },\n ui: ui.text(\"Approval granted\"),\n },\n }),\n ui.button({\n label: \"Cancel\",\n variant: \"outline\",\n onClickAction: {\n type: \"action-rejected\",\n data: { action: action.name, approvalId },\n },\n }),\n ],\n }),\n ],\n }),\n });\n },\n });\n};\n\n/**\n * Simple HMAC signing using the Web Crypto API (supported in Node 16+ and Browsers).\n */\nasync function signPayload(data: any, secret: string): Promise<string> {\n const msg = JSON.stringify(data);\n const encoder = new TextEncoder();\n const keyData = encoder.encode(secret);\n const dataToSign = encoder.encode(msg);\n\n const key = await crypto.subtle.importKey(\n \"raw\",\n keyData,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"]\n );\n\n const signature = await crypto.subtle.sign(\"HMAC\", key, dataToSign);\n return btoa(String.fromCharCode(...new Uint8Array(signature)));\n}\n"]}
@@ -228,10 +228,13 @@ interface RuntimeContext<TState = any> {
228
228
  state: TState;
229
229
  runId: string;
230
230
  stepCount: number;
231
- isDone: boolean;
232
231
  actions: Record<string, Action<any>>;
233
232
  ui: typeof ui;
234
- suspend: () => void;
233
+ /**
234
+ * Immediately interrupts the runtime execution.
235
+ * If an event is provided, it will be emitted before the runtime stops.
236
+ */
237
+ suspend: (event?: Event) => never;
235
238
  }
236
239
  /**
237
240
  * Standardized Hook Result for consistent DX.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "melony",
3
- "version": "0.1.25",
3
+ "version": "0.1.28",
4
4
  "main": "dist/index.js",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types.ts","../src/runtime.ts"],"names":["plugin","action"],"mappings":";;;AAiLO,IAAM,EAAA,GAAK;AAAA,EAChB,IAAA,EAAM,CACJ,KAAA,KACmB;AACnB,IAAA,MAAM,EAAE,QAAA,EAAU,GAAG,IAAA,EAAK,GAAI,KAAA;AAC9B,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,KAAA,EAAO,MAAM,QAAA,EAAS;AA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AA,IAAI,KAAA,EAAO;AAET,QAAA,MAAM,EAAE,GAAG,KAAA,EAAO,KAAA,EAAO,QAAQ,KAAA,EAAO,SAAA,EAAW,IAAA,CAAK,GAAA,EAAI,EAAE;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,MAAA,GAAS,CAAC,MAAA,KAAmB;AACxC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAQ,MAAM,CAAA;AAClC,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,GAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,IAAA,CAAK,OAAO;AAAA,GAC/B;AACF;AAKO,IAAM,MAAA,GAAS,CACpB,MAAA,KACc;AAKT,IAAM,MAAA,GAAS,CAAC,MAAA,KAA2B","file":"chunk-GTBFMQGD.js","sourcesContent":["import z from \"zod\";\n\n// ============================================\n// UI Protocol & Contracts\n// ============================================\n\nexport type UISize = \"sm\" | \"md\" | \"lg\";\nexport type UIAlign = \"start\" | \"center\" | \"end\" | \"stretch\";\nexport type UIJustify = \"start\" | \"center\" | \"end\" | \"between\" | \"around\";\nexport type UIWrap = \"nowrap\" | \"wrap\" | \"wrap-reverse\";\nexport type UIOrientation = \"horizontal\" | \"vertical\";\n\nexport type UIColor =\n | \"primary\"\n | \"secondary\"\n | \"success\"\n | \"danger\"\n | \"warning\"\n | \"info\"\n | \"background\"\n | \"foreground\"\n | \"muted\"\n | \"mutedForeground\"\n | \"border\";\n\nexport type UISpacing = \"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\" | \"xxl\";\n\n/**\n * UI Component Contracts\n * This acts as the source of truth for the SDUI protocol.\n */\nexport interface UIContract {\n card: {\n title?: string;\n subtitle?: string;\n background?: string;\n isLoading?: boolean;\n };\n row: {\n align?: UIAlign;\n justify?: UIJustify;\n wrap?: UIWrap;\n gap?: UISpacing;\n };\n col: {\n align?: UIAlign;\n justify?: UIJustify;\n gap?: UISpacing;\n width?: string | number;\n height?: string | number;\n padding?: UISpacing;\n };\n box: {\n padding?: UISpacing;\n margin?: string | number;\n background?: string;\n border?: boolean;\n borderRadius?: UISpacing;\n width?: string | number;\n height?: string | number;\n };\n spacer: {\n size?: UISpacing;\n direction?: UIOrientation;\n };\n divider: {\n orientation?: UIOrientation;\n color?: UIColor;\n };\n text: {\n value: string;\n size?: UISpacing;\n weight?: \"normal\" | \"medium\" | \"semibold\" | \"bold\";\n color?: UIColor;\n align?: UIAlign;\n };\n heading: {\n value: string;\n level?: 1 | 2 | 3 | 4 | 5 | 6;\n };\n badge: {\n label: string;\n variant?: \"primary\" | \"secondary\" | \"success\" | \"danger\" | \"warning\";\n size?: UISize;\n };\n image: {\n src: string;\n alt?: string;\n size?: UISize;\n };\n icon: {\n name: string;\n size?: UISize;\n color?: UIColor;\n };\n chart: {\n data: Array<{ label: string; value: number; color?: string }>;\n chartType?: \"bar\" | \"line\" | \"area\" | \"pie\";\n title?: string;\n };\n list: {};\n listItem: {\n onClickAction?: Event;\n gap?: UISpacing;\n };\n form: {\n onSubmitAction?: Event;\n };\n input: {\n name: string;\n label?: string;\n placeholder?: string;\n defaultValue?: string;\n inputType?: string;\n onChangeAction?: Event;\n };\n textarea: {\n name: string;\n label?: string;\n placeholder?: string;\n defaultValue?: string;\n rows?: number;\n onChangeAction?: Event;\n };\n select: {\n name: string;\n label?: string;\n options: Array<{ label: string; value: string }>;\n defaultValue?: string;\n placeholder?: string;\n onChangeAction?: Event;\n };\n checkbox: {\n name: string;\n label?: string;\n checked?: boolean;\n onChangeAction?: Event;\n };\n radioGroup: {\n name: string;\n options: Array<{ label: string; value: string; disabled?: boolean }>;\n label?: string;\n defaultValue?: string;\n orientation?: UIOrientation;\n onChangeAction?: Event;\n };\n label: {\n value: string;\n htmlFor?: string;\n required?: boolean;\n };\n button: {\n label: string;\n variant?:\n | \"primary\"\n | \"secondary\"\n | \"success\"\n | \"danger\"\n | \"outline\"\n | \"ghost\"\n | \"link\";\n size?: UISize;\n disabled?: boolean;\n onClickAction?: Event;\n };\n}\n\nexport type UINode<T extends keyof UIContract = keyof UIContract> = {\n type: T;\n props?: UIContract[T];\n children?: UINode<any>[];\n};\n\n/**\n * UI Builder for SDUI.\n * Typed using the UIContract source of truth.\n */\nexport const ui = {\n card: (\n props: UIContract[\"card\"] & { children?: UINode<any>[] }\n ): UINode<\"card\"> => {\n const { children, ...rest } = props;\n return { type: \"card\", props: rest, children };\n },\n row: (\n props: UIContract[\"row\"] & { children?: UINode<any>[] }\n ): UINode<\"row\"> => {\n const { children, ...rest } = props;\n return { type: \"row\", props: rest, children };\n },\n col: (\n props: UIContract[\"col\"] & { children?: UINode<any>[] }\n ): UINode<\"col\"> => {\n const { children, ...rest } = props;\n return { type: \"col\", props: rest, children };\n },\n box: (\n props: UIContract[\"box\"] & { children?: UINode<any>[] }\n ): UINode<\"box\"> => {\n const { children, ...rest } = props;\n return { type: \"box\", props: rest, children };\n },\n spacer: (props: UIContract[\"spacer\"]): UINode<\"spacer\"> => ({\n type: \"spacer\",\n props,\n }),\n divider: (props: UIContract[\"divider\"]): UINode<\"divider\"> => ({\n type: \"divider\",\n props,\n }),\n text: (\n value: string,\n props?: Omit<UIContract[\"text\"], \"value\">\n ): UINode<\"text\"> => ({\n type: \"text\",\n props: { ...props, value },\n }),\n heading: (\n value: string,\n level: UIContract[\"heading\"][\"level\"] = 1\n ): UINode<\"heading\"> => ({\n type: \"heading\",\n props: { value, level },\n }),\n badge: (\n label: string,\n variant: UIContract[\"badge\"][\"variant\"] = \"primary\",\n size: UISize = \"md\"\n ): UINode<\"badge\"> => ({\n type: \"badge\",\n props: { label, variant, size },\n }),\n image: (src: string, alt?: string, size: UISize = \"md\"): UINode<\"image\"> => ({\n type: \"image\",\n props: { src, alt, size },\n }),\n icon: (\n name: string,\n size: UISize = \"md\",\n color?: UIColor\n ): UINode<\"icon\"> => ({\n type: \"icon\",\n props: { name, size, color },\n }),\n chart: (props: UIContract[\"chart\"]): UINode<\"chart\"> => ({\n type: \"chart\",\n props,\n }),\n list: (children: UINode<any>[]): UINode<\"list\"> => ({\n type: \"list\",\n children,\n }),\n listItem: (\n props: UIContract[\"listItem\"] & { children: UINode<any>[] }\n ): UINode<\"listItem\"> => {\n const { children, ...rest } = props;\n return { type: \"listItem\", props: rest, children };\n },\n form: (\n props: UIContract[\"form\"] & { children?: UINode<any>[] }\n ): UINode<\"form\"> => {\n const { children, ...rest } = props;\n return { type: \"form\", props: rest, children };\n },\n input: (props: UIContract[\"input\"]): UINode<\"input\"> => ({\n type: \"input\",\n props,\n }),\n textarea: (props: UIContract[\"textarea\"]): UINode<\"textarea\"> => ({\n type: \"textarea\",\n props,\n }),\n select: (props: UIContract[\"select\"]): UINode<\"select\"> => ({\n type: \"select\",\n props,\n }),\n checkbox: (props: UIContract[\"checkbox\"]): UINode<\"checkbox\"> => ({\n type: \"checkbox\",\n props,\n }),\n radioGroup: (props: UIContract[\"radioGroup\"]): UINode<\"radioGroup\"> => ({\n type: \"radioGroup\",\n props,\n }),\n label: (\n value: string,\n props?: Omit<UIContract[\"label\"], \"value\">\n ): UINode<\"label\"> => ({\n type: \"label\",\n props: { ...props, value },\n }),\n button: (props: UIContract[\"button\"]): UINode<\"button\"> => ({\n type: \"button\",\n props,\n }),\n actions: {\n navigate: (url: string): Event => ({ type: \"client:navigate\", data: { url } }),\n openUrl: (url: string, target = \"_blank\"): Event => ({\n type: \"client:open-url\",\n data: { url, target },\n }),\n copy: (text: string): Event => ({ type: \"client:copy\", data: { text } }),\n reset: (): Event => ({ type: \"client:reset\" }),\n },\n};\n\n// ============================================\n// Events\n// ============================================\n\nexport type Role = \"user\" | \"assistant\" | \"system\";\n\nexport type Event = {\n type: string;\n data?: any;\n ui?: UINode;\n runId?: string;\n threadId?: string;\n timestamp?: number;\n role?: Role;\n state?: any;\n};\n\n// ============================================\n// Runtime & Hooks\n// ============================================\n\nexport interface Action<TParams extends z.ZodSchema = z.ZodObject<any>> {\n name: string;\n description?: string;\n paramsSchema: TParams;\n execute: (\n params: z.infer<TParams>,\n context: RuntimeContext\n ) => AsyncGenerator<Event, NextAction | void, unknown>;\n}\n\nexport interface NextAction {\n action?: string;\n params?: any;\n description?: string;\n [key: string]: any; // Allow metadata like toolCallId\n}\n\nexport interface RuntimeContext<TState = any> {\n state: TState;\n runId: string;\n stepCount: number;\n isDone: boolean;\n actions: Record<string, Action<any>>;\n ui: typeof ui;\n suspend: () => void;\n}\n\n/**\n * Standardized Hook Result for consistent DX.\n */\nexport type HookResult = Promise<Event | void>;\n\nexport interface Hooks {\n /**\n * Called when a run session begins.\n * Can return an Event to be emitted, or a NextAction to jump-start the loop.\n */\n onBeforeRun?: (\n input: { event: Event; runId: string; state: Record<string, any> },\n context: RuntimeContext\n ) => Promise<Event | NextAction | void>;\n\n /**\n * Called when a run session completes.\n */\n onAfterRun?: (context: RuntimeContext) => HookResult;\n\n /**\n * Called whenever an event is yielded by the runtime.\n */\n onEvent?: (event: Event, context: RuntimeContext) => HookResult;\n\n /**\n * Called before an action is executed.\n * Return an event to intercept/suspend the action.\n */\n onBeforeAction?: (\n call: { action: Action<any>; params: any; nextAction: NextAction },\n context: RuntimeContext\n ) => HookResult;\n\n /**\n * Called after an action completes.\n */\n onAfterAction?: (\n result: { action: Action<any>; data: NextAction | void },\n context: RuntimeContext\n ) => HookResult;\n}\n\n/**\n * A plugin is just a named set of hooks.\n */\nexport interface Plugin extends Hooks {\n name: string;\n}\n\nexport interface Config {\n actions: Record<string, Action<any>>;\n /**\n * The central brain for handling incoming events.\n */\n brain?: (\n event: Event,\n context: RuntimeContext\n ) => AsyncGenerator<Event, NextAction | void, unknown>;\n hooks?: Hooks;\n plugins?: Plugin[];\n safetyMaxSteps?: number;\n starterPrompts?: Array<{\n label: string;\n prompt: string;\n icon?: string;\n }>;\n options?: Array<{\n id: string;\n label: string;\n options: Array<{ id: string; label: string; value: any }>;\n type?: \"single\" | \"multiple\";\n defaultSelectedIds?: string[];\n }>;\n fileAttachments?: {\n enabled?: boolean;\n accept?: string; // e.g., \"image/*,.pdf\" for file input accept attribute\n maxFiles?: number; // Maximum number of files allowed\n maxFileSize?: number; // Maximum file size in bytes\n };\n}\n","import {\n Action,\n Event,\n NextAction,\n RuntimeContext,\n Config,\n Plugin,\n ui,\n} from \"./types\";\nimport { generateId } from \"./utils/generate-id\";\nimport { z } from \"zod\";\n\n/**\n * The Slim Runtime.\n * Single Responsibility: Orchestrate Event -> Action -> Event transitions.\n */\nexport class Runtime {\n private config: Config;\n\n constructor(config: Config) {\n this.config = config;\n }\n\n public async *run(input: {\n event: Event;\n runId?: string;\n state?: Record<string, any>;\n }): AsyncGenerator<Event> {\n const runId = input.runId ?? generateId();\n\n const context: RuntimeContext = {\n state: input.state ?? {},\n runId,\n stepCount: 0,\n isDone: false,\n actions: this.config.actions,\n ui,\n suspend: () => {\n context.isDone = true;\n },\n };\n\n let nextAction: NextAction | void = undefined;\n\n // 1. Trigger Plugins: onBeforeRun\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBeforeRun) {\n const result = await plugin.onBeforeRun(\n { event: input.event, runId, state: context.state },\n context\n );\n if (result) {\n if (\"type\" in result) {\n yield* this.emit(result as Event, context);\n } else {\n nextAction = result as NextAction;\n }\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeRun\n if (this.config.hooks?.onBeforeRun) {\n const result = await this.config.hooks.onBeforeRun(\n { event: input.event, runId, state: context.state },\n context\n );\n if (result) {\n if (\"type\" in result) {\n yield* this.emit(result as Event, context);\n } else {\n nextAction = result as NextAction;\n }\n }\n }\n\n if (context.isDone) return;\n\n yield* this.emit(\n { type: \"run-started\", data: { inputEvent: input.event } },\n context\n );\n\n // Initial dispatch of the incoming event to the agent's brain\n // Only if onBeforeRun didn't already provide a nextAction\n if (!nextAction && this.config.brain) {\n nextAction = yield* this.dispatchToBrain(input.event, context);\n }\n\n // Agentic loop\n while (nextAction && !context.isDone) {\n if (context.stepCount++ >= (this.config.safetyMaxSteps ?? 10)) {\n yield* this.emit(\n { type: \"error\", data: { message: \"Max steps exceeded\" } },\n context\n );\n break;\n }\n\n const current: NextAction = nextAction;\n nextAction = undefined; // Reset\n\n // 1. Resolve Action\n const actionName: string =\n current.action ?? Object.keys(this.config.actions)[0];\n const action: Action<any> = this.config.actions[actionName];\n\n if (!action) {\n yield* this.emit(\n {\n type: \"error\",\n data: { message: `Action ${actionName} not found` },\n },\n context\n );\n break;\n }\n\n // 2. Execute Action\n const result = yield* this.executeAction(action, current, context);\n\n // If the action or a plugin suspended the run (e.g. for HITL approval), \n // stop immediately before feeding the result back to the brain.\n if (context.isDone) break;\n\n // 3. Decide Next Step\n if (this.config.brain) {\n // If we have a brain, feed the result back to it to decide what to do next.\n // This keeps the brain in the loop for multi-step reasoning.\n nextAction = yield* this.dispatchToBrain(\n {\n type: \"action-result\",\n data: {\n ...current, // Preserve all metadata (like toolCallId)\n action: actionName,\n params: current.params,\n result,\n },\n },\n context\n );\n } else {\n // Simple mode: follow the action's own suggestion for the next step.\n nextAction = result;\n }\n }\n\n // 1. Trigger Plugins: onAfterRun\n for (const plugin of this.config.plugins || []) {\n if (plugin.onAfterRun) {\n const extra = await plugin.onAfterRun(context);\n if (extra) yield* this.emit(extra, context);\n }\n }\n\n // 2. Trigger Hook: onAfterRun\n if (this.config.hooks?.onAfterRun) {\n const extra = await this.config.hooks.onAfterRun(context);\n if (extra) yield* this.emit(extra, context);\n }\n }\n\n private async *dispatchToBrain(\n event: Event,\n context: RuntimeContext\n ): AsyncGenerator<Event, NextAction | void> {\n const generator = this.config.brain!(event, context);\n while (true) {\n const { value, done } = await generator.next();\n if (done) return value as NextAction | void;\n yield* this.emit(value as Event, context);\n }\n }\n\n private async *executeAction(\n action: Action,\n nextAction: NextAction,\n context: RuntimeContext\n ): AsyncGenerator<Event, NextAction | void> {\n const params = nextAction.params;\n\n // 1. Trigger Plugins: onBeforeAction\n for (const plugin of this.config.plugins || []) {\n if (plugin.onBeforeAction) {\n const hookResult = await plugin.onBeforeAction(\n { action, params, nextAction },\n context\n );\n if (hookResult) {\n yield* this.emit(hookResult, context);\n if (context.isDone) return;\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeAction\n if (this.config.hooks?.onBeforeAction) {\n const hookResult = await this.config.hooks.onBeforeAction(\n { action, params, nextAction },\n context\n );\n if (hookResult) {\n yield* this.emit(hookResult, context);\n if (context.isDone) return;\n }\n }\n\n try {\n const generator = action.execute(params, context);\n let result: NextAction | void;\n\n while (true) {\n const { value, done } = await generator.next();\n if (done) {\n result = value as NextAction | void;\n break;\n }\n yield* this.emit(value as Event, context);\n if (context.isDone) return;\n }\n\n // 3. Trigger Plugins: onAfterAction\n for (const plugin of this.config.plugins || []) {\n if (plugin.onAfterAction) {\n const extra = await plugin.onAfterAction(\n { action, data: result },\n context\n );\n if (extra) yield* this.emit(extra, context);\n }\n }\n\n // 4. Trigger Hook: onAfterAction\n if (this.config.hooks?.onAfterAction) {\n const extra = await this.config.hooks.onAfterAction(\n { action, data: result },\n context\n );\n if (extra) yield* this.emit(extra, context);\n }\n\n return result;\n } catch (error) {\n yield* this.emit(\n {\n type: \"error\",\n data: {\n action: action.name,\n error: error instanceof Error ? error.message : String(error),\n },\n },\n context\n );\n }\n }\n\n /**\n * Internal helper to yield an event and trigger the onEvent hook.\n */\n private async *emit(\n event: Event,\n context: RuntimeContext\n ): AsyncGenerator<Event> {\n const finalEvent = {\n ...event,\n runId: context.runId,\n timestamp: event.timestamp ?? Date.now(),\n role: event.role ?? \"assistant\",\n state: context.state,\n };\n\n // Yield the actual event first\n yield finalEvent;\n\n // 1. Trigger Plugins: onEvent\n for (const plugin of this.config.plugins || []) {\n if (plugin.onEvent) {\n const extra = await plugin.onEvent(finalEvent, context);\n if (extra) {\n yield { ...extra, runId: context.runId, timestamp: Date.now() };\n }\n }\n }\n\n // 2. Trigger Hook: onEvent for side-effects or extra events\n if (this.config.hooks?.onEvent) {\n const extra = await this.config.hooks.onEvent(finalEvent, context);\n if (extra) {\n // Yield extra event from hook, ensuring it has required metadata\n yield { ...extra, runId: context.runId, timestamp: Date.now() };\n }\n }\n }\n}\n\nexport const melony = (config: Config) => {\n const runtime = new Runtime(config);\n return {\n config,\n run: runtime.run.bind(runtime),\n };\n};\n\n/**\n * Helper to define an action with full type inference.\n */\nexport const action = <T extends z.ZodSchema>(\n config: Action<T>\n): Action<T> => config;\n\n/**\n * Helper to define a plugin.\n */\nexport const plugin = (config: Plugin): Plugin => config;\n"]}