melony 0.1.34 → 0.1.36
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.
- package/dist/adapters/hono.js +1 -3
- package/dist/adapters/hono.js.map +1 -1
- package/dist/{chunk-BPBQIKIH.js → chunk-DXG3RLWG.js} +11 -11
- package/dist/chunk-DXG3RLWG.js.map +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/index.d.ts +4 -8
- package/dist/index.js +1 -1
- package/dist/plugins/require-approval.d.ts +1 -1
- package/dist/plugins/require-approval.js +1 -1
- package/dist/{types-D3AeCiLW.d.ts → types-FEFI0LoL.d.ts} +3 -3
- package/package.json +1 -1
- package/dist/chunk-BPBQIKIH.js.map +0 -1
package/dist/adapters/hono.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/hono.ts"],"names":[],"mappings":";;;AAMO,IAAM,MAAA,GAAS,CAAC,QAAA,KAAwC;AAC7D,EAAA,OAAO,OAAO,CAAA,KAAW;AACvB,IAAA,IAAI,CAAA,CAAE,GAAA,CAAI,MAAA,KAAW,KAAA,EAAO;AAC1B,MAAA,OAAO,EAAE,IAAA,CAAK;AAAA,QACZ,cAAA,EAAgB,QAAA,CAAS,MAAA,CAAO,cAAA,IAAkB,EAAC;AAAA,QACnD,OAAA,EAAS,QAAA,CAAS,MAAA,CAAO,OAAA,IAAW,EAAC;AAAA,QACrC,eAAA,EAAiB,SAAS,MAAA,CAAO;AAAA,OAClC,CAAA;AAAA,IACH;AAEA,IAAA,MAAM,OAAA,GAAU,CAAA,CAAE,GAAA,CAAI,MAAA,EAAO;AAC7B,IAAA,MAAM,IAAA,GAAO,MAAM,CAAA,CAAE,GAAA,CAAI,IAAA,EAAK;AAC9B,IAAA,MAAM,QAAQ,IAAA,CAAK,KAAA;AAEnB,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,OAAO,EAAE,IAAA,CAAK,EAAE,KAAA,EAAO,iCAAA,IAAqC,GAAG,CAAA;AAAA,IACjE;AAGA,IAAA,KAAA,CAAM,KAAA,GAAQ;AAAA,MACZ,GAAG,KAAA,CAAM,KAAA;AAAA,MACT,cAAA,EAAgB;AAAA,KAClB;AAEA,IAAA,OAAO,oBAAA;AAAA,MACL,
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/hono.ts"],"names":[],"mappings":";;;AAMO,IAAM,MAAA,GAAS,CAAC,QAAA,KAAwC;AAC7D,EAAA,OAAO,OAAO,CAAA,KAAW;AACvB,IAAA,IAAI,CAAA,CAAE,GAAA,CAAI,MAAA,KAAW,KAAA,EAAO;AAC1B,MAAA,OAAO,EAAE,IAAA,CAAK;AAAA,QACZ,cAAA,EAAgB,QAAA,CAAS,MAAA,CAAO,cAAA,IAAkB,EAAC;AAAA,QACnD,OAAA,EAAS,QAAA,CAAS,MAAA,CAAO,OAAA,IAAW,EAAC;AAAA,QACrC,eAAA,EAAiB,SAAS,MAAA,CAAO;AAAA,OAClC,CAAA;AAAA,IACH;AAEA,IAAA,MAAM,OAAA,GAAU,CAAA,CAAE,GAAA,CAAI,MAAA,EAAO;AAC7B,IAAA,MAAM,IAAA,GAAO,MAAM,CAAA,CAAE,GAAA,CAAI,IAAA,EAAK;AAC9B,IAAA,MAAM,QAAQ,IAAA,CAAK,KAAA;AAEnB,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,OAAO,EAAE,IAAA,CAAK,EAAE,KAAA,EAAO,iCAAA,IAAqC,GAAG,CAAA;AAAA,IACjE;AAGA,IAAA,KAAA,CAAM,KAAA,GAAQ;AAAA,MACZ,GAAG,KAAA,CAAM,KAAA;AAAA,MACT,cAAA,EAAgB;AAAA,KAClB;AAEA,IAAA,OAAO,oBAAA;AAAA,MACL,QAAA,CAAS,IAAI,KAAK;AAAA,KACpB;AAAA,EACF,CAAA;AACF","file":"hono.js","sourcesContent":["import { Event } from \"../types\";\nimport { createStreamResponse } from \"../utils/create-stream-response\";\n\n/**\n * Event-centric Hono adapter for Melony.\n */\nexport const handle = (instance: { run: any; config: any }) => {\n return async (c: any) => {\n if (c.req.method === \"GET\") {\n return c.json({\n starterPrompts: instance.config.starterPrompts || [],\n options: instance.config.options || [],\n fileAttachments: instance.config.fileAttachments,\n });\n }\n\n const headers = c.req.header();\n const body = await c.req.json();\n const event = body.event as Event;\n\n if (!event) {\n return c.json({ error: \"Invalid request: event required\" }, 400);\n }\n\n // Merge headers into event state\n event.state = {\n ...event.state,\n requestHeaders: headers,\n };\n\n return createStreamResponse(\n instance.run(event)\n );\n };\n};\n"]}
|
|
@@ -112,16 +112,16 @@ var Runtime = class {
|
|
|
112
112
|
constructor(config) {
|
|
113
113
|
this.config = config;
|
|
114
114
|
}
|
|
115
|
-
async *run(
|
|
116
|
-
const runId =
|
|
115
|
+
async *run(event) {
|
|
116
|
+
const runId = event.runId ?? generateId();
|
|
117
117
|
const context = {
|
|
118
|
-
state:
|
|
118
|
+
state: event.state ?? {},
|
|
119
119
|
runId,
|
|
120
120
|
stepCount: 0,
|
|
121
121
|
actions: this.config.actions,
|
|
122
122
|
ui,
|
|
123
|
-
suspend: (
|
|
124
|
-
throw
|
|
123
|
+
suspend: (event2) => {
|
|
124
|
+
throw event2 || { type: "run-suspended" };
|
|
125
125
|
}
|
|
126
126
|
};
|
|
127
127
|
try {
|
|
@@ -129,7 +129,7 @@ var Runtime = class {
|
|
|
129
129
|
for (const plugin2 of this.config.plugins || []) {
|
|
130
130
|
if (plugin2.onBeforeRun) {
|
|
131
131
|
const result = yield* this.callHook(
|
|
132
|
-
plugin2.onBeforeRun({ event
|
|
132
|
+
plugin2.onBeforeRun({ event }, context),
|
|
133
133
|
context
|
|
134
134
|
);
|
|
135
135
|
if (result) {
|
|
@@ -139,7 +139,7 @@ var Runtime = class {
|
|
|
139
139
|
}
|
|
140
140
|
if (this.config.hooks?.onBeforeRun) {
|
|
141
141
|
const result = yield* this.callHook(
|
|
142
|
-
this.config.hooks.onBeforeRun({ event
|
|
142
|
+
this.config.hooks.onBeforeRun({ event }, context),
|
|
143
143
|
context
|
|
144
144
|
);
|
|
145
145
|
if (result) {
|
|
@@ -147,11 +147,11 @@ var Runtime = class {
|
|
|
147
147
|
}
|
|
148
148
|
}
|
|
149
149
|
yield* this.emit(
|
|
150
|
-
{ type: "run-started", data: { inputEvent:
|
|
150
|
+
{ type: "run-started", data: { inputEvent: event } },
|
|
151
151
|
context
|
|
152
152
|
);
|
|
153
153
|
if (!nextAction && this.config.brain) {
|
|
154
|
-
nextAction = yield* this.dispatchToBrain(
|
|
154
|
+
nextAction = yield* this.dispatchToBrain(event, context);
|
|
155
155
|
}
|
|
156
156
|
while (nextAction) {
|
|
157
157
|
if (context.stepCount++ >= (this.config.safetyMaxSteps ?? 10)) {
|
|
@@ -354,5 +354,5 @@ var action = (config) => config;
|
|
|
354
354
|
var plugin = (config) => config;
|
|
355
355
|
|
|
356
356
|
export { Runtime, action, melony, plugin, ui };
|
|
357
|
-
//# sourceMappingURL=chunk-
|
|
358
|
-
//# sourceMappingURL=chunk-
|
|
357
|
+
//# sourceMappingURL=chunk-DXG3RLWG.js.map
|
|
358
|
+
//# sourceMappingURL=chunk-DXG3RLWG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/runtime.ts"],"names":["event","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,MA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,CAAO,OAAA,CAAQ,UAAA,EAAY,OAAO,CAAA;AACpD,QAAA,WAAA,MAAiB,SAAS,SAAA,EAAW;AACnC,UAAA,MAAM,EAAE,GAAG,KAAA,EAAO,KAAA,EAAO,QAAQ,KAAA,EAAO,SAAA,EAAW,IAAA,CAAK,GAAA,EAAI,EAAE;AAAA,QAChE;AAAA,MACF;AAAA,IACF;AAGA,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,KAAA,EAAO,OAAA,EAAS;AAC9B,MAAA,MAAM,YAAY,IAAA,CAAK,MAAA,CAAO,KAAA,CAAM,OAAA,CAAQ,YAAY,OAAO,CAAA;AAC/D,MAAA,WAAA,MAAiB,SAAS,SAAA,EAAW;AAEnC,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,CAAe,MAAA,KAA2B;AAC9D,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAgB,MAAM,CAAA;AAC1C,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,KACsB;AAKjB,IAAM,MAAA,GAAS,CAAe,MAAA,KACnC","file":"chunk-DXG3RLWG.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 => ({\n type: \"client:navigate\",\n data: { url },\n }),\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 slot?: string;\n runId?: string;\n threadId?: string;\n timestamp?: number;\n role?: Role;\n state?: any;\n};\n\n// ============================================\n// Runtime & Hooks\n// ============================================\n\nexport type ActionExecute<\n TParams extends z.ZodSchema = z.ZodSchema,\n TState = any,\n> = (\n params: z.infer<TParams>,\n context: RuntimeContext<TState>,\n) => AsyncGenerator<Event, NextAction | void, unknown>;\n\nexport interface Action<\n TParams extends z.ZodSchema = z.ZodObject<any>,\n TState = any,\n> {\n name: string;\n description?: string;\n paramsSchema: TParams;\n execute: ActionExecute<TParams, TState>;\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, TState>>;\n ui: typeof ui;\n\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.\n * Now a generator to allow yielding multiple events and returning a result.\n */\nexport type HookGenerator<TReturn = void> = AsyncGenerator<\n Event,\n TReturn | void,\n unknown\n>;\n\nexport interface Hooks<TState = any> {\n /**\n * Called when a run session begins.\n * Can yield Events to be emitted, and return a NextAction to jump-start the loop.\n */\n onBeforeRun?: (\n input: { event: Event },\n context: RuntimeContext<TState>\n ) => HookGenerator<NextAction>;\n\n /**\n * Called when a run session completes.\n */\n onAfterRun?: (context: RuntimeContext<TState>) => HookGenerator;\n\n /**\n * Called whenever an event is yielded by the runtime.\n */\n onEvent?: (event: Event, context: RuntimeContext<TState>) => HookGenerator;\n\n /**\n * Called before an action is executed.\n * Yield events to intercept, and return a NextAction to redirect/suspend.\n */\n onBeforeAction?: (\n call: { action: Action<any, TState>; params: any; nextAction: NextAction },\n context: RuntimeContext<TState>\n ) => HookGenerator<NextAction>;\n\n /**\n * Called after an action completes.\n */\n onAfterAction?: (\n result: { action: Action<any, TState>; data: NextAction | void },\n context: RuntimeContext<TState>\n ) => HookGenerator<NextAction>;\n}\n\n/**\n * A plugin is just a named set of hooks.\n */\nexport interface Plugin<TState = any> extends Hooks<TState> {\n name: string;\n}\n\nexport type Brain<TState = any> = (\n event: Event,\n context: RuntimeContext<TState>\n) => AsyncGenerator<Event, NextAction | void, unknown>;\n\nexport interface Config<TState = any> {\n actions: Record<string, Action<any, TState>>;\n /**\n * The central brain for handling incoming events.\n */\n brain?: Brain<TState>;\n hooks?: Hooks<TState>;\n plugins?: Plugin<TState>[];\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 HookGenerator,\n} from \"./types\";\nimport { generateId } from \"./utils/generate-id\";\nimport { z } from \"zod\";\n\n/**\n * Helper to check if a value is a Melony Event.\n */\nfunction isEvent(val: any): val is Event {\n return val && typeof val === \"object\" && typeof val.type === \"string\";\n}\n\n/**\n * The Slim Runtime.\n * Single Responsibility: Orchestrate Event -> Action -> Event transitions.\n */\nexport class Runtime<TState = any> {\n private config: Config<TState>;\n\n constructor(config: Config<TState>) {\n this.config = config;\n }\n\n public async *run(event: Event): AsyncGenerator<Event> {\n const runId = event.runId ?? generateId();\n\n const context: RuntimeContext<TState> = {\n state: (event.state ?? {}) as TState,\n runId,\n stepCount: 0,\n actions: this.config.actions,\n ui,\n suspend: (event?: Event) => {\n throw event || { type: \"run-suspended\" };\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 = yield* this.callHook(\n plugin.onBeforeRun({ event }, context),\n context\n );\n if (result) {\n nextAction = result as NextAction;\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeRun\n if (this.config.hooks?.onBeforeRun) {\n const result = yield* this.callHook(\n this.config.hooks.onBeforeRun({ event }, context),\n context\n );\n if (result) {\n nextAction = result as NextAction;\n }\n }\n\n yield* this.emit(\n { type: \"run-started\", data: { inputEvent: 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(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 | undefined = current.action;\n\n if (!actionName) {\n yield* this.emit(\n {\n type: \"error\",\n data: { message: \"No action name provided in NextAction\" },\n },\n context\n );\n break;\n }\n\n const action: Action<any, TState> = 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 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 yield* this.callHook(plugin.onAfterRun(context), context);\n }\n }\n\n // 2. Trigger Hook: onAfterRun\n if (this.config.hooks?.onAfterRun) {\n yield* this.callHook(this.config.hooks.onAfterRun(context), context);\n }\n } catch (error) {\n let eventToEmit: Event | undefined;\n\n if (isEvent(error)) {\n eventToEmit = error;\n } else {\n // Wrap unexpected errors into an Event\n eventToEmit = {\n type: \"error\",\n data: {\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n };\n }\n\n if (eventToEmit) {\n yield* this.emit(eventToEmit, context);\n }\n\n return; // Gracefully stop the runtime\n }\n }\n\n private async *dispatchToBrain(\n event: Event,\n context: RuntimeContext<TState>\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<any, TState>,\n nextAction: NextAction,\n context: RuntimeContext<TState>\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 = yield* this.callHook(\n plugin.onBeforeAction({ action, params, nextAction }, context),\n context\n );\n if (hookResult) {\n nextAction = hookResult as NextAction;\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeAction\n if (this.config.hooks?.onBeforeAction) {\n const hookResult = yield* this.callHook(\n this.config.hooks.onBeforeAction({ action, params, nextAction }, context),\n context\n );\n if (hookResult) {\n nextAction = hookResult as NextAction;\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 = yield* this.callHook(\n plugin.onAfterAction({ action, data: result }, context),\n context\n );\n if (extra) {\n nextAction = extra as NextAction;\n }\n }\n }\n\n // 4. Trigger Hook: onAfterAction\n if (this.config.hooks?.onAfterAction) {\n const extra = yield* this.callHook(\n this.config.hooks.onAfterAction({ action, data: result }, context),\n context\n );\n if (extra) {\n nextAction = extra as NextAction;\n }\n }\n\n return result;\n } catch (error) {\n if (isEvent(error)) throw error;\n\n throw {\n type: \"error\",\n data: {\n action: action.name,\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n };\n }\n }\n\n /**\n * Internal helper to call a hook (generator) and yield its events.\n */\n private async *callHook<T>(\n generator: HookGenerator<T> | undefined,\n context: RuntimeContext<TState>\n ): AsyncGenerator<Event, T | void> {\n if (!generator) return;\n\n while (true) {\n const { value, done } = await generator.next();\n if (done) return value as T | void;\n yield* this.emit(value as Event, context);\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<TState>\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 generator = plugin.onEvent(finalEvent, context);\n for await (const extra of generator) {\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 generator = this.config.hooks.onEvent(finalEvent, context);\n for await (const extra of generator) {\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 = <TState = any>(config: Config<TState>) => {\n const runtime = new Runtime<TState>(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, TState = any>(\n config: Action<T, TState>\n): Action<T, TState> => config;\n\n/**\n * Helper to define a plugin.\n */\nexport const plugin = <TState = any>(config: Plugin<TState>): Plugin<TState> =>\n config;\n"]}
|
package/dist/client.d.ts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as Config, E as Event, A as Action, P as Plugin } from './types-
|
|
2
|
-
export { i as ActionExecute, B as Brain, H as HookGenerator, k as Hooks, N as NextAction, R as Role, j 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-
|
|
1
|
+
import { C as Config, E as Event, A as Action, P as Plugin } from './types-FEFI0LoL.js';
|
|
2
|
+
export { i as ActionExecute, B as Brain, H as HookGenerator, k as Hooks, N as NextAction, R as Role, j 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-FEFI0LoL.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
export { g as generateId } from './generate-id-DU8kwYc2.js';
|
|
5
5
|
|
|
@@ -10,9 +10,7 @@ export { g as generateId } from './generate-id-DU8kwYc2.js';
|
|
|
10
10
|
declare class Runtime<TState = any> {
|
|
11
11
|
private config;
|
|
12
12
|
constructor(config: Config<TState>);
|
|
13
|
-
run(
|
|
14
|
-
event: Event;
|
|
15
|
-
}): AsyncGenerator<Event>;
|
|
13
|
+
run(event: Event): AsyncGenerator<Event>;
|
|
16
14
|
private dispatchToBrain;
|
|
17
15
|
private executeAction;
|
|
18
16
|
/**
|
|
@@ -26,9 +24,7 @@ declare class Runtime<TState = any> {
|
|
|
26
24
|
}
|
|
27
25
|
declare const melony: <TState = any>(config: Config<TState>) => {
|
|
28
26
|
config: Config<TState>;
|
|
29
|
-
run: (
|
|
30
|
-
event: Event;
|
|
31
|
-
}) => AsyncGenerator<Event>;
|
|
27
|
+
run: (event: Event) => AsyncGenerator<Event>;
|
|
32
28
|
};
|
|
33
29
|
/**
|
|
34
30
|
* Helper to define an action with full type inference.
|
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-
|
|
2
|
+
export { Runtime, action, melony, plugin, ui } from './chunk-DXG3RLWG.js';
|
|
3
3
|
export { generateId } from './chunk-WAI5H335.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -230,7 +230,7 @@ interface RuntimeContext<TState = any> {
|
|
|
230
230
|
state: TState;
|
|
231
231
|
runId: string;
|
|
232
232
|
stepCount: number;
|
|
233
|
-
actions: Record<string, Action<any>>;
|
|
233
|
+
actions: Record<string, Action<any, TState>>;
|
|
234
234
|
ui: typeof ui;
|
|
235
235
|
/**
|
|
236
236
|
* Immediately interrupts the runtime execution.
|
|
@@ -264,7 +264,7 @@ interface Hooks<TState = any> {
|
|
|
264
264
|
* Yield events to intercept, and return a NextAction to redirect/suspend.
|
|
265
265
|
*/
|
|
266
266
|
onBeforeAction?: (call: {
|
|
267
|
-
action: Action<any>;
|
|
267
|
+
action: Action<any, TState>;
|
|
268
268
|
params: any;
|
|
269
269
|
nextAction: NextAction;
|
|
270
270
|
}, context: RuntimeContext<TState>) => HookGenerator<NextAction>;
|
|
@@ -272,7 +272,7 @@ interface Hooks<TState = any> {
|
|
|
272
272
|
* Called after an action completes.
|
|
273
273
|
*/
|
|
274
274
|
onAfterAction?: (result: {
|
|
275
|
-
action: Action<any>;
|
|
275
|
+
action: Action<any, TState>;
|
|
276
276
|
data: NextAction | void;
|
|
277
277
|
}, context: RuntimeContext<TState>) => HookGenerator<NextAction>;
|
|
278
278
|
}
|
package/package.json
CHANGED
|
@@ -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;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;AAAA,EACA,MAAA,EAAQ,CAAC,KAAA,MAAmD;AAAA,IAC1D,IAAA,EAAM,QAAA;AAAA,IACN;AAAA,GACF,CAAA;AAAA,EACA,OAAA,EAAS,CAAC,KAAA,MAAqD;AAA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,KAAA,EAAO,SAAA,EAAW,IAAA,CAAK,GAAA,EAAI,EAAE;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,MAAA,GAAS,CAAe,MAAA,KAA2B;AAC9D,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAgB,MAAM,CAAA;AAC1C,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,KACsB;AAKjB,IAAM,MAAA,GAAS,CAAe,MAAA,KACnC","file":"chunk-BPBQIKIH.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 => ({\n type: \"client:navigate\",\n data: { url },\n }),\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 slot?: string;\n runId?: string;\n threadId?: string;\n timestamp?: number;\n role?: Role;\n state?: any;\n};\n\n// ============================================\n// Runtime & Hooks\n// ============================================\n\nexport type ActionExecute<\n TParams extends z.ZodSchema = z.ZodSchema,\n TState = any,\n> = (\n params: z.infer<TParams>,\n context: RuntimeContext<TState>,\n) => AsyncGenerator<Event, NextAction | void, unknown>;\n\nexport interface Action<\n TParams extends z.ZodSchema = z.ZodObject<any>,\n TState = any,\n> {\n name: string;\n description?: string;\n paramsSchema: TParams;\n execute: ActionExecute<TParams, TState>;\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 /**\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.\n * Now a generator to allow yielding multiple events and returning a result.\n */\nexport type HookGenerator<TReturn = void> = AsyncGenerator<\n Event,\n TReturn | void,\n unknown\n>;\n\nexport interface Hooks<TState = any> {\n /**\n * Called when a run session begins.\n * Can yield Events to be emitted, and return a NextAction to jump-start the loop.\n */\n onBeforeRun?: (\n input: { event: Event },\n context: RuntimeContext<TState>\n ) => HookGenerator<NextAction>;\n\n /**\n * Called when a run session completes.\n */\n onAfterRun?: (context: RuntimeContext<TState>) => HookGenerator;\n\n /**\n * Called whenever an event is yielded by the runtime.\n */\n onEvent?: (event: Event, context: RuntimeContext<TState>) => HookGenerator;\n\n /**\n * Called before an action is executed.\n * Yield events to intercept, and return a NextAction to redirect/suspend.\n */\n onBeforeAction?: (\n call: { action: Action<any>; params: any; nextAction: NextAction },\n context: RuntimeContext<TState>\n ) => HookGenerator<NextAction>;\n\n /**\n * Called after an action completes.\n */\n onAfterAction?: (\n result: { action: Action<any>; data: NextAction | void },\n context: RuntimeContext<TState>\n ) => HookGenerator<NextAction>;\n}\n\n/**\n * A plugin is just a named set of hooks.\n */\nexport interface Plugin<TState = any> extends Hooks<TState> {\n name: string;\n}\n\nexport type Brain<TState = any> = (\n event: Event,\n context: RuntimeContext<TState>\n) => AsyncGenerator<Event, NextAction | void, unknown>;\n\nexport interface Config<TState = any> {\n actions: Record<string, Action<any, TState>>;\n /**\n * The central brain for handling incoming events.\n */\n brain?: Brain<TState>;\n hooks?: Hooks<TState>;\n plugins?: Plugin<TState>[];\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 HookGenerator,\n} from \"./types\";\nimport { generateId } from \"./utils/generate-id\";\nimport { z } from \"zod\";\n\n/**\n * Helper to check if a value is a Melony Event.\n */\nfunction isEvent(val: any): val is Event {\n return val && typeof val === \"object\" && typeof val.type === \"string\";\n}\n\n/**\n * The Slim Runtime.\n * Single Responsibility: Orchestrate Event -> Action -> Event transitions.\n */\nexport class Runtime<TState = any> {\n private config: Config<TState>;\n\n constructor(config: Config<TState>) {\n this.config = config;\n }\n\n public async *run(input: {\n event: Event;\n }): AsyncGenerator<Event> {\n const runId = input.event.runId ?? generateId();\n\n const context: RuntimeContext<TState> = {\n state: (input.event.state ?? {}) as TState,\n runId,\n stepCount: 0,\n actions: this.config.actions,\n ui,\n suspend: (event?: Event) => {\n throw event || { type: \"run-suspended\" };\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 = yield* this.callHook(\n plugin.onBeforeRun({ event: input.event }, context),\n context\n );\n if (result) {\n nextAction = result as NextAction;\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeRun\n if (this.config.hooks?.onBeforeRun) {\n const result = yield* this.callHook(\n this.config.hooks.onBeforeRun({ event: input.event }, context),\n context\n );\n if (result) {\n nextAction = result as NextAction;\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 | undefined = current.action;\n\n if (!actionName) {\n yield* this.emit(\n {\n type: \"error\",\n data: { message: \"No action name provided in NextAction\" },\n },\n context\n );\n break;\n }\n\n const action: Action<any, TState> = 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 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 yield* this.callHook(plugin.onAfterRun(context), context);\n }\n }\n\n // 2. Trigger Hook: onAfterRun\n if (this.config.hooks?.onAfterRun) {\n yield* this.callHook(this.config.hooks.onAfterRun(context), context);\n }\n } catch (error) {\n let eventToEmit: Event | undefined;\n\n if (isEvent(error)) {\n eventToEmit = error;\n } else {\n // Wrap unexpected errors into an Event\n eventToEmit = {\n type: \"error\",\n data: {\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n };\n }\n\n if (eventToEmit) {\n yield* this.emit(eventToEmit, context);\n }\n\n return; // Gracefully stop the runtime\n }\n }\n\n private async *dispatchToBrain(\n event: Event,\n context: RuntimeContext<TState>\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<any, TState>,\n nextAction: NextAction,\n context: RuntimeContext<TState>\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 = yield* this.callHook(\n plugin.onBeforeAction({ action, params, nextAction }, context),\n context\n );\n if (hookResult) {\n nextAction = hookResult as NextAction;\n }\n }\n }\n\n // 2. Trigger Hook: onBeforeAction\n if (this.config.hooks?.onBeforeAction) {\n const hookResult = yield* this.callHook(\n this.config.hooks.onBeforeAction({ action, params, nextAction }, context),\n context\n );\n if (hookResult) {\n nextAction = hookResult as NextAction;\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 = yield* this.callHook(\n plugin.onAfterAction({ action, data: result }, context),\n context\n );\n if (extra) {\n nextAction = extra as NextAction;\n }\n }\n }\n\n // 4. Trigger Hook: onAfterAction\n if (this.config.hooks?.onAfterAction) {\n const extra = yield* this.callHook(\n this.config.hooks.onAfterAction({ action, data: result }, context),\n context\n );\n if (extra) {\n nextAction = extra as NextAction;\n }\n }\n\n return result;\n } catch (error) {\n if (isEvent(error)) throw error;\n\n throw {\n type: \"error\",\n data: {\n action: action.name,\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n };\n }\n }\n\n /**\n * Internal helper to call a hook (generator) and yield its events.\n */\n private async *callHook<T>(\n generator: HookGenerator<T> | undefined,\n context: RuntimeContext<TState>\n ): AsyncGenerator<Event, T | void> {\n if (!generator) return;\n\n while (true) {\n const { value, done } = await generator.next();\n if (done) return value as T | void;\n yield* this.emit(value as Event, context);\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<TState>\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 generator = plugin.onEvent(finalEvent, context);\n for await (const extra of generator) {\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 generator = this.config.hooks.onEvent(finalEvent, context);\n for await (const extra of generator) {\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 = <TState = any>(config: Config<TState>) => {\n const runtime = new Runtime<TState>(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, TState = any>(\n config: Action<T, TState>\n): Action<T, TState> => config;\n\n/**\n * Helper to define a plugin.\n */\nexport const plugin = <TState = any>(config: Plugin<TState>): Plugin<TState> =>\n config;\n"]}
|