@morkaai/runtime 0.0.0-stage → 0.2.1

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 (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/bin/morka.cjs +57 -0
  4. package/dist/agent-actions/access.js +44 -0
  5. package/dist/agent-actions/manifest.js +52 -0
  6. package/dist/agent-actions/runner.js +69 -0
  7. package/dist/agents/account.js +42 -0
  8. package/dist/agents/acp-sandbox.js +118 -0
  9. package/dist/agents/activity.js +26 -0
  10. package/dist/agents/attachments.js +129 -0
  11. package/dist/agents/context.js +76 -0
  12. package/dist/agents/contracts.js +2 -0
  13. package/dist/agents/process.js +61 -0
  14. package/dist/agents/providers/acp.js +411 -0
  15. package/dist/agents/providers/claude.js +180 -0
  16. package/dist/agents/providers/codex.js +416 -0
  17. package/dist/agents/registry.js +76 -0
  18. package/dist/agents/sessions.js +331 -0
  19. package/dist/app-runtime/bridge.js +40 -0
  20. package/dist/app-runtime/starter/agents.json +1 -0
  21. package/dist/app-runtime/starter/index.html +11 -0
  22. package/dist/app-runtime/starter/main.js +0 -0
  23. package/dist/app-runtime/starter/package-lock.json +13 -0
  24. package/dist/app-runtime/starter/package.json +9 -0
  25. package/dist/app-runtime/starter/server.mjs +20 -0
  26. package/dist/app-runtime/starter/styles.css +0 -0
  27. package/dist/app-runtime/text-file.js +18 -0
  28. package/dist/branding/Morka.icns +0 -0
  29. package/dist/branding/README.md +24 -0
  30. package/dist/branding/generated-app-icon.png +0 -0
  31. package/dist/branding/morka-icon.png +0 -0
  32. package/dist/branding/morka-logo.png +0 -0
  33. package/dist/electron/main.js +802 -0
  34. package/dist/electron/preload.js +51 -0
  35. package/dist/instances/desktop.js +223 -0
  36. package/dist/instances/distribution.js +240 -0
  37. package/dist/instances/macos.js +62 -0
  38. package/dist/instances/repository.js +183 -0
  39. package/dist/instances/shadow-repository.js +95 -0
  40. package/dist/project/app-proxy.js +325 -0
  41. package/dist/project/bundle-toolchain.js +35 -0
  42. package/dist/project/drafts.js +27 -0
  43. package/dist/project/files.js +176 -0
  44. package/dist/project/live-preview.js +198 -0
  45. package/dist/project/managed-runtime.js +324 -0
  46. package/dist/project/node-lifecycle.js +45 -0
  47. package/dist/project/packages.js +302 -0
  48. package/dist/project/page-state.js +198 -0
  49. package/dist/project/project.js +112 -0
  50. package/dist/project/shadow-effects.js +156 -0
  51. package/dist/project/shadows.js +122 -0
  52. package/dist/project/toolchain.js +216 -0
  53. package/dist/renderer/activity.js +91 -0
  54. package/dist/renderer/app-setup.js +126 -0
  55. package/dist/renderer/chat-tools.css +83 -0
  56. package/dist/renderer/highlight.css +118 -0
  57. package/dist/renderer/icons/attach.png +0 -0
  58. package/dist/renderer/icons/brain-weight.png +0 -0
  59. package/dist/renderer/icons/brain.png +0 -0
  60. package/dist/renderer/icons/chat.png +0 -0
  61. package/dist/renderer/icons/chevron.png +0 -0
  62. package/dist/renderer/icons/clone.png +0 -0
  63. package/dist/renderer/icons/close.png +0 -0
  64. package/dist/renderer/icons/document.png +0 -0
  65. package/dist/renderer/icons/edit.png +0 -0
  66. package/dist/renderer/icons/folder.png +0 -0
  67. package/dist/renderer/icons/import.png +0 -0
  68. package/dist/renderer/icons/open-folder.png +0 -0
  69. package/dist/renderer/icons/play.png +0 -0
  70. package/dist/renderer/icons/plus.png +0 -0
  71. package/dist/renderer/icons/remove.png +0 -0
  72. package/dist/renderer/icons/search.png +0 -0
  73. package/dist/renderer/icons/send.png +0 -0
  74. package/dist/renderer/icons/shadow.png +0 -0
  75. package/dist/renderer/icons/stop.png +0 -0
  76. package/dist/renderer/icons/terminal.png +0 -0
  77. package/dist/renderer/index.html +130 -0
  78. package/dist/renderer/launcher/OFL.txt +93 -0
  79. package/dist/renderer/launcher/cell.js +322 -0
  80. package/dist/renderer/launcher/launcher.css +79 -0
  81. package/dist/renderer/launcher/lexend-caption-bold.ttf +0 -0
  82. package/dist/renderer/launcher.html +23 -0
  83. package/dist/renderer/licenses/dompurify.txt +202 -0
  84. package/dist/renderer/licenses/github-slugger.txt +5 -0
  85. package/dist/renderer/licenses/highlight.js.txt +29 -0
  86. package/dist/renderer/licenses/marked-footnote.txt +21 -0
  87. package/dist/renderer/licenses/marked-gfm-heading-id.txt +21 -0
  88. package/dist/renderer/licenses/marked.txt +44 -0
  89. package/dist/renderer/markdown.css +43 -0
  90. package/dist/renderer/markdown.js +74 -0
  91. package/dist/renderer/renderer.js +18902 -0
  92. package/dist/renderer/styles.css +351 -0
  93. package/dist/skills/morka-agent-action/SKILL.md +39 -0
  94. package/dist/skills/morka-app/SKILL.md +36 -0
  95. package/dist/skills/morka-shadow-authoring/SKILL.md +32 -0
  96. package/package.json +30 -4
@@ -0,0 +1,302 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppPackages = void 0;
4
+ exports.writableTree = writableTree;
5
+ exports.sealArtifactDirectory = sealArtifactDirectory;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const node_fs_1 = require("node:fs");
8
+ const promises_1 = require("node:fs/promises");
9
+ const node_path_1 = require("node:path");
10
+ const files_1 = require("./files");
11
+ const toolchain_1 = require("./toolchain");
12
+ const format = 5;
13
+ function inside(root, path) {
14
+ const rel = (0, node_path_1.relative)(root, path);
15
+ return !(0, node_path_1.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + node_path_1.sep);
16
+ }
17
+ function packageJson(source) {
18
+ const bytes = source.get("package.json");
19
+ if (!bytes)
20
+ throw new Error("A managed Node app needs its own app/package.json.");
21
+ const pkg = JSON.parse(bytes.toString());
22
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg))
23
+ throw new Error("Invalid app/package.json.");
24
+ if (source.get(".npmrc")?.toString().match(/(?:_auth|_password|token)\s*=/i)) {
25
+ throw new Error("Keep registry credentials in this app's private npm/npmrc profile, outside source.");
26
+ }
27
+ for (const section of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
28
+ for (const value of Object.values(pkg[section] ?? {})) {
29
+ if (typeof value !== "string")
30
+ throw new Error(`Invalid ${section} in app/package.json.`);
31
+ if (/^(?:file:|link:)/.test(value)) {
32
+ const path = value.replace(/^(?:file:|link:)/, "");
33
+ if ((0, node_path_1.isAbsolute)(path) || !inside("/app", (0, node_path_1.resolve)("/app", path)))
34
+ throw new Error("Local npm dependencies must be vendored inside app/.");
35
+ }
36
+ }
37
+ }
38
+ return pkg;
39
+ }
40
+ async function writableTree(root) {
41
+ const entries = await (0, promises_1.readdir)(root, { withFileTypes: true });
42
+ await (0, promises_1.chmod)(root, 0o700);
43
+ for (const entry of entries) {
44
+ const path = (0, node_path_1.join)(root, entry.name);
45
+ if (entry.isSymbolicLink())
46
+ continue;
47
+ if (entry.isDirectory())
48
+ await writableTree(path);
49
+ else
50
+ await (0, promises_1.chmod)(path, 0o600 | ((await (0, files_1.info)(path)).mode & 0o111));
51
+ }
52
+ }
53
+ async function seal(root, boundary) {
54
+ const base = boundary ?? await (0, promises_1.realpath)(root);
55
+ for (const entry of await (0, promises_1.readdir)(root, { withFileTypes: true })) {
56
+ const path = (0, node_path_1.join)(root, entry.name);
57
+ if (entry.isSymbolicLink()) {
58
+ if ((0, node_path_1.isAbsolute)(await (0, promises_1.readlink)(path)))
59
+ throw new Error("Installed package links must be relative so releases remain portable.");
60
+ if (!inside(base, await (0, promises_1.realpath)(path)))
61
+ throw new Error("An installed package created a link outside its release.");
62
+ }
63
+ else if (entry.isDirectory())
64
+ await seal(path, base);
65
+ else if (entry.isFile())
66
+ await (0, promises_1.chmod)(path, 0o444 | ((await (0, files_1.info)(path)).mode & 0o111));
67
+ else
68
+ throw new Error("Package artifacts may contain only regular files, directories and internal links.");
69
+ }
70
+ await (0, promises_1.chmod)(root, 0o555);
71
+ }
72
+ async function sealArtifactDirectory(root) { await seal(root); }
73
+ class AppPackages {
74
+ home;
75
+ toolchainRoot;
76
+ pending = new Map();
77
+ constructor(home, toolchainRoot) {
78
+ this.home = home;
79
+ this.toolchainRoot = toolchainRoot;
80
+ }
81
+ async prepare(source, options = {}) {
82
+ packageJson(source);
83
+ const toolchain = await (0, toolchain_1.bundledToolchain)(this.toolchainRoot);
84
+ const configHash = await this.configurationHash();
85
+ const request = this.key(source, toolchain, configHash);
86
+ const existing = this.pending.get(request);
87
+ if (existing)
88
+ return existing;
89
+ const task = this.build(new Map(source), toolchain, options, configHash).finally(() => this.pending.delete(request));
90
+ this.pending.set(request, task);
91
+ return task;
92
+ }
93
+ async configurationHash() {
94
+ const hash = (0, node_crypto_1.createHash)("sha256");
95
+ for (const name of ["npmrc", "npm.env", "build.env"]) {
96
+ const data = await (0, promises_1.readFile)((0, node_path_1.join)(this.home, "npm", name)).catch((error) => {
97
+ if (error.code === "ENOENT")
98
+ return Buffer.alloc(0);
99
+ throw error;
100
+ });
101
+ hash.update(name).update(data);
102
+ }
103
+ return hash.digest("hex");
104
+ }
105
+ async sameConfiguration(artifact) { return artifact.configHash === await this.configurationHash(); }
106
+ key(source, toolchain, configHash) {
107
+ return (0, node_crypto_1.createHash)("sha256").update(JSON.stringify({ format, toolchain: toolchain.identity, source: (0, files_1.digest)(source), configHash })).digest("hex");
108
+ }
109
+ async cached(source, toolchain, configHash) {
110
+ const key = this.key(source, toolchain, configHash);
111
+ const root = (0, node_path_1.join)(this.home, "releases", key);
112
+ const marker = await (0, promises_1.readFile)((0, node_path_1.join)(root, "artifact.json"), "utf8").catch(() => undefined);
113
+ if (!marker)
114
+ return;
115
+ const data = JSON.parse(marker);
116
+ if (data.format !== format || data.key !== key || data.sourceHash !== (0, files_1.digest)(source) || data.toolchain !== toolchain.identity ||
117
+ data.configHash !== configHash || this.key(source, toolchain, configHash) !== key)
118
+ return;
119
+ if (!(await (0, files_1.info)((0, node_path_1.join)(root, "app")))?.isDirectory())
120
+ return;
121
+ return { key, directory: (0, node_path_1.join)(root, "app"), source, sourceHash: data.sourceHash, toolchain, built: data.built, configHash };
122
+ }
123
+ async recover(key) {
124
+ if (typeof key !== "string" || !/^[a-f0-9]{64}$/.test(key))
125
+ return;
126
+ const root = (0, node_path_1.join)(this.home, "releases", key);
127
+ const marker = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(root, "artifact.json"), "utf8").catch(error => {
128
+ if (error.code === "ENOENT")
129
+ return "null";
130
+ throw error;
131
+ }));
132
+ if (!marker || typeof marker.configHash !== "string")
133
+ return;
134
+ const source = await (0, files_1.snapshot)((0, node_path_1.join)(root, "source"));
135
+ const toolchain = await (0, toolchain_1.bundledToolchain)(this.toolchainRoot);
136
+ if (marker.toolchain !== toolchain.identity) {
137
+ // A Node/toolchain upgrade can require rebuilding native modules. Use
138
+ // the saved source even when the checkout contains a different edit.
139
+ if (marker.format !== format || marker.key !== key || marker.sourceHash !== (0, files_1.digest)(source) ||
140
+ typeof marker.toolchain !== "string" ||
141
+ (0, node_crypto_1.createHash)("sha256").update(JSON.stringify({ format, toolchain: marker.toolchain,
142
+ source: marker.sourceHash, configHash: marker.configHash })).digest("hex") !== key)
143
+ return;
144
+ return this.prepare(source);
145
+ }
146
+ return this.cached(source, toolchain, marker.configHash);
147
+ }
148
+ async build(source, toolchain, options, configHash) {
149
+ options.signal?.throwIfAborted();
150
+ const cached = await this.cached(source, toolchain, configHash);
151
+ if (cached)
152
+ return cached;
153
+ const releases = (0, node_path_1.join)(this.home, "releases");
154
+ await (0, promises_1.mkdir)(releases, { recursive: true, mode: 0o700 });
155
+ const stage = await (0, promises_1.mkdtemp)((0, node_path_1.join)(releases, ".prepare-"));
156
+ const directory = (0, node_path_1.join)(stage, "app");
157
+ const profile = (0, node_path_1.join)(this.home, "npm");
158
+ const cache = (0, node_path_1.join)(this.home, "cache", "npm");
159
+ const npm = async (args, auth = true) => (0, toolchain_1.packageProcess)(toolchain, [...args, ...(options.offline ? ["--offline"] : [])], directory, profile, cache, { signal: options.signal, onLog: options.onLog, auth });
160
+ try {
161
+ await (0, promises_1.mkdir)(directory);
162
+ await (0, files_1.applyFiles)(directory, new Map(), source, options.signal);
163
+ const pkg = packageJson(source);
164
+ if (options.updateLock || !source.has("package-lock.json")) {
165
+ if (!options.updateLock && !source.has("package-lock.json"))
166
+ throw new Error("The app needs a committed package-lock.json. Add dependencies through its app/package.json in the chat draft.");
167
+ options.onLog?.("Resolving the app lockfile…\n");
168
+ await npm(["install", "--package-lock-only", "--ignore-scripts", "--no-audit", "--no-fund"]);
169
+ source.set("package-lock.json", await (0, promises_1.readFile)((0, node_path_1.join)(directory, "package-lock.json")));
170
+ const reused = await this.cached(source, toolchain, configHash);
171
+ if (reused)
172
+ return reused;
173
+ }
174
+ const lock = JSON.parse(source.get("package-lock.json").toString());
175
+ if (lock.lockfileVersion < 2 || !lock.packages)
176
+ throw new Error("Use an npm lockfile version 2 or newer.");
177
+ for (const data of Object.values(lock.packages)) {
178
+ if (typeof data.resolved === "string" && data.resolved.startsWith("file:") && !inside(directory, (0, node_path_1.resolve)(directory, data.resolved.slice(5)))) {
179
+ throw new Error("A locked local dependency points outside app/.");
180
+ }
181
+ }
182
+ options.onLog?.("Installing app dependencies in an isolated release…\n");
183
+ await npm(["ci", "--include=dev", "--foreground-scripts", "--no-audit", "--no-fund"]);
184
+ if (pkg.scripts?.build) {
185
+ options.onLog?.("Building the app…\n");
186
+ await npm(["run", "build"], false);
187
+ }
188
+ if (pkg.scripts?.["morka:check"]) {
189
+ options.onLog?.("Checking the app…\n");
190
+ await npm(["run", "morka:check"], false);
191
+ }
192
+ await npm(["prune", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"], false);
193
+ // Build tools must not rewrite the declarations being published.
194
+ if (!(await (0, promises_1.readFile)((0, node_path_1.join)(directory, "package.json"))).equals(source.get("package.json")))
195
+ throw new Error("An app build changed package.json. Update dependency declarations explicitly in the draft.");
196
+ await (0, promises_1.writeFile)((0, node_path_1.join)(directory, "package-lock.json"), source.get("package-lock.json"));
197
+ return await this.commit(stage, directory, source, toolchain, Boolean(pkg.scripts?.build), configHash);
198
+ }
199
+ finally {
200
+ if (await (0, files_1.info)(stage)) {
201
+ await writableTree(stage);
202
+ await (0, promises_1.rm)(stage, { recursive: true, force: true });
203
+ }
204
+ }
205
+ }
206
+ // A pure stylesheet edit can reuse installed dependencies without executing
207
+ // lifecycle scripts or changing the running process's immutable directory.
208
+ async styles(active, source, paths, signal) {
209
+ if (active.built || !await this.sameConfiguration(active) || !paths.length || paths.some(path => !path.endsWith(".css") || !source.has(path)))
210
+ return this.prepare(source, { signal });
211
+ const cached = await this.cached(source, active.toolchain, active.configHash);
212
+ if (cached)
213
+ return cached;
214
+ const stage = await (0, promises_1.mkdtemp)((0, node_path_1.join)(this.home, "releases", ".styles-"));
215
+ const directory = (0, node_path_1.join)(stage, "app");
216
+ try {
217
+ await (0, promises_1.cp)(active.directory, directory, { recursive: true, verbatimSymlinks: true, mode: node_fs_1.constants.COPYFILE_FICLONE });
218
+ const oldHome = (0, node_path_1.join)(active.directory, "..", "home");
219
+ if ((await (0, files_1.info)(oldHome))?.isDirectory())
220
+ await (0, promises_1.cp)(oldHome, (0, node_path_1.join)(stage, "home"), { recursive: true, verbatimSymlinks: true, mode: node_fs_1.constants.COPYFILE_FICLONE });
221
+ await writableTree(directory);
222
+ for (const path of paths) {
223
+ signal?.throwIfAborted();
224
+ await (0, promises_1.writeFile)((0, node_path_1.join)(directory, (0, files_1.projectPath)(path)), source.get(path));
225
+ }
226
+ return await this.commit(stage, directory, source, active.toolchain, false, active.configHash);
227
+ }
228
+ finally {
229
+ if (await (0, files_1.info)(stage)) {
230
+ await writableTree(stage);
231
+ await (0, promises_1.rm)(stage, { recursive: true, force: true });
232
+ }
233
+ }
234
+ }
235
+ async commit(stage, directory, source, toolchain, built, configHash, prebuiltFrom) {
236
+ if (configHash !== await this.configurationHash())
237
+ throw new Error("The app's private build configuration changed during preparation. Retry the update.");
238
+ const key = this.key(source, toolchain, configHash);
239
+ const root = (0, node_path_1.join)(this.home, "releases", key);
240
+ if (await (0, files_1.info)((0, node_path_1.join)(stage, "home", "tmp")))
241
+ await (0, promises_1.rm)((0, node_path_1.join)(stage, "home", "tmp"), { recursive: true, force: true });
242
+ await (0, promises_1.mkdir)((0, node_path_1.join)(stage, "source"));
243
+ await (0, files_1.applyFiles)((0, node_path_1.join)(stage, "source"), new Map(), source);
244
+ await seal((0, node_path_1.join)(stage, "source"));
245
+ await seal(directory);
246
+ if ((await (0, files_1.info)((0, node_path_1.join)(stage, "home")))?.isDirectory())
247
+ await seal((0, node_path_1.join)(stage, "home"));
248
+ await (0, promises_1.writeFile)((0, node_path_1.join)(stage, "artifact.json"), JSON.stringify({ format, key, sourceHash: (0, files_1.digest)(source), toolchain: toolchain.identity, built, configHash, ...(prebuiltFrom ? { prebuiltFrom } : {}) }) + "\n");
249
+ try {
250
+ await (0, promises_1.rename)(stage, root);
251
+ }
252
+ catch (error) {
253
+ if (!(await this.cached(source, toolchain, configHash)))
254
+ throw error;
255
+ }
256
+ return { key, directory: (0, node_path_1.join)(root, "app"), source, sourceHash: (0, files_1.digest)(source), toolchain, built, configHash };
257
+ }
258
+ async importPrepared(directory, source) {
259
+ const toolchain = await (0, toolchain_1.bundledToolchain)(this.toolchainRoot);
260
+ const marker = await (0, promises_1.readFile)((0, node_path_1.join)(directory, "artifact.json"), "utf8").catch(() => undefined);
261
+ if (!marker)
262
+ return;
263
+ const data = JSON.parse(marker);
264
+ if (data.format !== format || typeof data.configHash !== "string" || data.sourceHash !== (0, files_1.digest)(source) || data.toolchain !== toolchain.identity || data.key !== this.key(source, toolchain, data.configHash)) {
265
+ throw new Error("The packaged app release does not match its source or bundled Node runtime.");
266
+ }
267
+ const configHash = await this.configurationHash();
268
+ const existing = await this.cached(source, toolchain, configHash);
269
+ if (existing)
270
+ return existing;
271
+ const releases = (0, node_path_1.join)(this.home, "releases");
272
+ await (0, promises_1.mkdir)(releases, { recursive: true, mode: 0o700 });
273
+ const stage = await (0, promises_1.mkdtemp)((0, node_path_1.join)(releases, ".import-"));
274
+ try {
275
+ await (0, promises_1.cp)((0, node_path_1.join)(directory, "app"), (0, node_path_1.join)(stage, "app"), { recursive: true, verbatimSymlinks: true, mode: node_fs_1.constants.COPYFILE_FICLONE });
276
+ if ((await (0, files_1.info)((0, node_path_1.join)(directory, "home")))?.isDirectory())
277
+ await (0, promises_1.cp)((0, node_path_1.join)(directory, "home"), (0, node_path_1.join)(stage, "home"), { recursive: true, verbatimSymlinks: true, mode: node_fs_1.constants.COPYFILE_FICLONE });
278
+ return await this.commit(stage, (0, node_path_1.join)(stage, "app"), source, toolchain, data.built, configHash, data.key);
279
+ }
280
+ finally {
281
+ if (await (0, files_1.info)(stage)) {
282
+ await writableTree(stage);
283
+ await (0, promises_1.rm)(stage, { recursive: true, force: true });
284
+ }
285
+ }
286
+ }
287
+ async collect(protectedKeys, keep = 5) {
288
+ const releases = (0, node_path_1.join)(this.home, "releases");
289
+ const entries = await (0, promises_1.readdir)(releases, { withFileTypes: true }).catch(() => []);
290
+ const versions = (await Promise.all(entries.filter(entry => entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)).map(async (entry) => ({
291
+ key: entry.name, time: (await (0, files_1.info)((0, node_path_1.join)(releases, entry.name, "artifact.json")))?.mtimeMs ?? 0,
292
+ })))).sort((a, b) => b.time - a.time);
293
+ const retained = new Set([...protectedKeys, ...versions.slice(0, keep).map(entry => entry.key)]);
294
+ for (const version of versions)
295
+ if (!retained.has(version.key)) {
296
+ const directory = (0, node_path_1.join)(releases, version.key);
297
+ await writableTree(directory);
298
+ await (0, promises_1.rm)(directory, { recursive: true, force: true });
299
+ }
300
+ }
301
+ }
302
+ exports.AppPackages = AppPackages;
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pageState = pageState;
4
+ // This function is serialized into the preview's main world. Keep it self-contained.
5
+ async function pageState(command, argument) {
6
+ const page = window;
7
+ if (!page.__morkaLive) {
8
+ let pending = 0;
9
+ let paused = false;
10
+ let locked = false;
11
+ let resume;
12
+ let gate = Promise.resolve();
13
+ const fetch = window.fetch;
14
+ window.fetch = async function (...args) {
15
+ if (paused)
16
+ await gate;
17
+ pending++;
18
+ try {
19
+ const response = await fetch.apply(this, args);
20
+ void response.clone().arrayBuffer().catch(() => { }).finally(() => { pending--; });
21
+ return response;
22
+ }
23
+ catch (error) {
24
+ pending--;
25
+ throw error;
26
+ }
27
+ };
28
+ const send = XMLHttpRequest.prototype.send;
29
+ XMLHttpRequest.prototype.send = function (body) {
30
+ const request = this;
31
+ const run = () => {
32
+ pending++;
33
+ request.addEventListener("loadend", () => { pending--; }, { once: true });
34
+ try {
35
+ send.call(request, body);
36
+ }
37
+ catch (error) {
38
+ pending--;
39
+ throw error;
40
+ }
41
+ };
42
+ if (paused)
43
+ void gate.then(run);
44
+ else
45
+ run();
46
+ };
47
+ const key = (element) => {
48
+ if (element === document.documentElement)
49
+ return "html";
50
+ if (element.id)
51
+ return "#" + CSS.escape(element.id);
52
+ const parts = [];
53
+ let current = element;
54
+ while (current && current !== document.documentElement) {
55
+ const tag = current.localName;
56
+ const siblings = current.parentElement ? [...current.parentElement.children].filter(item => item.localName === tag) : [];
57
+ parts.unshift(`${tag}:nth-of-type(${siblings.indexOf(current) + 1})`);
58
+ current = current.parentElement;
59
+ }
60
+ return "html>" + parts.join(">");
61
+ };
62
+ const find = (selector) => { try {
63
+ return document.querySelector(selector);
64
+ }
65
+ catch {
66
+ return null;
67
+ } };
68
+ for (const type of ["click", "pointerdown", "keydown", "beforeinput", "submit", "change"]) {
69
+ document.addEventListener(type, event => {
70
+ if (locked && event.isTrusted) {
71
+ event.preventDefault();
72
+ event.stopImmediatePropagation();
73
+ }
74
+ }, true);
75
+ }
76
+ page.__morkaLive = {
77
+ async capture() {
78
+ if ([...document.querySelectorAll('input[type="file"]')].some(input => input.files?.length)) {
79
+ throw Error("Finish or cancel the file selection before applying this update.");
80
+ }
81
+ locked = true;
82
+ await page.morkaLifecycle?.beforeUpdate?.();
83
+ await page.morka?.whenIdle?.();
84
+ paused = true;
85
+ gate = new Promise(resolve => { resume = resolve; });
86
+ const deadline = Date.now() + 30_000;
87
+ while (pending) {
88
+ if (!locked)
89
+ throw Error("The update was cancelled.");
90
+ if (Date.now() > deadline)
91
+ throw Error("Waiting for the app's current requests to finish. Retry the update when they complete.");
92
+ await new Promise(resolve => setTimeout(resolve, 20));
93
+ }
94
+ const custom = await page.morkaLifecycle?.capture?.();
95
+ let storage;
96
+ try {
97
+ storage = { origin: location.origin, local: Object.entries(localStorage), session: Object.entries(sessionStorage) };
98
+ }
99
+ catch { }
100
+ const controls = [...document.querySelectorAll("input,textarea,select")]
101
+ .filter(input => !input.matches('input[type="file"],input[type="hidden"],input[type="submit"],input[type="button"]') &&
102
+ (!input.matches('input[type="checkbox"],input[type="radio"]') || Boolean(input.closest("form"))))
103
+ .map(input => ({ key: key(input), tag: input.localName, type: input.type, name: input.name,
104
+ value: input.value, checked: input.checked,
105
+ start: input.selectionStart, end: input.selectionEnd,
106
+ direction: input.selectionDirection }));
107
+ return { url: location.href, history: history.state, custom, controls, storage,
108
+ focus: document.hasFocus() && document.activeElement ? key(document.activeElement) : undefined,
109
+ scroll: [window.scrollX, window.scrollY],
110
+ scrollers: [...document.querySelectorAll("*")].filter(item => item.scrollTop || item.scrollLeft)
111
+ .map(item => ({ key: key(item), x: item.scrollLeft, y: item.scrollTop })),
112
+ details: [...document.querySelectorAll("details")].map(item => ({ key: key(item), open: item.open })) };
113
+ },
114
+ async restore(state) {
115
+ if (state.storage && state.storage.origin !== location.origin) {
116
+ for (const [name, entries] of [["localStorage", state.storage.local], ["sessionStorage", state.storage.session]]) {
117
+ try {
118
+ for (const [key, value] of entries)
119
+ if (page[name].getItem(key) === null)
120
+ page[name].setItem(key, value);
121
+ }
122
+ catch { }
123
+ }
124
+ }
125
+ await page.morkaLifecycle?.ready;
126
+ if (state.history !== null && state.history !== undefined)
127
+ history.replaceState(state.history, "");
128
+ for (const saved of state.controls) {
129
+ const input = find(saved.key);
130
+ if (!input || input.localName !== saved.tag || input.type !== saved.type || input.name !== saved.name)
131
+ continue;
132
+ if (input instanceof HTMLInputElement && ["checkbox", "radio"].includes(input.type))
133
+ input.checked = saved.checked;
134
+ else {
135
+ const prototype = input instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype
136
+ : input instanceof HTMLSelectElement ? HTMLSelectElement.prototype : HTMLInputElement.prototype;
137
+ Object.getOwnPropertyDescriptor(prototype, "value")?.set?.call(input, saved.value);
138
+ input.dispatchEvent(new Event("input", { bubbles: true }));
139
+ }
140
+ try {
141
+ if (saved.start !== null)
142
+ input.setSelectionRange(saved.start, saved.end, saved.direction);
143
+ }
144
+ catch { }
145
+ }
146
+ await page.morkaLifecycle?.restore?.(state.custom);
147
+ for (const saved of state.details) {
148
+ const details = find(saved.key);
149
+ if (details instanceof HTMLDetailsElement)
150
+ details.open = saved.open;
151
+ }
152
+ if (state.focus)
153
+ find(state.focus)?.focus({ preventScroll: true });
154
+ await new Promise(resolve => { const timer = setTimeout(resolve, 100); requestAnimationFrame(() => { clearTimeout(timer); resolve(); }); });
155
+ window.scrollTo(...state.scroll);
156
+ for (const saved of state.scrollers)
157
+ find(saved.key)?.scrollTo(saved.x, saved.y);
158
+ },
159
+ resume() { locked = false; paused = false; resume?.(); resume = undefined; },
160
+ async styles(styles) {
161
+ const links = [...document.querySelectorAll('link[rel="stylesheet"]')];
162
+ const replacements = links.filter(link => {
163
+ const url = new URL(link.href);
164
+ return url.protocol === location.protocol && url.host === location.host;
165
+ }).map(link => {
166
+ const url = new URL(link.href);
167
+ url.searchParams.set("morka-update", String(Date.now()));
168
+ return { link, url: url.href };
169
+ });
170
+ if (!replacements.length)
171
+ return true;
172
+ await Promise.all(replacements.map(({ link, url }) => new Promise((resolve, reject) => {
173
+ const replacement = link.cloneNode();
174
+ replacement.href = url;
175
+ const timer = setTimeout(() => { replacement.remove(); reject(Error("The updated stylesheet could not load.")); }, 10_000);
176
+ replacement.onload = () => { clearTimeout(timer); link.remove(); resolve(); };
177
+ replacement.onerror = () => { clearTimeout(timer); replacement.remove(); reject(Error("The updated stylesheet could not load.")); };
178
+ link.after(replacement);
179
+ })));
180
+ return true;
181
+ },
182
+ };
183
+ }
184
+ const live = page.__morkaLive;
185
+ if (command === "install")
186
+ return;
187
+ if (command === "ready") {
188
+ await page.morkaLifecycle?.ready;
189
+ return;
190
+ }
191
+ try {
192
+ return await live[command](argument);
193
+ }
194
+ catch (error) {
195
+ live.resume();
196
+ throw error;
197
+ }
198
+ }
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.starterManifest = void 0;
4
+ exports.jsonFile = jsonFile;
5
+ exports.object = object;
6
+ exports.pathList = pathList;
7
+ exports.loopback = loopback;
8
+ exports.readManifest = readManifest;
9
+ exports.instructionPaths = instructionPaths;
10
+ exports.compileProject = compileProject;
11
+ const manifest_1 = require("../agent-actions/manifest");
12
+ const files_1 = require("./files");
13
+ exports.starterManifest = {
14
+ version: 1,
15
+ runtime: { type: "node", script: "start", url: "http://127.0.0.1:0/", ready: "http://127.0.0.1:0/health" },
16
+ agentActions: { definitions: "agents.json", skills: "skills" },
17
+ };
18
+ function jsonFile(value) {
19
+ return Buffer.from(JSON.stringify(value, null, 2) + "\n");
20
+ }
21
+ function object(value) {
22
+ if (!value || typeof value !== "object" || Array.isArray(value))
23
+ throw new Error("Expected a JSON object.");
24
+ return value;
25
+ }
26
+ function pathList(value) {
27
+ if (!Array.isArray(value) || value.length > 64)
28
+ throw new Error("Invalid project path list.");
29
+ return [...new Set(value.map(files_1.projectPath))];
30
+ }
31
+ function loopback(value) {
32
+ const url = typeof value === "string" ? URL.parse(value) : null;
33
+ if (!url || !["http:", "https:"].includes(url.protocol) || !["127.0.0.1", "[::1]", "localhost"].includes(url.hostname) ||
34
+ url.username || url.password)
35
+ throw new Error("The service preview must use a local HTTP URL.");
36
+ return url;
37
+ }
38
+ function readManifest(files) {
39
+ const raw = files.get(files_1.entryFile)?.toString();
40
+ if (!raw)
41
+ throw new Error(`The project root must contain ${files_1.entryFile}.`);
42
+ const config = object(JSON.parse(raw));
43
+ if (config.version !== 1)
44
+ throw new Error("Unsupported project manifest version.");
45
+ const rawRuntime = object(config.runtime);
46
+ if (rawRuntime.type !== "node")
47
+ throw new Error('Set runtime.type to "node".');
48
+ const url = loopback(rawRuntime.url ?? "http://127.0.0.1:0/");
49
+ const ready = rawRuntime.ready === undefined ? new URL("/health", url) : loopback(rawRuntime.ready);
50
+ if (ready.origin !== url.origin)
51
+ throw new Error("The readiness URL must use the preview origin.");
52
+ const script = rawRuntime.script ?? "start";
53
+ if (typeof script !== "string" || !/^[a-zA-Z0-9:_-]+$/.test(script))
54
+ throw new Error("Invalid app startup script.");
55
+ const runtime = { type: "node", script, url: url.href, ready: ready.href };
56
+ if (rawRuntime.migration !== undefined) {
57
+ const { id, script, compatibility } = object(rawRuntime.migration);
58
+ if (typeof id !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/.test(id) ||
59
+ typeof script !== "string" || !/^[a-zA-Z0-9:_-]+$/.test(script) || compatibility !== "backward-compatible") {
60
+ throw new Error("A live database migration must name an npm script and declare backward-compatible schema changes.");
61
+ }
62
+ runtime.migration = { id, script, compatibility };
63
+ }
64
+ const manifest = { version: 1, runtime };
65
+ if (config.agentActions !== undefined) {
66
+ const actions = object(config.agentActions);
67
+ manifest.agentActions = { definitions: (0, files_1.projectPath)(actions.definitions),
68
+ ...(actions.skills === undefined ? {} : { skills: (0, files_1.projectPath)(actions.skills) }) };
69
+ }
70
+ if (config.instructions !== undefined)
71
+ manifest.instructions = pathList(config.instructions);
72
+ if (config.shadows !== undefined) {
73
+ if (!Array.isArray(config.shadows) || config.shadows.length > 32)
74
+ throw new Error("Invalid Shadow list.");
75
+ const ids = new Set();
76
+ manifest.shadows = config.shadows.map(value => {
77
+ const { id, version, digest, skill, rule } = object(value);
78
+ if (typeof id !== "string" || !manifest_1.actionName.test(id) || ids.has(id) ||
79
+ typeof version !== "string" || !version || typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) {
80
+ throw new Error("Invalid Shadow ID or version.");
81
+ }
82
+ ids.add(id);
83
+ return { id, version, digest, skill: (0, files_1.projectPath)(skill), rule: (0, files_1.projectPath)(rule) };
84
+ });
85
+ }
86
+ return manifest;
87
+ }
88
+ function instructionPaths(manifest) {
89
+ return [...new Set([...(manifest.instructions ?? []), ...manifest.shadows?.flatMap(({ skill, rule }) => [skill, rule]) ?? []])];
90
+ }
91
+ async function compileProject(files) {
92
+ const manifest = readManifest(files);
93
+ const text = (name) => (name && files.get(name)?.toString()) || "";
94
+ for (const name of instructionPaths(manifest)) {
95
+ if (!text(name).trim() || files.get(name).length > 32 * 1024)
96
+ throw new Error(`Invalid rule or skill: ${name}`);
97
+ }
98
+ const agentFiles = Object.create(null);
99
+ const definitions = manifest.agentActions?.definitions;
100
+ if (definitions && files.has(definitions)) {
101
+ agentFiles["agents.json"] = text(definitions);
102
+ const root = manifest.agentActions?.skills;
103
+ if (root) {
104
+ for (const [name, bytes] of files) {
105
+ if (name.startsWith(root + "/") && name.endsWith("/SKILL.md")) {
106
+ agentFiles["skills/" + name.slice(root.length + 1)] = bytes.toString();
107
+ }
108
+ }
109
+ }
110
+ }
111
+ return { manifest, files, agentFiles, actions: (0, manifest_1.compileActions)(agentFiles) };
112
+ }