@ryuhq/sdk 0.1.13 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +19 -6
  2. package/dist/agent-plugin.cjs +46 -0
  3. package/dist/agent-plugin.d.cts +42 -32
  4. package/dist/agent-plugin.d.ts +42 -32
  5. package/dist/agent-plugin.js +1 -1
  6. package/dist/agent.cjs +9 -0
  7. package/dist/agent.d.cts +377 -1
  8. package/dist/agent.d.ts +377 -1
  9. package/dist/agent.js +4 -2
  10. package/dist/app-Bkw7LlCK.d.ts +129 -0
  11. package/dist/app-DNaGmLVf.d.cts +129 -0
  12. package/dist/builder.cjs +1095 -0
  13. package/dist/builder.d.cts +212 -0
  14. package/dist/builder.d.ts +212 -0
  15. package/dist/builder.js +28 -0
  16. package/dist/chunk-A3RGEPDG.js +250 -0
  17. package/dist/chunk-FZSFZOIN.js +200 -0
  18. package/dist/{chunk-ODFEUVPW.js → chunk-HACAGK65.js} +1 -18
  19. package/dist/{chunk-AO2KJRDD.js → chunk-IEUQ3CDG.js} +125 -2
  20. package/dist/chunk-IKEDLLFY.js +19 -0
  21. package/dist/chunk-IOLP5FFE.js +354 -0
  22. package/dist/{chunk-G6FLVEC4.js → chunk-JX6DDRXV.js} +46 -0
  23. package/dist/chunk-T5676WL2.js +240 -0
  24. package/dist/chunk-TLDPEGC7.js +21 -0
  25. package/dist/chunk-TXSHHZF2.js +0 -0
  26. package/dist/{chunk-MTUBUPIV.js → chunk-ULSVL7EC.js} +8 -227
  27. package/dist/chunk-VLIRNNAE.js +154 -0
  28. package/dist/chunk-W3KPP4WN.js +135 -0
  29. package/dist/cli.cjs +258 -14
  30. package/dist/cli.js +96 -16
  31. package/dist/client-D5U6ssPc.d.cts +84 -0
  32. package/dist/client-D5U6ssPc.d.ts +84 -0
  33. package/dist/index.cjs +519 -5
  34. package/dist/index.d.cts +16 -632
  35. package/dist/index.d.ts +16 -632
  36. package/dist/index.js +63 -695
  37. package/dist/manifest.cjs +129 -3
  38. package/dist/manifest.d.cts +105 -2
  39. package/dist/manifest.d.ts +105 -2
  40. package/dist/manifest.js +7 -1
  41. package/dist/mcp/client.cjs +180 -0
  42. package/dist/mcp/client.d.cts +49 -0
  43. package/dist/mcp/client.d.ts +49 -0
  44. package/dist/mcp/client.js +10 -0
  45. package/dist/mcp/server.cjs +370 -0
  46. package/dist/mcp/server.d.cts +126 -0
  47. package/dist/mcp/server.d.ts +126 -0
  48. package/dist/mcp/server.js +9 -0
  49. package/dist/mcp.cjs +376 -0
  50. package/dist/mcp.d.cts +2 -0
  51. package/dist/mcp.d.ts +2 -0
  52. package/dist/mcp.js +17 -0
  53. package/dist/model.cjs +141 -0
  54. package/dist/model.d.cts +33 -0
  55. package/dist/model.d.ts +33 -0
  56. package/dist/model.js +18 -0
  57. package/dist/plugin.cjs +46 -0
  58. package/dist/plugin.d.cts +215 -0
  59. package/dist/plugin.d.ts +215 -0
  60. package/dist/plugin.js +8 -0
  61. package/dist/runnable.cjs +1230 -0
  62. package/dist/runnable.d.cts +271 -0
  63. package/dist/runnable.d.ts +271 -0
  64. package/dist/runnable.js +28 -0
  65. package/dist/{index-B6SkaAjJ.d.ts → tool-DSx2bFx8.d.ts} +35 -458
  66. package/dist/{index-BvAB5eMk.d.cts → tool-u-VR0fLF.d.cts} +35 -458
  67. package/package.json +38 -2
  68. package/src/agent/loop.test.ts +4 -4
  69. package/src/agent/tools.ts +3 -3
  70. package/src/agent-plugin.test.ts +58 -0
  71. package/src/agent-plugin.ts +108 -35
  72. package/src/cli/dev.test.ts +26 -47
  73. package/src/cli/dev.ts +10 -2
  74. package/src/cli.ts +98 -15
  75. package/src/exports-lockstep.test.ts +92 -0
  76. package/src/generated/plugin-manifest.ts +243 -27
  77. package/src/index.ts +35 -0
  78. package/src/manifest-schema.test.ts +30 -1
  79. package/src/manifest.fixtures.test.ts +13 -3
  80. package/src/manifest.test.ts +96 -10
  81. package/src/manifest.ts +334 -187
  82. package/src/mcp/index.ts +18 -0
  83. package/src/model/index.ts +22 -0
  84. package/src/plugin/ryu-plugin.ts +82 -0
  85. package/src/runnable/app.test.ts +2 -0
  86. package/src/runnable/app.ts +5 -2
  87. package/src/runnable/index.ts +2 -0
  88. package/src/runnable/primitives.ts +57 -0
  89. package/src/runnable/tool.ts +1 -1
  90. package/src/runnable/turn-hook.ts +4 -1
@@ -0,0 +1,1230 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/runnable/index.ts
31
+ var runnable_exports = {};
32
+ __export(runnable_exports, {
33
+ PRIMITIVE_BINDINGS: () => PRIMITIVE_BINDINGS,
34
+ appToolId: () => appToolId,
35
+ createPrimitives: () => createPrimitives,
36
+ defineAgent: () => defineAgent,
37
+ defineApp: () => defineApp,
38
+ defineSkill: () => defineSkill,
39
+ defineTool: () => defineTool,
40
+ defineWorkflow: () => defineWorkflow,
41
+ httpPrimitiveTransport: () => httpPrimitiveTransport
42
+ });
43
+ module.exports = __toCommonJS(runnable_exports);
44
+
45
+ // src/manifest.ts
46
+ var import_node_module = require("module");
47
+ var import_zod = require("zod");
48
+ var RunnableKindSchema = import_zod.z.enum([
49
+ "agent",
50
+ "workflow",
51
+ "tool",
52
+ "skill",
53
+ // A companion surface (in-desktop panel). Added so a packable plugin can
54
+ // declare a companion runnable that flows through Core's existing Companion
55
+ // handler → app_contrib → `GET /api/plugins/contributions` → the desktop
56
+ // `/plugin/<id>` route. Its `config.ui_entry` (see `CompanionRunnableConfigSchema`)
57
+ // is what `ryu pack` bundles into `ui_code`.
58
+ "companion"
59
+ ]);
60
+ var RunnableMetaSchema = import_zod.z.object({
61
+ /** Stable unique identifier (e.g. `"agent-researcher"`). */
62
+ id: import_zod.z.string().min(1),
63
+ /** Human-readable display name. */
64
+ name: import_zod.z.string().min(1),
65
+ /** Which kind of runnable this entry describes. */
66
+ kind: RunnableKindSchema,
67
+ /**
68
+ * Optional per-kind config blob. Mirrors Core's `RunnableEntry.config`
69
+ * (`Option<serde_json::Value>`) so a manifest authored here round-trips
70
+ * through Core-strict validation. Left opaque (a record) at this authoring
71
+ * layer; the per-kind shape is enforced by Core's `validate_runnable`.
72
+ *
73
+ * For a `companion` runnable, `config.ui_entry` names the plugin's UI entry
74
+ * module (relative to the manifest dir). `ryu pack` bundles that entry into
75
+ * the emitted `ui_code`; Core's `CompanionConfig.ui_entry` is the lockstep
76
+ * field so a packed companion validates.
77
+ */
78
+ config: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
79
+ });
80
+ function labelImpersonatesSystemChrome(label) {
81
+ const lower = label.toLowerCase();
82
+ return lower.includes("ryu") || lower.includes("system");
83
+ }
84
+ var CompanionSurfaceSchema = import_zod.z.object({
85
+ /** Display label for the companion panel tab or tooltip. Anti-impersonation:
86
+ * may not pose as first-party Ryu/system chrome (see
87
+ * {@link labelImpersonatesSystemChrome}). */
88
+ label: import_zod.z.string().min(1).refine((value) => !labelImpersonatesSystemChrome(value), {
89
+ message: "companion label must not impersonate system chrome (must not contain 'ryu' or 'system')"
90
+ }),
91
+ /** Icon identifier resolved by the desktop shell. */
92
+ icon: import_zod.z.string().optional(),
93
+ /** Keyboard shortcut string (e.g. `"ctrl+shift+r"`). */
94
+ shortcut: import_zod.z.string().optional()
95
+ });
96
+ var TurnHookContributionSchema = import_zod.z.object({
97
+ /** Stable id for this hook (unique within the plugin). */
98
+ id: import_zod.z.string().min(1),
99
+ /** Turn boundary this fires on. Today only `"post_assistant_turn"`. */
100
+ on: import_zod.z.string().min(1).default("post_assistant_turn"),
101
+ /** The JS hook body executed in the sandbox (returns a directive). */
102
+ code: import_zod.z.string().min(1).optional(),
103
+ /** Path to the hook body, relative to the plugin root (`hooks/<name>.js`). */
104
+ code_file: import_zod.z.string().min(1).optional(),
105
+ /**
106
+ * Cheap pre-gate mirroring Core's `HookMatch` (serde name `match` on
107
+ * `TurnHookContribution.run_when`). MUST round-trip through this schema:
108
+ * `ryu pack`/`publish` persist `safeParse(...).data`, so a field missing here
109
+ * is silently STRIPPED before signing — a tool-gated `pre_tool_use` hook
110
+ * (e.g. `tools: ["bash*"]`) would lose its gate and run on EVERY tool call.
111
+ */
112
+ match: import_zod.z.object({
113
+ /** Run only if the request set this composer flag true. */
114
+ flag: import_zod.z.string().optional(),
115
+ /** Run if the last user message starts with any of these prefixes. */
116
+ commands: import_zod.z.array(import_zod.z.string()).default([]),
117
+ /** Run if the plugin has stored state for this conversation. */
118
+ stateful: import_zod.z.boolean().default(false),
119
+ /** Run if `ctx.tool_name` matches any of these `*`-wildcard patterns. */
120
+ tools: import_zod.z.array(import_zod.z.string()).default([])
121
+ }).optional()
122
+ }).refine((h) => Boolean(h.code) !== Boolean(h.code_file), {
123
+ message: "a turn hook must declare exactly one of 'code' (inline body) or 'code_file' (path to hooks/<name>.js)",
124
+ path: ["code_file"]
125
+ });
126
+ var HookEventContributionSchema = import_zod.z.object({
127
+ /** Fully-qualified event id: `<plugin id>#<event name>`, e.g. `@acme/meetings#meeting.ended`. */
128
+ id: import_zod.z.string().min(1),
129
+ /** Human-readable title for the event picker. */
130
+ title: import_zod.z.string().min(1),
131
+ /** What the event means and when it fires. */
132
+ description: import_zod.z.string().optional(),
133
+ /** Example of the `ctx.event` payload. Documentation, not a validated schema. */
134
+ payload_example: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
135
+ });
136
+ var PiExtensionContributionSchema = import_zod.z.object({
137
+ /** Stable id for this extension within the plugin (`[a-z0-9][a-z0-9._-]*`). */
138
+ id: import_zod.z.string().min(1),
139
+ /** Path to the source, relative to the plugin root: `pi-extensions/<name>.ts`. */
140
+ file: import_zod.z.string().min(1),
141
+ /** Optional one-liner describing what the extension adds to the agent. */
142
+ description: import_zod.z.string().optional()
143
+ });
144
+ var OutputStyleContributionSchema = import_zod.z.object({
145
+ /** Stable id for this style within the plugin (`[a-z0-9][a-z0-9._-]*`). It is
146
+ * also the persisted selection key, so it must survive a settings key and a URL
147
+ * path. */
148
+ id: import_zod.z.string().min(1),
149
+ /** SOURCE form: path to the Markdown file, relative to the plugin root —
150
+ * exactly `output-styles/<name>.md`. `ryu pack` replaces this with `source`. */
151
+ file: import_zod.z.string().min(1).optional(),
152
+ /** WIRE form: the file's contents verbatim, frontmatter INCLUDED. The whole file
153
+ * rather than a pre-split body plus mirrored `name`/`description` keys, so a
154
+ * plugin style and a user's own `output-styles/*.md` go through one parser and
155
+ * the frontmatter stays the single source of truth for a style's metadata. */
156
+ source: import_zod.z.string().optional()
157
+ });
158
+ var DEFAULT_WIDGET_MIME = "text/html+skybridge";
159
+ var DEFAULT_WIDGET_DISPLAY_MODE = "inline";
160
+ var WidgetContributionSchema = import_zod.z.object({
161
+ /** The fully-qualified tool id whose result renders this widget. */
162
+ tool_id: import_zod.z.string().min(1),
163
+ /** `ui://widget/<slug>.html` — the widget resource uri. */
164
+ uri: import_zod.z.string().min(1),
165
+ /** Source entry (e.g. `src/apps/checklist/index.tsx`) for `ryu pack`. */
166
+ ui_entry: import_zod.z.string().optional(),
167
+ /** Widget MIME dialect (default `text/html+skybridge`). */
168
+ mime: import_zod.z.string().default(DEFAULT_WIDGET_MIME),
169
+ /** Default display mode (`inline` | `fullscreen` | `pip`). */
170
+ default_display_mode: import_zod.z.string().default(DEFAULT_WIDGET_DISPLAY_MODE)
171
+ });
172
+ var ChatWidgetTemplateSchema = import_zod.z.object({
173
+ id: import_zod.z.string().regex(/^[a-z0-9][a-z0-9._:-]*$/),
174
+ title: import_zod.z.string().min(1),
175
+ description: import_zod.z.string().optional(),
176
+ triggers: import_zod.z.array(import_zod.z.string()).default([]),
177
+ examples: import_zod.z.array(import_zod.z.string()).default([]),
178
+ backing: import_zod.z.object({
179
+ tool_id: import_zod.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/).optional(),
180
+ view_id: import_zod.z.string().regex(/^[a-z0-9][a-z0-9._:-]*$/).optional()
181
+ }),
182
+ display_mode: import_zod.z.string().min(1),
183
+ safe_action_ids: import_zod.z.array(import_zod.z.string().regex(/^[a-z0-9][a-z0-9._-]*$/)).default([]),
184
+ availability: import_zod.z.string().default("available")
185
+ }).superRefine((value, ctx) => {
186
+ const count = Number(Boolean(value.backing.tool_id)) + Number(Boolean(value.backing.view_id));
187
+ if (count !== 1 && value.availability === "available") {
188
+ ctx.addIssue({ code: "custom", path: ["backing"], message: "available templates need exactly one backing tool_id or view_id" });
189
+ }
190
+ if (count > 1) {
191
+ ctx.addIssue({ code: "custom", path: ["backing"], message: "backing must declare at most one of tool_id or view_id" });
192
+ }
193
+ });
194
+ var ToolAppConfigSchema = import_zod.z.object({
195
+ /** MCP tool slug this runnable wraps — the fully-qualified `<server>.<name>` id. */
196
+ slug: import_zod.z.string().min(1),
197
+ /** The tool description the model reads when choosing it. Carried here because a
198
+ * packed app's manifest is the only channel (there is no `generated.rs`); Core's
199
+ * app-tool synthesis reads it back onto the `RegistryTool`. */
200
+ description: import_zod.z.string(),
201
+ /** JSON Schema for the tool's arguments (used for validation + the LLM tool
202
+ * surface). Snake_case to match `widget_accessible`. Absent = no arguments. */
203
+ input_schema: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
204
+ /** True when calling this tool renders the app's widget (carries the template). */
205
+ widget: import_zod.z.boolean().default(false),
206
+ /** True when a mounted widget may `callTool` this tool (a companion), or when a
207
+ * render tool's widget may call any companion the app declares. */
208
+ widget_accessible: import_zod.z.boolean().default(false),
209
+ /** Optional status label shown while the render tool runs. */
210
+ invoking: import_zod.z.string().optional(),
211
+ /** Optional status label shown when the render tool finishes. */
212
+ invoked: import_zod.z.string().optional()
213
+ });
214
+ var ContributesSchema = import_zod.z.object({
215
+ turn_hooks: import_zod.z.array(TurnHookContributionSchema).default([]),
216
+ /** App events this plugin EMITS — the provider half of the hook system, whose
217
+ * consumer half is `turn_hooks`. Mirrors the Rust `Contributes.hook_events`;
218
+ * omitting it here would have `ryu pack` strip every declared event before
219
+ * signing, leaving an app that emits events nothing is allowed to subscribe to. */
220
+ hook_events: import_zod.z.array(HookEventContributionSchema).default([]),
221
+ composer_controls: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
222
+ /** Chat feature descriptors whose behavior is implemented by the host shell.
223
+ * Mirrors the Rust-side `Contributes.chat_features`; keeping this field in the
224
+ * authoring schema prevents `ryu pack` from silently deleting a plugin's chat
225
+ * feature declaration before signing. */
226
+ chat_features: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
227
+ settings_tabs: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
228
+ slash_commands: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
229
+ /** App widgets (Ryu Apps). Each binds a render tool id to its
230
+ * `ui://widget/<slug>.html` template. Mirrors the Rust-side
231
+ * `Contributes.widgets` field, without which the CLI's zod parse would strip
232
+ * every widget an app authored here declares. */
233
+ widgets: import_zod.z.array(WidgetContributionSchema).default([]),
234
+ /** Metadata-only chat widget templates. */
235
+ chat_widget_templates: import_zod.z.array(ChatWidgetTemplateSchema).optional(),
236
+ /** App-registered sidebar sections (header + live list) and buttons (single nav
237
+ * rows). Loosely typed here — the shell owns the spec vocabulary — matching how
238
+ * `composer_controls`/`settings_tabs` are declared. Mirrors the Rust-side
239
+ * `Contributes.sidebar_sections` / `Contributes.sidebar_buttons`. */
240
+ sidebar_sections: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
241
+ sidebar_buttons: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
242
+ /** App-registered workspace dock panels (a tab in the desktop's bottom/right
243
+ * dock). Loosely typed for the same reason as the surfaces above — the shell
244
+ * owns the `panel` render-mode vocabulary and the `spec` payload. Mirrors the
245
+ * Rust-side `Contributes.dock_panels`; without it the CLI's zod parse would
246
+ * strip the dock panel an app declares here. */
247
+ dock_panels: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
248
+ /** App-registered live activities (the desktop "Dynamic Island" cards). Loosely
249
+ * typed for the same reason as the surfaces above — the shell owns the
250
+ * `spec` vocabulary. Mirrors the Rust-side `Contributes.live_activities`;
251
+ * without it the CLI's zod parse would strip every live activity an app
252
+ * declares here, so a packed bundle would ship a dock that silently stays
253
+ * empty. */
254
+ live_activities: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
255
+ /** Deletable data categories the app owns — one "Delete all X" row in Settings
256
+ * → Danger Zone. Mirrors the Rust-side `Contributes.data_categories`; without
257
+ * it the CLI's zod parse would strip the declaration before signing, and the
258
+ * app's danger-zone row would simply never appear on any node that installed
259
+ * the packed bundle. Loosely typed here for the same reason as the surfaces
260
+ * above — Core is the layer that types it, because Core is the layer that has
261
+ * to resolve the id to something that can actually delete the rows. */
262
+ data_categories: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
263
+ /** Language servers the plugin declares, keyed by server name — the mirror of
264
+ * Claude Code's `.lsp.json` / `lspServers`, so a config written for either host
265
+ * loads in the other. Mirrors the Rust-side `Contributes.lsp_servers`; without
266
+ * it the CLI's zod parse would strip every language server a plugin declares,
267
+ * before the manifest is signed.
268
+ *
269
+ * The ENTRY is deliberately a loose record and not a 13-field `z.object()`
270
+ * mirroring `LspServerContribution`. Claude Code owns this field vocabulary,
271
+ * not Ryu: a typed object here would strip a field from a newer Claude release
272
+ * on its way through `ryu pack` — the same silent-deletion bug this field
273
+ * exists to fix, one level down. Core is the layer that types it, because Core
274
+ * is the layer that acts on it. */
275
+ lsp_servers: import_zod.z.record(import_zod.z.string(), import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default({}),
276
+ /** Pi extensions the plugin ships — TypeScript the managed `ryu` (Pi) agent
277
+ * loads at process start. Mirrors the Rust-side `Contributes.pi_extensions`;
278
+ * without it the CLI's zod parse would strip the declaration before signing,
279
+ * and the packed plugin would ship a `pi-extensions/` folder nothing loads.
280
+ *
281
+ * Typed (not a loose record) because Ryu owns this vocabulary — three fields,
282
+ * all of them Core-interpreted — unlike `lsp_servers`, whose entry shape is
283
+ * Claude Code's to extend. */
284
+ pi_extensions: import_zod.z.array(PiExtensionContributionSchema).default([]),
285
+ /** Output styles the plugin ships — Markdown files that rewrite the system
286
+ * prompt's voice. Mirrors the Rust-side `Contributes.output_styles`; without it
287
+ * the CLI's zod parse would strip the declaration, and `ryu pack` would sign a
288
+ * bundle whose styles simply do not exist. Worse than the usual case of that
289
+ * bug: the styles' `.md` files are not carried by the bundle either, so there
290
+ * would be no residue to notice — the plugin would install clean and contribute
291
+ * nothing. */
292
+ output_styles: import_zod.z.array(OutputStyleContributionSchema).default([]),
293
+ /** Per-message actions contributed by an enabled plugin. Kept as loose records
294
+ * so renderer-specific `kind`/`args` payloads survive `ryu pack` unchanged. */
295
+ message_actions: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([])
296
+ });
297
+ var SetupStepSchema = import_zod.z.object({
298
+ /** Card heading (e.g. the companion app name). */
299
+ title: import_zod.z.string().optional(),
300
+ /** Instruction body shown under the title. */
301
+ description: import_zod.z.string().optional(),
302
+ /** Label for the optional action button. */
303
+ actionLabel: import_zod.z.string().optional(),
304
+ /** URL the action button opens (validated server-side on publish). */
305
+ actionUrl: import_zod.z.string().optional()
306
+ });
307
+ var AppDependencySchema = import_zod.z.object({
308
+ /** The `id` of the plugin this one depends on. */
309
+ id: import_zod.z.string().min(1, "dependency id is required"),
310
+ /** Optional MINIMUM version the dependency must satisfy (`"1.2.0"` = `">=1.2.0"`). */
311
+ min_version: import_zod.z.string().min(1).optional()
312
+ });
313
+ var CapabilityReqSchema = import_zod.z.object({
314
+ /** Capability name (e.g. `"rag"`, `"memory"`, `"tts"`). Matched against a
315
+ * provider's `provides[].capability`. */
316
+ capability: import_zod.z.string().min(1, "capability name is required"),
317
+ /** Optional MINIMUM capability version the bound provider must satisfy
318
+ * (`"1.2.0"` = `">=1.2.0"`). Absent = any version. */
319
+ min_version: import_zod.z.string().min(1).optional()
320
+ });
321
+ var RequiresSchema = import_zod.z.object({
322
+ /** Other plugins that must be installed + enabled before this one enables. */
323
+ apps: import_zod.z.array(AppDependencySchema).default([]),
324
+ /**
325
+ * Abstract capability edges the broker resolves to a bound provider at
326
+ * enable time. Mirrors `Requires::capabilities` in
327
+ * `crates/ryu-kernel-contracts` — an `apps` edge names a specific plugin; a
328
+ * `capabilities` edge names a capability and lets the binding registry choose
329
+ * the provider. Each is lowered to an app-id graph edge once bound, so the
330
+ * enable/disable/cycle machinery is shared. Empty for the common case.
331
+ */
332
+ capabilities: import_zod.z.array(CapabilityReqSchema).default([]),
333
+ /**
334
+ * Permission grants implied by the dependencies. Declaration only — the
335
+ * Gateway remains the sole authority on what a grant *allows*, and Core's
336
+ * dependency graph resolves `apps` only.
337
+ */
338
+ grants: import_zod.z.array(import_zod.z.string()).default([])
339
+ });
340
+ var SurfaceSchema = import_zod.z.enum([
341
+ /** The Ryu Gateway. */
342
+ "gateway",
343
+ /** A headless Core node (no UI). */
344
+ "core",
345
+ /** The Tauri desktop app. */
346
+ "desktop",
347
+ /** The Electron dynamic-island companion. */
348
+ "island",
349
+ /** The Expo/React-Native mobile app. */
350
+ "mobile",
351
+ /** The browser extension. */
352
+ "extension",
353
+ /** The Next.js web app. */
354
+ "web",
355
+ /** The terminal client. */
356
+ "cli"
357
+ ]);
358
+ var EnginesReqSchema = import_zod.z.object({
359
+ /** Floor for the terminal (`cli`) surface. */
360
+ cli: import_zod.z.string().optional(),
361
+ /** Floor for the Tauri desktop app. */
362
+ desktop: import_zod.z.string().optional(),
363
+ /** Floor for the browser extension. */
364
+ extension: import_zod.z.string().optional(),
365
+ /** Floor for the Ryu Gateway. */
366
+ gateway: import_zod.z.string().optional(),
367
+ /** Floor for the dynamic-island companion. */
368
+ island: import_zod.z.string().optional(),
369
+ /** Floor for the mobile app. */
370
+ mobile: import_zod.z.string().optional(),
371
+ /** Floor for the running **Core** (e.g. `">=0.3.0"`). Required. */
372
+ ryu: import_zod.z.string().min(1, "engines.ryu is required when engines is present"),
373
+ /** Floor for the Next.js web app. */
374
+ web: import_zod.z.string().optional()
375
+ });
376
+ var McpServerAuthSchema = import_zod.z.object({
377
+ client_id: import_zod.z.string().min(1).optional(),
378
+ type: import_zod.z.literal("oauth")
379
+ }).strict();
380
+ var McpServerDeclSchema = import_zod.z.object({
381
+ args: import_zod.z.array(import_zod.z.string()).default([]),
382
+ auth: McpServerAuthSchema.optional(),
383
+ command: import_zod.z.string().optional(),
384
+ command_env: import_zod.z.string().optional(),
385
+ description: import_zod.z.string().optional(),
386
+ enabled: import_zod.z.boolean().default(true),
387
+ env: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).default({}),
388
+ headers: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).default({}),
389
+ type: import_zod.z.enum(["stdio", "http", "streamable-http", "streamable_http", "sse"]).optional(),
390
+ url: import_zod.z.url().optional()
391
+ }).superRefine((server, context) => {
392
+ if (!(server.command || server.url)) {
393
+ context.addIssue({
394
+ code: "custom",
395
+ message: "an MCP server requires command or url"
396
+ });
397
+ }
398
+ if (!server.auth) {
399
+ return;
400
+ }
401
+ if (server.command || server.type === "stdio" || !server.url) {
402
+ context.addIssue({
403
+ code: "custom",
404
+ message: "OAuth is supported only for remote HTTP MCP servers"
405
+ });
406
+ return;
407
+ }
408
+ if (Object.keys(server.headers).some(
409
+ (name) => name.toLowerCase() === "authorization"
410
+ )) {
411
+ context.addIssue({
412
+ code: "custom",
413
+ message: "OAuth cannot be combined with a static Authorization header"
414
+ });
415
+ }
416
+ const url = new URL(server.url);
417
+ const loopback = url.hostname === "localhost" || url.hostname.startsWith("127.") || url.hostname === "[::1]" || url.hostname === "::1";
418
+ if (url.username || url.password || url.hash) {
419
+ context.addIssue({
420
+ code: "custom",
421
+ message: "OAuth MCP URLs cannot contain credentials or fragments"
422
+ });
423
+ }
424
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
425
+ context.addIssue({
426
+ code: "custom",
427
+ message: "OAuth MCP URLs must use HTTPS except on loopback"
428
+ });
429
+ }
430
+ });
431
+ var PluginManifestSchema = import_zod.z.object({
432
+ /** Reverse-domain unique identifier (e.g. `"com.example.my-plugin"`). */
433
+ id: import_zod.z.string().min(1, "id is required"),
434
+ /** Human-readable display name shown in the plugin store / launcher. */
435
+ name: import_zod.z.string().min(1, "name is required"),
436
+ /**
437
+ * Semver version string (e.g. `"1.0.0"`). Core's loader rejects any manifest
438
+ * whose version is not valid semver; the regex here enforces the same rule at
439
+ * SDK-build time.
440
+ */
441
+ version: import_zod.z.string().regex(
442
+ /^\d+\.\d+\.\d+(?:-[\w.]+)?(?:\+[\w.]+)?$/,
443
+ "version must be a valid semver string (e.g. 1.0.0)"
444
+ ),
445
+ /**
446
+ * Lower-case hex `sha256(utf8_bytes(ui_code))` binding the plugin's bundled
447
+ * sandboxed-UI code to this manifest. `ryu pack` / `ryu publish` compute it and
448
+ * write it here BEFORE the manifest is signed, so the hash rides INSIDE the
449
+ * Gateway-signed surface while the `ui_code` blob rides OUTSIDE it as payload;
450
+ * Core's install path recomputes the hash over the fetched code and rejects a
451
+ * mismatch fail-closed. Absent for a manifest-only plugin (no bundled UI).
452
+ * Mirrors Core's `PluginManifest.ui_code_sha256`.
453
+ */
454
+ ui_code_sha256: import_zod.z.string().nullish(),
455
+ /** The Runnables this plugin bundles. */
456
+ runnables: import_zod.z.array(RunnableMetaSchema).default([]),
457
+ /**
458
+ * Permission grants this plugin declares it needs (e.g. `"mcp:web_search"`).
459
+ * Declarations only — grant enforcement is the Gateway's responsibility.
460
+ */
461
+ permission_grants: import_zod.z.array(import_zod.z.string()).default([]),
462
+ /** Remote or stdio MCP servers registered by this plugin. */
463
+ mcp_servers: import_zod.z.record(import_zod.z.string(), McpServerDeclSchema).optional(),
464
+ /**
465
+ * Optional Companion surface (an in-desktop overlay or sidebar panel).
466
+ * Absent when the plugin has no Companion surface.
467
+ */
468
+ companion: CompanionSurfaceSchema.optional(),
469
+ /**
470
+ * VS-Code-style activation events (`"*"`, `"onStartup"`, `"onChat"`,
471
+ * `"onCommand:<id>"`). Empty = eager. Turn-hook plugins are driven by their
472
+ * enabled flag, so `["*"]` is the usual value.
473
+ */
474
+ activation_events: import_zod.z.array(import_zod.z.string()).default([]),
475
+ /**
476
+ * Contribution points: server-side turn hooks + declarative UI widgets.
477
+ * Absent for a plugin that contributes nothing here.
478
+ */
479
+ contributes: ContributesSchema.optional(),
480
+ /**
481
+ * **Plugin-to-plugin dependencies** — the other plugins this one needs. Core
482
+ * resolves them into a topological enable order (dependencies enable first;
483
+ * disabling one is refused while an enabled dependent needs it).
484
+ *
485
+ * Absent = **no dependencies**, the backward-compatible default. Kept
486
+ * `.optional()` (never defaulted) so a manifest that declares none serialises
487
+ * with no `requires` key at all, exactly like Core's
488
+ * `#[serde(skip_serializing_if = "Option::is_none")]`.
489
+ */
490
+ requires: RequiresSchema.optional(),
491
+ /**
492
+ * Host surfaces this plugin runs on. **Empty or absent = runs on EVERY
493
+ * surface** — the backward-compatible default, which must never be read as
494
+ * "runs nowhere". Core filters only when the list is explicitly non-empty, and
495
+ * only at the read boundary (`GET /api/plugins`, keyed on `x-ryu-surface`), so
496
+ * an unsupported-target plugin stays installable and inspectable.
497
+ */
498
+ targets: import_zod.z.array(SurfaceSchema).default([]),
499
+ /**
500
+ * Host version floors — the semver requirement each surface must satisfy for
501
+ * this plugin to install. Mirrors Core's `EnginesReq`
502
+ * (`crates/core/kernel-contracts/src/manifest.rs`).
503
+ *
504
+ * `ryu` is the **Core** floor and the only required key (it is the legacy
505
+ * spelling; every manifest in the wild carries just that one). The rest are
506
+ * optional per-surface floors.
507
+ *
508
+ * REGRESSION THIS FIXES: `engines` was absent from this schema entirely, and
509
+ * zod strips unlisted keys — so `ryu pack` silently dropped the whole block
510
+ * from every bundle it produced. A plugin could declare a Core floor, publish,
511
+ * and ship a bundle that declared none. Any new host floor MUST be added here
512
+ * as well as in the Rust contract, or it does not survive packing.
513
+ */
514
+ engines: EnginesReqSchema.optional(),
515
+ /**
516
+ * Optional per-item AFFILIATE terms: the commission paid to a referrer when a
517
+ * referred user buys this (paid) item. `value` is basis points for `percent`
518
+ * (2000 = 20%) or minor units (cents) for `flat`. Absent (or `enabled:false`)
519
+ * falls back to the seller org owner's default affiliate terms. This is the
520
+ * authoring surface for the marketplace publish body's `affiliate` field (the
521
+ * server re-validates it); it only takes effect on a paid item.
522
+ */
523
+ affiliate: import_zod.z.object({
524
+ enabled: import_zod.z.boolean().default(false),
525
+ rule: import_zod.z.object({
526
+ type: import_zod.z.enum(["percent", "flat"]),
527
+ value: import_zod.z.number().nonnegative(),
528
+ recurring: import_zod.z.boolean().default(false),
529
+ durationMonths: import_zod.z.number().int().positive().nullish(),
530
+ fundedBy: import_zod.z.enum(["platform", "seller"]).default("platform")
531
+ }).optional()
532
+ }).optional(),
533
+ // ── Rich listing metadata (Phase 1.5) ──────────────────────────────────────
534
+ // Optional store-listing fields a plugin author declares so the marketplace
535
+ // detail dialog renders a richer App-Store-style preview. Field names align
536
+ // with the Claude `.claude-plugin/marketplace.json` plugin-entry standard where
537
+ // one exists (`author`, `homepage`, `keywords`, `category`, `license`); the
538
+ // rest are Ryu extensions. `ryu publish` forwards these FLAT into the publish
539
+ // body (not inside the signed manifest blob) so the control plane stores them.
540
+ // All optional + additive: a manifest omitting them still validates.
541
+ /** Longer plain/markdown description shown in the detail dialog. */
542
+ description: import_zod.z.string().optional(),
543
+ /** Short one-line pitch shown under the name (Ryu extension). */
544
+ tagline: import_zod.z.string().optional(),
545
+ /**
546
+ * Publisher identity. A bare string OR a Claude-style object; `ryu publish`
547
+ * resolves it to the display `developer` (`author.name` when an object).
548
+ */
549
+ author: import_zod.z.union([
550
+ import_zod.z.string(),
551
+ import_zod.z.object({
552
+ name: import_zod.z.string(),
553
+ email: import_zod.z.string().optional(),
554
+ url: import_zod.z.string().optional()
555
+ })
556
+ ]).optional(),
557
+ /** Public source repository URL (Claude/Codex `repository`). */
558
+ repository: import_zod.z.string().url().optional(),
559
+ /** True when the provider operates outside the local Ryu runtime. */
560
+ external: import_zod.z.boolean().optional(),
561
+ /** Project/marketing homepage — maps to the listing `website` (Claude field). */
562
+ homepage: import_zod.z.string().optional(),
563
+ /** Free-text search keywords (Claude field). */
564
+ keywords: import_zod.z.array(import_zod.z.string()).optional(),
565
+ /** Stable Marketplace filter labels (Ryu extension). */
566
+ tags: import_zod.z.array(import_zod.z.string()).optional(),
567
+ /** Taxonomy category beyond the runnable kinds (Claude field). */
568
+ category: import_zod.z.string().optional(),
569
+ /** SPDX-ish license identifier (Claude field). */
570
+ license: import_zod.z.string().optional(),
571
+ /** Square logo/icon URL for the listing card + detail header. */
572
+ iconUrl: import_zod.z.string().optional(),
573
+ /**
574
+ * Icon-primitive id for the listing card (Ryu extension): an Iconify/icons0
575
+ * `prefix:name`, a bare Hugeicons name, or a URL, resolved by the shared `Icon`
576
+ * primitive. A monochrome GLYPH masked with the current text colour — distinct
577
+ * from `iconUrl` (a raster logo). Falls back to `iconUrl` when omitted.
578
+ */
579
+ icon: import_zod.z.string().optional(),
580
+ /** Optional detail-page hero banner metadata forwarded to the marketplace. */
581
+ banner: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
582
+ /**
583
+ * Dithered-gradient background for the card's icon square (Ryu extension),
584
+ * mirroring dither-kit's `DitherGradient` props. `from`/`to` are a palette-colour
585
+ * name (`green`, `blue`, `purple`, `pink`, `orange`, `red`, `grey`) or a hue
586
+ * number (0–360); `direction` is where `to` ends up. Renders behind the glyph in
587
+ * place of a flat `iconBackground`; the render layer validates + falls back.
588
+ */
589
+ iconDither: import_zod.z.object({
590
+ from: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
591
+ to: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional(),
592
+ direction: import_zod.z.enum(["up", "down", "left", "right"]).optional()
593
+ }).optional(),
594
+ /** Ordered App-Store-style screenshot gallery URLs (Ryu extension). */
595
+ screenshots: import_zod.z.array(import_zod.z.string()).optional(),
596
+ /** Privacy policy URL surfaced on detail (Ryu extension). */
597
+ privacyPolicyUrl: import_zod.z.string().optional(),
598
+ /** Terms-of-service URL surfaced on detail (Ryu extension). */
599
+ termsOfServiceUrl: import_zod.z.string().optional(),
600
+ /**
601
+ * Human-readable capability strings (Ryu extension). When omitted the control
602
+ * plane derives a default from `permission_grants`, so declaring this is only
603
+ * needed to override the derived labels.
604
+ */
605
+ capabilities: import_zod.z.array(import_zod.z.string()).optional(),
606
+ /** Example prompt chips shown on detail (Ryu extension). */
607
+ examplePrompts: import_zod.z.array(import_zod.z.string()).optional(),
608
+ /**
609
+ * Optional companion/config card (Ryu extension): a single setup step or an
610
+ * array of steps guiding the user through post-install configuration.
611
+ */
612
+ setup: import_zod.z.union([SetupStepSchema, import_zod.z.array(SetupStepSchema)]).optional()
613
+ }).superRefine((manifest, context) => {
614
+ const hasOAuthServer = Object.values(manifest.mcp_servers ?? {}).some(
615
+ (server) => server.auth?.type === "oauth"
616
+ );
617
+ if (!hasOAuthServer) {
618
+ return;
619
+ }
620
+ for (const grant of ["mcp:server", "identity.read"]) {
621
+ if (!manifest.permission_grants.includes(grant)) {
622
+ context.addIssue({
623
+ code: "custom",
624
+ message: `OAuth MCP servers require the ${grant} permission grant`,
625
+ path: ["permission_grants"]
626
+ });
627
+ }
628
+ }
629
+ });
630
+
631
+ // src/runnable/agent.ts
632
+ var CAPABILITY_SLOTS = ["rag", "memory", "tts", "stt"];
633
+ function lowerChatSlot(chat) {
634
+ if (chat === void 0) {
635
+ return {};
636
+ }
637
+ if (typeof chat === "string") {
638
+ return { model: chat };
639
+ }
640
+ return {
641
+ model: chat.model,
642
+ engine: chat.engine,
643
+ persona: chat.persona,
644
+ modelPrefKey: chat.modelPrefKey
645
+ };
646
+ }
647
+ function lowerCapabilitySlot(capability, slot, card) {
648
+ if (slot === void 0 || slot === false) {
649
+ return;
650
+ }
651
+ if (slot === true) {
652
+ card.capabilities.push({ capability });
653
+ return;
654
+ }
655
+ if (typeof slot === "string") {
656
+ card.capabilities.push({ capability });
657
+ card.providers[capability] = slot;
658
+ return;
659
+ }
660
+ card.capabilities.push(
661
+ slot.minVersion ? { capability, min_version: slot.minVersion } : { capability }
662
+ );
663
+ if (slot.provider) {
664
+ card.providers[capability] = slot.provider;
665
+ }
666
+ }
667
+ function lowerSlots(options) {
668
+ const card = {
669
+ ...lowerChatSlot(options.chat),
670
+ capabilities: [],
671
+ providers: {},
672
+ tools: []
673
+ };
674
+ for (const capability of CAPABILITY_SLOTS) {
675
+ lowerCapabilitySlot(capability, options[capability], card);
676
+ }
677
+ for (const t of options.tools ?? []) {
678
+ card.tools.push(typeof t === "string" ? t : t.id);
679
+ }
680
+ return card;
681
+ }
682
+ function defaultRun(card) {
683
+ return async (input, ctx) => {
684
+ const content = typeof input === "string" ? input : JSON.stringify(input ?? "");
685
+ const messages = card.persona ? [
686
+ { role: "system", content: card.persona },
687
+ { role: "user", content }
688
+ ] : [{ role: "user", content }];
689
+ const result = await ctx.gateway.chat(messages);
690
+ return result.content;
691
+ };
692
+ }
693
+ function cardConfig(card) {
694
+ const config = {};
695
+ if (card.model) {
696
+ config.model = card.model;
697
+ }
698
+ if (card.engine) {
699
+ config.engine = card.engine;
700
+ }
701
+ if (card.persona) {
702
+ config.persona = card.persona;
703
+ }
704
+ if (card.modelPrefKey) {
705
+ config.model_pref_key = card.modelPrefKey;
706
+ }
707
+ if (Object.keys(card.providers).length > 0) {
708
+ config.capability_providers = card.providers;
709
+ }
710
+ if (card.tools.length > 0) {
711
+ config.tools = card.tools;
712
+ }
713
+ return config;
714
+ }
715
+ function agentToManifest(agent, options) {
716
+ const config = cardConfig(agent.card);
717
+ const meta = {
718
+ id: agent.id,
719
+ name: agent.name,
720
+ kind: "agent",
721
+ ...Object.keys(config).length > 0 ? { config } : {}
722
+ };
723
+ const hasRequires = agent.card.capabilities.length > 0 || (options.grants?.length ?? 0) > 0;
724
+ const raw = {
725
+ id: options.id,
726
+ name: options.name ?? agent.name,
727
+ version: options.version,
728
+ runnables: [meta],
729
+ ...hasRequires ? {
730
+ requires: {
731
+ apps: [],
732
+ capabilities: agent.card.capabilities,
733
+ grants: options.grants ?? []
734
+ }
735
+ } : {}
736
+ };
737
+ const result = PluginManifestSchema.safeParse(raw);
738
+ if (!result.success) {
739
+ const first = result.error.issues[0];
740
+ const field = first?.path.join(".") ?? "unknown";
741
+ const message = first?.message ?? "validation failed";
742
+ throw new Error(
743
+ `agent manifest validation failed at '${field}': ${message}`
744
+ );
745
+ }
746
+ return result.data;
747
+ }
748
+ function defineAgent(options) {
749
+ const { id, name } = options;
750
+ const card = lowerSlots(options);
751
+ const run = options.run ?? defaultRun(card);
752
+ return {
753
+ id,
754
+ name,
755
+ kind: "agent",
756
+ run,
757
+ card,
758
+ toManifest(manifestOptions) {
759
+ return agentToManifest(this, manifestOptions);
760
+ }
761
+ };
762
+ }
763
+
764
+ // src/runnable/app.ts
765
+ var DEFAULT_APP_WIDGET_MIME = "text/html+skybridge";
766
+ var DEFAULT_APP_DISPLAY_MODE = "inline";
767
+ var WIDGET_RENDER_GRANT = "widget:render";
768
+ function withWidgetRenderGrant(grants, widgets) {
769
+ const out = [...grants];
770
+ if (widgets.length > 0 && !out.includes(WIDGET_RENDER_GRANT)) {
771
+ out.push(WIDGET_RENDER_GRANT);
772
+ }
773
+ return out;
774
+ }
775
+ function appToolId(server, name) {
776
+ return `${server}.${name}`;
777
+ }
778
+ function defineApp(options) {
779
+ const server = options.server ?? options.slug;
780
+ const uri = `ui://widget/${options.slug}.html`;
781
+ const mime = options.mime ?? DEFAULT_APP_WIDGET_MIME;
782
+ const displayMode = options.displayMode ?? DEFAULT_APP_DISPLAY_MODE;
783
+ const hasCompanions = options.tools.some((t) => t.accessible === true);
784
+ const runnables = [];
785
+ const widgets = [];
786
+ for (const spec of options.tools) {
787
+ const isRender = spec.accessible !== true;
788
+ const id = appToolId(server, spec.name);
789
+ const config = {
790
+ slug: id,
791
+ description: spec.description,
792
+ widget: isRender,
793
+ widget_accessible: isRender ? hasCompanions : true,
794
+ ...spec.inputSchema ? { input_schema: spec.inputSchema } : {},
795
+ ...spec.invoking ? { invoking: spec.invoking } : {},
796
+ ...spec.invoked ? { invoked: spec.invoked } : {}
797
+ };
798
+ runnables.push({
799
+ id,
800
+ name: spec.name,
801
+ kind: "tool",
802
+ config
803
+ });
804
+ if (isRender) {
805
+ widgets.push({
806
+ tool_id: id,
807
+ uri,
808
+ ui_entry: options.uiEntry,
809
+ mime,
810
+ default_display_mode: displayMode
811
+ });
812
+ }
813
+ }
814
+ const contributes = {
815
+ turn_hooks: [],
816
+ chat_features: [],
817
+ // This builder synthesises an app from its runnables; an app that emits
818
+ // events declares them in a hand-authored `manifest.json`, same as
819
+ // `lsp_servers` below.
820
+ hook_events: [],
821
+ composer_controls: [],
822
+ settings_tabs: [],
823
+ slash_commands: [],
824
+ sidebar_sections: [],
825
+ sidebar_buttons: [],
826
+ dock_panels: [],
827
+ live_activities: [],
828
+ // Empty for the same reason as every sibling family above: this builder
829
+ // synthesises `widgets` from the app's own runnables and nothing else, and
830
+ // takes no `contributes` passthrough. An app that wants to declare language
831
+ // servers writes them in a hand-authored `manifest.json`.
832
+ lsp_servers: {},
833
+ // Same reason again: a danger-zone category, a Pi extension and an output
834
+ // style are all hand-authored declarations, not something derivable from
835
+ // runnables. An output style in particular points at a Markdown file next
836
+ // to the manifest, which this builder never writes.
837
+ data_categories: [],
838
+ pi_extensions: [],
839
+ output_styles: [],
840
+ message_actions: [],
841
+ widgets
842
+ };
843
+ const raw = {
844
+ id: options.id,
845
+ name: options.title,
846
+ version: options.version,
847
+ runnables,
848
+ // An app that synthesises widgets MUST hold `widget:render`, so this
849
+ // builder declares it rather than leaving the author to discover it.
850
+ //
851
+ // Core gates widget promotion on declared-AND-enabled-AND-granted, and a
852
+ // missing grant fails as `DeniedNoGrant` — which is an `info!` log and
853
+ // nothing else. The widget silently renders as plain text, with no error
854
+ // in the UI and nothing pointing at the manifest. Every app scaffolded
855
+ // through `defineApp` hit that, because the only fix was a grant string
856
+ // the templates never mention and the builder never added; the one
857
+ // working example on disk hand-writes it.
858
+ //
859
+ // Added only when there is a widget to render, and unioned rather than
860
+ // overwritten so an author's own `grants` list survives and re-declaring
861
+ // it is not an error.
862
+ permission_grants: withWidgetRenderGrant(options.grants ?? [], widgets),
863
+ activation_events: options.activationEvents ?? ["*"],
864
+ contributes,
865
+ // `targets: []` means EVERY surface, so an app that declares none is
866
+ // unrestricted — the backward-compatible default.
867
+ targets: options.targets ?? [],
868
+ // `requires` stays ABSENT (not `{apps:[],grants:[]}`) when undeclared, so the
869
+ // emitted manifest carries no key at all — matching Core's
870
+ // `Option<Requires>` + `skip_serializing_if = "Option::is_none"`.
871
+ ...options.requires ? {
872
+ requires: {
873
+ apps: options.requires.apps ?? [],
874
+ capabilities: options.requires.capabilities ?? [],
875
+ grants: options.requires.grants ?? []
876
+ }
877
+ } : {}
878
+ };
879
+ const result = PluginManifestSchema.safeParse(raw);
880
+ if (!result.success) {
881
+ const first = result.error.issues[0];
882
+ const field = first?.path.join(".") ?? "unknown";
883
+ const message = first?.message ?? "validation failed";
884
+ throw new Error(
885
+ `manifest.json validation failed at '${field}': ${message}`
886
+ );
887
+ }
888
+ return result.data;
889
+ }
890
+
891
+ // src/model/gateway.ts
892
+ var native = __toESM(require("@ryuhq/sdk-native"), 1);
893
+ function assertAllowedEgressUrl(baseUrl) {
894
+ native.assertAllowedEgress(baseUrl);
895
+ }
896
+
897
+ // src/runnable/primitives.ts
898
+ function dataUrlToBytes(dataUrl) {
899
+ const match = /^data:([^;,]*)(;base64)?,([\s\S]*)$/.exec(dataUrl);
900
+ if (!match) {
901
+ throw new Error(
902
+ "stt.transcribe expects an `audio` value that is a data: URL (data:<mime>;base64,<data>)"
903
+ );
904
+ }
905
+ const mediaType = match[1] || "application/octet-stream";
906
+ const isBase64 = Boolean(match[2]);
907
+ const payload = match[3] ?? "";
908
+ if (isBase64) {
909
+ const binary = atob(payload);
910
+ const bytes = new Uint8Array(binary.length);
911
+ for (let i = 0; i < binary.length; i++) {
912
+ bytes[i] = binary.charCodeAt(i);
913
+ }
914
+ return { bytes, mediaType };
915
+ }
916
+ return {
917
+ bytes: new TextEncoder().encode(decodeURIComponent(payload)),
918
+ mediaType
919
+ };
920
+ }
921
+ function bytesToDataUrl(bytes, mediaType) {
922
+ let binary = "";
923
+ const chunk = 32768;
924
+ for (let i = 0; i < bytes.length; i += chunk) {
925
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
926
+ }
927
+ return `data:${mediaType};base64,${btoa(binary)}`;
928
+ }
929
+ function httpPrimitiveTransport(options) {
930
+ const base = options.nodeUrl.replace(/\/+$/, "");
931
+ assertAllowedEgressUrl(base);
932
+ const doFetch = options.fetchImpl ?? fetch;
933
+ const authHeader = () => options.token ? { authorization: `Bearer ${options.token}` } : {};
934
+ const failDetail = async (path, res) => {
935
+ const detail = await res.text().catch(() => "");
936
+ return new Error(
937
+ `Ryu primitive call ${path} failed: ${res.status} ${res.statusText}${detail ? ` \u2014 ${detail}` : ""}`
938
+ );
939
+ };
940
+ const post = async (path, body) => {
941
+ const res = await doFetch(`${base}${path}`, {
942
+ method: "POST",
943
+ headers: { "content-type": "application/json", ...authHeader() },
944
+ body: JSON.stringify(body ?? {})
945
+ });
946
+ if (!res.ok) {
947
+ throw await failDetail(path, res);
948
+ }
949
+ const text = await res.text();
950
+ return text ? JSON.parse(text) : void 0;
951
+ };
952
+ const transcribeDirect = async (body) => {
953
+ const input = body ?? {};
954
+ if (!input.audio) {
955
+ throw new Error(
956
+ "stt.transcribe requires an `audio` data: URL (the recorded audio)"
957
+ );
958
+ }
959
+ const { bytes, mediaType } = dataUrlToBytes(input.audio);
960
+ const form = new FormData();
961
+ form.append(
962
+ "file",
963
+ new Blob([bytes], { type: mediaType || "audio/wav" }),
964
+ input.filename ?? "recording.wav"
965
+ );
966
+ const res = await doFetch(`${base}/api/voice/transcribe`, {
967
+ method: "POST",
968
+ headers: authHeader(),
969
+ body: form
970
+ });
971
+ if (!res.ok) {
972
+ throw await failDetail("/api/voice/transcribe", res);
973
+ }
974
+ const parsed = await res.json();
975
+ return (parsed.text ?? "").trim();
976
+ };
977
+ const speakDirect = async (body) => {
978
+ const res = await doFetch(`${base}/api/voice/speak`, {
979
+ method: "POST",
980
+ headers: { "content-type": "application/json", ...authHeader() },
981
+ body: JSON.stringify(body ?? {})
982
+ });
983
+ if (!res.ok) {
984
+ throw await failDetail("/api/voice/speak", res);
985
+ }
986
+ const bytes = new Uint8Array(await res.arrayBuffer());
987
+ const mediaType = res.headers.get("content-type") || "audio/wav";
988
+ return bytesToDataUrl(bytes, mediaType);
989
+ };
990
+ const generateImageDirect = async (body) => {
991
+ const res = await doFetch(`${base}/api/images/generate`, {
992
+ method: "POST",
993
+ headers: { "content-type": "application/json", ...authHeader() },
994
+ body: JSON.stringify(body ?? {})
995
+ });
996
+ if (!res.ok) {
997
+ throw await failDetail("/api/images/generate", res);
998
+ }
999
+ const parsed = await res.json();
1000
+ return (parsed.data ?? []).map(
1001
+ (item) => item.url ? item.url : `data:image/png;base64,${item.b64_json ?? ""}`
1002
+ );
1003
+ };
1004
+ return {
1005
+ bridge(method, args) {
1006
+ if (!options.pluginId) {
1007
+ return Promise.reject(
1008
+ new Error(
1009
+ `bridge primitive "${method}" requires a pluginId (the /api/plugins/:id/host caller identity)`
1010
+ )
1011
+ );
1012
+ }
1013
+ return post(`/api/plugins/${options.pluginId}/host`, { method, args });
1014
+ },
1015
+ direct(path, body) {
1016
+ if (path === "/api/voice/transcribe") {
1017
+ return transcribeDirect(body);
1018
+ }
1019
+ if (path === "/api/voice/speak") {
1020
+ return speakDirect(body);
1021
+ }
1022
+ if (path === "/api/images/generate") {
1023
+ return generateImageDirect(body);
1024
+ }
1025
+ return post(path, body);
1026
+ },
1027
+ capability(cap, body) {
1028
+ return post(`/api/host/capability/${cap}`, body);
1029
+ }
1030
+ };
1031
+ }
1032
+ var PRIMITIVE_BINDINGS = {
1033
+ // Bridge families (existing `PluginHookBridge`).
1034
+ "engines.complete": {
1035
+ transport: "bridge",
1036
+ method: "model.complete",
1037
+ grant: "hook:side-model"
1038
+ },
1039
+ "background.list": {
1040
+ transport: "bridge",
1041
+ method: "background.list",
1042
+ grant: "background:control"
1043
+ },
1044
+ "background.stop": {
1045
+ transport: "bridge",
1046
+ method: "background.stop",
1047
+ grant: "background:control"
1048
+ },
1049
+ // Host-direct media data-path (the host holds the node token; returns data: URLs).
1050
+ "image.generate": {
1051
+ transport: "direct",
1052
+ path: "/api/images/generate",
1053
+ grant: "media:generate"
1054
+ },
1055
+ "tts.speak": {
1056
+ transport: "direct",
1057
+ path: "/api/voice/speak",
1058
+ grant: "media:generate"
1059
+ },
1060
+ "stt.transcribe": {
1061
+ transport: "direct",
1062
+ path: "/api/voice/transcribe",
1063
+ grant: "media:transcribe"
1064
+ },
1065
+ // Broker capabilities — no rpc family yet (@requires-grant).
1066
+ "rag.retrieve": { transport: "broker", capability: "rag" },
1067
+ "rag.embed": { transport: "broker", capability: "rag" },
1068
+ "rag.rerank": { transport: "broker", capability: "rag" },
1069
+ "memory.recall": { transport: "broker", capability: "memory" },
1070
+ "memory.store": { transport: "broker", capability: "memory" },
1071
+ "realtime.broadcast": { transport: "broker", capability: "realtime" },
1072
+ "realtime.subscribe": { transport: "broker", capability: "realtime" },
1073
+ "durable.checkpoint": { transport: "broker", capability: "durable" },
1074
+ "durable.resume": { transport: "broker", capability: "durable" },
1075
+ "engines.embed": { transport: "broker", capability: "engines" }
1076
+ };
1077
+ function brokerCall(transport, cap, op, input) {
1078
+ return transport.capability(cap, { op, input });
1079
+ }
1080
+ function createPrimitives(transport) {
1081
+ return {
1082
+ background: {
1083
+ list: (input) => transport.bridge("background.list", {
1084
+ producer: input?.producer,
1085
+ running_only: input?.runningOnly
1086
+ }),
1087
+ stop: (input) => transport.bridge("background.stop", {
1088
+ process_id: input.processId
1089
+ })
1090
+ },
1091
+ rag: {
1092
+ retrieve: (input) => brokerCall(transport, "rag", "retrieve", input),
1093
+ embed: (input) => brokerCall(transport, "rag", "embed", input),
1094
+ rerank: (input) => brokerCall(transport, "rag", "rerank", input)
1095
+ },
1096
+ memory: {
1097
+ recall: (input) => brokerCall(transport, "memory", "recall", input),
1098
+ store: (input) => brokerCall(transport, "memory", "store", input)
1099
+ },
1100
+ realtime: {
1101
+ broadcast: (input) => brokerCall(transport, "realtime", "broadcast", input).then(
1102
+ () => void 0
1103
+ ),
1104
+ subscribe: (input) => brokerCall(
1105
+ transport,
1106
+ "realtime",
1107
+ "subscribe",
1108
+ input
1109
+ )
1110
+ },
1111
+ durable: {
1112
+ checkpoint: (input) => brokerCall(transport, "durable", "checkpoint", input),
1113
+ resume: (input) => brokerCall(transport, "durable", "resume", input)
1114
+ },
1115
+ engines: {
1116
+ // Bridge family: model.complete → host.sideModel (wire keys are snake_case).
1117
+ complete: (input) => transport.bridge("model.complete", {
1118
+ prompt: input.prompt,
1119
+ system: input.system,
1120
+ model: input.model,
1121
+ model_pref_key: input.modelPrefKey,
1122
+ effort: input.effort
1123
+ }),
1124
+ embed: (input) => brokerCall(transport, "engines", "embed", input)
1125
+ },
1126
+ tts: {
1127
+ speak: (input) => transport.direct("/api/voice/speak", input)
1128
+ },
1129
+ stt: {
1130
+ transcribe: (input) => transport.direct("/api/voice/transcribe", input)
1131
+ },
1132
+ image: {
1133
+ generate: (input) => transport.direct("/api/images/generate", input)
1134
+ }
1135
+ };
1136
+ }
1137
+
1138
+ // src/runnable/skill.ts
1139
+ function defineSkill(options) {
1140
+ const { id, name, run } = options;
1141
+ return {
1142
+ id,
1143
+ name,
1144
+ kind: "skill",
1145
+ run
1146
+ };
1147
+ }
1148
+
1149
+ // src/runnable/tool.ts
1150
+ function validateInput(input, schema, toolId) {
1151
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
1152
+ throw new Error(
1153
+ `[ryu-sdk] Tool "${toolId}" input must be an object, got ${JSON.stringify(input)}`
1154
+ );
1155
+ }
1156
+ const record = input;
1157
+ for (const requiredKey of schema.required ?? []) {
1158
+ if (!(requiredKey in record)) {
1159
+ throw new Error(
1160
+ `[ryu-sdk] Tool "${toolId}" input missing required field "${requiredKey}"`
1161
+ );
1162
+ }
1163
+ }
1164
+ for (const [key, prop] of Object.entries(schema.properties)) {
1165
+ if (!(key in record)) {
1166
+ continue;
1167
+ }
1168
+ const value = record[key];
1169
+ if (!checkType(value, prop.type)) {
1170
+ throw new Error(
1171
+ `[ryu-sdk] Tool "${toolId}" input field "${key}" expected type "${prop.type}", got ${JSON.stringify(value)}`
1172
+ );
1173
+ }
1174
+ }
1175
+ }
1176
+ function checkType(value, type) {
1177
+ switch (type) {
1178
+ case "string":
1179
+ return typeof value === "string";
1180
+ case "number":
1181
+ case "integer":
1182
+ return typeof value === "number";
1183
+ case "boolean":
1184
+ return typeof value === "boolean";
1185
+ case "array":
1186
+ return Array.isArray(value);
1187
+ case "object":
1188
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1189
+ default:
1190
+ return false;
1191
+ }
1192
+ }
1193
+ function defineTool(options) {
1194
+ const { id, name, schema, run } = options;
1195
+ const code = `return await (${run.toString()})(input, host);`;
1196
+ return {
1197
+ id,
1198
+ name,
1199
+ kind: "tool",
1200
+ schema,
1201
+ code,
1202
+ run(input, ctx) {
1203
+ validateInput(input, schema, id);
1204
+ return run(input, ctx);
1205
+ }
1206
+ };
1207
+ }
1208
+
1209
+ // src/runnable/workflow.ts
1210
+ function defineWorkflow(options) {
1211
+ const { id, name, run } = options;
1212
+ return {
1213
+ id,
1214
+ name,
1215
+ kind: "workflow",
1216
+ run
1217
+ };
1218
+ }
1219
+ // Annotate the CommonJS export names for ESM import in node:
1220
+ 0 && (module.exports = {
1221
+ PRIMITIVE_BINDINGS,
1222
+ appToolId,
1223
+ createPrimitives,
1224
+ defineAgent,
1225
+ defineApp,
1226
+ defineSkill,
1227
+ defineTool,
1228
+ defineWorkflow,
1229
+ httpPrimitiveTransport
1230
+ });