create-ryu-app 0.0.5

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/LICENSE ADDED
@@ -0,0 +1,179 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any patent
81
+ claims embodied in the Work constitute direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this License
83
+ for that Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text
106
+ file distributed as part of the Derivative Works; within
107
+ the Source form or documentation, if provided along with the
108
+ Derivative Works; or, within a display generated by the
109
+ Derivative Works, if and wherever such third-party notices
110
+ normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License.
112
+ You may add Your own attribution notices within Derivative
113
+ Works that You distribute, alongside or in addition to the
114
+ NOTICE text from the Work, provided that such additional
115
+ attribution notices cannot be construed as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, copy, modify, merge,
119
+ publish, distribute, sublicense, and/or sell copies of Your modifications,
120
+ and to permit persons to whom the Work is furnished to do so,
121
+ subject to the following conditions:
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any conditions of title,
141
+ merchantability, or fitness for a particular purpose and
142
+ noninfringement. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or all other
155
+ commercial damages or losses), even if such Contributor has been
156
+ advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may offer only
163
+ conditions consistent with this License.
164
+
165
+ END OF TERMS AND CONDITIONS
166
+
167
+ Copyright 2026 A Major Pte. Ltd.
168
+
169
+ Licensed under the Apache License, Version 2.0 (the "License");
170
+ you may not use this file except in compliance with the License.
171
+ You may obtain a copy of the License at
172
+
173
+ http://www.apache.org/licenses/LICENSE-2.0
174
+
175
+ Unless required by applicable law or agreed to in writing, software
176
+ distributed under the License is distributed on an "AS IS" BASIS,
177
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
178
+ See the License for the specific language governing permissions and
179
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # <img src="https://raw.githubusercontent.com/amajorai/ryu/main/.github/logo.png" width="50" align="middle" alt="" />&nbsp; create-ryu-app
2
+
3
+ > Scaffold a starter Ryu SDK project in one command. Part of [Ryu](../../README.md).
4
+
5
+ [![License](https://shieldcn.dev/badge/License-Apache--2.0-73DC8C.svg?logo=apache&logoColor=white)](./LICENSE)
6
+ [![Stack](https://shieldcn.dev/badge/TypeScript-CLI-3178C6.svg?logo=typescript&logoColor=white)](../../README.md)
7
+
8
+ `create-ryu-app` is the project scaffolder for the Ryu SDK. Running it generates a starter project with a Runnable, a gateway-pointed model config, and a `plugin.json` (legacy `ryu.json`) manifest validated against the PluginManifest schema, so a new plugin compiles and packs out of the box. It depends on `@ryuhq/sdk` by semver.
9
+
10
+ Pick a starter with `--template` (default `agent`):
11
+
12
+ | Template | Emits | Factory |
13
+ |---|---|---|
14
+ | `agent` | A loop-owning Runnable agent | `Agent` / `ryuTool` |
15
+ | `hook-plugin` | A post-assistant-turn plugin | `definePlugin` + `defineTurnHook` |
16
+ | `ryu-app` | An interactive in-chat widget | `defineApp` + a self-contained widget |
17
+ | `companion-plugin` | A Ryu App whose widget calls a companion tool, plus a panel surface | `defineApp` |
18
+
19
+ **Tier:** OSS, Apache-2.0
20
+
21
+ ## Install / Build
22
+
23
+ ```bash
24
+ # scaffold a new project (default: agent template)
25
+ bunx create-ryu-app <name>
26
+
27
+ # scaffold a specific template
28
+ bunx create-ryu-app <name> --template ryu-app
29
+
30
+ # build from source
31
+ bun run build # tsup → dist/
32
+ bun test
33
+ ```
34
+
35
+ ## What it provides
36
+
37
+ - A one-command scaffolder (`create-ryu-app <name> [--template <t>]`) bundled with a `template/<name>/` tree per starter.
38
+ - A generated starter Runnable plus a gateway-pointed model config.
39
+ - A `plugin.json` / `ryu.json` manifest validated against the PluginManifest schema, ready for `ryu pack`.
40
+
41
+ ## License
42
+
43
+ Apache-2.0. See [LICENSE](./LICENSE). © 2026 A Major Pte. Ltd.
package/dist/index.js ADDED
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+
3
+ // index.ts
4
+ import {
5
+ cpSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ writeFileSync
11
+ } from "fs";
12
+ import { dirname, join, resolve } from "path";
13
+ import { fileURLToPath } from "url";
14
+ import { PluginManifestSchema } from "@ryuhq/sdk/manifest";
15
+ var RE_WORD_SEPARATOR = /[-_\s]+/;
16
+ var RE_VALID_NAME = /^[a-z0-9][a-z0-9-_]*$/i;
17
+ var RE_LABEL_IMPERSONATES = /ryu|system/i;
18
+ var SAFE_COMPANION_LABEL = "App Panel";
19
+ var SDK_DEPENDENCY_RANGE = "^0.0.5";
20
+ var TEMPLATES = {
21
+ agent: { devEntry: "src/agent.ts" },
22
+ "hook-plugin": { devEntry: "src/plugin.ts" },
23
+ "ryu-app": {
24
+ devEntry: "src/app.ts",
25
+ extraDependencies: { react: "^19.2.0", "react-dom": "^19.2.0" }
26
+ },
27
+ "companion-plugin": {
28
+ devEntry: "src/app.ts",
29
+ extraDependencies: { react: "^19.2.0", "react-dom": "^19.2.0" }
30
+ }
31
+ };
32
+ var DEFAULT_TEMPLATE = "agent";
33
+ var STAMPABLE_EXTENSIONS = [".json", ".ts", ".tsx", ".html", ".md"];
34
+ function exitError(message) {
35
+ process.stderr.write(`error: ${message}
36
+ `);
37
+ process.exit(1);
38
+ }
39
+ function printUsage() {
40
+ const templates = Object.keys(TEMPLATES).join(" | ");
41
+ process.stderr.write(
42
+ [
43
+ "create-ryu-app \u2014 scaffold a starter Ryu SDK project",
44
+ "",
45
+ "Usage:",
46
+ " bunx create-ryu-app <name> [--template <template>]",
47
+ "",
48
+ "Arguments:",
49
+ " <name> Project directory name (also used as the app id slug)",
50
+ "",
51
+ "Options:",
52
+ ` --template One of: ${templates} (default: ${DEFAULT_TEMPLATE})`,
53
+ ""
54
+ ].join("\n")
55
+ );
56
+ }
57
+ function toDisplayName(slug) {
58
+ return slug.split(RE_WORD_SEPARATOR).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
59
+ }
60
+ function toCompanionLabel(displayName) {
61
+ return RE_LABEL_IMPERSONATES.test(displayName) ? SAFE_COMPANION_LABEL : displayName;
62
+ }
63
+ function stampTemplate(filePath, replacements) {
64
+ let content = readFileSync(filePath, "utf8");
65
+ for (const [placeholder, value] of Object.entries(replacements)) {
66
+ content = content.replaceAll(placeholder, value);
67
+ }
68
+ writeFileSync(filePath, content, "utf8");
69
+ }
70
+ function stampTree(dir, replacements) {
71
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
72
+ const full = join(dir, entry.name);
73
+ if (entry.isDirectory()) {
74
+ stampTree(full, replacements);
75
+ continue;
76
+ }
77
+ if (STAMPABLE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
78
+ stampTemplate(full, replacements);
79
+ }
80
+ }
81
+ }
82
+ function resolveTemplateDir(template) {
83
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
84
+ const candidates = [
85
+ join(moduleDir, "template", template),
86
+ join(moduleDir, "..", "template", template)
87
+ ];
88
+ const found = candidates.find((dir) => existsSync(dir));
89
+ if (!found) {
90
+ exitError(
91
+ `template directory not found for '${template}' (looked in: ${candidates.join(", ")})`
92
+ );
93
+ }
94
+ return found;
95
+ }
96
+ function scaffold(name, outDir, template = DEFAULT_TEMPLATE) {
97
+ const slug = name.trim();
98
+ if (!slug) {
99
+ exitError("name must not be empty");
100
+ }
101
+ if (!RE_VALID_NAME.test(slug)) {
102
+ exitError(
103
+ "name must start with a letter or digit and contain only letters, digits, hyphens, and underscores"
104
+ );
105
+ }
106
+ const spec = TEMPLATES[template];
107
+ if (!spec) {
108
+ exitError(
109
+ `unknown template '${template}' \u2014 expected one of: ${Object.keys(TEMPLATES).join(", ")}`
110
+ );
111
+ }
112
+ const projectDir = resolve(join(outDir, slug));
113
+ if (existsSync(projectDir)) {
114
+ exitError(`directory already exists: ${projectDir}`);
115
+ }
116
+ const templateDir = resolveTemplateDir(template);
117
+ const displayName = toDisplayName(slug);
118
+ mkdirSync(projectDir, { recursive: true });
119
+ cpSync(templateDir, projectDir, { recursive: true });
120
+ stampTree(projectDir, {
121
+ __APP_NAME__: slug,
122
+ __APP_DISPLAY_NAME__: displayName,
123
+ __COMPANION_LABEL__: toCompanionLabel(displayName)
124
+ });
125
+ const manifestPath = join(projectDir, "plugin.json");
126
+ const parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
127
+ const validation = PluginManifestSchema.safeParse(parsed);
128
+ if (!validation.success) {
129
+ const first = validation.error.issues[0];
130
+ const field = first?.path.join(".") ?? "unknown";
131
+ const msg = first?.message ?? "validation failed";
132
+ exitError(`generated plugin.json is invalid at '${field}': ${msg}`);
133
+ }
134
+ const pkgJson = {
135
+ name: slug,
136
+ version: "0.1.0",
137
+ type: "module",
138
+ scripts: {
139
+ dev: `bun run ${spec.devEntry}`,
140
+ pack: "bunx ryu pack ."
141
+ },
142
+ dependencies: {
143
+ "@ryuhq/sdk": SDK_DEPENDENCY_RANGE,
144
+ ...spec.extraDependencies
145
+ }
146
+ };
147
+ writeFileSync(
148
+ join(projectDir, "package.json"),
149
+ JSON.stringify(pkgJson, null, 2),
150
+ "utf8"
151
+ );
152
+ return projectDir;
153
+ }
154
+ function parseArgs(argv) {
155
+ let name;
156
+ let template = DEFAULT_TEMPLATE;
157
+ for (let i = 0; i < argv.length; i += 1) {
158
+ const arg = argv[i];
159
+ if (arg === "--template") {
160
+ const next = argv[i + 1];
161
+ if (!next) {
162
+ return { error: "--template requires a value" };
163
+ }
164
+ template = next;
165
+ i += 1;
166
+ continue;
167
+ }
168
+ if (arg?.startsWith("--template=")) {
169
+ template = arg.slice("--template=".length);
170
+ continue;
171
+ }
172
+ if (arg?.startsWith("-")) {
173
+ return { error: `unknown option: ${arg}` };
174
+ }
175
+ if (name === void 0) {
176
+ name = arg;
177
+ continue;
178
+ }
179
+ return { error: "too many arguments \u2014 expected exactly one <name>" };
180
+ }
181
+ return { name, template };
182
+ }
183
+ if (import.meta.main) {
184
+ const parsed = parseArgs(process.argv.slice(2));
185
+ if ("error" in parsed) {
186
+ printUsage();
187
+ exitError(parsed.error);
188
+ }
189
+ if (!parsed.name) {
190
+ printUsage();
191
+ exitError("name argument is required");
192
+ }
193
+ const created = scaffold(parsed.name, process.cwd(), parsed.template);
194
+ process.stdout.write(
195
+ [
196
+ "",
197
+ ` created ${parsed.name}/ (${parsed.template})`,
198
+ "",
199
+ " next steps:",
200
+ ` cd ${parsed.name}`,
201
+ " bun install",
202
+ " bun dev # runs the template entry",
203
+ " bun run pack # validate and bundle plugin.json",
204
+ ""
205
+ ].join("\n")
206
+ );
207
+ process.stdout.write(` project: ${created}
208
+
209
+ `);
210
+ }
211
+ export {
212
+ parseArgs,
213
+ scaffold
214
+ };
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "create-ryu-app",
3
+ "version": "0.0.5",
4
+ "type": "module",
5
+ "description": "Scaffold a starter Ryu SDK project with a Runnable, gateway-pointed model config, and plugin.json manifest",
6
+ "bin": {
7
+ "create-ryu-app": "./dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "template",
12
+ "README.md"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "scripts": {
18
+ "build": "tsup",
19
+ "test": "bun test",
20
+ "clean": "rm -rf dist"
21
+ },
22
+ "dependencies": {
23
+ "@ryuhq/sdk": "^0.0.5"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "^1.3.4",
27
+ "tsup": "^8.5.1",
28
+ "typescript": "^5"
29
+ }
30
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "id": "com.example.__APP_NAME__",
3
+ "name": "__APP_DISPLAY_NAME__",
4
+ "version": "0.1.0",
5
+ "runnables": [
6
+ {
7
+ "id": "agent-main",
8
+ "name": "Main Agent",
9
+ "kind": "agent"
10
+ }
11
+ ],
12
+ "permission_grants": [],
13
+ "companion": {
14
+ "label": "__COMPANION_LABEL__",
15
+ "icon": "sparkles",
16
+ "shortcut": "ctrl+shift+r"
17
+ }
18
+ }
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Starter Agent — a declarative, loop-owning Ryu agent.
4
+ *
5
+ * Run with:
6
+ * bun run src/agent.ts
7
+ *
8
+ * This is an expense-tracker skeleton: it reads the user's Gmail through an
9
+ * existing Ryu tool (Composio) and summarizes the expenses it finds. The agent
10
+ * OWNS its tool-calling loop — you don't write the loop, you declare the agent.
11
+ *
12
+ * Every model call goes through the Ryu gateway of the node you target. Set
13
+ * RYU_GATEWAY_URL (default http://127.0.0.1:7981) and RYU_GATEWAY_TOKEN for
14
+ * inference; set RYU_CORE_URL (default http://127.0.0.1:7980) and RYU_TOKEN for
15
+ * tool execution. No provider key belongs in this file — credentials live in the
16
+ * gateway/Core config.
17
+ *
18
+ * Before this works end to end you need, once:
19
+ * 1. A Composio API key set on the node (Settings → Integrations).
20
+ * 2. A Core agent (here "agent-expense") whose allowlist includes the Gmail
21
+ * actions below. `agentId` binds this SDK agent to it for governance.
22
+ * 3. On first run the agent emits an `auth_required` event with a Gmail OAuth
23
+ * link — open it, connect Gmail, then run again.
24
+ */
25
+
26
+ import { Agent, ryuTool } from "@ryuhq/sdk/agent";
27
+
28
+ const MODEL_ID = process.env.RYU_MODEL ?? "gpt-4o-mini";
29
+
30
+ const agent = new Agent({
31
+ name: "expense-tracker",
32
+ model: MODEL_ID,
33
+ agentId: "agent-expense",
34
+ instructions:
35
+ "You are an expense tracker. Search the user's Gmail for receipts and " +
36
+ "expense emails, read the relevant ones, and return a concise list of " +
37
+ "expenses with amount, merchant, date, and a category.",
38
+ tools: {
39
+ gmailSearch: ryuTool("composio__GMAIL_SEARCH_EMAILS", {
40
+ description: "Search the user's Gmail messages",
41
+ parameters: {
42
+ type: "object",
43
+ properties: {
44
+ query: {
45
+ type: "string",
46
+ description:
47
+ 'Gmail search query, e.g. "receipt OR invoice newer_than:30d"',
48
+ },
49
+ },
50
+ required: ["query"],
51
+ },
52
+ }),
53
+ gmailGet: ryuTool("composio__GMAIL_GET_EMAIL", {
54
+ description: "Fetch a single Gmail message by id",
55
+ }),
56
+ },
57
+ });
58
+
59
+ const result = await agent.generate(
60
+ "Find my expenses from the last 30 days and summarize them."
61
+ );
62
+
63
+ if (result.authRequired) {
64
+ process.stdout.write(
65
+ `\nConnect your account to continue: ${result.authRequired.url ?? "(see message)"}\n`
66
+ );
67
+ } else {
68
+ process.stdout.write(`\n${result.text}\n`);
69
+ process.stdout.write(`\n(${result.steps} step(s))\n`);
70
+ }
71
+
72
+ // ── Prefer the raw model client instead? ──────────────────────────────────────
73
+ // For a single text turn with no tools, skip the agent loop entirely:
74
+ //
75
+ // import { defineModel } from "@ryuhq/sdk";
76
+ // const model = defineModel(MODEL_ID);
77
+ // for await (const delta of model.stream([{ role: "user", content: "hi" }])) {
78
+ // if (delta.content) process.stdout.write(delta.content);
79
+ // }
@@ -0,0 +1,62 @@
1
+ {
2
+ "id": "com.example.__APP_NAME__",
3
+ "name": "__APP_DISPLAY_NAME__",
4
+ "version": "0.1.0",
5
+ "runnables": [
6
+ {
7
+ "id": "__APP_NAME____render",
8
+ "name": "render",
9
+ "kind": "tool",
10
+ "config": {
11
+ "slug": "__APP_NAME____render",
12
+ "description": "Render the interactive panel inline in the chat reply.",
13
+ "widget": true,
14
+ "widget_accessible": true,
15
+ "invoking": "Rendering…",
16
+ "invoked": "Ready"
17
+ }
18
+ },
19
+ {
20
+ "id": "__APP_NAME____save",
21
+ "name": "save",
22
+ "kind": "tool",
23
+ "config": {
24
+ "slug": "__APP_NAME____save",
25
+ "description": "Persist the panel's current state. Callable by the mounted widget via callTool.",
26
+ "widget": false,
27
+ "widget_accessible": true,
28
+ "input_schema": {
29
+ "type": "object",
30
+ "properties": {
31
+ "state": {
32
+ "type": "object"
33
+ }
34
+ },
35
+ "required": ["state"]
36
+ }
37
+ }
38
+ }
39
+ ],
40
+ "permission_grants": [],
41
+ "activation_events": ["*"],
42
+ "contributes": {
43
+ "turn_hooks": [],
44
+ "composer_controls": [],
45
+ "settings_tabs": [],
46
+ "slash_commands": [],
47
+ "widgets": [
48
+ {
49
+ "tool_id": "__APP_NAME____render",
50
+ "uri": "ui://widget/__APP_NAME__.html",
51
+ "ui_entry": "src/widget.tsx",
52
+ "mime": "text/html+skybridge",
53
+ "default_display_mode": "inline"
54
+ }
55
+ ]
56
+ },
57
+ "companion": {
58
+ "label": "App Panel",
59
+ "icon": "sidebar",
60
+ "shortcut": "ctrl+shift+p"
61
+ }
62
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * __APP_DISPLAY_NAME__ — a companion Ryu App (widget + a callable companion tool).
3
+ *
4
+ * This template goes one step past the plain Ryu App: besides the "render" tool
5
+ * that mounts the widget, it declares a `save` tool marked `accessible: true` — a
6
+ * COMPANION the mounted widget may invoke over the capability-gated bridge:
7
+ *
8
+ * await window.openai.callTool("__APP_NAME____save", { state })
9
+ *
10
+ * The host routes that call through the Gateway (allowlist + audit) before it
11
+ * reaches Core; the frame never holds a token. It also declares a full-page
12
+ * `companion` surface (an in-desktop panel) whose label is a fixed literal so it
13
+ * can never impersonate first-party Ryu/system chrome.
14
+ *
15
+ * bun run src/app.ts # prints the assembled manifest
16
+ * bunx ryu pack . # bundles src/widget.tsx into ui_code + writes plugin.json
17
+ *
18
+ * v1 boundary: DECLARATIVE PASS-THROUGH only — there is no `run` handler for the
19
+ * tools. The render widget draws from `window.openai.toolInput` / `toolOutput`;
20
+ * the `save` companion is a call target (its handler is the serialized apps/core
21
+ * tool-exec slice, not shipped here). Keep the widget self-contained: no network.
22
+ */
23
+
24
+ import { defineApp, type PluginManifest } from "@ryuhq/sdk";
25
+
26
+ const app = defineApp({
27
+ id: "com.example.__APP_NAME__",
28
+ title: "__APP_DISPLAY_NAME__",
29
+ version: "0.1.0",
30
+ slug: "__APP_NAME__",
31
+ uiEntry: "src/widget.tsx",
32
+ tools: [
33
+ {
34
+ name: "render",
35
+ description: "Render the interactive panel inline in the chat reply.",
36
+ invoking: "Rendering…",
37
+ invoked: "Ready",
38
+ },
39
+ {
40
+ name: "save",
41
+ description:
42
+ "Persist the panel's current state. Callable by the mounted widget via callTool.",
43
+ accessible: true,
44
+ inputSchema: {
45
+ type: "object",
46
+ properties: { state: { type: "object" } },
47
+ required: ["state"],
48
+ },
49
+ },
50
+ ],
51
+ });
52
+
53
+ // `defineApp` models the render/companion tool split but not the full-page
54
+ // companion SURFACE, so add it here. The label is a fixed literal that passes the
55
+ // anti-impersonation refine (must not contain "ryu" or "system").
56
+ const manifest: PluginManifest = {
57
+ ...app,
58
+ companion: { label: "App Panel", icon: "sidebar", shortcut: "ctrl+shift+p" },
59
+ };
60
+
61
+ export default manifest;
62
+
63
+ if (import.meta.main) {
64
+ process.stdout.write(`${JSON.stringify(manifest, null, 2)}\n`);
65
+ }
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>__APP_DISPLAY_NAME__</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="./widget.tsx"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,81 @@
1
+ /**
2
+ * __APP_DISPLAY_NAME__ widget — a companion widget that calls BACK to the host.
3
+ *
4
+ * `ryu pack` bundles this into a single self-contained HTML document. It runs in
5
+ * a null-origin `sandbox="allow-scripts"` iframe under a hard-pinned CSP
6
+ * (`connect-src 'none'`, no eval). NEVER `fetch` or reference a remote URL — the
7
+ * frame is offline; the ONLY channel to the node is `window.openai`.
8
+ *
9
+ * The Save button demonstrates the companion callTool bridge: the host validates
10
+ * the capability, routes the call through the Gateway, and executes it in Core.
11
+ */
12
+
13
+ import { StrictMode, useState } from "react";
14
+ import { createRoot } from "react-dom/client";
15
+
16
+ /** The minimal Apps bridge this widget uses (installed synchronously by the host
17
+ * before this module runs). `callTool` is gated by the app's `tool:call` grant. */
18
+ interface RyuWidgetBridge {
19
+ callTool?(name: string, args: unknown): Promise<unknown>;
20
+ toolInput?: { title?: string };
21
+ toolOutput?: { title?: string };
22
+ }
23
+
24
+ declare global {
25
+ interface Window {
26
+ openai?: RyuWidgetBridge;
27
+ }
28
+ }
29
+
30
+ const SAVE_TOOL_ID = "__APP_NAME____save";
31
+
32
+ function Widget() {
33
+ const bridge = window.openai ?? {};
34
+ const title =
35
+ bridge.toolOutput?.title ??
36
+ bridge.toolInput?.title ??
37
+ "__APP_DISPLAY_NAME__";
38
+ const [note, setNote] = useState("");
39
+ const [status, setStatus] = useState<"idle" | "saving" | "saved" | "error">(
40
+ "idle"
41
+ );
42
+
43
+ async function save() {
44
+ if (!bridge.callTool) {
45
+ setStatus("error");
46
+ return;
47
+ }
48
+ setStatus("saving");
49
+ try {
50
+ await bridge.callTool(SAVE_TOOL_ID, { state: { note } });
51
+ setStatus("saved");
52
+ } catch {
53
+ setStatus("error");
54
+ }
55
+ }
56
+
57
+ return (
58
+ <main className="ryu-app">
59
+ <h1>{title}</h1>
60
+ <textarea
61
+ aria-label="Note"
62
+ onChange={(event) => setNote(event.target.value)}
63
+ placeholder="Type a note to persist…"
64
+ value={note}
65
+ />
66
+ <button onClick={save} type="button">
67
+ Save
68
+ </button>
69
+ <p className="status">{status}</p>
70
+ </main>
71
+ );
72
+ }
73
+
74
+ const rootEl = document.getElementById("root");
75
+ if (rootEl) {
76
+ createRoot(rootEl).render(
77
+ <StrictMode>
78
+ <Widget />
79
+ </StrictMode>
80
+ );
81
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "id": "com.example.__APP_NAME__",
3
+ "name": "__APP_DISPLAY_NAME__",
4
+ "version": "0.1.0",
5
+ "runnables": [],
6
+ "permission_grants": [],
7
+ "activation_events": ["*"],
8
+ "contributes": {
9
+ "turn_hooks": [
10
+ {
11
+ "id": "flag-terse",
12
+ "on": "post_assistant_turn",
13
+ "code": "return await ((ctx, host) => {\n const last = ctx.transcript.at(-1);\n if (last && last.role === \"assistant\" && last.content.trim().length < 40) {\n host.log(\"terse reply flagged\");\n return { kind: \"note\", text: \"That reply looked brief \\u2014 want more detail?\" };\n }\n return { kind: \"none\" };\n})(ctx, host);"
14
+ }
15
+ ],
16
+ "composer_controls": [
17
+ {
18
+ "id": "hook.toggle",
19
+ "type": "toggle",
20
+ "flag": "com.example.__APP_NAME__"
21
+ }
22
+ ],
23
+ "settings_tabs": [],
24
+ "slash_commands": [],
25
+ "widgets": []
26
+ }
27
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * __APP_DISPLAY_NAME__ — a turn-hook plugin.
3
+ *
4
+ * A turn hook is server-side logic Core runs after each assistant turn, inside its
5
+ * capability-gated plugin sandbox (`apps/core/src/plugin_host/`). The hook sees a
6
+ * `ctx` (agent, conversation, transcript, flags) and a `host` bridge (logging,
7
+ * `sideModel`, namespaced `storage`), and returns a directive:
8
+ * - `{ kind: "none" }` — do nothing
9
+ * - `{ kind: "note", text }` — attach an out-of-band note to the turn
10
+ * - `{ kind: "continue", text }` — feed text back for another assistant turn
11
+ *
12
+ * This is the SAME shape the built-in double-check / goal / advisor plugins use.
13
+ * The `run` body must be SELF-CONTAINED: it executes in a fresh sandbox with only
14
+ * `ctx` and `host` in scope, so it cannot capture imports, closures, or module
15
+ * variables — reference only `ctx`, `host`, and language built-ins.
16
+ *
17
+ * bun run src/plugin.ts # prints the assembled manifest
18
+ * bunx ryu pack . # serializes the hook + writes plugin.json
19
+ */
20
+
21
+ import { definePlugin, defineTurnHook } from "@ryuhq/sdk";
22
+
23
+ const manifest = definePlugin({
24
+ id: "com.example.__APP_NAME__",
25
+ name: "__APP_DISPLAY_NAME__",
26
+ version: "0.1.0",
27
+ grants: [],
28
+ composerControls: [
29
+ { id: "hook.toggle", type: "toggle", flag: "com.example.__APP_NAME__" },
30
+ ],
31
+ turnHooks: [
32
+ defineTurnHook({
33
+ id: "flag-terse",
34
+ run: (ctx, host) => {
35
+ const last = ctx.transcript.at(-1);
36
+ if (
37
+ last &&
38
+ last.role === "assistant" &&
39
+ last.content.trim().length < 40
40
+ ) {
41
+ host.log("terse reply flagged");
42
+ return {
43
+ kind: "note",
44
+ text: "That reply looked brief — want more detail?",
45
+ };
46
+ }
47
+ return { kind: "none" };
48
+ },
49
+ }),
50
+ ],
51
+ });
52
+
53
+ export default manifest;
54
+
55
+ if (import.meta.main) {
56
+ process.stdout.write(`${JSON.stringify(manifest, null, 2)}\n`);
57
+ }
@@ -0,0 +1,54 @@
1
+ {
2
+ "id": "com.example.__APP_NAME__",
3
+ "name": "__APP_DISPLAY_NAME__",
4
+ "version": "0.1.0",
5
+ "runnables": [
6
+ {
7
+ "id": "__APP_NAME____render",
8
+ "name": "render",
9
+ "kind": "tool",
10
+ "config": {
11
+ "slug": "__APP_NAME____render",
12
+ "description": "Render the __APP_DISPLAY_NAME__ widget inline in the chat reply.",
13
+ "widget": true,
14
+ "widget_accessible": false,
15
+ "input_schema": {
16
+ "type": "object",
17
+ "properties": {
18
+ "title": {
19
+ "type": "string",
20
+ "description": "Heading shown in the widget"
21
+ },
22
+ "items": {
23
+ "type": "array",
24
+ "items": {
25
+ "type": "string"
26
+ },
27
+ "description": "Rows to render"
28
+ }
29
+ },
30
+ "required": ["title"]
31
+ },
32
+ "invoking": "Rendering…",
33
+ "invoked": "Ready"
34
+ }
35
+ }
36
+ ],
37
+ "permission_grants": [],
38
+ "activation_events": ["*"],
39
+ "contributes": {
40
+ "turn_hooks": [],
41
+ "composer_controls": [],
42
+ "settings_tabs": [],
43
+ "slash_commands": [],
44
+ "widgets": [
45
+ {
46
+ "tool_id": "__APP_NAME____render",
47
+ "uri": "ui://widget/__APP_NAME__.html",
48
+ "ui_entry": "src/widget.tsx",
49
+ "mime": "text/html+skybridge",
50
+ "default_display_mode": "inline"
51
+ }
52
+ ]
53
+ }
54
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * __APP_DISPLAY_NAME__ — a Ryu App (interactive in-chat widget).
3
+ *
4
+ * A Ryu App bundles a "render" tool whose result mounts a self-contained widget
5
+ * inline in the chat reply. This module is the AUTHORING source of truth: it uses
6
+ * `defineApp` to assemble the `plugin.json` manifest that ships alongside it.
7
+ *
8
+ * bun run src/app.ts # prints the assembled manifest
9
+ * bunx ryu pack . # bundles src/widget.tsx into ui_code + writes plugin.json
10
+ *
11
+ * v1 boundary: this is DECLARATIVE PASS-THROUGH only. There is no `run` handler —
12
+ * the widget renders from `window.openai.toolInput` / `toolOutput` (the arguments
13
+ * the model passed and the structured content Core echoes back). Third-party tool
14
+ * CODE execution needs the plugin runtime, which is a later tier. Keep the widget
15
+ * self-contained: no network fetches (the CSP blocks egress), assets inline.
16
+ */
17
+
18
+ import { defineApp } from "@ryuhq/sdk";
19
+
20
+ const manifest = defineApp({
21
+ id: "com.example.__APP_NAME__",
22
+ title: "__APP_DISPLAY_NAME__",
23
+ version: "0.1.0",
24
+ slug: "__APP_NAME__",
25
+ uiEntry: "src/widget.tsx",
26
+ tools: [
27
+ {
28
+ name: "render",
29
+ description:
30
+ "Render the __APP_DISPLAY_NAME__ widget inline in the chat reply.",
31
+ invoking: "Rendering…",
32
+ invoked: "Ready",
33
+ inputSchema: {
34
+ type: "object",
35
+ properties: {
36
+ title: { type: "string", description: "Heading shown in the widget" },
37
+ items: {
38
+ type: "array",
39
+ items: { type: "string" },
40
+ description: "Rows to render",
41
+ },
42
+ },
43
+ required: ["title"],
44
+ },
45
+ },
46
+ ],
47
+ });
48
+
49
+ export default manifest;
50
+
51
+ if (import.meta.main) {
52
+ process.stdout.write(`${JSON.stringify(manifest, null, 2)}\n`);
53
+ }
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>__APP_DISPLAY_NAME__</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="./widget.tsx"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,59 @@
1
+ /**
2
+ * __APP_DISPLAY_NAME__ widget — the in-chat surface `ryu pack` bundles into a
3
+ * single, self-contained HTML document (inline CSS + one inline module script).
4
+ *
5
+ * IMPORTANT — sandbox contract:
6
+ * - Mounts inside a null-origin `sandbox="allow-scripts"` iframe under a
7
+ * hard-pinned CSP: `connect-src 'none'`, `img-src data:`, no eval. So NEVER
8
+ * `fetch`, load a CDN script, or reference a remote URL — the frame is offline
9
+ * by construction. All host access goes through `window.openai`.
10
+ * - Read your inputs from `window.openai.toolInput` (the model's arguments) and
11
+ * `window.openai.toolOutput` (the structured content Core echoed back).
12
+ */
13
+
14
+ import { StrictMode } from "react";
15
+ import { createRoot } from "react-dom/client";
16
+
17
+ /** The minimal slice of the Apps bridge this widget reads (installed
18
+ * synchronously by the host before this module runs). */
19
+ interface RyuWidgetBridge {
20
+ toolInput?: { title?: string; items?: string[] };
21
+ toolOutput?: { title?: string; items?: string[] };
22
+ }
23
+
24
+ declare global {
25
+ interface Window {
26
+ openai?: RyuWidgetBridge;
27
+ }
28
+ }
29
+
30
+ function Widget() {
31
+ const bridge = window.openai ?? {};
32
+ const data = bridge.toolOutput ?? bridge.toolInput ?? {};
33
+ const title = data.title ?? "__APP_DISPLAY_NAME__";
34
+ const items = data.items ?? [];
35
+
36
+ return (
37
+ <main className="ryu-app">
38
+ <h1>{title}</h1>
39
+ {items.length === 0 ? (
40
+ <p className="empty">No rows yet.</p>
41
+ ) : (
42
+ <ul>
43
+ {items.map((item, index) => (
44
+ <li key={`${index}-${item}`}>{item}</li>
45
+ ))}
46
+ </ul>
47
+ )}
48
+ </main>
49
+ );
50
+ }
51
+
52
+ const rootEl = document.getElementById("root");
53
+ if (rootEl) {
54
+ createRoot(rootEl).render(
55
+ <StrictMode>
56
+ <Widget />
57
+ </StrictMode>
58
+ );
59
+ }