@skaile/skailify-core 0.0.0 → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,596 @@
1
+ import * as z$1 from "zod";
2
+ import { z } from "zod";
3
+ import { PARENT_ORIGIN_QUERY_PARAM, consoleLogger, createSkaileApp, createWebSocketAppTransport, defineAppCapability, resolveAppConnectionParams, setAssistantPresentation } from "@skaile/workspaces/app-sdk";
4
+ // src/client.ts
5
+ /**
6
+ * The Skailify client: one per page. It owns the connection to Skaile (the
7
+ * host handshake, the app channel, a fresh token on every reconnect), keeps
8
+ * the capabilities in step with what the mounted components register, tells
9
+ * the agent which view is on screen, and keeps a short activity log the app
10
+ * can show. It imports no UI framework: an app without one calls it directly,
11
+ * and the React and Angular adapters are thin wrappers around it.
12
+ *
13
+ * It connects only inside a Skaile session: the platform embeds an app with the
14
+ * app channel switched on in an iframe whose URL carries `skaileParentOrigin`.
15
+ * Opened on its own, the app does not connect and registrations cost nothing.
16
+ */
17
+ /** Types an action's handler from its input schema, for an action declared outside a component. */
18
+ function agentAction(action) {
19
+ return action;
20
+ }
21
+ /** The longest a call may wait for the view to settle */
22
+ const MAX_WAIT_MS = 1e4;
23
+ /**
24
+ * The embedding host's origin, or null when the app is not embedded in Skaile. Read once at start: the app's own
25
+ * navigation may drop the query parameter, and every reconnect needs it.
26
+ */
27
+ function skaileParentOrigin(windowRef = globalThis) {
28
+ if (!windowRef?.location || !windowRef.parent || windowRef.parent === windowRef) return null;
29
+ const origin = new URLSearchParams(windowRef.location.search).get(PARENT_ORIGIN_QUERY_PARAM);
30
+ return origin && origin !== "*" && origin !== "null" ? origin : null;
31
+ }
32
+ /**
33
+ * Resolves after the browser had a chance to render: the next frame, or after {@link RENDER_FALLBACK_MS} when no frame
34
+ * comes. Browsers pause animation frames in background tabs and hidden iframes, so a frame alone could wait forever.
35
+ */
36
+ function afterRender() {
37
+ return new Promise((resolve) => {
38
+ const raf = globalThis.requestAnimationFrame;
39
+ setTimeout(() => {
40
+ if (!raf) return resolve();
41
+ const fallback = setTimeout(resolve, RENDER_FALLBACK_MS);
42
+ raf(() => {
43
+ clearTimeout(fallback);
44
+ resolve();
45
+ });
46
+ }, 0);
47
+ });
48
+ }
49
+ /** What stands in for state that JSON cannot carry (a BigInt, a cycle) */
50
+ const NOT_SERIALISABLE = { error: "state is not JSON-serialisable" };
51
+ /** The value itself when JSON can carry it, else {@link NOT_SERIALISABLE}: one bad value never fails a whole answer. */
52
+ function jsonSafe(value) {
53
+ try {
54
+ JSON.stringify(value);
55
+ return value;
56
+ } catch {
57
+ return NOT_SERIALISABLE;
58
+ }
59
+ }
60
+ /** How long to wait for an animation frame before treating the page as rendered */
61
+ const RENDER_FALLBACK_MS = 50;
62
+ /** Marks a capability whose handler waits for the view itself, so the wrapper does not wait a second time. */
63
+ const SETTLES_ITSELF = Symbol("skailify.settlesItself");
64
+ function describe(error) {
65
+ return error instanceof Error ? error.message : String(error);
66
+ }
67
+ function summarize(value, max = 120) {
68
+ if (value === void 0) return void 0;
69
+ let text;
70
+ try {
71
+ text = typeof value === "string" ? value : JSON.stringify(value);
72
+ } catch {
73
+ return;
74
+ }
75
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
76
+ }
77
+ function createSkailify(options) {
78
+ const baseLogger = options.logger ?? consoleLogger;
79
+ const logger = {
80
+ ...baseLogger,
81
+ error(message, fields) {
82
+ baseLogger.error(message, fields);
83
+ if (!closed && (message === "app reconnect gave up" || message === "app reconnect refused permanently")) {
84
+ setStatus({
85
+ state: "error",
86
+ message: message.replace(/^app /, "")
87
+ });
88
+ log({
89
+ direction: "out",
90
+ label: "connection lost",
91
+ detail: message,
92
+ error: true
93
+ });
94
+ }
95
+ }
96
+ };
97
+ const zone = options.zone ?? {
98
+ inside: (fn) => fn(),
99
+ outside: (fn) => fn()
100
+ };
101
+ const settleTimeout = Math.min(options.settleTimeoutMs ?? 3e3, MAX_WAIT_MS);
102
+ const activityLimit = options.activityLimit ?? 40;
103
+ const fullName = (name) => `app.${name}`;
104
+ const agentName = (name) => `app.${options.appId}.${name}`;
105
+ let app = null;
106
+ let started = null;
107
+ let closed = false;
108
+ let assistant = options.assistant;
109
+ let hostOrigin = null;
110
+ let status = { state: "idle" };
111
+ let activity = [];
112
+ let activitySeq = 0;
113
+ let capabilityInfo = [];
114
+ let snapshot = {
115
+ status,
116
+ activity,
117
+ capabilities: capabilityInfo
118
+ };
119
+ const listeners = /* @__PURE__ */ new Set();
120
+ const emit = () => {
121
+ snapshot = {
122
+ status,
123
+ activity,
124
+ capabilities: capabilityInfo
125
+ };
126
+ for (const listener of [...listeners]) listener();
127
+ };
128
+ const setStatus = (next) => {
129
+ status = next;
130
+ emit();
131
+ };
132
+ const log = (entry) => {
133
+ activity = [{
134
+ ...entry,
135
+ id: ++activitySeq,
136
+ at: Date.now()
137
+ }, ...activity].slice(0, activityLimit);
138
+ emit();
139
+ };
140
+ let viewSeq = 0;
141
+ /** Each view with its order: the view rendered last is the one on screen. */
142
+ const views = /* @__PURE__ */ new Map();
143
+ const states = /* @__PURE__ */ new Map();
144
+ const viewListeners = /* @__PURE__ */ new Set();
145
+ let reportQueued = false;
146
+ const viewChanged = () => {
147
+ for (const listener of [...viewListeners]) listener();
148
+ if (reportQueued) return;
149
+ reportQueued = true;
150
+ queueMicrotask(() => {
151
+ reportQueued = false;
152
+ reportIfChanged();
153
+ });
154
+ };
155
+ function currentView() {
156
+ let top;
157
+ for (const entry of views.values()) if (!top || entry.order > top.order) top = entry;
158
+ if (top) return top.view;
159
+ const id = options.navigation?.current?.();
160
+ if (!id) return null;
161
+ return {
162
+ id,
163
+ title: (options.navigation?.views().find((v) => v.id === id))?.title
164
+ };
165
+ }
166
+ function readState() {
167
+ const out = {};
168
+ for (const { name, read } of states.values()) try {
169
+ out[name] = jsonSafe(read());
170
+ } catch (error) {
171
+ out[name] = { error: describe(error) };
172
+ }
173
+ return out;
174
+ }
175
+ const loading = () => [...views.values()].some((v) => v.view.loading === true);
176
+ /** Effects running now: while one runs, the view is not settled even when no view is loading */
177
+ let inFlight = 0;
178
+ const busy = () => inFlight > 0 || loading();
179
+ /** What goes out in `view_report`; the app id stands in when no view is known, since the report needs one. */
180
+ function report() {
181
+ const view = currentView();
182
+ return view ? {
183
+ viewId: view.id,
184
+ title: view.title,
185
+ state: view.state
186
+ } : { viewId: options.appId };
187
+ }
188
+ let lastReport = "";
189
+ const unserialisableLogged = /* @__PURE__ */ new Set();
190
+ let sentLoading = false;
191
+ /**
192
+ * Reports the view when it changed (always with `force`), and says `loading` when the app becomes busy and `settled`
193
+ * when it stops (with `force`, whenever it is not busy).
194
+ */
195
+ function reportIfChanged(force = false) {
196
+ if (!app) return;
197
+ let next = report();
198
+ let key;
199
+ try {
200
+ key = JSON.stringify(next);
201
+ } catch (error) {
202
+ if (!unserialisableLogged.has(next.viewId)) {
203
+ unserialisableLogged.add(next.viewId);
204
+ logger.error(`skailify: the state of view ${next.viewId} is not JSON-serialisable`, { message: describe(error) });
205
+ }
206
+ next = {
207
+ viewId: next.viewId,
208
+ title: next.title,
209
+ state: NOT_SERIALISABLE
210
+ };
211
+ key = JSON.stringify(next);
212
+ }
213
+ if (force || key !== lastReport) {
214
+ lastReport = key;
215
+ try {
216
+ app.reportView(next);
217
+ } catch (error) {
218
+ logger.error("skailify: could not report the view", { message: describe(error) });
219
+ }
220
+ }
221
+ const now = busy();
222
+ if (now && !sentLoading) {
223
+ sentLoading = true;
224
+ app.loading("view loading");
225
+ } else if (!now && (sentLoading || force)) {
226
+ sentLoading = false;
227
+ app.settled();
228
+ }
229
+ }
230
+ function settle(timeoutMs = settleTimeout) {
231
+ const limit = Math.min(Math.max(timeoutMs, 0), MAX_WAIT_MS);
232
+ return zone.outside(() => new Promise((resolve) => {
233
+ let finished = false;
234
+ let rendered = false;
235
+ const finish = (settled) => {
236
+ if (finished) return;
237
+ finished = true;
238
+ clearTimeout(timer);
239
+ viewListeners.delete(check);
240
+ reportIfChanged(true);
241
+ resolve(settled);
242
+ };
243
+ const check = () => {
244
+ if (rendered && !loading()) finish(true);
245
+ };
246
+ const timer = setTimeout(() => finish(!loading()), limit);
247
+ viewListeners.add(check);
248
+ Promise.resolve().then(() => options.rendered?.()).catch(() => void 0).then(afterRender).then(() => {
249
+ rendered = true;
250
+ check();
251
+ });
252
+ }));
253
+ }
254
+ let actionSeq = 0;
255
+ /** Registered actions in order; a later one with the same name wins. */
256
+ const actions = /* @__PURE__ */ new Map();
257
+ const defined = /* @__PURE__ */ new WeakMap();
258
+ let registered = /* @__PURE__ */ new Map();
259
+ /** Wraps the handler: logs the call, and after an effect waits for the view to settle. */
260
+ function define(action) {
261
+ if (defined.has(action)) return defined.get(action) ?? null;
262
+ const name = fullName(action.name);
263
+ const isEffect = (action.kind ?? "effect") === "effect";
264
+ const settlesItself = action[SETTLES_ITSELF] === true;
265
+ let capability;
266
+ try {
267
+ if (agentName(action.name).length > 64) throw new Error(`${agentName(action.name)} is longer than 64 characters, the gateway would drop it`);
268
+ capability = defineAppCapability({
269
+ ...action,
270
+ name,
271
+ handler: async (args, ctx) => {
272
+ log({
273
+ direction: "in",
274
+ label: action.name,
275
+ detail: summarize(args)
276
+ });
277
+ if (isEffect) {
278
+ inFlight++;
279
+ sentLoading = true;
280
+ app?.loading(action.name);
281
+ }
282
+ try {
283
+ const result = await zone.inside(() => action.handler(args, ctx));
284
+ log({
285
+ direction: "out",
286
+ label: action.name,
287
+ detail: summarize(result)
288
+ });
289
+ return result;
290
+ } catch (error) {
291
+ log({
292
+ direction: "out",
293
+ label: action.name,
294
+ detail: describe(error),
295
+ error: true
296
+ });
297
+ throw error;
298
+ } finally {
299
+ if (isEffect) {
300
+ inFlight--;
301
+ if (settlesItself) reportIfChanged(true);
302
+ else await settle();
303
+ }
304
+ }
305
+ }
306
+ });
307
+ } catch (error) {
308
+ logger.error(`skailify: ${name} not registered: ${describe(error)}`, { name });
309
+ capability = null;
310
+ }
311
+ defined.set(action, capability);
312
+ return capability;
313
+ }
314
+ const generic = [];
315
+ function sync() {
316
+ const now = /* @__PURE__ */ new Map();
317
+ for (const action of [...generic, ...actions.values()]) {
318
+ const capability = define(action);
319
+ if (capability) now.set(capability.name, capability);
320
+ }
321
+ capabilityInfo = [...now.values()].map((c) => ({
322
+ name: c.name,
323
+ agentName: agentName(c.name.slice(4)),
324
+ displayName: c.displayName,
325
+ description: c.description,
326
+ kind: c.kind,
327
+ requiresApproval: c.requiresApproval,
328
+ effectClass: c.effectClass
329
+ }));
330
+ wanted = now;
331
+ emit();
332
+ if (wireQueued) return;
333
+ wireQueued = true;
334
+ queueMicrotask(flushWire);
335
+ }
336
+ let wanted = /* @__PURE__ */ new Map();
337
+ let wireQueued = false;
338
+ function flushWire() {
339
+ wireQueued = false;
340
+ if (!app) return;
341
+ const before = registered;
342
+ registered = wanted;
343
+ for (const name of before.keys()) if (!wanted.has(name)) app.deregisterCapability(name);
344
+ for (const [name, capability] of wanted) if (before.get(name) !== capability) app.registerCapability(capability);
345
+ }
346
+ async function connect(transport) {
347
+ app = createSkaileApp({
348
+ appId: options.appId,
349
+ transport,
350
+ logger,
351
+ reconnect: options.reconnect
352
+ });
353
+ handle.app = app;
354
+ registered = /* @__PURE__ */ new Map();
355
+ sync();
356
+ flushWire();
357
+ reportIfChanged(true);
358
+ app.onSessionChange((session) => {
359
+ if (session) {
360
+ setStatus({
361
+ state: "connected",
362
+ sessionId: session.sessionId,
363
+ userId: session.userId
364
+ });
365
+ log({
366
+ direction: "out",
367
+ label: "connected",
368
+ detail: `session ${session.sessionId}`
369
+ });
370
+ } else if (!closed) {
371
+ log({
372
+ direction: "out",
373
+ label: "disconnected"
374
+ });
375
+ setStatus(options.reconnect === false ? {
376
+ state: "error",
377
+ message: "connection lost"
378
+ } : { state: "reconnecting" });
379
+ }
380
+ });
381
+ if (closed) {
382
+ await app.close();
383
+ return;
384
+ }
385
+ await app.connect();
386
+ }
387
+ async function run() {
388
+ if (closed) return;
389
+ if (options.enabled === false) {
390
+ setStatus({ state: "standalone" });
391
+ return;
392
+ }
393
+ if (options.transport) {
394
+ setStatus({ state: "connecting" });
395
+ return connect(options.transport);
396
+ }
397
+ const parentOrigin = skaileParentOrigin(options.windowRef);
398
+ if (!parentOrigin) {
399
+ setStatus({ state: "standalone" });
400
+ return;
401
+ }
402
+ hostOrigin = parentOrigin;
403
+ const resolve = options.resolveParams ?? ((appId, origin, presentation) => resolveAppConnectionParams({
404
+ appId,
405
+ parentOrigin: origin,
406
+ ...presentation ? { assistant: presentation } : {}
407
+ }));
408
+ const resolveParams = async (appId, origin) => {
409
+ const sent = assistant;
410
+ const params = await resolve(appId, origin, sent);
411
+ if (assistant !== sent && assistant && !closed) postAssistant(assistant);
412
+ return params;
413
+ };
414
+ const createTransport = options.createTransport ?? ((url, sessionToken) => createWebSocketAppTransport({
415
+ url,
416
+ sessionToken
417
+ }));
418
+ setStatus({ state: "connecting" });
419
+ let primed = await resolveParams(options.appId, parentOrigin);
420
+ if (closed) return;
421
+ return connect(createTransport(primed.url, () => {
422
+ if (primed) {
423
+ const token = primed.token;
424
+ primed = null;
425
+ return token;
426
+ }
427
+ return resolveParams(options.appId, parentOrigin).then((params) => params.token);
428
+ }));
429
+ }
430
+ function postAssistant(presentation) {
431
+ if (!hostOrigin) return;
432
+ try {
433
+ (options.postAssistant ?? ((appId, parentOrigin, p) => setAssistantPresentation({
434
+ appId,
435
+ parentOrigin,
436
+ presentation: p
437
+ })))(options.appId, hostOrigin, presentation);
438
+ } catch (error) {
439
+ logger.warn("skailify: could not send the assistant hints", { message: describe(error) });
440
+ }
441
+ }
442
+ const handle = {
443
+ appId: options.appId,
444
+ app: null,
445
+ start() {
446
+ if (!started) started = zone.outside(run).catch((error) => {
447
+ if (closed) return;
448
+ const message = describe(error);
449
+ logger.error("skailify: could not connect to Skaile", { message });
450
+ setStatus({
451
+ state: "error",
452
+ message
453
+ });
454
+ log({
455
+ direction: "out",
456
+ label: "connect failed",
457
+ detail: message,
458
+ error: true
459
+ });
460
+ });
461
+ return started;
462
+ },
463
+ setAssistant(presentation) {
464
+ assistant = presentation;
465
+ if (started && !closed) postAssistant(presentation);
466
+ },
467
+ async close() {
468
+ closed = true;
469
+ await app?.close();
470
+ setStatus({ state: "closed" });
471
+ },
472
+ registerAction(added) {
473
+ const action = added;
474
+ if (action.name.startsWith("app.")) throw new Error(`skailify: action names are relative, write "${action.name.slice(4)}" instead of "${action.name}"`);
475
+ const key = ++actionSeq;
476
+ actions.set(key, action);
477
+ sync();
478
+ return () => {
479
+ if (actions.delete(key)) sync();
480
+ };
481
+ },
482
+ viewOrder: () => ++viewSeq,
483
+ registerView(view, order) {
484
+ const key = ++viewSeq;
485
+ const entry = {
486
+ view,
487
+ order: order ?? key
488
+ };
489
+ views.set(key, entry);
490
+ viewChanged();
491
+ return {
492
+ update(next) {
493
+ if (!views.has(key)) return;
494
+ views.set(key, {
495
+ view: next,
496
+ order: entry.order
497
+ });
498
+ viewChanged();
499
+ },
500
+ remove() {
501
+ if (views.delete(key)) viewChanged();
502
+ }
503
+ };
504
+ },
505
+ registerState(name, read) {
506
+ const key = ++viewSeq;
507
+ states.set(key, {
508
+ name,
509
+ read
510
+ });
511
+ return () => {
512
+ states.delete(key);
513
+ };
514
+ },
515
+ currentView,
516
+ readState,
517
+ agentName,
518
+ loading,
519
+ settle,
520
+ fullName,
521
+ subscribe(listener) {
522
+ listeners.add(listener);
523
+ return () => listeners.delete(listener);
524
+ },
525
+ getSnapshot: () => snapshot,
526
+ log
527
+ };
528
+ generic.push(...genericCapabilities(handle, options.navigation));
529
+ sync();
530
+ return handle;
531
+ }
532
+ // src/capabilities.ts
533
+ /**
534
+ * The generic capabilities every app gets: read what the user sees, and,
535
+ * when the app hands in its navigation, list the views and show one. They are
536
+ * router-agnostic: the app says what its views are and how to show one.
537
+ */
538
+ function viewState(client, settled) {
539
+ const view = client.currentView();
540
+ return {
541
+ view: view ? {
542
+ id: view.id,
543
+ title: view.title,
544
+ state: jsonSafe(view.state)
545
+ } : null,
546
+ state: client.readState(),
547
+ actions: client.getSnapshot().capabilities.map((c) => c.agentName),
548
+ settled: settled && !client.loading()
549
+ };
550
+ }
551
+ const settledNote = "When settled is false a view was still loading when the wait timed out: the state may be incomplete, so read it again with get_view_state.";
552
+ function genericCapabilities(client, navigation) {
553
+ const name = client.agentName;
554
+ const generic = [agentAction({
555
+ name: "get_view_state",
556
+ displayName: "Read what the user sees",
557
+ description: `Read the current state of the ${client.appId} app: the view on screen (id, title and a summary of what it shows), the state the app exposes to agents, and the actions available now. Call this first, and again after acting. It waits until no view is loading. ${settledNote}`,
558
+ kind: "query",
559
+ input: z$1.object({ timeoutMs: z$1.number().int().min(0).optional().describe("How long to wait at most for a loading view, in ms") }),
560
+ handler: async ({ timeoutMs }) => viewState(client, await client.settle(timeoutMs))
561
+ })];
562
+ if (!navigation) return generic;
563
+ generic.push(agentAction({
564
+ name: "list_views",
565
+ displayName: "List the views",
566
+ description: `List the views (pages) of the ${client.appId} app: id, title, whether it is in the menu, and the parameters it takes. Use the id with ${name("navigate")}.`,
567
+ kind: "query",
568
+ input: z$1.object({}),
569
+ handler: async () => ({
570
+ current: client.currentView()?.id ?? null,
571
+ views: navigation.views()
572
+ })
573
+ }), {
574
+ ...agentAction({
575
+ name: "navigate",
576
+ displayName: "Show a view",
577
+ description: `Show a view of the app, with the parameters it takes (see ${name("list_views")}). Waits until the view has loaded, then returns the view state. ${settledNote}`,
578
+ kind: "effect",
579
+ input: z$1.object({
580
+ view: z$1.string().describe("View id from list_views"),
581
+ params: z$1.record(z$1.string(), z$1.string()).optional().describe("Parameters of the view, by name")
582
+ }),
583
+ handler: async ({ view, params }) => {
584
+ const views = navigation.views();
585
+ if (!views.some((v) => v.id === view)) throw new Error(`no view ${view}; views: ${views.map((v) => v.id).join(", ") || "none"}`);
586
+ await navigation.navigate(view, params ?? {});
587
+ return viewState(client, await client.settle());
588
+ }
589
+ }),
590
+ [SETTLES_ITSELF]: true
591
+ });
592
+ return generic;
593
+ }
594
+ export { MAX_WAIT_MS, agentAction, createSkailify, skaileParentOrigin, viewState, z };
595
+
596
+ //# sourceMappingURL=index.js.map