@orbiworkspace/sdk 0.1.0 → 0.2.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/ai.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ export type AiProvider = 'anthropic' | 'openai' | 'google';
2
+ export interface AiClientConfig {
3
+ provider: AiProvider;
4
+ model: string;
5
+ /** Pass to the provider SDK: `new Anthropic({ baseURL, apiKey })`, `new OpenAI({ baseURL, apiKey })`. */
6
+ baseURL: string;
7
+ apiKey: string;
8
+ }
9
+ export interface AiOptions {
10
+ /** The gateway's address; on Orbi Apps `ORBI_MODEL_BASE_URL`. */
11
+ baseUrl?: string;
12
+ /** On Orbi Apps `ORBI_SESSION_KEY`. */
13
+ key?: string;
14
+ provider?: AiProvider;
15
+ model?: string;
16
+ fetch?: typeof fetch;
17
+ }
18
+ export interface AiMessage {
19
+ role: 'user' | 'assistant';
20
+ content: string;
21
+ }
22
+ export interface AiTool {
23
+ description: string;
24
+ /** A JSON Schema of the tool's input object. */
25
+ parameters: Record<string, unknown>;
26
+ run(input: Record<string, unknown>): unknown | Promise<unknown>;
27
+ }
28
+ export interface AgentResult {
29
+ /** The model's last answer. */
30
+ text: string;
31
+ steps: number;
32
+ toolCalls: Array<{
33
+ name: string;
34
+ input: Record<string, unknown>;
35
+ }>;
36
+ }
37
+ export declare class AiError extends Error {
38
+ readonly code: string;
39
+ readonly status: number;
40
+ constructor(code: string, status: number, message: string);
41
+ }
42
+ /** Where the gateway is and which model the app was given; throws when the app has no gateway. */
43
+ export declare function aiConfig(options?: AiOptions): AiClientConfig;
44
+ /** The models of Orbi, with a one-call `chat` and a small tool loop `agent`. */
45
+ export declare function createAi(options?: AiOptions): {
46
+ /** For a provider SDK: its base address, the key to pass, and the model to name. */
47
+ client: () => AiClientConfig;
48
+ /** One answer to a conversation. */
49
+ chat(opts: {
50
+ system?: string;
51
+ messages: AiMessage[];
52
+ maxTokens?: number;
53
+ }): Promise<string>;
54
+ /**
55
+ * A small tool loop: the model answers or asks for tools, the app's `run` functions answer it,
56
+ * until the model answers without a tool or `maxSteps` is reached. A tool that throws gives the
57
+ * model its error message, so it can try another way.
58
+ */
59
+ agent(opts: {
60
+ system?: string;
61
+ input: string;
62
+ tools?: Record<string, AiTool>;
63
+ maxSteps?: number;
64
+ maxTokens?: number;
65
+ }): Promise<AgentResult>;
66
+ };
package/dist/ai.js ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ // Models through Orbi's model gateway, for an app whose manifest says `ai.via: orbi`. On Orbi Apps
3
+ // every app session gets the gateway's address and a session key; the gateway puts the workspace's
4
+ // real key on each request, counts the tokens against the app's credit cap, and allows only the
5
+ // model the app was given. Any provider SDK works with `client()`; `chat()` and `agent()` are small
6
+ // helpers for apps that want no SDK. The agent's loop, tools and memory are the app's own code.
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.AiError = void 0;
9
+ exports.aiConfig = aiConfig;
10
+ exports.createAi = createAi;
11
+ class AiError extends Error {
12
+ code;
13
+ status;
14
+ constructor(code, status, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.status = status;
18
+ this.name = 'AiError';
19
+ }
20
+ }
21
+ exports.AiError = AiError;
22
+ function env(name) {
23
+ const proc = globalThis.process;
24
+ return proc?.env?.[name];
25
+ }
26
+ /** Where the gateway is and which model the app was given; throws when the app has no gateway. */
27
+ function aiConfig(options = {}) {
28
+ const base = (options.baseUrl ?? env('ORBI_MODEL_BASE_URL') ?? '').replace(/\/+$/, '');
29
+ const key = options.key ?? env('ORBI_SESSION_KEY') ?? '';
30
+ const provider = (options.provider ?? env('ORBI_AI_PROVIDER'));
31
+ const model = options.model ?? env('ORBI_AI_MODEL') ?? '';
32
+ if (!base || !key || !provider || !model) {
33
+ throw new AiError('sdk.ai_unavailable', 0, 'No model gateway here: declare "ai": { "via": "orbi" } in orbi.manifest and run on Orbi Apps, or pass baseUrl, key, provider and model');
34
+ }
35
+ return { provider, model, baseURL: `${base}/${provider}`, apiKey: key };
36
+ }
37
+ /** The models of Orbi, with a one-call `chat` and a small tool loop `agent`. */
38
+ function createAi(options = {}) {
39
+ const doFetch = options.fetch ?? fetch;
40
+ const config = () => aiConfig(options);
41
+ async function send(system, history, tools, maxTokens) {
42
+ const c = config();
43
+ const anthropic = c.provider === 'anthropic';
44
+ const toolList = Object.entries(tools);
45
+ const body = anthropic
46
+ ? { model: c.model, max_tokens: maxTokens, ...(system ? { system } : {}), messages: history, ...(toolList.length ? { tools: toolList.map(([name, t]) => ({ name, description: t.description, input_schema: t.parameters })) } : {}) }
47
+ : { model: c.model, max_tokens: maxTokens, messages: [...(system ? [{ role: 'system', content: system }] : []), ...history], ...(toolList.length ? { tools: toolList.map(([name, t]) => ({ type: 'function', function: { name, description: t.description, parameters: t.parameters } })) } : {}) };
48
+ const res = await doFetch(anthropic ? `${c.baseURL}/v1/messages` : `${c.baseURL}/chat/completions`, {
49
+ method: 'POST',
50
+ headers: { 'Content-Type': 'application/json', ...(anthropic ? { 'x-api-key': c.apiKey, 'anthropic-version': '2023-06-01' } : { Authorization: `Bearer ${c.apiKey}` }) },
51
+ body: JSON.stringify(body),
52
+ });
53
+ const json = (await res.json().catch(() => ({})));
54
+ if (!res.ok) {
55
+ const err = json.error;
56
+ const message = typeof err === 'string' ? err : (err?.message ?? json.message ?? res.statusText);
57
+ throw new AiError(typeof err === 'object' && err ? (err.code ?? err.type ?? `http.${res.status}`) : `http.${res.status}`, res.status, message);
58
+ }
59
+ if (anthropic) {
60
+ const content = (json.content ?? []);
61
+ return {
62
+ text: content.filter((b) => b.type === 'text').map((b) => b.text ?? '').join(''),
63
+ calls: content.filter((b) => b.type === 'tool_use').map((b) => ({ id: b.id, name: b.name, input: b.input ?? {} })),
64
+ raw: { role: 'assistant', content },
65
+ };
66
+ }
67
+ const message = (json.choices?.[0]?.message ?? {});
68
+ return {
69
+ text: message.content ?? '',
70
+ calls: (message.tool_calls ?? []).map((t) => ({ id: t.id, name: t.function.name, input: safeJson(t.function.arguments) })),
71
+ raw: { role: 'assistant', content: message.content ?? null, ...(message.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) },
72
+ };
73
+ }
74
+ function results(calls, outputs) {
75
+ if (config().provider === 'anthropic')
76
+ return [{ role: 'user', content: calls.map((c, i) => ({ type: 'tool_result', tool_use_id: c.id, content: outputs[i] })) }];
77
+ return calls.map((c, i) => ({ role: 'tool', tool_call_id: c.id, content: outputs[i] }));
78
+ }
79
+ return {
80
+ /** For a provider SDK: its base address, the key to pass, and the model to name. */
81
+ client: config,
82
+ /** One answer to a conversation. */
83
+ async chat(opts) {
84
+ return (await send(opts.system, opts.messages, {}, opts.maxTokens ?? 1024)).text;
85
+ },
86
+ /**
87
+ * A small tool loop: the model answers or asks for tools, the app's `run` functions answer it,
88
+ * until the model answers without a tool or `maxSteps` is reached. A tool that throws gives the
89
+ * model its error message, so it can try another way.
90
+ */
91
+ async agent(opts) {
92
+ const tools = opts.tools ?? {};
93
+ const history = [{ role: 'user', content: opts.input }];
94
+ const toolCalls = [];
95
+ const maxSteps = opts.maxSteps ?? 8;
96
+ for (let step = 1;; step += 1) {
97
+ const turn = await send(opts.system, history, tools, opts.maxTokens ?? 2048);
98
+ if (turn.calls.length === 0 || step >= maxSteps)
99
+ return { text: turn.text, steps: step, toolCalls };
100
+ history.push(turn.raw);
101
+ const outputs = [];
102
+ for (const call of turn.calls) {
103
+ toolCalls.push({ name: call.name, input: call.input });
104
+ const tool = tools[call.name];
105
+ try {
106
+ if (!tool)
107
+ throw new Error(`no tool named ${call.name}`);
108
+ const out = await tool.run(call.input);
109
+ outputs.push(typeof out === 'string' ? out : JSON.stringify(out ?? null));
110
+ }
111
+ catch (err) {
112
+ outputs.push(`error: ${err.message}`);
113
+ }
114
+ }
115
+ history.push(...results(turn.calls, outputs));
116
+ }
117
+ },
118
+ };
119
+ }
120
+ function safeJson(text) {
121
+ try {
122
+ const v = JSON.parse(text);
123
+ return v && typeof v === 'object' ? v : {};
124
+ }
125
+ catch {
126
+ return {};
127
+ }
128
+ }
@@ -0,0 +1,32 @@
1
+ import type { OrbiGrantKind } from './index';
2
+ export type PickerKind = OrbiGrantKind;
3
+ export interface PickerOptions {
4
+ kind: PickerKind;
5
+ /** More than one resource at once. */
6
+ multiple?: boolean;
7
+ /**
8
+ * `installation` asks for a grant of the app itself, used by its own calls too; only the app's
9
+ * owner and an admin of the workspace can give one. By default the grant is the person's.
10
+ */
11
+ for?: 'user' | 'installation';
12
+ }
13
+ export interface PickedResource {
14
+ kind: PickerKind;
15
+ id: string;
16
+ name: string;
17
+ }
18
+ /** What the picker answers: the picked resources, or null when the person closed it without picking. */
19
+ export type PickerResult = {
20
+ items: PickedResource[];
21
+ } | null;
22
+ export declare const PICKER_OPEN = "orbi.picker.open";
23
+ export declare const PICKER_RESULT = "orbi.picker.result";
24
+ /** The picker path on the app's own address, which the gate sends on to Orbi. */
25
+ export declare function pickerPath(id: string, options: PickerOptions): string;
26
+ /**
27
+ * Opens Orbi's picker and waits for the person. Call it from a click: outside Orbi's tab it opens
28
+ * a window, which a browser allows only then.
29
+ */
30
+ export declare function openPicker(options: PickerOptions, env?: {
31
+ window?: Window;
32
+ }): Promise<PickerResult>;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ // Orbi's picker for an app's own page: the person picks a board, folder, collection,
3
+ // agent, space or member in a list Orbi draws, and the pick becomes a grant the app's calls may
4
+ // use. Inside Orbi's tab the request goes to Orbi's page around the app; on its own the app opens
5
+ // `/__orbi/picker` in a window, which its address sends on to Orbi. Either way Orbi writes the
6
+ // grant with the person's own session: what arrives here only says what was picked.
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.PICKER_RESULT = exports.PICKER_OPEN = void 0;
9
+ exports.pickerPath = pickerPath;
10
+ exports.openPicker = openPicker;
11
+ exports.PICKER_OPEN = 'orbi.picker.open';
12
+ exports.PICKER_RESULT = 'orbi.picker.result';
13
+ const isResult = (data, id) => {
14
+ const d = data;
15
+ return typeof d === 'object' && d !== null && d.type === exports.PICKER_RESULT && d.id === id;
16
+ };
17
+ const requestId = () => {
18
+ const bytes = new Uint8Array(12);
19
+ globalThis.crypto.getRandomValues(bytes);
20
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
21
+ };
22
+ /** The picker path on the app's own address, which the gate sends on to Orbi. */
23
+ function pickerPath(id, options) {
24
+ const q = new URLSearchParams({ kind: options.kind, id });
25
+ if (options.multiple)
26
+ q.set('multiple', '1');
27
+ if (options.for === 'installation')
28
+ q.set('for', 'installation');
29
+ return `/__orbi/picker?${q.toString()}`;
30
+ }
31
+ /**
32
+ * Opens Orbi's picker and waits for the person. Call it from a click: outside Orbi's tab it opens
33
+ * a window, which a browser allows only then.
34
+ */
35
+ function openPicker(options, env = {}) {
36
+ const w = env.window ?? globalThis.window;
37
+ const id = requestId();
38
+ const framed = w.parent !== w;
39
+ return new Promise((resolve, reject) => {
40
+ let popup = null;
41
+ let watch;
42
+ const done = (result) => {
43
+ w.removeEventListener('message', onMessage);
44
+ if (watch)
45
+ clearInterval(watch);
46
+ resolve(result);
47
+ };
48
+ // Only the window that was asked may answer: Orbi's page around the app, or the picker window.
49
+ const onMessage = (event) => {
50
+ const from = framed ? w.parent : popup;
51
+ if (!from || event.source !== from || !isResult(event.data, id))
52
+ return;
53
+ done(event.data.cancelled ? null : { items: Array.isArray(event.data.items) ? event.data.items : [] });
54
+ };
55
+ w.addEventListener('message', onMessage);
56
+ if (framed) {
57
+ // The request carries nothing secret and Orbi's address is not known here; the answer is
58
+ // checked by its source instead.
59
+ w.parent.postMessage({ type: exports.PICKER_OPEN, id, kind: options.kind, multiple: Boolean(options.multiple), for: options.for ?? 'user' }, '*');
60
+ return;
61
+ }
62
+ popup = w.open(pickerPath(id, options), `orbi-picker-${id}`, 'popup,width=480,height=640');
63
+ if (!popup) {
64
+ w.removeEventListener('message', onMessage);
65
+ reject(new Error('The picker window was blocked; open the picker from a click'));
66
+ return;
67
+ }
68
+ watch = setInterval(() => {
69
+ if (popup?.closed)
70
+ done(null);
71
+ }, 500);
72
+ });
73
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { aiConfig, createAi, AiError, type AiClientConfig, type AiMessage, type AiOptions, type AiProvider, type AiTool, type AgentResult } from './ai';
1
2
  export interface OrbiClientOptions {
2
3
  /** Orbi's address, for example https://api.orbiwork.space. Defaults to `ORBI_URL`. */
3
4
  url?: string;
@@ -39,8 +40,13 @@ export interface OrbiApp {
39
40
  mode: 'live' | 'dev';
40
41
  /** Whether the approved manifest has sign-in with Orbi. */
41
42
  signIn: boolean;
43
+ /**
44
+ * The address people reach this environment of the app at (the preview's for a development
45
+ * key), for links the app hands out; null when Orbi Apps does not host the app.
46
+ */
47
+ url: string | null;
42
48
  }
43
- /** A field to read from a document (plan 33.9). */
49
+ /** A field to read from a document. */
44
50
  export interface ExtractField {
45
51
  /** 1-64 letters, digits or `_`; the key of the answer. */
46
52
  name: string;
@@ -74,6 +80,31 @@ export interface ExtractResult<T extends Record<string, unknown> = Record<string
74
80
  needsReview: boolean;
75
81
  model: string;
76
82
  }
83
+ /** A file the app keeps in Orbi. */
84
+ /** Whom an action call is for, as Orbi says; the agent that made the call cannot change it. */
85
+ export interface ActionCallContext {
86
+ id: string;
87
+ /** The person's id, the same `sub` their identity carries; null when no person is behind the call. */
88
+ onBehalfOf: string | null;
89
+ }
90
+ export interface OrbiFile {
91
+ id: string;
92
+ name: string;
93
+ mimeType: string;
94
+ sizeBytes: number;
95
+ version: number;
96
+ createdAt: string;
97
+ }
98
+ /** A card the app gave to an agent: its number, state and, once the agent finished, its result. */
99
+ export interface AgentRun {
100
+ number: number;
101
+ state: 'backlog' | 'todo' | 'queued' | 'in_progress' | 'review' | 'done' | 'error';
102
+ finished: boolean;
103
+ result: {
104
+ text: string;
105
+ title: string | null;
106
+ } | null;
107
+ }
77
108
  /** An error Orbi answered with: a stable `code`, the HTTP status and a diagnostic message. */
78
109
  export declare class OrbiError extends Error {
79
110
  readonly code: string;
@@ -82,7 +113,7 @@ export declare class OrbiError extends Error {
82
113
  constructor(code: string, status: number, message: string, params?: Record<string, string>);
83
114
  }
84
115
  /**
85
- * A person signed in with Orbi (plan 33.7). Keep it on the server, in the person's session: it
116
+ * A person signed in with Orbi. Keep it on the server, in the person's session: it
86
117
  * holds the refresh token and the private DPoP key every token of it is bound to. It is plain
87
118
  * JSON, so it can be stored as is; `asUser` renews it in place and calls `onRefresh`.
88
119
  */
@@ -99,7 +130,102 @@ export interface OrbiUser {
99
130
  sub: string;
100
131
  name?: string;
101
132
  email?: string;
133
+ /** Their role in the workspace (`admin`, `member`, `viewer`), when the manifest's identity asks for `role`. */
134
+ role?: string;
135
+ /** Their title in the workspace, when the manifest asks for `title` and they have one. */
136
+ title?: string;
137
+ /** The spaces they hold a role in, with that role, when the manifest asks for `spaces`. */
138
+ spaces?: Array<{
139
+ name: string;
140
+ role: string;
141
+ }>;
142
+ }
143
+ /** A kind of resource Orbi's picker lets a person give an app. */
144
+ export type OrbiGrantKind = 'project' | 'folder' | 'collection' | 'agent' | 'space' | 'user';
145
+ /** A resource picked for the app that a call may use; `owner` says whose pick it was. */
146
+ export interface OrbiGrant {
147
+ kind: OrbiGrantKind;
148
+ id: string;
149
+ name: string;
150
+ /** The space it is in, an agent's title or a member's e-mail. */
151
+ detail: string | null;
152
+ owner: 'user' | 'installation';
153
+ }
154
+ /** An invitation of a person outside the workspace into one resource of the app. */
155
+ export interface OrbiGuestInvite {
156
+ id: string;
157
+ email: string;
158
+ name: string | null;
159
+ resource: string;
160
+ /** The page the invitation link opens, under the manifest's `guests.paths`. */
161
+ path: string;
162
+ expiresAt: string;
163
+ accepted: boolean;
164
+ revoked: boolean;
165
+ createdAt: string;
166
+ /** In live, what became of the e-mail: `queued`, `sent`, `rejected` or `suppressed`; null in a preview. */
167
+ mail: 'queued' | 'sent' | 'rejected' | 'suppressed' | null;
168
+ }
169
+ /** A card as an app reads it: enough to show and link to it, never its comments or runs. */
170
+ export interface OrbiTask {
171
+ number: number;
172
+ title: string;
173
+ state: string;
174
+ description: string;
175
+ board: {
176
+ id: string;
177
+ name: string;
178
+ };
179
+ tags: string[];
180
+ /** YYYY-MM-DD. */
181
+ dueDate: string | null;
182
+ /** The card in Orbi, for a link back. */
183
+ url: string;
184
+ createdAt: string;
185
+ updatedAt: string;
186
+ }
187
+ /** What `tasks.create` answers: a real card, or on a preview the card it would have opened. */
188
+ export type OrbiTaskCreated = {
189
+ preview: false;
190
+ task: OrbiTask;
191
+ } | {
192
+ preview: true;
193
+ task: Omit<OrbiTask, 'number' | 'url' | 'createdAt' | 'updatedAt'> & {
194
+ number: null;
195
+ url: null;
196
+ createdAt: null;
197
+ updatedAt: null;
198
+ };
199
+ };
200
+ /** The notice an app's action channel brings when a person's role, title or spaces change. */
201
+ export declare const IDENTITY_NOTICE = "$identity.changed";
202
+ /** What Orbi verified about a guest an app let in: the e-mail they proved and the resource they came for. */
203
+ export interface OrbiGuest {
204
+ email: string;
205
+ /** The domain of `email`, for telling one company's guests from another's. */
206
+ emailDomain: string;
207
+ /** The resource the invitation or link was bound to, such as a meeting id. */
208
+ resource: string;
102
209
  }
210
+ /**
211
+ * The person the gate let through to a hosted app, from its identity header. `source` says who
212
+ * they are to the workspace: `orbi` for a member, `external` for a guest. A guest has `guest` and
213
+ * none of a member's fields (`role`, `title`, `spaces`), and the app cannot act on their behalf.
214
+ */
215
+ export interface OrbiRequestUser extends OrbiUser {
216
+ source: 'orbi' | 'external';
217
+ guest?: OrbiGuest;
218
+ /** `live` or `preview`: which address the request reached. */
219
+ environment: 'live' | 'preview';
220
+ /** On a preview, the admin looking at the app as this person. */
221
+ viewedBy?: string;
222
+ }
223
+ /** The header the gate puts on every request it lets through to a hosted app. */
224
+ export declare const IDENTITY_HEADER = "x-orbi-identity";
225
+ /** A request as Node, Express, Nest and Fetch give it: only its headers are read. */
226
+ export type RequestLike = {
227
+ headers: Headers | Record<string, string | string[] | undefined>;
228
+ };
103
229
  export interface SignInStart {
104
230
  url: string;
105
231
  /** Store these with the person's session until the return: the verifier proves the code is yours. */
@@ -123,12 +249,107 @@ export declare function createOrbiClient(options?: OrbiClientOptions): {
123
249
  update(number: number, data: Partial<T> & Record<string, unknown>): Promise<OrbiRecord<T>>;
124
250
  };
125
251
  /**
126
- * Document extraction (plan 33.9): a file and the fields to read, a value and a confidence per
252
+ * Document extraction: a file and the fields to read, a value and a confidence per
127
253
  * field back. With no credit left it throws `app.extract_no_credits`: keep the record for a
128
254
  * person. The file is not kept by Orbi.
129
255
  */
130
256
  extract: <T extends Record<string, unknown> = Record<string, unknown>>(opts: ExtractOptions, retried?: boolean) => Promise<ExtractResult<T>>;
131
- /** Sign-in with Orbi (plan 33.7): the authorization code flow with PKCE and DPoP. */
257
+ files: {
258
+ upload(file: Blob | Uint8Array | ArrayBuffer, filename: string, mimeType?: string, opts?: {
259
+ folderId?: string;
260
+ }): Promise<OrbiFile>;
261
+ list(opts?: {
262
+ limit?: number;
263
+ offset?: number;
264
+ }): Promise<{
265
+ items: OrbiFile[];
266
+ total: number;
267
+ }>;
268
+ get(id: string): Promise<OrbiFile>;
269
+ /** The file's bytes. */
270
+ download(id: string): Promise<ArrayBuffer>;
271
+ };
272
+ events: {
273
+ emit(name: string, data?: Record<string, unknown>, opts?: {
274
+ idempotencyKey?: string;
275
+ }): Promise<{
276
+ eventId: string;
277
+ environment: "live" | "preview";
278
+ repeated: boolean;
279
+ }>;
280
+ };
281
+ agents: {
282
+ run(name: string, opts: {
283
+ input: string;
284
+ title?: string;
285
+ }): Promise<AgentRun>;
286
+ get(number: number): Promise<AgentRun>;
287
+ wait(number: number, opts?: {
288
+ timeoutMs?: number;
289
+ intervalMs?: number;
290
+ }): Promise<AgentRun>;
291
+ };
292
+ actions: {
293
+ listen(handlers: Record<string, (input: Record<string, unknown>, call: ActionCallContext) => unknown | Promise<unknown>>, opts?: {
294
+ signal?: AbortSignal;
295
+ wait?: number;
296
+ concurrency?: number;
297
+ onIdentityChanged?: (sub: string) => unknown | Promise<unknown>;
298
+ }): Promise<void>;
299
+ };
300
+ /**
301
+ * Vectors for texts from Orbi's own model (`orbi.embed` in the manifest), 768 numbers each,
302
+ * to keep in the app's Postgres for similarity search. At most 64 texts a call.
303
+ */
304
+ embed(texts: string[]): Promise<{
305
+ model: string;
306
+ dimensions: number;
307
+ vectors: number[][];
308
+ }>;
309
+ /**
310
+ * The resources picked for the app in Orbi's picker (`openPicker` in `@orbiworkspace/sdk/browser`).
311
+ * With the app's own key only what the app itself was given; `asUser` adds the person's picks.
312
+ */
313
+ grants: {
314
+ list(kind: OrbiGrantKind): Promise<{
315
+ items: OrbiGrant[];
316
+ }>;
317
+ };
318
+ /**
319
+ * Models through Orbi's model gateway (`"ai": { "via": "orbi" }` in the manifest): `client()`
320
+ * for a provider SDK, `chat()` for one answer, `agent()` for a small tool loop. The spending
321
+ * counts against the app's monthly credit cap.
322
+ */
323
+ ai: {
324
+ client: () => import("./ai").AiClientConfig;
325
+ chat(opts: {
326
+ system?: string;
327
+ messages: import("./ai").AiMessage[];
328
+ maxTokens?: number;
329
+ }): Promise<string>;
330
+ agent(opts: {
331
+ system?: string;
332
+ input: string;
333
+ tools?: Record<string, import("./ai").AiTool>;
334
+ maxSteps?: number;
335
+ maxTokens?: number;
336
+ }): Promise<import("./ai").AgentResult>;
337
+ };
338
+ /**
339
+ * For the app's own agent (`orbi.mcp` in the manifest): Orbi's MCP address, whose tools are the
340
+ * collections the manifest names, and the app's own short-lived token. The token can do what
341
+ * the app may, so give it only to an agent the app trusts; ask again before `expiresAt`.
342
+ */
343
+ mcp: {
344
+ connection(): Promise<{
345
+ url: string;
346
+ headers: {
347
+ Authorization: string;
348
+ };
349
+ expiresAt: number;
350
+ }>;
351
+ };
352
+ /** Sign-in with Orbi: the authorization code flow with PKCE and DPoP. */
132
353
  signIn: {
133
354
  /** The address to send the person to, and what to keep until they come back. */
134
355
  start(opts: {
@@ -146,10 +367,28 @@ export declare function createOrbiClient(options?: OrbiClientOptions): {
146
367
  }>;
147
368
  };
148
369
  /**
149
- * The client on behalf of a signed-in person: every call carries a DPoP proof, reaches only
150
- * what both the app and the person may, and renews the session before it runs out.
370
+ * Who called, on an app Orbi Apps hosts: the gate signs the person into every
371
+ * request it lets through. Null when the request did not come through the gate or its token is
372
+ * not this app's, altered or expired; the app needs no sign-in page of its own.
373
+ */
374
+ userFromRequest(req: RequestLike): Promise<OrbiRequestUser | null>;
375
+ /**
376
+ * Middleware for Express, Nest and Node: the request goes on with `req.orbiUser` set, or is
377
+ * answered 401 when no person came through the gate.
378
+ */
379
+ requireUser(): (req: RequestLike & {
380
+ orbiUser?: OrbiRequestUser;
381
+ }, res: {
382
+ statusCode: number;
383
+ setHeader(name: string, value: string): unknown;
384
+ end(body?: string): unknown;
385
+ }, next: (err?: unknown) => void) => void;
386
+ /**
387
+ * The client on behalf of a person: every call carries a DPoP proof, reaches only what both
388
+ * the app and the person may, and renews the session before it runs out. Give it the session
389
+ * from sign-in, or, on an app Orbi Apps hosts, the request itself.
151
390
  */
152
- asUser(session: OrbiUserSession, opts?: {
391
+ asUser(from: OrbiUserSession | RequestLike, opts?: {
153
392
  onRefresh?: (session: OrbiUserSession) => void | Promise<void>;
154
393
  }): {
155
394
  collection<T = Record<string, unknown>>(name: string): {
@@ -165,6 +404,60 @@ export declare function createOrbiClient(options?: OrbiClientOptions): {
165
404
  };
166
405
  /** What the app may know of the person, as its approved manifest names it. */
167
406
  me(): Promise<OrbiUser>;
407
+ /**
408
+ * Cards on the boards picked for the app, within what the person sees and may
409
+ * write. The manifest asks for `orbi.tasks` (`read`, or `create` to open cards too). There
410
+ * is no app-key version: whose reach bounds the cards is always a person's.
411
+ */
412
+ tasks: {
413
+ search(q: string, opts?: {
414
+ board?: string;
415
+ limit?: number;
416
+ }): Promise<{
417
+ items: OrbiTask[];
418
+ }>;
419
+ get(number: number): Promise<OrbiTask>;
420
+ /** Opens a card on a picked board, tagged with the app's name. A preview opens nothing and answers the card it would open. */
421
+ create(input: {
422
+ board: string;
423
+ title: string;
424
+ description?: string;
425
+ dueDate?: string;
426
+ }): Promise<OrbiTaskCreated>;
427
+ };
428
+ /**
429
+ * People outside the workspace, let into one resource (a meeting) on this person's behalf.
430
+ * The manifest names where guests may go (`orbi.guests.paths`). Orbi sends the invitation
431
+ * and checks who the guest is; letting them in is the app's. A preview mails nothing: the
432
+ * invitation lands in the preview inbox on the app's page. The live e-mail is Orbi's: the
433
+ * app may add the occasion (`title`, `startsAt`, `endsAt`, which also make a calendar file)
434
+ * and a plain `note` of at most 300 characters without links.
435
+ */
436
+ guests: {
437
+ invite(input: {
438
+ email: string;
439
+ resource: string;
440
+ name?: string;
441
+ path?: string;
442
+ expiresAt?: string;
443
+ title?: string;
444
+ startsAt?: string;
445
+ endsAt?: string;
446
+ note?: string;
447
+ }): Promise<OrbiGuestInvite>;
448
+ list(opts?: {
449
+ resource?: string;
450
+ }): Promise<{
451
+ items: OrbiGuestInvite[];
452
+ }>;
453
+ revoke(id: string): Promise<void>;
454
+ };
455
+ /** The person's own picks and the app's, each one they still see. */
456
+ grants: {
457
+ list(kind: OrbiGrantKind): Promise<{
458
+ items: OrbiGrant[];
459
+ }>;
460
+ };
168
461
  };
169
462
  };
170
463
  export type OrbiClient = ReturnType<typeof createOrbiClient>;
package/dist/index.js CHANGED
@@ -1,11 +1,16 @@
1
1
  "use strict";
2
- // Orbi SDK for TypeScript (plan 33.9). A thin client of the public API: it trades the app's key
2
+ // Orbi SDK for TypeScript. A thin client of the public API: it trades the app's key
3
3
  // for a short-lived access token, renews it before it runs out and turns Orbi's error codes into
4
- // `OrbiError`. The permissions are enforced by Orbi, not here (33.4): a call outside the app's
4
+ // `OrbiError`. The permissions are enforced by Orbi, not here: a call outside the app's
5
5
  // approved manifest comes back as `app.permission_missing` with the collection's name.
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.OrbiError = void 0;
7
+ exports.IDENTITY_HEADER = exports.IDENTITY_NOTICE = exports.OrbiError = exports.AiError = exports.createAi = exports.aiConfig = void 0;
8
8
  exports.createOrbiClient = createOrbiClient;
9
+ const ai_1 = require("./ai");
10
+ var ai_2 = require("./ai");
11
+ Object.defineProperty(exports, "aiConfig", { enumerable: true, get: function () { return ai_2.aiConfig; } });
12
+ Object.defineProperty(exports, "createAi", { enumerable: true, get: function () { return ai_2.createAi; } });
13
+ Object.defineProperty(exports, "AiError", { enumerable: true, get: function () { return ai_2.AiError; } });
9
14
  /** An error Orbi answered with: a stable `code`, the HTTP status and a diagnostic message. */
10
15
  class OrbiError extends Error {
11
16
  code;
@@ -27,6 +32,38 @@ function env(name) {
27
32
  const proc = globalThis.process;
28
33
  return proc?.env?.[name];
29
34
  }
35
+ /** The notice an app's action channel brings when a person's role, title or spaces change. */
36
+ exports.IDENTITY_NOTICE = '$identity.changed';
37
+ /** The person's fields from a token's claims, only those it carries. */
38
+ const personOf = (c) => ({
39
+ sub: c.sub,
40
+ ...(c.name ? { name: c.name } : {}),
41
+ ...(c.email ? { email: c.email } : {}),
42
+ ...(c.role ? { role: c.role } : {}),
43
+ ...(c.title ? { title: c.title } : {}),
44
+ ...(Array.isArray(c.spaces) ? { spaces: c.spaces } : {}),
45
+ });
46
+ /** The header the gate puts on every request it lets through to a hosted app. */
47
+ exports.IDENTITY_HEADER = 'x-orbi-identity';
48
+ const IDENTITY_TOKEN_TYPE = 'orbi-identity+jwt';
49
+ const IDENTITY_SUBJECT_TYPE = 'urn:orbi:params:oauth:token-type:identity';
50
+ /** Orbi's signing keys are read again after this long, or at once for a key not seen yet. */
51
+ const JWKS_TTL_MS = 10 * 60_000;
52
+ const headerOf = (req, name) => {
53
+ const h = req.headers;
54
+ const value = typeof h.get === 'function' ? h.get(name) : h[name];
55
+ return Array.isArray(value) ? value[0] : (value ?? undefined);
56
+ };
57
+ const fromB64url = (part) => Uint8Array.from(atob(part.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (part.length % 4)) % 4)), (c) => c.charCodeAt(0));
58
+ /** The `source` an identity token states, read without checking it: only for refusing early. */
59
+ const sourceOf = (token) => {
60
+ try {
61
+ return JSON.parse(new TextDecoder().decode(fromB64url(token.split('.')[1] ?? ''))).source;
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ };
30
67
  const b64url = (bytes) => {
31
68
  const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
32
69
  let bin = '';
@@ -98,6 +135,9 @@ function createOrbiClient(options = {}) {
98
135
  }
99
136
  if (!res.ok)
100
137
  throw await readError(res);
138
+ // A removal answers with no body.
139
+ if (res.status === 204)
140
+ return undefined;
101
141
  return (await res.json());
102
142
  }
103
143
  function collectionOf(auth, name, onUnauthorized) {
@@ -150,7 +190,238 @@ function createOrbiClient(options = {}) {
150
190
  throw await readError(res);
151
191
  return (await res.json());
152
192
  }
193
+ /** Sends a request with a body of its own (a form, bytes) and renews the token once on 401. */
194
+ async function raw(method, path, body, retried = false) {
195
+ const target = `${url}${path}`;
196
+ const res = await doFetch(target, { method, headers: await appAuth(method, target), ...(body ? { body } : {}) });
197
+ if (res.status === 401 && !retried) {
198
+ token = null;
199
+ return raw(method, path, body, true);
200
+ }
201
+ if (!res.ok)
202
+ throw await readError(res);
203
+ return res;
204
+ }
205
+ /**
206
+ * The app's files, kept in Orbi's Files in a folder of the app's own, where people
207
+ * see them too; needs `orbi.files` in the manifest. A development or preview key writes to the
208
+ * folder's "Preview" subfolder. A file sent again under the same name is its next version.
209
+ * `upload` may name a folder a person gave the app in Orbi's picker (`folderId`); the app reads
210
+ * and lists only its own folder.
211
+ */
212
+ const files = {
213
+ async upload(file, filename, mimeType, opts = {}) {
214
+ const form = new FormData();
215
+ const blob = file instanceof Blob ? file : new Blob([file instanceof ArrayBuffer ? new Uint8Array(file) : new Uint8Array(file)], { type: mimeType ?? 'application/octet-stream' });
216
+ if (opts.folderId)
217
+ form.set('folderId', opts.folderId);
218
+ form.set('file', blob, filename);
219
+ return (await raw('POST', '/v1/files', form)).json();
220
+ },
221
+ list(opts = {}) {
222
+ const query = new URLSearchParams();
223
+ if (opts.limit !== undefined)
224
+ query.set('limit', String(opts.limit));
225
+ if (opts.offset !== undefined)
226
+ query.set('offset', String(opts.offset));
227
+ const qs = query.toString();
228
+ return call(appAuth, qs ? `/v1/files?${qs}` : '/v1/files');
229
+ },
230
+ get(id) {
231
+ return call(appAuth, `/v1/files/${encodeURIComponent(id)}`);
232
+ },
233
+ /** The file's bytes. */
234
+ async download(id) {
235
+ return (await raw('GET', `/v1/files/${encodeURIComponent(id)}/content`)).arrayBuffer();
236
+ },
237
+ };
238
+ /**
239
+ * Events to Orbi's flows: a name the manifest's `events` declares and data that
240
+ * matches its schema. The live app's event starts the flows listening to it; a preview's starts
241
+ * nothing real. Give an idempotency key to make a retry the same event.
242
+ */
243
+ const events = {
244
+ emit(name, data = {}, opts = {}) {
245
+ return call(appAuth, '/v1/events', 'POST', { name, data, ...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}) });
246
+ },
247
+ };
248
+ /**
249
+ * Work for the workspace's agents (`orbi.agents` in the manifest): a card on the board the
250
+ * manifest names, assigned to the agent. It runs in Orbi on the workspace's credits; only the
251
+ * live app opens real cards. `run` returns at once; `wait` follows the card until the agent
252
+ * finishes or the time is up.
253
+ */
254
+ const agents = {
255
+ run(name, opts) {
256
+ return call(appAuth, `/v1/agents/${encodeURIComponent(name)}/runs`, 'POST', { input: opts.input, ...(opts.title ? { title: opts.title } : {}) });
257
+ },
258
+ get(number) {
259
+ return call(appAuth, `/v1/agents/runs/${number}`);
260
+ },
261
+ async wait(number, opts = {}) {
262
+ const until = Date.now() + (opts.timeoutMs ?? 10 * 60_000);
263
+ for (;;) {
264
+ const run = await agents.get(number);
265
+ if (run.finished || Date.now() >= until)
266
+ return run;
267
+ await new Promise((resolve) => setTimeout(resolve, opts.intervalMs ?? 5000));
268
+ }
269
+ },
270
+ };
271
+ /** A JSON request whose answer has no body (204). */
272
+ async function send(method, path, body, retried = false) {
273
+ const target = `${url}${path}`;
274
+ const res = await doFetch(target, { method, headers: { ...(await appAuth(method, target)), 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
275
+ if (res.status === 401 && !retried) {
276
+ token = null;
277
+ return send(method, path, body, true);
278
+ }
279
+ if (!res.ok)
280
+ throw await readError(res);
281
+ }
282
+ /**
283
+ * The app's actions (`actions` in the manifest): what Orbi's agents may make the app do. `listen`
284
+ * asks Orbi for the next call, runs its handler and sends the answer, until `signal` aborts. The
285
+ * app reaches Orbi, so this works wherever the app runs. A handler that throws answers with its
286
+ * message; one that returns sends its value (JSON, at most 64 KB). Up to `concurrency` calls
287
+ * (4 by default) run at once, so a slow one does not hold the others back. `onIdentityChanged`
288
+ * hears that a person's role, title or spaces changed, for an app that keeps them in its data.
289
+ * A handler's second argument says whom the call is for: `onBehalfOf` is the person's id (the
290
+ * same `sub` their identity carries) when a person is behind the call, and null when nobody is
291
+ * (an unattended flow). Orbi sets it, not the agent; an app answers within that person's reach.
292
+ */
293
+ const actions = {
294
+ async listen(handlers, opts = {}) {
295
+ const running = new Set();
296
+ const limit = Math.max(1, opts.concurrency ?? 4);
297
+ const answer = async (job) => {
298
+ // Orbi's own notice that a person's role, title or spaces changed: the app reads them
299
+ // again (the next request's identity carries the new values).
300
+ const handler = job.name === exports.IDENTITY_NOTICE
301
+ ? async (input) => {
302
+ await opts.onIdentityChanged?.(String(input.sub ?? ''));
303
+ return null;
304
+ }
305
+ : handlers[job.name];
306
+ let result;
307
+ try {
308
+ if (!handler)
309
+ throw new Error(`no handler for the action ${job.name}`);
310
+ result = { output: (await handler(job.input, { id: job.id, onBehalfOf: job.onBehalfOf ?? null })) ?? null };
311
+ }
312
+ catch (err) {
313
+ result = { error: String(err.message ?? err).slice(0, 2000) };
314
+ }
315
+ const path = `/v1/actions/calls/${encodeURIComponent(job.id)}/result`;
316
+ for (let attempt = 0;; attempt += 1) {
317
+ try {
318
+ await send('POST', path, result);
319
+ return;
320
+ }
321
+ catch (err) {
322
+ const status = err instanceof OrbiError ? err.status : 0;
323
+ // A call Orbi no longer waits for (409) takes no answer at all.
324
+ if (status === 409)
325
+ return;
326
+ // A refusal of the answer itself (too large, say) is told as an error, so the call
327
+ // does not just time out; the handler's real answer is never replaced for a blip.
328
+ if (status >= 400 && status < 500) {
329
+ await send('POST', path, { error: `The app could not send its answer: ${err.message}`.slice(0, 2000) }).catch(() => undefined);
330
+ return;
331
+ }
332
+ if (attempt >= 3)
333
+ return;
334
+ await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
335
+ }
336
+ }
337
+ };
338
+ while (!opts.signal?.aborted) {
339
+ if (running.size >= limit) {
340
+ await Promise.race(running);
341
+ continue;
342
+ }
343
+ let next;
344
+ try {
345
+ next = await call(appAuth, `/v1/actions/next?wait=${opts.wait ?? 25}`);
346
+ }
347
+ catch {
348
+ // Orbi restarting or the network gone for a moment: ask again shortly.
349
+ await new Promise((resolve) => setTimeout(resolve, 2000));
350
+ continue;
351
+ }
352
+ const job = next.call;
353
+ if (!job) {
354
+ // With no wait the poll would spin; a short pause keeps it a poll.
355
+ if (opts.wait === 0)
356
+ await new Promise((resolve) => setTimeout(resolve, 1000));
357
+ continue;
358
+ }
359
+ const task = answer(job).finally(() => running.delete(task));
360
+ running.add(task);
361
+ }
362
+ await Promise.all(running);
363
+ },
364
+ };
153
365
  let clientId = null;
366
+ let jwks = null;
367
+ async function signingKey(kid) {
368
+ const find = () => jwks?.keys.find((k) => k.kid === kid);
369
+ if (!jwks || Date.now() - jwks.at > JWKS_TTL_MS || !find()) {
370
+ const res = await doFetch(`${url}/v1/oauth/jwks`);
371
+ if (!res.ok)
372
+ throw await readError(res);
373
+ jwks = { keys: (await res.json()).keys, at: Date.now() };
374
+ }
375
+ const jwk = find();
376
+ if (!jwk)
377
+ return null;
378
+ const { kty, crv, x, y } = jwk;
379
+ return globalThis.crypto.subtle.importKey('jwk', { kty, crv, x, y }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
380
+ }
381
+ /** The person in a gate identity token, or null when it is not this app's, altered or expired. */
382
+ async function verifyIdentity(token) {
383
+ const parts = (token ?? '').split('.');
384
+ if (parts.length !== 3)
385
+ return null;
386
+ let header;
387
+ let claims;
388
+ try {
389
+ header = JSON.parse(new TextDecoder().decode(fromB64url(parts[0])));
390
+ claims = JSON.parse(new TextDecoder().decode(fromB64url(parts[1])));
391
+ }
392
+ catch {
393
+ return null;
394
+ }
395
+ if (header.alg !== 'ES256' || header.typ !== IDENTITY_TOKEN_TYPE || !header.kid)
396
+ return null;
397
+ const verifyKey = await signingKey(header.kid);
398
+ if (!verifyKey)
399
+ return null;
400
+ const ok = await globalThis.crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, verifyKey, fromB64url(parts[2]), new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
401
+ if (!ok || typeof claims.sub !== 'string' || typeof claims.exp !== 'number' || claims.exp * 1000 <= Date.now())
402
+ return null;
403
+ clientId ??= (await call(appAuth, '/v1/app')).clientId;
404
+ if (claims.aud !== clientId)
405
+ return null;
406
+ const environment = claims.env === 'preview' ? 'preview' : 'live';
407
+ if (claims.source === 'external') {
408
+ const g = claims.guest;
409
+ // A guest token without what Orbi verified is not one Orbi made; it lets no one in.
410
+ if (typeof g?.email !== 'string' || typeof g.emailDomain !== 'string' || typeof g.resource !== 'string')
411
+ return null;
412
+ const guest = { email: g.email, emailDomain: g.emailDomain, resource: g.resource };
413
+ return { sub: claims.sub, ...(claims.name ? { name: claims.name } : {}), email: guest.email, source: 'external', guest, environment };
414
+ }
415
+ // An Orbi older than the field signs no source; its tokens are all members'.
416
+ if (claims.source !== undefined && claims.source !== 'orbi')
417
+ return null;
418
+ return {
419
+ ...personOf({ ...claims, sub: claims.sub }),
420
+ source: 'orbi',
421
+ environment,
422
+ ...(claims.act?.sub ? { viewedBy: claims.act.sub } : {}),
423
+ };
424
+ }
154
425
  return {
155
426
  /** The app as Orbi knows it: its client id, name and whether its key is live or a developer's. */
156
427
  app() {
@@ -161,12 +432,49 @@ function createOrbiClient(options = {}) {
161
432
  return collectionOf(appAuth, name);
162
433
  },
163
434
  /**
164
- * Document extraction (plan 33.9): a file and the fields to read, a value and a confidence per
435
+ * Document extraction: a file and the fields to read, a value and a confidence per
165
436
  * field back. With no credit left it throws `app.extract_no_credits`: keep the record for a
166
437
  * person. The file is not kept by Orbi.
167
438
  */
168
439
  extract,
169
- /** Sign-in with Orbi (plan 33.7): the authorization code flow with PKCE and DPoP. */
440
+ files,
441
+ events,
442
+ agents,
443
+ actions,
444
+ /**
445
+ * Vectors for texts from Orbi's own model (`orbi.embed` in the manifest), 768 numbers each,
446
+ * to keep in the app's Postgres for similarity search. At most 64 texts a call.
447
+ */
448
+ embed(texts) {
449
+ return call(appAuth, '/v1/embed', 'POST', { texts });
450
+ },
451
+ /**
452
+ * The resources picked for the app in Orbi's picker (`openPicker` in `@orbiworkspace/sdk/browser`).
453
+ * With the app's own key only what the app itself was given; `asUser` adds the person's picks.
454
+ */
455
+ grants: {
456
+ list(kind) {
457
+ return call(appAuth, `/v1/grants?kind=${encodeURIComponent(kind)}`);
458
+ },
459
+ },
460
+ /**
461
+ * Models through Orbi's model gateway (`"ai": { "via": "orbi" }` in the manifest): `client()`
462
+ * for a provider SDK, `chat()` for one answer, `agent()` for a small tool loop. The spending
463
+ * counts against the app's monthly credit cap.
464
+ */
465
+ ai: (0, ai_1.createAi)({ fetch: doFetch }),
466
+ /**
467
+ * For the app's own agent (`orbi.mcp` in the manifest): Orbi's MCP address, whose tools are the
468
+ * collections the manifest names, and the app's own short-lived token. The token can do what
469
+ * the app may, so give it only to an agent the app trusts; ask again before `expiresAt`.
470
+ */
471
+ mcp: {
472
+ async connection() {
473
+ const value = await accessToken();
474
+ return { url: `${url}/v1/mcp`, headers: { Authorization: `Bearer ${value}` }, expiresAt: token?.renewAt ?? Date.now() };
475
+ },
476
+ },
477
+ /** Sign-in with Orbi: the authorization code flow with PKCE and DPoP. */
170
478
  signIn: {
171
479
  /** The address to send the person to, and what to keep until they come back. */
172
480
  async start(opts) {
@@ -185,19 +493,65 @@ function createOrbiClient(options = {}) {
185
493
  const body = (await postToken({ grant_type: 'authorization_code', code: opts.code, redirect_uri: opts.redirectUri, code_verifier: opts.codeVerifier }, { DPoP: await dpopProof(dpopKey, 'POST', tokenUrl) }));
186
494
  const claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(body.id_token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))));
187
495
  return {
188
- user: { sub: claims.sub, ...(claims.name ? { name: claims.name } : {}), ...(claims.email ? { email: claims.email } : {}) },
496
+ user: personOf(claims),
189
497
  session: { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + body.expires_in * 1000, dpopKey },
190
498
  };
191
499
  },
192
500
  },
193
501
  /**
194
- * The client on behalf of a signed-in person: every call carries a DPoP proof, reaches only
195
- * what both the app and the person may, and renews the session before it runs out.
502
+ * Who called, on an app Orbi Apps hosts: the gate signs the person into every
503
+ * request it lets through. Null when the request did not come through the gate or its token is
504
+ * not this app's, altered or expired; the app needs no sign-in page of its own.
505
+ */
506
+ async userFromRequest(req) {
507
+ return verifyIdentity(headerOf(req, exports.IDENTITY_HEADER));
508
+ },
509
+ /**
510
+ * Middleware for Express, Nest and Node: the request goes on with `req.orbiUser` set, or is
511
+ * answered 401 when no person came through the gate.
196
512
  */
197
- asUser(session, opts = {}) {
513
+ requireUser() {
514
+ return (req, res, next) => {
515
+ verifyIdentity(headerOf(req, exports.IDENTITY_HEADER)).then((user) => {
516
+ if (!user) {
517
+ res.statusCode = 401;
518
+ res.setHeader('content-type', 'application/json');
519
+ res.end(JSON.stringify({ code: 'orbi.identity_missing', message: 'Open this app through Orbi' }));
520
+ return;
521
+ }
522
+ req.orbiUser = user;
523
+ next();
524
+ }, (err) => next(err));
525
+ };
526
+ },
527
+ /**
528
+ * The client on behalf of a person: every call carries a DPoP proof, reaches only what both
529
+ * the app and the person may, and renews the session before it runs out. Give it the session
530
+ * from sign-in, or, on an app Orbi Apps hosts, the request itself.
531
+ */
532
+ asUser(from, opts = {}) {
533
+ // A request from the gate carries the person's identity token; it is traded for a
534
+ // session on the first call, with a DPoP key made here.
535
+ const request = 'headers' in from ? from : null;
536
+ const session = request ? { accessToken: '', refreshToken: '', expiresAt: 0, dpopKey: {} } : from;
198
537
  let refreshing = null;
199
538
  const refresh = async () => {
200
539
  const tokenUrl = `${url}/v1/oauth/token`;
540
+ if (request && !session.refreshToken) {
541
+ const pair = await globalThis.crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
542
+ session.dpopKey = await globalThis.crypto.subtle.exportKey('jwk', pair.privateKey);
543
+ const subject = headerOf(request, exports.IDENTITY_HEADER);
544
+ if (!subject)
545
+ throw new OrbiError('sdk.identity_missing', 401, 'The request carries no Orbi identity; it did not come through the Orbi Apps gate');
546
+ // Orbi refuses the trade for a guest anyway; saying so here names the reason.
547
+ if (sourceOf(subject) === 'external')
548
+ throw new OrbiError('sdk.guest_no_session', 403, 'The request is a guest\'s; an app acts only on behalf of Orbi members');
549
+ const traded = (await postToken({ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', subject_token: subject, subject_token_type: IDENTITY_SUBJECT_TYPE }, { DPoP: await dpopProof(session.dpopKey, 'POST', tokenUrl) }));
550
+ session.accessToken = traded.access_token;
551
+ session.refreshToken = traded.refresh_token;
552
+ session.expiresAt = Date.now() + traded.expires_in * 1000;
553
+ return;
554
+ }
201
555
  const body = (await postToken({ grant_type: 'refresh_token', refresh_token: session.refreshToken }, { DPoP: await dpopProof(session.dpopKey, 'POST', tokenUrl) }));
202
556
  session.accessToken = body.access_token;
203
557
  session.refreshToken = body.refresh_token;
@@ -227,6 +581,49 @@ function createOrbiClient(options = {}) {
227
581
  me() {
228
582
  return call(userAuth, '/v1/oauth/userinfo', 'GET', undefined, expire);
229
583
  },
584
+ /**
585
+ * Cards on the boards picked for the app, within what the person sees and may
586
+ * write. The manifest asks for `orbi.tasks` (`read`, or `create` to open cards too). There
587
+ * is no app-key version: whose reach bounds the cards is always a person's.
588
+ */
589
+ tasks: {
590
+ search(q, opts = {}) {
591
+ const qs = new URLSearchParams({ q, ...(opts.board ? { board: opts.board } : {}), ...(opts.limit ? { limit: String(opts.limit) } : {}) });
592
+ return call(userAuth, `/v1/tasks/search?${qs.toString()}`, 'GET', undefined, expire);
593
+ },
594
+ get(number) {
595
+ return call(userAuth, `/v1/tasks/${number}`, 'GET', undefined, expire);
596
+ },
597
+ /** Opens a card on a picked board, tagged with the app's name. A preview opens nothing and answers the card it would open. */
598
+ create(input) {
599
+ return call(userAuth, '/v1/tasks', 'POST', input, expire);
600
+ },
601
+ },
602
+ /**
603
+ * People outside the workspace, let into one resource (a meeting) on this person's behalf.
604
+ * The manifest names where guests may go (`orbi.guests.paths`). Orbi sends the invitation
605
+ * and checks who the guest is; letting them in is the app's. A preview mails nothing: the
606
+ * invitation lands in the preview inbox on the app's page. The live e-mail is Orbi's: the
607
+ * app may add the occasion (`title`, `startsAt`, `endsAt`, which also make a calendar file)
608
+ * and a plain `note` of at most 300 characters without links.
609
+ */
610
+ guests: {
611
+ invite(input) {
612
+ return call(userAuth, '/v1/guests', 'POST', input, expire);
613
+ },
614
+ list(opts = {}) {
615
+ return call(userAuth, opts.resource ? `/v1/guests?resource=${encodeURIComponent(opts.resource)}` : '/v1/guests', 'GET', undefined, expire);
616
+ },
617
+ async revoke(id) {
618
+ await call(userAuth, `/v1/guests/${encodeURIComponent(id)}`, 'DELETE', undefined, expire);
619
+ },
620
+ },
621
+ /** The person's own picks and the app's, each one they still see. */
622
+ grants: {
623
+ list(kind) {
624
+ return call(userAuth, `/v1/grants?kind=${encodeURIComponent(kind)}`, 'GET', undefined, expire);
625
+ },
626
+ },
230
627
  };
231
628
  },
232
629
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbiworkspace/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "TypeScript SDK for Orbi's public API: an app reads Orbi's data with its approved permissions.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://orbiwork.space",
@@ -16,6 +16,24 @@
16
16
  },
17
17
  "main": "./dist/index.js",
18
18
  "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./browser": {
25
+ "types": "./dist/browser.d.ts",
26
+ "default": "./dist/browser.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "typesVersions": {
31
+ "*": {
32
+ "browser": [
33
+ "./dist/browser.d.ts"
34
+ ]
35
+ }
36
+ },
19
37
  "files": [
20
38
  "dist",
21
39
  "README.md"