@almateam/app-sdk 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alma Labs, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,145 @@
1
- # Temporary Holding Version
1
+ # Alma app SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Types and the host bridge for apps that run inside Alma. The full guide —
4
+ manifest, scopes, operations, limits and sharing — is at
5
+ https://docs.alma.team/developers/apps.
6
+
7
+ An app imports the SDK as `@alma/app-sdk`. Install the published package under
8
+ that name, for its types:
9
+
10
+ ```sh
11
+ npm install --save-dev @alma/app-sdk@npm:@almateam/app-sdk@^0.3.1
12
+ ```
13
+
14
+ Alma builds an app's source with its own current copy of the SDK, whatever
15
+ version the source installs or pins, so the copy you install never ships. The
16
+ SDK's runtime has no dependency and holds no credential (the `alma-app` command
17
+ uses the MCP client); an app runs in Alma's isolated frame and talks to its host
18
+ through it:
19
+
20
+ ```ts
21
+ import { createAppSdk, hostTransport } from "@alma/app-sdk";
22
+
23
+ const alma = createAppSdk(hostTransport());
24
+ const page = await alma.listTopics({
25
+ type: "account",
26
+ filter: ["stage:eq:Live"],
27
+ sort: "-renewal_date",
28
+ limit: 50,
29
+ });
30
+ const next = page.meta.next_cursor
31
+ ? await alma.listTopics({ type: "account", cursor: page.meta.next_cursor })
32
+ : null;
33
+ const topic = await alma.getTopicRecord(topicId);
34
+ const receipt = await alma.setTopicField(topicId, "stage", "Signed");
35
+ ```
36
+
37
+ Every call names an Alma `/v1` operation by its OpenAPI operationId
38
+ (`listTopics`, `createTopic`, `listTopicTypes`, `getTopicRecord`,
39
+ `getTopicFactDiscussion`, `downloadTopicFactAttachment`, `setTopicField`,
40
+ `runWorkflow`, `listWorkflowExecutions`, `getExecution`, …); the typed helpers
41
+ wrap `alma.call(operationId, { params, query, body })`. These are the same
42
+ public routes an API key calls, so an app built on them could run off-platform.
43
+ The host refuses an unknown operation, a path parameter that is not a UUID (or,
44
+ for a field, a field key), and any operation outside the manifest's `scopes`
45
+ (`topics:read`, `facts:confirm`, `workflows:read`, `workflows:run`), and
46
+ forwards only the query keys an operation declares.
47
+
48
+ A call resolves once it is done, within 30 seconds, or rejects. A change
49
+ (`setTopicField`, `createWorkflowLesson`, `updateLesson`) is the viewer's own
50
+ act: it saves as them where they may edit that record and is refused where they
51
+ cannot. Nobody is asked and no dialog appears: the promise resolves with the
52
+ result, or rejects with the refusal's words.
53
+
54
+ The app talks to its host on one channel that belongs to the document the Space
55
+ loaded; the SDK finds it there. A document the frame navigates to has no
56
+ channel, and the host closes the Space when the frame leaves or reloads its
57
+ document, so an app never navigates its own frame, and never rewrites its
58
+ document with `document.open` or `document.write`. The frame's policy refuses
59
+ fetches, images, forms and navigation to anywhere else: everything an app needs
60
+ is in its own files or comes through the SDK.
61
+
62
+ A change never goes past the viewer's current access: a value is set only on a
63
+ topic the viewer can edit, and is parsed against its field — a date that is not
64
+ one, or a choice outside the field's options, is refused. Setting a value the
65
+ field already holds confirms it as the viewer's.
66
+
67
+ ## Records: the workspace's typed topics
68
+
69
+ An app keeps no store of its own. Its records are the workspace's topics, of the
70
+ types its manifest declares (`types`): each type's `key` and `name`, its
71
+ `fields` (a key, a name, a value type of `text`, `date`, `number`, `money` or
72
+ `choice`, and a choice's `options`) and its `relationships` (a `label`, the key
73
+ of the type it points at, such as `person` or `contact`, and a `cardinality`).
74
+ When an owner's share installs the app, the workspace's type of that key is
75
+ reused, gaining what it lacks, or created. `listTopics({ type, filter, sort })`
76
+ reads them as the viewer, `setTopicField` changes one as the viewer, and
77
+ `createTopic(name, typeId)` (the id from `listTopicTypes()`) creates one: the
78
+ host shows Alma's own access sheet, starting from the app's audience, and the
79
+ viewer chooses who can see it. A relationship's values sit under
80
+ `rel_<label>__<type key>` (`rel_csm__person`). A version declaring a type, field
81
+ or relationship the shared version did not is wider and asks an owner; while the
82
+ app is installed, the workspace's schema editor lists it under "Used by" and
83
+ refuses to retype or remove what it declares.
84
+
85
+ ## Workflows: the app's backend
86
+
87
+ An app's backend is the ordinary workflows its manifest names (`workflows`, by
88
+ id, with the `workflows:run` scope): workflows of the workspace, edited by their
89
+ managers and run as they stand. `listWorkflows()` marks them `runnable` where
90
+ the viewer may start them; `runWorkflow(id, { topicId, input })` starts one as
91
+ the viewer (`POST /v1/workflows/{id}/executions`), with nobody asked: the viewer
92
+ must be in the app's audience and, on a record, able to edit it. The run acts as
93
+ them. Follow it with `waitForExecution(run.id, { onUpdate })`, which polls
94
+ `GET /v1/executions/{id}` with backoff: a run paused at an approval step reads
95
+ `waiting`, with the people it waits on in `approvers` (its Task is theirs, not
96
+ the viewer's), and a failed run's `error` is safe to show.
97
+ `listRuns(id, { topicId })` finds the runs started on a record when the app is
98
+ opened again.
99
+
100
+ ```ts
101
+ const run = await alma.runWorkflow(markLive.id, { topicId });
102
+ const done = await alma.waitForExecution(run.id, {
103
+ onUpdate: (execution) => {
104
+ if (execution.status === "waiting")
105
+ show(`Waiting for ${execution.approvers.map((p) => p.name).join(", ")}`);
106
+ },
107
+ });
108
+ ```
109
+
110
+ An attachment download returns only a receipt (`attachment_id`, `filename`,
111
+ `status`): the host fetches the file itself, and neither its URL nor the session
112
+ token reaches the app.
113
+
114
+ ## Developing an app
115
+
116
+ The package carries the `alma-app` command, which runs under Node.
117
+ `npx alma-app dev [folder] --app <app id>` (or `bunx`) pushes the folder's
118
+ source (`manifest.json` beside `index.html`, and the `.tsx`, `.ts`, `.jsx`,
119
+ `.js`, `.mjs`, `.css`, `.html`, `.svg` and `.json` files around it, leaving out
120
+ `node_modules`, `dist`, `build`, dotfiles and lockfiles) as a new draft version
121
+ now and on every save, signed in as you in the browser; Alma builds it and your
122
+ draft moves to it. Without `--app` the first push starts a new app; a member of
123
+ several workspaces names one with `--org <organization id>`.
124
+
125
+ While you have your own app open, what it logs (`console`) and every error it
126
+ does not catch show in its Manage sheet, under Logs, beside how the workflows it
127
+ starts last ran. Only your own sessions are heard: what an app logs can carry
128
+ its viewer's data, so nothing from anyone else's session reaches you.
129
+
130
+ ## Limits
131
+
132
+ The frame's policy is not a seal. Three resource hints (`dns-prefetch`,
133
+ `preconnect`, `prerender`) reach the network in Chromium whatever the policy
134
+ says, so the runtime refuses every hint rel (those three, `prefetch`, `preload`,
135
+ `modulepreload`): it removes them from `index.html`, drops them when a script
136
+ writes a link's rel (through `rel`, `relList` or `setAttribute`), and removes
137
+ any hint link that reaches the document another way. An app should not use
138
+ resource hints; its own files load without them.
139
+
140
+ What remains: a hint link an HTML parser makes (`innerHTML`,
141
+ `insertAdjacentHTML`, an adopted `DOMParser` document) is acted on as it is
142
+ inserted, before the runtime can remove it, and one inside a declarative shadow
143
+ root is not seen. So in Chromium an app's author can still receive what the app
144
+ reads as its viewer; members are trusted, and a version's files can be
145
+ downloaded for audit.
package/bridge.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** The one channel between an app and its host. */
2
+ export interface HostLine {
3
+ post(message: Record<string, unknown>): void;
4
+ /** Everything the host says, as it sent it. */
5
+ listen(heard: (message: unknown) => void): void;
6
+ }
7
+ /** The host opens a `MessageChannel` for each launch and hands one end to the
8
+ * runtime's loader in the launch handshake; the loader leaves it on the
9
+ * document's own global object as `__almaHostPort`, where this reads it.
10
+ * Everything an app asks, and everything it is told, travels on that port.
11
+ *
12
+ * The port is reachable by every script in the document on purpose: an app's
13
+ * scripts are the app, and hiding the port from some of them would protect
14
+ * nothing. What matters is where it lives. A global belongs to one document,
15
+ * so a document the frame navigates to starts with a new global and no port.
16
+ *
17
+ * A host on a release from before the port hands over none. The app then
18
+ * speaks the way that host listens: messages to the window that embeds it,
19
+ * on the origin the launch address names. Which of the two a host answers
20
+ * is the host's decision alone, so an app gains nothing by choosing. */
21
+ export declare function hostLine(): HostLine;
package/cli.js ADDED
@@ -0,0 +1,365 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/main.ts
4
+ import { resolve } from "path";
5
+ import { parseArgs } from "util";
6
+
7
+ // src/cli/dev.ts
8
+ import { watch } from "node:fs";
9
+
10
+ // src/cli/project.ts
11
+ import { readdir, readFile } from "node:fs/promises";
12
+ import { join, relative, sep } from "node:path";
13
+ var SOURCE_FILE = /\.(?:tsx|ts|jsx|js|mjs|css|html|svg|json)$/;
14
+ var LOCKFILES = new Set([
15
+ "package-lock.json",
16
+ "npm-shrinkwrap.json",
17
+ "bun.lock",
18
+ "bun.lockb",
19
+ "yarn.lock",
20
+ "pnpm-lock.yaml"
21
+ ]);
22
+ var SKIPPED_DIRECTORIES = new Set(["node_modules", "dist", "build"]);
23
+ function isProjectPath(path) {
24
+ const parts = path.split(/[\\/]/);
25
+ return SOURCE_FILE.test(path) && !LOCKFILES.has(parts.at(-1) ?? "") && parts.every((part) => !part.startsWith(".") && !SKIPPED_DIRECTORIES.has(part));
26
+ }
27
+ async function readProject(directory) {
28
+ const manifestText = await readFile(join(directory, "manifest.json"), "utf8").catch(() => {
29
+ throw new Error(`No manifest.json in ${directory}. An app's folder holds its manifest beside index.html.`);
30
+ });
31
+ const manifest = JSON.parse(manifestText);
32
+ if (typeof manifest !== "object" || manifest === null)
33
+ throw new Error("manifest.json is not an object");
34
+ const source = {};
35
+ for (const entry of await readdir(directory, {
36
+ recursive: true,
37
+ withFileTypes: true
38
+ })) {
39
+ if (!entry.isFile())
40
+ continue;
41
+ const path = relative(directory, join(entry.parentPath, entry.name)).split(sep).join("/");
42
+ if (path === "manifest.json" || !isProjectPath(path))
43
+ continue;
44
+ source[path] = await readFile(join(directory, path), "utf8");
45
+ }
46
+ return { manifest, source };
47
+ }
48
+
49
+ // src/cli/push.ts
50
+ class BuilderRefusal extends Error {
51
+ }
52
+
53
+ class Unauthorized extends Error {
54
+ }
55
+ async function callTool(connection, name, args, retried = false) {
56
+ const request = connection.fetch ?? fetch;
57
+ try {
58
+ const response = await request(connection.endpoint, {
59
+ method: "POST",
60
+ headers: {
61
+ authorization: `Bearer ${await connection.token()}`,
62
+ "content-type": "application/json",
63
+ accept: "application/json, text/event-stream",
64
+ ...connection.organizationId ? { "x-organization-id": connection.organizationId } : {}
65
+ },
66
+ body: JSON.stringify({
67
+ jsonrpc: "2.0",
68
+ id: crypto.randomUUID(),
69
+ method: "tools/call",
70
+ params: { name, arguments: args }
71
+ })
72
+ });
73
+ if (response.status === 401)
74
+ throw new Unauthorized;
75
+ const body = await response.json().catch(() => null);
76
+ if (!response.ok || typeof body !== "object" || body === null) {
77
+ const message = typeof body === "object" && body !== null && "message" in body ? String(body.message) : `Alma answered ${response.status}`;
78
+ throw new BuilderRefusal(message);
79
+ }
80
+ if ("error" in body)
81
+ throw new BuilderRefusal(JSON.stringify(body.error));
82
+ const result = body.result;
83
+ const text = (result?.content?.[0]?.text ?? "").replace(/^<untrusted_content[^>]*>\s*([\s\S]*?)\s*<\/untrusted_content>\s*$/, "$1");
84
+ if (result?.isError)
85
+ throw new BuilderRefusal(text);
86
+ try {
87
+ return JSON.parse(text);
88
+ } catch {
89
+ throw new BuilderRefusal(text);
90
+ }
91
+ } catch (error) {
92
+ if (!(error instanceof Unauthorized))
93
+ throw error;
94
+ if (retried)
95
+ throw new BuilderRefusal("Alma refused the sign-in. Sign in again.");
96
+ await connection.reauthorize();
97
+ return callTool(connection, name, args, true);
98
+ }
99
+ }
100
+ async function pushVersion(connection, project, appId, signal) {
101
+ const args = {
102
+ manifest: project.manifest,
103
+ source: project.source,
104
+ ...appId ? { app_id: appId } : {},
105
+ ...connection.organizationId ? { organization_id: connection.organizationId } : {}
106
+ };
107
+ for (;; ) {
108
+ signal?.throwIfAborted();
109
+ const answer = await callTool(connection, appId ? "alma_add_app_version" : "alma_create_app", args);
110
+ if (answer["status"] === "building")
111
+ continue;
112
+ return {
113
+ app_id: String(answer["app_id"]),
114
+ version_id: String(answer["version_id"]),
115
+ app_installation_id: String(answer["app_installation_id"]),
116
+ draft_url: String(answer["draft_url"]),
117
+ new_version: answer["new_version"] === true
118
+ };
119
+ }
120
+ }
121
+
122
+ // src/cli/dev.ts
123
+ async function runDev(options) {
124
+ const { directory, connection, onEvent, signal } = options;
125
+ let appId = options.appId;
126
+ let pending = true;
127
+ let pushing = null;
128
+ let timer = null;
129
+ const push = async () => {
130
+ while (pending && !signal.aborted) {
131
+ pending = false;
132
+ onEvent({ kind: "pushing" });
133
+ try {
134
+ const version = await pushVersion(connection, await readProject(directory), appId, signal);
135
+ appId = version.app_id;
136
+ onEvent({ kind: "pushed", version });
137
+ } catch (error) {
138
+ if (signal.aborted)
139
+ return;
140
+ onEvent({
141
+ kind: "failed",
142
+ message: error instanceof Error ? error.message : String(error)
143
+ });
144
+ }
145
+ }
146
+ };
147
+ const schedule = () => {
148
+ pending = true;
149
+ if (timer)
150
+ clearTimeout(timer);
151
+ timer = setTimeout(() => {
152
+ timer = null;
153
+ pushing ??= push().finally(() => {
154
+ pushing = null;
155
+ if (pending)
156
+ schedule();
157
+ });
158
+ }, options.settleMs ?? 300);
159
+ };
160
+ const watcher = watch(directory, { recursive: true }, (_event, path) => {
161
+ if (path && isProjectPath(String(path)))
162
+ schedule();
163
+ });
164
+ try {
165
+ pushing = push().finally(() => {
166
+ pushing = null;
167
+ });
168
+ await new Promise((resolve) => {
169
+ if (signal.aborted)
170
+ resolve();
171
+ signal.addEventListener("abort", () => resolve(), { once: true });
172
+ });
173
+ } finally {
174
+ watcher.close();
175
+ if (timer)
176
+ clearTimeout(timer);
177
+ await pushing?.catch(() => {});
178
+ }
179
+ }
180
+
181
+ // src/cli/signIn.ts
182
+ import { spawn } from "node:child_process";
183
+ import { chmod, mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
184
+ import { createServer } from "node:http";
185
+ import { homedir } from "node:os";
186
+ import { dirname, join as join2 } from "node:path";
187
+ import {
188
+ auth
189
+ } from "@modelcontextprotocol/sdk/client/auth.js";
190
+ var STORE = join2(homedir(), ".config", "alma", "app-cli.json");
191
+ var CALLBACK_PORT = 53682;
192
+ var CALLBACK_TIMEOUT_MS = 5 * 60000;
193
+ var SCOPE = "openid email profile offline_access";
194
+ async function load(server) {
195
+ const all = await readFile2(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
196
+ return all[server] ?? {};
197
+ }
198
+ async function save(server, stored) {
199
+ const all = await readFile2(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
200
+ all[server] = stored;
201
+ const folder = dirname(STORE);
202
+ await mkdir(folder, { recursive: true, mode: 448 });
203
+ await chmod(folder, 448);
204
+ const temporary = `${STORE}.${process.pid}.tmp`;
205
+ await writeFile(temporary, JSON.stringify(all, null, 2), { mode: 384 });
206
+ await chmod(temporary, 384);
207
+ await rename(temporary, STORE);
208
+ }
209
+ function openBrowser(url) {
210
+ const [command, ...args] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
211
+ const opener = spawn(command, args, { stdio: "ignore", detached: true });
212
+ opener.on("error", () => {});
213
+ opener.unref();
214
+ }
215
+ function listenForCode(state) {
216
+ return new Promise((listening, failToListen) => {
217
+ let settle;
218
+ const code = new Promise((resolve, reject) => {
219
+ settle = { resolve, reject };
220
+ });
221
+ code.catch(() => {});
222
+ const server = createServer((request, response) => {
223
+ const url = new URL(request.url ?? "/", `http://127.0.0.1:${CALLBACK_PORT}`);
224
+ if (url.pathname !== "/callback") {
225
+ response.writeHead(404).end();
226
+ return;
227
+ }
228
+ const received = url.searchParams.get("code");
229
+ const done = (text) => {
230
+ response.writeHead(200, { "content-type": "text/plain" }).end(text);
231
+ clearTimeout(timer);
232
+ server.close();
233
+ };
234
+ if (url.searchParams.get("state") !== state || !received) {
235
+ done("Sign-in was not completed. You can close this tab.");
236
+ settle.reject(new Error("Sign-in was not completed."));
237
+ return;
238
+ }
239
+ done("Signed in to Alma. You can close this tab.");
240
+ settle.resolve(received);
241
+ });
242
+ const timer = setTimeout(() => {
243
+ server.close();
244
+ settle.reject(new Error(`Sign-in timed out: the browser did not return to this machine within ${CALLBACK_TIMEOUT_MS / 60000} minutes. Run the command again to retry.`));
245
+ }, CALLBACK_TIMEOUT_MS);
246
+ timer.unref();
247
+ server.on("error", (error) => {
248
+ clearTimeout(timer);
249
+ failToListen(error.code === "EADDRINUSE" ? new Error(`Port ${CALLBACK_PORT} is busy, so the browser has nowhere to return the sign-in to. Close whatever is using it (often another \`alma-app\` sign-in still waiting) and run the command again.`) : error);
250
+ });
251
+ server.listen(CALLBACK_PORT, "127.0.0.1", () => listening({ code }));
252
+ });
253
+ }
254
+ function signedInAuthor(server) {
255
+ const redirect = `http://127.0.0.1:${CALLBACK_PORT}/callback`;
256
+ let attempt = { state: "" };
257
+ let verifier = "";
258
+ const provider = {
259
+ get redirectUrl() {
260
+ return redirect;
261
+ },
262
+ get clientMetadata() {
263
+ return {
264
+ client_name: "Alma app dev",
265
+ redirect_uris: [redirect],
266
+ grant_types: ["authorization_code", "refresh_token"],
267
+ response_types: ["code"],
268
+ token_endpoint_auth_method: "none",
269
+ scope: SCOPE
270
+ };
271
+ },
272
+ state: () => attempt.state,
273
+ clientInformation: async () => (await load(server)).client,
274
+ saveClientInformation: async (client) => save(server, { ...await load(server), client }),
275
+ tokens: async () => (await load(server)).tokens,
276
+ saveTokens: async (tokens) => save(server, { ...await load(server), tokens }),
277
+ redirectToAuthorization: async (url) => {
278
+ attempt.listener = await listenForCode(attempt.state);
279
+ console.info(`Sign in to Alma in your browser:
280
+ ${url.toString()}`);
281
+ openBrowser(url.toString());
282
+ },
283
+ saveCodeVerifier: (value) => {
284
+ verifier = value;
285
+ },
286
+ codeVerifier: () => verifier
287
+ };
288
+ const authorize = async () => {
289
+ attempt = { state: crypto.randomUUID() };
290
+ const started = await auth(provider, { serverUrl: server, scope: SCOPE });
291
+ if (started === "AUTHORIZED")
292
+ return;
293
+ if (!attempt.listener)
294
+ throw new Error("Sign-in did not open the browser.");
295
+ const code = await attempt.listener.code;
296
+ await auth(provider, {
297
+ serverUrl: server,
298
+ scope: SCOPE,
299
+ authorizationCode: code
300
+ });
301
+ };
302
+ return {
303
+ async token() {
304
+ let tokens = (await load(server)).tokens;
305
+ if (!tokens) {
306
+ await authorize();
307
+ tokens = (await load(server)).tokens;
308
+ }
309
+ if (!tokens)
310
+ throw new Error("Sign-in did not return a token.");
311
+ return tokens.access_token;
312
+ },
313
+ reauthorize: authorize
314
+ };
315
+ }
316
+
317
+ // src/cli/main.ts
318
+ var USAGE = `Usage: alma-app dev [folder] [--app <app id>] [--org <organization id>] [--server <MCP url>]
319
+
320
+ Pushes the app in [folder] (default: here) to Alma as a new draft version, now
321
+ and on every save, signed in to Alma in your browser.`;
322
+ var { values, positionals } = parseArgs({
323
+ args: process.argv.slice(2),
324
+ allowPositionals: true,
325
+ options: {
326
+ help: { type: "boolean", short: "h" },
327
+ app: { type: "string" },
328
+ org: { type: "string" },
329
+ server: { type: "string", default: "https://mcp.alma.team/mcp" }
330
+ }
331
+ });
332
+ if (values.help || positionals[0] === "help") {
333
+ console.info(USAGE);
334
+ process.exit(0);
335
+ }
336
+ if (positionals[0] !== "dev") {
337
+ console.error(USAGE);
338
+ process.exit(1);
339
+ }
340
+ var directory = resolve(positionals[1] ?? ".");
341
+ var endpoint = values.server ?? "https://mcp.alma.team/mcp";
342
+ var author = signedInAuthor(endpoint);
343
+ var controller = new AbortController;
344
+ process.on("SIGINT", () => controller.abort());
345
+ console.info(`Watching ${directory}. Ctrl-C stops.`);
346
+ await runDev({
347
+ directory,
348
+ appId: values.app ?? null,
349
+ connection: {
350
+ endpoint,
351
+ token: author.token,
352
+ reauthorize: author.reauthorize,
353
+ ...values.org ? { organizationId: values.org } : {}
354
+ },
355
+ signal: controller.signal,
356
+ onEvent: (event) => {
357
+ if (event.kind === "pushing")
358
+ console.info("Building a new draft\u2026");
359
+ else if (event.kind === "failed")
360
+ console.error(event.message);
361
+ else
362
+ console.info(event.version.new_version ? `Draft updated. Open it: ${event.version.draft_url}` + (values.app ? "" : `
363
+ (--app ${event.version.app_id})`) : "No change since the last version.");
364
+ }
365
+ });
@@ -0,0 +1,416 @@
1
+ export interface AnalyticsEconomics {
2
+ hands: number;
3
+ meetings: number;
4
+ reporting: number;
5
+ duplicates: number;
6
+ saas: number;
7
+ baseline: number;
8
+ run_cost: number;
9
+ net: number;
10
+ }
11
+ /** A run as the viewer who may read it reads it from an app. */
12
+ export interface AppExecution {
13
+ id: string;
14
+ workflow_id: string;
15
+ /** The record the run is on, when it was started on one. */
16
+ topic_id: string | null;
17
+ /** `waiting`: paused on people, whom `approvers` names. */
18
+ status: "pending" | "running" | "waiting" | "completed" | "failed" | "cancelled";
19
+ trigger_type: string;
20
+ response_content: string | null;
21
+ /** Why it failed, in words the app may show. */
22
+ error: string | null;
23
+ /** Empty when anyone in the workspace may decide. */
24
+ approvers: {
25
+ id: string;
26
+ name: string;
27
+ }[];
28
+ started_at: string | null;
29
+ completed_at: string | null;
30
+ created_at: string;
31
+ }
32
+ export interface AppFactDiscussion {
33
+ discussion: TopicDiscussion | null;
34
+ }
35
+ /** A workflow's lesson as an app writes it. */
36
+ export interface AppLesson {
37
+ id: string;
38
+ content: string;
39
+ workflow_id: string | null;
40
+ /** Pass it back as `expected_revision` on the next save. */
41
+ edit_revision: string;
42
+ }
43
+ export interface AppOutcome {
44
+ id: string;
45
+ name: string;
46
+ description: string | null;
47
+ signal: string | null;
48
+ parent_outcome_id: string | null;
49
+ status: string;
50
+ created_at: string;
51
+ updated_at: string;
52
+ /** The groups that own it, as the viewer reads them. */
53
+ owning_groups: string[];
54
+ /** Active workflows serving it that the viewer can open. */
55
+ live_workflow_count: number;
56
+ }
57
+ /** A run an app started, as it started: poll `getExecution` with its `id`. */
58
+ export interface AppRunReceipt {
59
+ id: string;
60
+ workflow_id: string;
61
+ status: string;
62
+ created_at: string;
63
+ }
64
+ export interface AppTopicRecord {
65
+ topic: TopicRef;
66
+ record: KnowledgeRecord;
67
+ facts: TopicFact[];
68
+ }
69
+ /**
70
+ * A row of the member Workflows list: a workflow the viewer reads the card
71
+ * of, or one the app's manifest names that the viewer may start.
72
+ */
73
+ export interface AppWorkflowSummary {
74
+ id: string;
75
+ name: string;
76
+ /** The newest run, on the organization's calendar, and how it went. */
77
+ last_run?: string;
78
+ /** Paused only when the newest run waits on one of the viewer's own Tasks. */
79
+ state: "proposed" | "draft" | "live" | "paused";
80
+ /**
81
+ * A workflow the app's manifest names, which the viewer may start with
82
+ * `runWorkflow`.
83
+ */
84
+ runnable?: true;
85
+ /** The facts the Workflows list sorts and filters by. */
86
+ index?: {
87
+ createdAt: string;
88
+ updatedAt: string;
89
+ createdByViewer: boolean;
90
+ creator?: {
91
+ membershipId: string;
92
+ name: string;
93
+ };
94
+ triggerTypes: string[];
95
+ sources: {
96
+ slug: string;
97
+ label: string;
98
+ }[];
99
+ lastRun?: {
100
+ at: string;
101
+ outcome: WorkflowRunOutcome;
102
+ };
103
+ };
104
+ }
105
+ export interface CreatedTopicRecord {
106
+ id: string;
107
+ name: string;
108
+ topic_type_id: string | null;
109
+ }
110
+ /**
111
+ * A value: its text as written, its typed reading where its field's type
112
+ * parsed it, and the topic it refers to where the caller can reach it.
113
+ */
114
+ export interface FactValue {
115
+ text: string;
116
+ typed: TypedValue | null;
117
+ ref: ValueRef | null;
118
+ }
119
+ /**
120
+ * The topic as Knowledge renders it. Cadence, review configuration and
121
+ * cost stay private.
122
+ */
123
+ export interface KnowledgeRecord {
124
+ template: {
125
+ name: string;
126
+ icon: string;
127
+ } | null;
128
+ sections: RecordSection[];
129
+ updates: RecordUpdate[];
130
+ /** A refresh of the topic is in flight. */
131
+ updating: boolean;
132
+ audience?: RecordAudience;
133
+ /** Whether the viewer may edit this topic's values. */
134
+ viewer_can_edit: boolean;
135
+ }
136
+ export interface OrganizationAnalytics {
137
+ coverage: {
138
+ sources: {
139
+ slug: string;
140
+ name: string;
141
+ connected: boolean;
142
+ }[];
143
+ members_invited: number;
144
+ members_connected: number;
145
+ requested_sources: {
146
+ name: string;
147
+ }[];
148
+ };
149
+ outcomes: {
150
+ committed: number;
151
+ automated: number;
152
+ blind_spots: number;
153
+ };
154
+ workflows: {
155
+ operating: number;
156
+ in_build: number;
157
+ waiting_on_people: number;
158
+ };
159
+ roi: {
160
+ operating_workflows: number;
161
+ pending_workflows: number;
162
+ realized: AnalyticsEconomics;
163
+ potential_net: number;
164
+ hidden_priced_count: number;
165
+ } | null;
166
+ }
167
+ export interface PageMeta {
168
+ hasMore: boolean;
169
+ }
170
+ /** Who a record reaches, as its sharing mark says it — never the roster. */
171
+ export interface RecordAudience {
172
+ scope: "everyone" | "tier" | "restricted";
173
+ phrase: string;
174
+ }
175
+ export interface RecordFact {
176
+ id: string;
177
+ value: FactValue;
178
+ /** Who confirmed the value and when; absent while unverified. */
179
+ verified_by?: {
180
+ name: string | null;
181
+ at: string;
182
+ };
183
+ /** The viewer can read a discussion about this value. */
184
+ has_discussion?: true;
185
+ }
186
+ export interface RecordSection {
187
+ id: string;
188
+ key: string;
189
+ name: string;
190
+ value_type: "text" | "date" | "number" | "money" | "choice";
191
+ currency?: string;
192
+ options?: string[];
193
+ facts: RecordFact[];
194
+ }
195
+ export interface RecordUpdate {
196
+ id: string;
197
+ kind: "raw" | "summary";
198
+ when: string;
199
+ text: string;
200
+ source?: string;
201
+ importance?: "normal" | "high";
202
+ count?: number;
203
+ edited?: boolean;
204
+ }
205
+ export interface TopicDiscussion {
206
+ topic_id: string;
207
+ fact_id: string;
208
+ messages: TopicDiscussionMessage[];
209
+ items?: (TopicDiscussionMessage | TopicDiscussionMarker)[];
210
+ }
211
+ export interface TopicDiscussionMarker {
212
+ id: string;
213
+ marker: string;
214
+ }
215
+ export interface TopicDiscussionMessage {
216
+ id: string;
217
+ role: "user" | "assistant";
218
+ text: string;
219
+ at: string;
220
+ author: {
221
+ kind: "alma" | "self" | "member" | "external";
222
+ name: string;
223
+ };
224
+ reasoning?: string;
225
+ reasoning_seconds?: number;
226
+ queued?: true;
227
+ acting_for?: string;
228
+ attachments?: {
229
+ id: string;
230
+ filename: string;
231
+ mime_type?: string;
232
+ note?: string;
233
+ }[];
234
+ tools?: {
235
+ id: string;
236
+ tool_name: string;
237
+ label: string;
238
+ kind: "activity" | "decision";
239
+ state: "running" | "done" | "failed";
240
+ receipt?: "Awaiting decision" | "Approved" | "Refused";
241
+ open_tasks?: true;
242
+ }[];
243
+ }
244
+ export interface TopicFact {
245
+ id: string;
246
+ field_key: string;
247
+ value: FactValue;
248
+ verified_at: string | null;
249
+ }
250
+ export interface TopicFieldReceipt {
251
+ status: "saved" | "confirmed" | "unchanged";
252
+ topic_id: string;
253
+ field_key: string;
254
+ fact_id: string;
255
+ value: {
256
+ text: string;
257
+ typed: TypedValue | null;
258
+ };
259
+ }
260
+ export interface TopicRecord {
261
+ id: string;
262
+ name: string;
263
+ slug: string;
264
+ icon: string | null;
265
+ status: string;
266
+ parent_id: string | null;
267
+ folder_id: string | null;
268
+ type: {
269
+ key: string;
270
+ name: string;
271
+ icon: string | null;
272
+ } | null;
273
+ values: Record<string, FactValue[]>;
274
+ unverified_value_count: number;
275
+ can_edit: boolean;
276
+ created_at: string;
277
+ updated_at: string;
278
+ }
279
+ export interface TopicRef {
280
+ id: string;
281
+ name: string;
282
+ }
283
+ export interface TopicType {
284
+ id: string;
285
+ key: string;
286
+ name: string;
287
+ icon: string | null;
288
+ description: string;
289
+ fields: {
290
+ key: string;
291
+ name: string;
292
+ value_type: "text" | "date" | "number" | "money" | "choice";
293
+ currency?: string;
294
+ options?: string[];
295
+ holds: "one" | "many";
296
+ }[];
297
+ relationships: {
298
+ key: string;
299
+ name: string;
300
+ target_type: string | null;
301
+ cardinality: string;
302
+ holds: "one" | "many";
303
+ }[];
304
+ }
305
+ export type TypedValue = {
306
+ type: "date";
307
+ value: string;
308
+ } | {
309
+ type: "number";
310
+ value: number;
311
+ } | {
312
+ type: "money";
313
+ value: number;
314
+ currency?: string;
315
+ } | {
316
+ type: "choice";
317
+ value: string;
318
+ };
319
+ export interface ValueDetail {
320
+ label: string;
321
+ value: string;
322
+ typed?: TypedValue;
323
+ }
324
+ /**
325
+ * The topic a relationship value refers to — present only where the caller
326
+ * can reach it, with that topic's own current field values.
327
+ */
328
+ export interface ValueRef {
329
+ topic_id: string;
330
+ name: string;
331
+ type_key: string | null;
332
+ detail: ValueDetail[];
333
+ }
334
+ /** A workflow as a member reads it — never its configuration. */
335
+ export interface WorkflowCard {
336
+ id: string;
337
+ name: string;
338
+ does?: string;
339
+ trigger?: string;
340
+ sources: string[];
341
+ steps: {
342
+ title: string;
343
+ }[];
344
+ /** Newest first. */
345
+ runs: WorkflowRun[];
346
+ lessons: WorkflowLesson[];
347
+ can_edit_lessons: boolean;
348
+ /** Only topics the viewer can open. */
349
+ topics: WorkflowTopic[];
350
+ audience?: RecordAudience;
351
+ }
352
+ export interface WorkflowLesson {
353
+ id: string;
354
+ text: string;
355
+ added: string;
356
+ /** Present only when the viewer may edit it; pass it back on a save. */
357
+ edit_revision?: string;
358
+ }
359
+ export interface WorkflowRun {
360
+ id: string;
361
+ /** When it ran, on the organization's calendar. */
362
+ when: string;
363
+ outcome: WorkflowRunOutcome;
364
+ /** Present only where the viewer can open every topic the run touched. */
365
+ summary?: string;
366
+ /** The viewer's own open Task on this run. */
367
+ task_id?: string;
368
+ }
369
+ export type WorkflowRunOutcome = "ran" | "edited" | "skipped" | "failed" | "running" | "waiting";
370
+ export interface WorkflowTopic {
371
+ id: string;
372
+ name: string;
373
+ role: "reads" | "updates";
374
+ }
375
+ /** What an app's call of each operation resolves with: the response's
376
+ * `data`, or `{ data, meta }` when the response pages. */
377
+ export interface AppOperationResults {
378
+ /** List typed records */
379
+ listTopics: {
380
+ data: TopicRecord[];
381
+ meta: {
382
+ next_cursor: string | null;
383
+ };
384
+ };
385
+ /** Create a topic */
386
+ createTopic: CreatedTopicRecord;
387
+ /** Read the field contract */
388
+ listTopicTypes: TopicType[];
389
+ /** Get a topic's record */
390
+ getTopicRecord: AppTopicRecord;
391
+ /** Get the discussion about a value */
392
+ getTopicFactDiscussion: AppFactDiscussion;
393
+ /** Set a field's value */
394
+ setTopicField: TopicFieldReceipt;
395
+ /** List workflows */
396
+ listWorkflows: AppWorkflowSummary[];
397
+ /** Read a workflow as a member reads it */
398
+ getWorkflowCard: WorkflowCard;
399
+ /** Trigger a workflow run */
400
+ runWorkflow: AppRunReceipt;
401
+ /** List a workflow's runs */
402
+ listWorkflowExecutions: AppExecution[];
403
+ /** Get a workflow run */
404
+ getExecution: AppExecution;
405
+ /** Create a lesson */
406
+ createLesson: AppLesson;
407
+ /** Update a lesson */
408
+ updateLesson: AppLesson;
409
+ /** List outcomes */
410
+ listOutcomes: {
411
+ data: AppOutcome[];
412
+ meta: PageMeta;
413
+ };
414
+ /** Get the organization's defined aggregates */
415
+ getOrganizationAnalytics: OrganizationAnalytics;
416
+ }
package/index.d.ts ADDED
@@ -0,0 +1,136 @@
1
+ import type * as Api from "./generated/apiTypes";
2
+ export * from "./navigation";
3
+ export type * from "./generated/apiTypes";
4
+ /** Which records `listTopics` reads. A field filter is
5
+ * `<field>:<op>:<value>` (op: eq, ne, lt, lte, gt, gte, contains), and a
6
+ * field filter or sort needs `type`. `sort` is a field or `name`,
7
+ * `created_at`, `updated_at`; `-` in front sorts descending. */
8
+ export interface TopicQuery {
9
+ type?: string;
10
+ filter?: string[];
11
+ sort?: string;
12
+ cursor?: string;
13
+ limit?: number;
14
+ }
15
+ export interface AttachmentDownloadReceipt {
16
+ status: "downloaded" | "download_started";
17
+ attachment_id: string;
18
+ filename: string;
19
+ }
20
+ /** What each operation resolves with. A download is the host's own: it
21
+ * fetches the file and hands the app this receipt, never the URL. */
22
+ interface OperationResults extends Api.AppOperationResults {
23
+ downloadTopicFactAttachment: AttachmentDownloadReceipt;
24
+ }
25
+ export type OperationResult<K extends AppOperationId> = OperationResults[K];
26
+ /** How `waitForExecution` polls: it starts at `firstDelayMs` and doubles up
27
+ * to `maxDelayMs`, and calls `onWaiting` each time the run is waiting. */
28
+ export interface PollOptions {
29
+ firstDelayMs?: number;
30
+ maxDelayMs?: number;
31
+ /** Stops polling and rejects. */
32
+ signal?: AbortSignal;
33
+ /** Each read while the run is still going, so the app can show
34
+ * "Waiting for Lena". */
35
+ onUpdate?: (execution: Api.AppExecution) => void;
36
+ }
37
+ /** Every Alma `/v1` operation an app may call, by OpenAPI operationId, and
38
+ * whether it only reads or makes a change as its viewer. The host refuses
39
+ * any other name and any operation outside the manifest's scopes. */
40
+ declare const APP_OPERATIONS: {
41
+ readonly listTopics: "read";
42
+ readonly createTopic: "change";
43
+ readonly listTopicTypes: "read";
44
+ readonly getTopicRecord: "read";
45
+ readonly getTopicFactDiscussion: "read";
46
+ readonly downloadTopicFactAttachment: "read";
47
+ readonly setTopicField: "change";
48
+ readonly listWorkflows: "read";
49
+ readonly getWorkflowCard: "read";
50
+ readonly createLesson: "change";
51
+ readonly updateLesson: "change";
52
+ readonly runWorkflow: "change";
53
+ readonly listWorkflowExecutions: "read";
54
+ readonly getExecution: "read";
55
+ readonly listOutcomes: "read";
56
+ readonly getOrganizationAnalytics: "read";
57
+ };
58
+ export type AppOperationId = keyof typeof APP_OPERATIONS;
59
+ export interface AppRequest {
60
+ /** Path template parameters; the host refuses any that is not a UUID. */
61
+ params?: Record<string, string>;
62
+ /** Only the query keys the operation declares reach the API. */
63
+ query?: Record<string, string | number | string[] | undefined>;
64
+ body?: Record<string, unknown>;
65
+ }
66
+ export interface AppTransport {
67
+ /** Resolves with the response's `data`, or `{ data, meta }` when the
68
+ * response pages. A change is the viewer's own act: it resolves with the
69
+ * result where they may make it, and rejects with the refusal's words
70
+ * where they may not. */
71
+ call<T>(operationId: AppOperationId, request?: AppRequest): Promise<T>;
72
+ }
73
+ export declare function createAppSdk(transport: AppTransport): {
74
+ call: <T>(operationId: AppOperationId, request?: AppRequest) => Promise<T>;
75
+ listTopics: (query?: TopicQuery) => Promise<{
76
+ data: Api.TopicRecord[];
77
+ meta: {
78
+ next_cursor: string | null;
79
+ };
80
+ }>;
81
+ getTopicRecord: (topicId: string) => Promise<Api.AppTopicRecord>;
82
+ getTopicFactDiscussion: (topicId: string, factId: string) => Promise<Api.AppFactDiscussion>;
83
+ /** The host downloads the file itself; the app receives only a receipt. */
84
+ downloadTopicFactAttachment: (topicId: string, factId: string, turn: {
85
+ kind: "message" | "queued";
86
+ id: string;
87
+ }, attachmentId: string) => Promise<AttachmentDownloadReceipt>;
88
+ /** Sets one field as the viewer, where they may edit the topic;
89
+ * rejects with the refusal's words where they may not. Nobody is asked.
90
+ * Setting a value the field already holds confirms it as theirs. On a
91
+ * relationship, `refTopicId` names the topic the value refers to. */
92
+ setTopicField: (topicId: string, fieldKey: string, value: string, refTopicId?: string) => Promise<Api.TopicFieldReceipt>;
93
+ /** Creates a record as the viewer. Who can see it is the viewer's
94
+ * choice in Alma's own access sheet, never the app's. */
95
+ createTopic: (name: string, topicTypeId?: string) => Promise<Api.CreatedTopicRecord>;
96
+ /** Every type, its fields and its relationships. */
97
+ listTopicTypes: <T = Api.TopicType[]>() => Promise<T>;
98
+ listWorkflows: () => Promise<Api.AppWorkflowSummary[]>;
99
+ /** Starts a workflow the app's manifest names as the viewer. Nobody is
100
+ * asked: it starts where they may run it and, on a record, edit that
101
+ * record, and rejects with the refusal's words otherwise. */
102
+ runWorkflow: (workflowId: string, run?: {
103
+ topicId?: string;
104
+ input?: Record<string, unknown>;
105
+ }) => Promise<Api.AppRunReceipt>;
106
+ /** A run the viewer started: running, waiting on people, or how it
107
+ * ended. */
108
+ getExecution: (executionId: string) => Promise<Api.AppExecution>;
109
+ /** The newest runs of a workflow the app names that the viewer may read,
110
+ * on one record when `topicId` names it: how an app opened again finds
111
+ * the run it started. */
112
+ listRuns: (workflowId: string, run?: {
113
+ topicId?: string;
114
+ }) => Promise<Api.AppExecution[]>;
115
+ /** Polls a run with backoff until it finishes, and resolves with how it
116
+ * ended. A run waiting on an approver can wait for a long time; pass a
117
+ * `signal` to stop. */
118
+ waitForExecution: (executionId: string, options?: PollOptions) => Promise<Api.AppExecution>;
119
+ getWorkflowCard: (workflowId: string) => Promise<Api.WorkflowCard>;
120
+ /** A lesson every later run of the workflow follows. Screened: wording
121
+ * that reads as an instruction to Alma is refused with the reason. */
122
+ createWorkflowLesson: (workflowId: string, content: string) => Promise<Api.AppLesson>;
123
+ /** Pass the `edit_revision` the card gave; a save made meanwhile is
124
+ * refused rather than overwritten. */
125
+ updateLesson: (lessonId: string, content: string, editRevision: string) => Promise<Api.AppLesson>;
126
+ listOutcomes: (page?: {
127
+ limit?: number;
128
+ offset?: number;
129
+ }) => Promise<{
130
+ data: Api.AppOutcome[];
131
+ meta: Api.PageMeta;
132
+ }>;
133
+ /** Alma's own package only, on an installation granted `analytics:org`. */
134
+ getOrganizationAnalytics: () => Promise<Api.OrganizationAnalytics>;
135
+ };
136
+ export declare function hostTransport(): AppTransport;
package/index.js ADDED
@@ -0,0 +1,218 @@
1
+ // src/bridge.ts
2
+ function hostLine() {
3
+ const port = globalThis.__almaHostPort;
4
+ if (typeof MessagePort !== "undefined" && port instanceof MessagePort) {
5
+ port.start();
6
+ return {
7
+ post: (message) => port.postMessage(message),
8
+ listen: (heard) => port.addEventListener("message", (event) => heard(event.data))
9
+ };
10
+ }
11
+ const hostOrigin = new URLSearchParams(location.search).get("host");
12
+ if (!hostOrigin || !URL.canParse(hostOrigin) || new URL(hostOrigin).origin !== hostOrigin || parent === window)
13
+ throw new Error("Open this app in Alma");
14
+ return {
15
+ post: (message) => parent.postMessage(message, hostOrigin),
16
+ listen: (heard) => window.addEventListener("message", (event) => {
17
+ if (event.source === parent && event.origin === hostOrigin)
18
+ heard(event.data);
19
+ })
20
+ };
21
+ }
22
+
23
+ // src/navigation.ts
24
+ function applicationPath(value) {
25
+ if (typeof value !== "string" || value.length > 2048 || !value.startsWith("/") || value.startsWith("//") || /[\\?#]/.test(value) || [...value].some((character) => character.charCodeAt(0) < 32))
26
+ return null;
27
+ const parsed = new URL(value, "https://application.invalid");
28
+ return parsed.origin === "https://application.invalid" && parsed.pathname === value ? value : null;
29
+ }
30
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
31
+ function hostNavigation() {
32
+ const line = hostLine();
33
+ let path = applicationPath(document.documentElement.dataset["almaPath"]) ?? "/";
34
+ const listeners = new Set;
35
+ let reported = 0;
36
+ line.listen((told) => {
37
+ if (typeof told !== "object" || told === null)
38
+ return;
39
+ const message = told;
40
+ if (message["type"] !== "alma:navigation")
41
+ return;
42
+ const next = applicationPath(message["path"]);
43
+ if (next === null || next === path)
44
+ return;
45
+ path = next;
46
+ const answered = message["echo_of"];
47
+ const echo = typeof answered !== "number" || !Number.isInteger(answered) || answered < 1 || answered > reported ? null : answered === reported ? "latest" : "earlier";
48
+ for (const listener of listeners)
49
+ listener(path, echo);
50
+ });
51
+ return {
52
+ getPath: () => path,
53
+ subscribe: (listener) => {
54
+ listeners.add(listener);
55
+ return () => listeners.delete(listener);
56
+ },
57
+ navigate: (next) => {
58
+ if (applicationPath(next) === null)
59
+ throw new Error("App navigation requires a relative path");
60
+ reported += 1;
61
+ line.post({ type: "alma:navigate", path: next, seq: reported });
62
+ },
63
+ openApps: () => line.post({ type: "alma:leave" }),
64
+ openTasks: (taskId) => {
65
+ if (taskId !== undefined && !UUID.test(taskId))
66
+ throw new Error("A Task is named by its id");
67
+ line.post({
68
+ type: "alma:tasks",
69
+ ...taskId ? { task_id: taskId } : {}
70
+ });
71
+ },
72
+ openTopic: (topicId) => {
73
+ if (!UUID.test(topicId))
74
+ throw new Error("A topic is named by its id");
75
+ line.post({ type: "alma:topic", topic_id: topicId });
76
+ }
77
+ };
78
+ }
79
+
80
+ // src/index.ts
81
+ var FINISHED = [
82
+ "completed",
83
+ "failed",
84
+ "cancelled"
85
+ ];
86
+ function createAppSdk(transport) {
87
+ const getExecution = (executionId) => transport.call("getExecution", {
88
+ params: { id: executionId }
89
+ });
90
+ return {
91
+ call: (operationId, request) => transport.call(operationId, request),
92
+ listTopics: (query = {}) => transport.call("listTopics", {
93
+ query: {
94
+ type: query.type,
95
+ filter: query.filter,
96
+ sort: query.sort,
97
+ cursor: query.cursor,
98
+ limit: query.limit
99
+ }
100
+ }),
101
+ getTopicRecord: (topicId) => transport.call("getTopicRecord", {
102
+ params: { id: topicId }
103
+ }),
104
+ getTopicFactDiscussion: (topicId, factId) => transport.call("getTopicFactDiscussion", { params: { id: topicId, factId } }),
105
+ downloadTopicFactAttachment: (topicId, factId, turn, attachmentId) => transport.call("downloadTopicFactAttachment", {
106
+ params: { id: topicId, factId, attachmentId },
107
+ query: { turn_kind: turn.kind, turn_id: turn.id }
108
+ }),
109
+ setTopicField: (topicId, fieldKey, value, refTopicId) => transport.call("setTopicField", {
110
+ params: { id: topicId, key: fieldKey },
111
+ body: { value, ...refTopicId ? { ref_topic_id: refTopicId } : {} }
112
+ }),
113
+ createTopic: (name, topicTypeId) => transport.call("createTopic", {
114
+ body: { name, ...topicTypeId ? { topic_type_id: topicTypeId } : {} }
115
+ }),
116
+ listTopicTypes: () => transport.call("listTopicTypes"),
117
+ listWorkflows: () => transport.call("listWorkflows"),
118
+ runWorkflow: (workflowId, run = {}) => transport.call("runWorkflow", {
119
+ params: { id: workflowId },
120
+ body: {
121
+ ...run.topicId ? { topic_id: run.topicId } : {},
122
+ ...run.input ? { input: run.input } : {}
123
+ }
124
+ }),
125
+ getExecution,
126
+ listRuns: (workflowId, run = {}) => transport.call("listWorkflowExecutions", {
127
+ params: { id: workflowId },
128
+ query: { topic_id: run.topicId }
129
+ }),
130
+ waitForExecution: async (executionId, options = {}) => {
131
+ let delay = options.firstDelayMs ?? 1000;
132
+ const max = options.maxDelayMs ?? 30000;
133
+ for (;; ) {
134
+ options.signal?.throwIfAborted();
135
+ const execution = await getExecution(executionId);
136
+ if (FINISHED.includes(execution.status))
137
+ return execution;
138
+ options.onUpdate?.(execution);
139
+ await new Promise((resolve, reject) => {
140
+ const timer = setTimeout(resolve, delay);
141
+ options.signal?.addEventListener("abort", () => {
142
+ clearTimeout(timer);
143
+ reject(options.signal?.reason);
144
+ }, { once: true });
145
+ });
146
+ delay = Math.min(delay * 2, max);
147
+ }
148
+ },
149
+ getWorkflowCard: (workflowId) => transport.call("getWorkflowCard", {
150
+ params: { id: workflowId }
151
+ }),
152
+ createWorkflowLesson: (workflowId, content) => transport.call("createLesson", {
153
+ body: { workflow_id: workflowId, content }
154
+ }),
155
+ updateLesson: (lessonId, content, editRevision) => transport.call("updateLesson", {
156
+ params: { id: lessonId },
157
+ body: { content, expected_revision: editRevision }
158
+ }),
159
+ listOutcomes: (page = {}) => transport.call("listOutcomes", {
160
+ query: { limit: page.limit, offset: page.offset }
161
+ }),
162
+ getOrganizationAnalytics: () => transport.call("getOrganizationAnalytics")
163
+ };
164
+ }
165
+ function hostTransport() {
166
+ const line = hostLine();
167
+ const pending = new Map;
168
+ line.listen((told) => {
169
+ if (typeof told !== "object" || told === null)
170
+ return;
171
+ const message = told;
172
+ if (message["type"] !== "alma:result" || typeof message["id"] !== "string")
173
+ return;
174
+ const call = pending.get(message["id"]);
175
+ if (!call)
176
+ return;
177
+ clearTimeout(call.timer);
178
+ pending.delete(message["id"]);
179
+ if (typeof message["error"] === "string")
180
+ call.reject(new Error(message["error"]));
181
+ else if (message["meta"] !== undefined)
182
+ call.resolve({ data: message["data"], meta: message["meta"] });
183
+ else
184
+ call.resolve(message["data"]);
185
+ });
186
+ return {
187
+ call: (operationId, request = {}) => new Promise((resolve, reject) => {
188
+ const id = crypto.randomUUID();
189
+ const timer = setTimeout(() => {
190
+ pending.delete(id);
191
+ reject(new Error("The host did not answer. Reload the app to reconnect."));
192
+ }, 30000);
193
+ pending.set(id, {
194
+ resolve: (data) => resolve(data),
195
+ reject,
196
+ timer
197
+ });
198
+ const query = {};
199
+ for (const [key, value] of Object.entries(request.query ?? {}))
200
+ if (value !== undefined)
201
+ query[key] = Array.isArray(value) ? value : String(value);
202
+ line.post({
203
+ type: "alma:operation",
204
+ id,
205
+ operation: operationId,
206
+ params: request.params ?? {},
207
+ query,
208
+ ...request.body ? { body: request.body } : {}
209
+ });
210
+ })
211
+ };
212
+ }
213
+ export {
214
+ applicationPath,
215
+ createAppSdk,
216
+ hostNavigation,
217
+ hostTransport
218
+ };
@@ -0,0 +1,21 @@
1
+ /** Paths belong to one installation. The host chooses the containing route;
2
+ * an app cannot use this bridge to navigate to an arbitrary host URL. */
3
+ export declare function applicationPath(value: unknown): string | null;
4
+ /** What a host announcement answers: nothing (`null`, the host moved on its
5
+ * own — the address bar, back and forward), the `latest` move this app
6
+ * reported with `navigate`, or an `earlier` one the app has since moved on
7
+ * from. An app follows the host's own moves, never an earlier echo, and a
8
+ * latest echo only when it is somewhere else (a host move crossed its own). */
9
+ export type AppNavigationEcho = "latest" | "earlier" | null;
10
+ export interface AppNavigation {
11
+ getPath(): string;
12
+ /** Each path the host announces, and what the announcement answers. */
13
+ subscribe(listener: (path: string, echo: AppNavigationEcho) => void): () => void;
14
+ navigate(path: string): void;
15
+ openApps(): void;
16
+ /** Tasks, or one of the viewer's own Tasks by id. */
17
+ openTasks(taskId?: string): void;
18
+ /** A topic, in the organization's Knowledge tab. */
19
+ openTopic(topicId: string): void;
20
+ }
21
+ export declare function hostNavigation(): AppNavigation;
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "@almateam/app-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "Types, host bridge and the alma-app dev command for apps that run in Alma. Alma builds every app with its own current copy of the SDK; install this for the types and the command.",
5
+ "license": "MIT",
6
+ "homepage": "https://docs.alma.team/developers/apps",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "import": "./index.js"
13
+ }
14
+ },
15
+ "types": "./index.d.ts",
16
+ "bin": {
17
+ "alma-app": "./cli.js"
18
+ },
19
+ "dependencies": {
20
+ "@modelcontextprotocol/sdk": "^1.32.1"
21
+ }
22
+ }