dokiworlds-app-sdk 0.1.0 → 0.4.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.
- package/GUIDE.md +257 -0
- package/README.md +48 -26
- package/WORLD_PACKAGE_GUIDE.md +116 -0
- package/package.json +24 -20
- package/src/index.d.ts +86 -82
- package/src/index.js +310 -285
- package/src/llm_config.d.ts +13 -0
- package/src/llm_config.js +71 -0
package/src/index.js
CHANGED
|
@@ -1,285 +1,310 @@
|
|
|
1
|
-
export const APP_PROTOCOL = "dokiworld.app";
|
|
2
|
-
export const APP_PROTOCOL_VERSION = 2;
|
|
3
|
-
export const DEFAULT_APP_LAUNCH_TIMEOUT_MS = 60 * 60 * 1_000;
|
|
4
|
-
|
|
5
|
-
const MAX_ID_LENGTH = 200;
|
|
6
|
-
const MAX_PAYLOAD_BYTES = 64 * 1024;
|
|
7
|
-
const MAX_PAYLOAD_DEPTH = 12;
|
|
8
|
-
const MAX_PAYLOAD_NODES = 2_000;
|
|
9
|
-
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10
|
-
const isId = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH;
|
|
11
|
-
const defaultId = (kind) => `${kind}-${globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}`;
|
|
12
|
-
|
|
13
|
-
function isBoundedValue(value) {
|
|
14
|
-
let encoded;
|
|
15
|
-
try { encoded = JSON.stringify(value); } catch { return false; }
|
|
16
|
-
if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > MAX_PAYLOAD_BYTES) return false;
|
|
17
|
-
let nodes = 0;
|
|
18
|
-
const visit = (item, depth) => {
|
|
19
|
-
if (++nodes > MAX_PAYLOAD_NODES || depth > MAX_PAYLOAD_DEPTH) return false;
|
|
20
|
-
if (item === null || typeof item === "string" || typeof item === "boolean") return true;
|
|
21
|
-
if (typeof item === "number") return Number.isFinite(item);
|
|
22
|
-
if (Array.isArray(item)) return item.every((child) => visit(child, depth + 1));
|
|
23
|
-
return isRecord(item) && Object.entries(item).every(([key, child]) => key.length <= MAX_ID_LENGTH && visit(child, depth + 1));
|
|
24
|
-
};
|
|
25
|
-
return visit(value, 0);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const isContract = (value) => isRecord(value) && isId(value.contract)
|
|
29
|
-
&& Number.isInteger(value.version) && value.version > 0
|
|
30
|
-
&& Object.hasOwn(value, "data") && isBoundedValue(value.data);
|
|
31
|
-
const isLaunchResult = (value) => isRecord(value) && (
|
|
32
|
-
(value.status === "completed" && isContract(value.output))
|
|
33
|
-
|| (value.status === "cancelled" && value.output === undefined)
|
|
34
|
-
);
|
|
35
|
-
|
|
36
|
-
export class AppsCapabilityError extends Error {
|
|
37
|
-
constructor(code, message) {
|
|
38
|
-
super(message);
|
|
39
|
-
this.name = "AppsCapabilityError";
|
|
40
|
-
this.code = code;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export class AppsCapabilityTimeoutError extends AppsCapabilityError {
|
|
45
|
-
constructor() {
|
|
46
|
-
super("timeout", "DokiWorlds apps.launch timed out");
|
|
47
|
-
this.name = "AppsCapabilityTimeoutError";
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Attach the apps.launch capability to an established app session channel. */
|
|
52
|
-
export function createAppsClientExtension(client, { createId = defaultId, launchTimeoutMs = DEFAULT_APP_LAUNCH_TIMEOUT_MS } = {}) {
|
|
53
|
-
if (typeof client?.send !== "function" || typeof client?.onMessage !== "function") throw new Error("Invalid app session channel");
|
|
54
|
-
if (!Number.isFinite(launchTimeoutMs) || launchTimeoutMs <= 0) throw new Error("Invalid App launch timeout");
|
|
55
|
-
const pending = new Map();
|
|
56
|
-
let disposed = false;
|
|
57
|
-
const finish = (requestId, outcome) => {
|
|
58
|
-
const request = pending.get(requestId);
|
|
59
|
-
if (!request) return;
|
|
60
|
-
clearTimeout(request.timer);
|
|
61
|
-
pending.delete(requestId);
|
|
62
|
-
outcome instanceof Error ? request.reject(outcome) : request.resolve(outcome);
|
|
63
|
-
};
|
|
64
|
-
const unsubscribe = client.onMessage((message) => {
|
|
65
|
-
if (!isRecord(message) || message.type !== "dokiworld-app-apps-response" || !isRecord(message.payload)) return;
|
|
66
|
-
const { requestId, operation, status, result, error } = message.payload;
|
|
67
|
-
if (!isId(requestId) || !pending.has(requestId) || operation !== "launch") return;
|
|
68
|
-
if (status === "fulfilled") {
|
|
69
|
-
if (isBoundedValue(result) && isLaunchResult(result)) finish(requestId, result);
|
|
70
|
-
else finish(requestId, new AppsCapabilityError("invalid-host-result", "DokiWorlds returned an invalid apps.launch result"));
|
|
71
|
-
} else if (status === "rejected" && isRecord(error) && isId(error.code) && typeof error.message === "string") {
|
|
72
|
-
finish(requestId, new AppsCapabilityError(error.code, error.message));
|
|
73
|
-
}
|
|
74
|
-
});
|
|
75
|
-
return Object.freeze({
|
|
76
|
-
launch(input) {
|
|
77
|
-
if (disposed) return Promise.reject(new AppsCapabilityError("disposed", "The apps capability was disposed"));
|
|
78
|
-
if (!isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) {
|
|
79
|
-
return Promise.reject(new AppsCapabilityError("invalid-request", "Invalid apps.launch request"));
|
|
80
|
-
}
|
|
81
|
-
const requestId = createId("apps-request");
|
|
82
|
-
if (!isId(requestId) || pending.has(requestId)) {
|
|
83
|
-
return Promise.reject(new AppsCapabilityError("invalid-request-id", "Invalid or duplicate request id"));
|
|
84
|
-
}
|
|
85
|
-
return new Promise((resolve, reject) => {
|
|
86
|
-
const timer = setTimeout(() => finish(requestId, new AppsCapabilityTimeoutError()), launchTimeoutMs);
|
|
87
|
-
pending.set(requestId, { resolve, reject, timer });
|
|
88
|
-
try { client.send("dokiworld-app-apps-request", { requestId, operation: "launch", input }); }
|
|
89
|
-
catch (error) { finish(requestId, error instanceof Error ? error : new Error(String(error))); }
|
|
90
|
-
});
|
|
91
|
-
},
|
|
92
|
-
dispose() {
|
|
93
|
-
if (disposed) return;
|
|
94
|
-
disposed = true;
|
|
95
|
-
unsubscribe();
|
|
96
|
-
for (const requestId of pending.keys()) finish(requestId, new AppsCapabilityError("disposed", "The apps capability was disposed"));
|
|
97
|
-
},
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Host adapter: the host decides which App may launch and handles its lifecycle. */
|
|
102
|
-
export function createAppsHostExtension(host, { launch } = {}) {
|
|
103
|
-
if (typeof host?.send !== "function" || typeof host?.onMessage !== "function") throw new Error("Invalid app host channel");
|
|
104
|
-
let disposed = false;
|
|
105
|
-
const inFlight = new Map();
|
|
106
|
-
const unsubscribe = host.onMessage(async (message) => {
|
|
107
|
-
if (disposed || !isRecord(message) || message.type !== "dokiworld-app-apps-request" || !isRecord(message.payload)) return;
|
|
108
|
-
const { requestId, operation, input } = message.payload;
|
|
109
|
-
if (!isId(requestId) || operation !== "launch" || !isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) return;
|
|
110
|
-
let outcome = inFlight.get(requestId);
|
|
111
|
-
if (!outcome) {
|
|
112
|
-
outcome = Promise.resolve().then(async () => {
|
|
113
|
-
if (typeof launch !== "function") return { status: "rejected", error: { code: "unsupported-operation", message: "DokiWorlds does not provide apps.launch" } };
|
|
114
|
-
try {
|
|
115
|
-
const result = await launch(input);
|
|
116
|
-
return isBoundedValue(result) && isLaunchResult(result)
|
|
117
|
-
? { status: "fulfilled", result }
|
|
118
|
-
: { status: "rejected", error: { code: "invalid-host-result", message: "DokiWorlds returned an invalid apps.launch result" } };
|
|
119
|
-
} catch (error) {
|
|
120
|
-
return { status: "rejected", error: { code: isRecord(error) && isId(error.code) ? error.code : "operation-failed", message: "DokiWorlds could not complete apps.launch" } };
|
|
121
|
-
}
|
|
122
|
-
});
|
|
123
|
-
inFlight.set(requestId, outcome);
|
|
124
|
-
}
|
|
125
|
-
host.send("dokiworld-app-apps-response", { requestId, operation, ...await outcome });
|
|
126
|
-
});
|
|
127
|
-
return Object.freeze({ dispose() { if (!disposed) { disposed = true; unsubscribe(); inFlight.clear(); } } });
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Host side of the minimal v2 lifecycle used by locally embedded Apps. */
|
|
131
|
-
export function createAppHost({ appId, runId, target, input, scope = globalThis.window, expectedOrigin = "null", createId = defaultId } = {}) {
|
|
132
|
-
if (!isId(appId) || !isId(runId) || !target?.postMessage || !scope?.addEventListener || !scope?.removeEventListener || !isContract(input)) {
|
|
133
|
-
throw new Error("Invalid app host configuration");
|
|
134
|
-
}
|
|
135
|
-
if (expectedOrigin !== "null") {
|
|
136
|
-
let parsed;
|
|
137
|
-
try { parsed = new URL(expectedOrigin); } catch { throw new Error("Invalid app host origin"); }
|
|
138
|
-
if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.origin !== expectedOrigin) throw new Error("Invalid app host origin");
|
|
139
|
-
}
|
|
140
|
-
let instanceId = null;
|
|
141
|
-
let disposed = false;
|
|
142
|
-
let connected = false;
|
|
143
|
-
const listeners = new Set();
|
|
144
|
-
const send = (type, payload) => {
|
|
145
|
-
if (!instanceId) throw new Error("The app has not sent ready");
|
|
146
|
-
const messageId = createId("message");
|
|
147
|
-
if (!isId(messageId)) throw new Error("Invalid app message id");
|
|
148
|
-
target.postMessage({ type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload }, expectedOrigin === "null" ? "*" : expectedOrigin);
|
|
149
|
-
};
|
|
150
|
-
const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
151
|
-
const handleMessage = async (event) => {
|
|
152
|
-
if (disposed || !connected || event.source !== target || event.origin !== expectedOrigin || !isRecord(event.data)) return;
|
|
153
|
-
const message = event.data;
|
|
154
|
-
if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || !isId(message.instanceId)) return;
|
|
155
|
-
if (message.type === "dokiworld-app-ready") {
|
|
156
|
-
if (instanceId !== message.instanceId) instanceId = message.instanceId;
|
|
157
|
-
send("dokiworld-app-init", { locale: "en", grantedScopes: [], context: {}, input });
|
|
158
|
-
return;
|
|
159
|
-
}
|
|
160
|
-
if (message.instanceId !== instanceId || message.runId !== runId || !isId(message.messageId) || !isRecord(message.payload)) return;
|
|
161
|
-
if (message.type === "dokiworld-app-complete") {
|
|
162
|
-
const { resultId, output } = message.payload;
|
|
163
|
-
if (!isId(resultId) || !isContract(output)) return;
|
|
164
|
-
let decision = { status: "accepted" };
|
|
165
|
-
try { decision = await handlers.onComplete?.(output) ?? decision; }
|
|
166
|
-
catch { decision = { status: "rejected" }; }
|
|
167
|
-
send("dokiworld-app-complete-ack", { resultId, status: decision.status === "accepted" ? "accepted" : "rejected" });
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
if (message.type === "dokiworld-app-request-exit") {
|
|
171
|
-
handlers.onRequestExit?.();
|
|
172
|
-
return;
|
|
173
|
-
}
|
|
174
|
-
for (const listener of listeners) listener(message);
|
|
175
|
-
};
|
|
176
|
-
let handlers = {};
|
|
177
|
-
scope.addEventListener("message", handleMessage);
|
|
178
|
-
const dispose = () => {
|
|
179
|
-
if (disposed) return;
|
|
180
|
-
disposed = true;
|
|
181
|
-
scope.removeEventListener("message", handleMessage);
|
|
182
|
-
listeners.clear();
|
|
183
|
-
};
|
|
184
|
-
return Object.freeze({
|
|
185
|
-
send, onMessage,
|
|
186
|
-
connect(nextHandlers = {}) {
|
|
187
|
-
if (disposed || connected) throw new Error("The app host is disposed or already connected");
|
|
188
|
-
connected = true;
|
|
189
|
-
handlers = nextHandlers;
|
|
190
|
-
return dispose;
|
|
191
|
-
},
|
|
192
|
-
dispose,
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
/** Minimal protocol-v2 client for an App embedded in a DokiWorlds host. */
|
|
197
|
-
export function createAppClient({ appId, scope = globalThis.window, targetOrigin = "*", instanceId = defaultId("instance"), createId = defaultId, readyRetryMs = 500 } = {}) {
|
|
198
|
-
if (!isId(appId) || !isId(instanceId) || !scope?.parent?.postMessage || !scope?.addEventListener || !scope?.removeEventListener) throw new Error("Invalid app client identity or window");
|
|
199
|
-
if (!Number.isFinite(readyRetryMs) || readyRetryMs <= 0) throw new Error("Invalid App ready retry interval");
|
|
200
|
-
let runId = null;
|
|
201
|
-
let
|
|
202
|
-
|
|
203
|
-
let
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
if (!
|
|
216
|
-
const
|
|
217
|
-
if (
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
if (
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
return
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
1
|
+
export const APP_PROTOCOL = "dokiworld.app";
|
|
2
|
+
export const APP_PROTOCOL_VERSION = 2;
|
|
3
|
+
export const DEFAULT_APP_LAUNCH_TIMEOUT_MS = 60 * 60 * 1_000;
|
|
4
|
+
|
|
5
|
+
const MAX_ID_LENGTH = 200;
|
|
6
|
+
const MAX_PAYLOAD_BYTES = 64 * 1024;
|
|
7
|
+
const MAX_PAYLOAD_DEPTH = 12;
|
|
8
|
+
const MAX_PAYLOAD_NODES = 2_000;
|
|
9
|
+
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10
|
+
const isId = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH;
|
|
11
|
+
const defaultId = (kind) => `${kind}-${globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}`;
|
|
12
|
+
|
|
13
|
+
function isBoundedValue(value) {
|
|
14
|
+
let encoded;
|
|
15
|
+
try { encoded = JSON.stringify(value); } catch { return false; }
|
|
16
|
+
if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > MAX_PAYLOAD_BYTES) return false;
|
|
17
|
+
let nodes = 0;
|
|
18
|
+
const visit = (item, depth) => {
|
|
19
|
+
if (++nodes > MAX_PAYLOAD_NODES || depth > MAX_PAYLOAD_DEPTH) return false;
|
|
20
|
+
if (item === null || typeof item === "string" || typeof item === "boolean") return true;
|
|
21
|
+
if (typeof item === "number") return Number.isFinite(item);
|
|
22
|
+
if (Array.isArray(item)) return item.every((child) => visit(child, depth + 1));
|
|
23
|
+
return isRecord(item) && Object.entries(item).every(([key, child]) => key.length <= MAX_ID_LENGTH && visit(child, depth + 1));
|
|
24
|
+
};
|
|
25
|
+
return visit(value, 0);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const isContract = (value) => isRecord(value) && isId(value.contract)
|
|
29
|
+
&& Number.isInteger(value.version) && value.version > 0
|
|
30
|
+
&& Object.hasOwn(value, "data") && isBoundedValue(value.data);
|
|
31
|
+
const isLaunchResult = (value) => isRecord(value) && (
|
|
32
|
+
(value.status === "completed" && isContract(value.output))
|
|
33
|
+
|| (value.status === "cancelled" && value.output === undefined)
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
export class AppsCapabilityError extends Error {
|
|
37
|
+
constructor(code, message) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = "AppsCapabilityError";
|
|
40
|
+
this.code = code;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class AppsCapabilityTimeoutError extends AppsCapabilityError {
|
|
45
|
+
constructor() {
|
|
46
|
+
super("timeout", "DokiWorlds apps.launch timed out");
|
|
47
|
+
this.name = "AppsCapabilityTimeoutError";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Attach the apps.launch capability to an established app session channel. */
|
|
52
|
+
export function createAppsClientExtension(client, { createId = defaultId, launchTimeoutMs = DEFAULT_APP_LAUNCH_TIMEOUT_MS } = {}) {
|
|
53
|
+
if (typeof client?.send !== "function" || typeof client?.onMessage !== "function") throw new Error("Invalid app session channel");
|
|
54
|
+
if (!Number.isFinite(launchTimeoutMs) || launchTimeoutMs <= 0) throw new Error("Invalid App launch timeout");
|
|
55
|
+
const pending = new Map();
|
|
56
|
+
let disposed = false;
|
|
57
|
+
const finish = (requestId, outcome) => {
|
|
58
|
+
const request = pending.get(requestId);
|
|
59
|
+
if (!request) return;
|
|
60
|
+
clearTimeout(request.timer);
|
|
61
|
+
pending.delete(requestId);
|
|
62
|
+
outcome instanceof Error ? request.reject(outcome) : request.resolve(outcome);
|
|
63
|
+
};
|
|
64
|
+
const unsubscribe = client.onMessage((message) => {
|
|
65
|
+
if (!isRecord(message) || message.type !== "dokiworld-app-apps-response" || !isRecord(message.payload)) return;
|
|
66
|
+
const { requestId, operation, status, result, error } = message.payload;
|
|
67
|
+
if (!isId(requestId) || !pending.has(requestId) || operation !== "launch") return;
|
|
68
|
+
if (status === "fulfilled") {
|
|
69
|
+
if (isBoundedValue(result) && isLaunchResult(result)) finish(requestId, result);
|
|
70
|
+
else finish(requestId, new AppsCapabilityError("invalid-host-result", "DokiWorlds returned an invalid apps.launch result"));
|
|
71
|
+
} else if (status === "rejected" && isRecord(error) && isId(error.code) && typeof error.message === "string") {
|
|
72
|
+
finish(requestId, new AppsCapabilityError(error.code, error.message));
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return Object.freeze({
|
|
76
|
+
launch(input) {
|
|
77
|
+
if (disposed) return Promise.reject(new AppsCapabilityError("disposed", "The apps capability was disposed"));
|
|
78
|
+
if (!isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) {
|
|
79
|
+
return Promise.reject(new AppsCapabilityError("invalid-request", "Invalid apps.launch request"));
|
|
80
|
+
}
|
|
81
|
+
const requestId = createId("apps-request");
|
|
82
|
+
if (!isId(requestId) || pending.has(requestId)) {
|
|
83
|
+
return Promise.reject(new AppsCapabilityError("invalid-request-id", "Invalid or duplicate request id"));
|
|
84
|
+
}
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const timer = setTimeout(() => finish(requestId, new AppsCapabilityTimeoutError()), launchTimeoutMs);
|
|
87
|
+
pending.set(requestId, { resolve, reject, timer });
|
|
88
|
+
try { client.send("dokiworld-app-apps-request", { requestId, operation: "launch", input }); }
|
|
89
|
+
catch (error) { finish(requestId, error instanceof Error ? error : new Error(String(error))); }
|
|
90
|
+
});
|
|
91
|
+
},
|
|
92
|
+
dispose() {
|
|
93
|
+
if (disposed) return;
|
|
94
|
+
disposed = true;
|
|
95
|
+
unsubscribe();
|
|
96
|
+
for (const requestId of pending.keys()) finish(requestId, new AppsCapabilityError("disposed", "The apps capability was disposed"));
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Host adapter: the host decides which App may launch and handles its lifecycle. */
|
|
102
|
+
export function createAppsHostExtension(host, { launch } = {}) {
|
|
103
|
+
if (typeof host?.send !== "function" || typeof host?.onMessage !== "function") throw new Error("Invalid app host channel");
|
|
104
|
+
let disposed = false;
|
|
105
|
+
const inFlight = new Map();
|
|
106
|
+
const unsubscribe = host.onMessage(async (message) => {
|
|
107
|
+
if (disposed || !isRecord(message) || message.type !== "dokiworld-app-apps-request" || !isRecord(message.payload)) return;
|
|
108
|
+
const { requestId, operation, input } = message.payload;
|
|
109
|
+
if (!isId(requestId) || operation !== "launch" || !isRecord(input) || !isId(input.appId) || !isContract(input.input) || !isBoundedValue(input)) return;
|
|
110
|
+
let outcome = inFlight.get(requestId);
|
|
111
|
+
if (!outcome) {
|
|
112
|
+
outcome = Promise.resolve().then(async () => {
|
|
113
|
+
if (typeof launch !== "function") return { status: "rejected", error: { code: "unsupported-operation", message: "DokiWorlds does not provide apps.launch" } };
|
|
114
|
+
try {
|
|
115
|
+
const result = await launch(input);
|
|
116
|
+
return isBoundedValue(result) && isLaunchResult(result)
|
|
117
|
+
? { status: "fulfilled", result }
|
|
118
|
+
: { status: "rejected", error: { code: "invalid-host-result", message: "DokiWorlds returned an invalid apps.launch result" } };
|
|
119
|
+
} catch (error) {
|
|
120
|
+
return { status: "rejected", error: { code: isRecord(error) && isId(error.code) ? error.code : "operation-failed", message: "DokiWorlds could not complete apps.launch" } };
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
inFlight.set(requestId, outcome);
|
|
124
|
+
}
|
|
125
|
+
host.send("dokiworld-app-apps-response", { requestId, operation, ...await outcome });
|
|
126
|
+
});
|
|
127
|
+
return Object.freeze({ dispose() { if (!disposed) { disposed = true; unsubscribe(); inFlight.clear(); } } });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Host side of the minimal v2 lifecycle used by locally embedded Apps. */
|
|
131
|
+
export function createAppHost({ appId, runId, target, input, scope = globalThis.window, expectedOrigin = "null", createId = defaultId } = {}) {
|
|
132
|
+
if (!isId(appId) || !isId(runId) || !target?.postMessage || !scope?.addEventListener || !scope?.removeEventListener || !isContract(input)) {
|
|
133
|
+
throw new Error("Invalid app host configuration");
|
|
134
|
+
}
|
|
135
|
+
if (expectedOrigin !== "null") {
|
|
136
|
+
let parsed;
|
|
137
|
+
try { parsed = new URL(expectedOrigin); } catch { throw new Error("Invalid app host origin"); }
|
|
138
|
+
if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.origin !== expectedOrigin) throw new Error("Invalid app host origin");
|
|
139
|
+
}
|
|
140
|
+
let instanceId = null;
|
|
141
|
+
let disposed = false;
|
|
142
|
+
let connected = false;
|
|
143
|
+
const listeners = new Set();
|
|
144
|
+
const send = (type, payload) => {
|
|
145
|
+
if (!instanceId) throw new Error("The app has not sent ready");
|
|
146
|
+
const messageId = createId("message");
|
|
147
|
+
if (!isId(messageId)) throw new Error("Invalid app message id");
|
|
148
|
+
target.postMessage({ type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload }, expectedOrigin === "null" ? "*" : expectedOrigin);
|
|
149
|
+
};
|
|
150
|
+
const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
151
|
+
const handleMessage = async (event) => {
|
|
152
|
+
if (disposed || !connected || event.source !== target || event.origin !== expectedOrigin || !isRecord(event.data)) return;
|
|
153
|
+
const message = event.data;
|
|
154
|
+
if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || !isId(message.instanceId)) return;
|
|
155
|
+
if (message.type === "dokiworld-app-ready") {
|
|
156
|
+
if (instanceId !== message.instanceId) instanceId = message.instanceId;
|
|
157
|
+
send("dokiworld-app-init", { locale: "en", grantedScopes: [], context: {}, input });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (message.instanceId !== instanceId || message.runId !== runId || !isId(message.messageId) || !isRecord(message.payload)) return;
|
|
161
|
+
if (message.type === "dokiworld-app-complete") {
|
|
162
|
+
const { resultId, output } = message.payload;
|
|
163
|
+
if (!isId(resultId) || !isContract(output)) return;
|
|
164
|
+
let decision = { status: "accepted" };
|
|
165
|
+
try { decision = await handlers.onComplete?.(output) ?? decision; }
|
|
166
|
+
catch { decision = { status: "rejected" }; }
|
|
167
|
+
send("dokiworld-app-complete-ack", { resultId, status: decision.status === "accepted" ? "accepted" : "rejected" });
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (message.type === "dokiworld-app-request-exit") {
|
|
171
|
+
handlers.onRequestExit?.();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
for (const listener of listeners) listener(message);
|
|
175
|
+
};
|
|
176
|
+
let handlers = {};
|
|
177
|
+
scope.addEventListener("message", handleMessage);
|
|
178
|
+
const dispose = () => {
|
|
179
|
+
if (disposed) return;
|
|
180
|
+
disposed = true;
|
|
181
|
+
scope.removeEventListener("message", handleMessage);
|
|
182
|
+
listeners.clear();
|
|
183
|
+
};
|
|
184
|
+
return Object.freeze({
|
|
185
|
+
send, onMessage,
|
|
186
|
+
connect(nextHandlers = {}) {
|
|
187
|
+
if (disposed || connected) throw new Error("The app host is disposed or already connected");
|
|
188
|
+
connected = true;
|
|
189
|
+
handlers = nextHandlers;
|
|
190
|
+
return dispose;
|
|
191
|
+
},
|
|
192
|
+
dispose,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Minimal protocol-v2 client for an App embedded in a DokiWorlds host. */
|
|
197
|
+
export function createAppClient({ appId, scope = globalThis.window, targetOrigin = "*", instanceId = defaultId("instance"), createId = defaultId, readyRetryMs = 500 } = {}) {
|
|
198
|
+
if (!isId(appId) || !isId(instanceId) || !scope?.parent?.postMessage || !scope?.addEventListener || !scope?.removeEventListener) throw new Error("Invalid app client identity or window");
|
|
199
|
+
if (!Number.isFinite(readyRetryMs) || readyRetryMs <= 0) throw new Error("Invalid App ready retry interval");
|
|
200
|
+
let runId = null;
|
|
201
|
+
let input = null;
|
|
202
|
+
const initializationWaiters = new Set();
|
|
203
|
+
let connected = false;
|
|
204
|
+
let disposed = false;
|
|
205
|
+
let readyTimer = null;
|
|
206
|
+
const listeners = new Set();
|
|
207
|
+
const acknowledgements = new Map();
|
|
208
|
+
const sendReady = () => {
|
|
209
|
+
const message = { type: "dokiworld-app-ready", protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId };
|
|
210
|
+
if (scope.ReactNativeWebView?.postMessage) scope.ReactNativeWebView.postMessage(JSON.stringify(message));
|
|
211
|
+
else scope.parent.postMessage(message, targetOrigin);
|
|
212
|
+
};
|
|
213
|
+
const send = (type, payload) => {
|
|
214
|
+
if (disposed) throw new Error("The app client was disposed");
|
|
215
|
+
if (!runId) throw new Error("The app has not received init");
|
|
216
|
+
const messageId = createId("message");
|
|
217
|
+
if (!isId(messageId)) throw new Error("Invalid app message id");
|
|
218
|
+
const message = { type, protocol: APP_PROTOCOL, protocolVersion: APP_PROTOCOL_VERSION, appId, instanceId, runId, messageId, payload };
|
|
219
|
+
if (scope.ReactNativeWebView?.postMessage) scope.ReactNativeWebView.postMessage(JSON.stringify(message));
|
|
220
|
+
else scope.parent.postMessage(message, targetOrigin);
|
|
221
|
+
return message;
|
|
222
|
+
};
|
|
223
|
+
const onMessage = (listener) => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
224
|
+
const apps = createAppsClientExtension({ send, onMessage }, { createId });
|
|
225
|
+
const handleMessage = (event) => {
|
|
226
|
+
if (disposed || !connected || event.source !== scope.parent || !isRecord(event.data)) return;
|
|
227
|
+
if (targetOrigin !== "*" && event.origin !== targetOrigin) return;
|
|
228
|
+
const message = event.data;
|
|
229
|
+
if (message.protocol !== APP_PROTOCOL || message.protocolVersion !== APP_PROTOCOL_VERSION || message.appId !== appId || message.instanceId !== instanceId) return;
|
|
230
|
+
if (message.type === "dokiworld-app-init" && isId(message.runId) && isId(message.messageId)) {
|
|
231
|
+
if (!isRecord(message.payload) || !isContract(message.payload.input)) return;
|
|
232
|
+
if (runId) {
|
|
233
|
+
if (runId === message.runId) send("dokiworld-app-initialized", {});
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
runId = message.runId;
|
|
237
|
+
input = structuredClone(message.payload.input);
|
|
238
|
+
if (readyTimer !== null) { clearInterval(readyTimer); readyTimer = null; }
|
|
239
|
+
send("dokiworld-app-initialized", {});
|
|
240
|
+
for (const pending of initializationWaiters) {
|
|
241
|
+
clearTimeout(pending.timer);
|
|
242
|
+
pending.resolve(structuredClone(input));
|
|
243
|
+
}
|
|
244
|
+
initializationWaiters.clear();
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (runId && message.runId === runId && isId(message.messageId) && isRecord(message.payload)) {
|
|
248
|
+
if (message.type === "dokiworld-app-complete-ack") {
|
|
249
|
+
const pending = isId(message.payload.resultId)
|
|
250
|
+
&& (message.payload.status === "accepted" || message.payload.status === "rejected")
|
|
251
|
+
? acknowledgements.get(message.payload.resultId)
|
|
252
|
+
: null;
|
|
253
|
+
if (pending) {
|
|
254
|
+
clearTimeout(pending.timer);
|
|
255
|
+
acknowledgements.delete(message.payload.resultId);
|
|
256
|
+
pending.resolve(message.payload.status);
|
|
257
|
+
}
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
for (const listener of listeners) listener(message);
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
scope.addEventListener("message", handleMessage);
|
|
264
|
+
const dispose = () => {
|
|
265
|
+
if (disposed) return;
|
|
266
|
+
disposed = true;
|
|
267
|
+
scope.removeEventListener("message", handleMessage);
|
|
268
|
+
if (readyTimer !== null) clearInterval(readyTimer);
|
|
269
|
+
apps.dispose();
|
|
270
|
+
for (const pending of initializationWaiters) { clearTimeout(pending.timer); pending.reject(new Error("The app client was disposed")); }
|
|
271
|
+
initializationWaiters.clear();
|
|
272
|
+
for (const pending of acknowledgements.values()) { clearTimeout(pending.timer); pending.reject(new Error("The app client was disposed")); }
|
|
273
|
+
acknowledgements.clear();
|
|
274
|
+
listeners.clear();
|
|
275
|
+
};
|
|
276
|
+
return Object.freeze({
|
|
277
|
+
appId, instanceId, get runId() { return runId; }, get input() { return input === null ? null : structuredClone(input); }, apps,
|
|
278
|
+
whenReady({ timeoutMs = 10_000 } = {}) {
|
|
279
|
+
if (disposed) return Promise.reject(new Error("The app client was disposed"));
|
|
280
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.reject(new Error("Invalid initialization timeout"));
|
|
281
|
+
if (input !== null) return Promise.resolve(structuredClone(input));
|
|
282
|
+
return new Promise((resolve, reject) => {
|
|
283
|
+
const pending = { resolve, reject, timer: null };
|
|
284
|
+
pending.timer = setTimeout(() => { initializationWaiters.delete(pending); reject(new Error("App initialization timed out")); }, timeoutMs);
|
|
285
|
+
initializationWaiters.add(pending);
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
requestExit() { send("dokiworld-app-request-exit", {}); },
|
|
289
|
+
complete(output) {
|
|
290
|
+
if (disposed) return Promise.reject(new Error("The app client was disposed"));
|
|
291
|
+
if (!isContract(output)) return Promise.reject(new Error("Invalid app output"));
|
|
292
|
+
const resultId = createId("result");
|
|
293
|
+
if (!isId(resultId) || acknowledgements.has(resultId)) return Promise.reject(new Error("Invalid or duplicate app result id"));
|
|
294
|
+
return new Promise((resolve, reject) => {
|
|
295
|
+
const timer = setTimeout(() => { acknowledgements.delete(resultId); reject(new Error("App completion acknowledgement timed out")); }, 3_000);
|
|
296
|
+
acknowledgements.set(resultId, { resolve, reject, timer });
|
|
297
|
+
try { send("dokiworld-app-complete", { resultId, output }); }
|
|
298
|
+
catch (error) { clearTimeout(timer); acknowledgements.delete(resultId); reject(error); }
|
|
299
|
+
});
|
|
300
|
+
},
|
|
301
|
+
connect() {
|
|
302
|
+
if (disposed || connected) throw new Error("The app client is disposed or already connected");
|
|
303
|
+
connected = true;
|
|
304
|
+
sendReady();
|
|
305
|
+
readyTimer = setInterval(() => { if (!runId) sendReady(); }, readyRetryMs);
|
|
306
|
+
return dispose;
|
|
307
|
+
},
|
|
308
|
+
dispose,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare class LlmRuntimeError extends Error { readonly code: string }
|
|
2
|
+
export interface LlmMessage { role: 'system' | 'user' | 'assistant'; content: string }
|
|
3
|
+
export interface LlmInvokeRequest { model?: string; messages: LlmMessage[]; temperature?: number; maxTokens?: number; requestId?: string; signal?: AbortSignal }
|
|
4
|
+
export interface LlmInvokeResult { content: string; model: string; usage: unknown }
|
|
5
|
+
/** A text model enabled by the platform for the current world session. */
|
|
6
|
+
export interface LlmModel { modelId: string; tierId?: string; recommended?: boolean; priceDiamonds?: number }
|
|
7
|
+
export interface LlmRuntime {
|
|
8
|
+
/** Fetches the current platform-approved text models; do not hard-code model IDs. */
|
|
9
|
+
listModels(options?: { signal?: AbortSignal }): Promise<readonly LlmModel[]>
|
|
10
|
+
invoke(request: LlmInvokeRequest): Promise<LlmInvokeResult>
|
|
11
|
+
}
|
|
12
|
+
/** Uses an HttpOnly world session; API keys and provider URLs never enter the client. */
|
|
13
|
+
export declare function createLlmRuntime(options: { worldId?: string; endpoint?: string; fetch?: typeof fetch } ): LlmRuntime
|