@orbiworkspace/sdk 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @orbiworkspace/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
+ TypeScript SDK for Orbi's public API. An app connected on Orbi's **Apps** page reads the collections
4
+ its approved `orbi.manifest` names.
5
+
6
+ ```bash
7
+ npm install @orbiworkspace/sdk
8
+ ```
9
+
10
+ ```ts
11
+ import { createOrbiClient } from '@orbiworkspace/sdk';
12
+
13
+ // ORBI_URL and ORBI_APP_KEY come from the environment.
14
+ const orbi = createOrbiClient();
15
+ const { items } = await orbi.collection('Receipts').list({ limit: 20 });
16
+ await orbi.collection('Expense reports').create({ month: '2026-11', total: 1250 });
17
+ ```
18
+
19
+ From plain JavaScript the package is CommonJS: `const { createOrbiClient } = require('@orbiworkspace/sdk')`,
20
+ or `import` from an ES module. On Orbi Apps, Orbi sets `ORBI_URL`,
21
+ `ORBI_PUBLIC_URL` and `ORBI_APP_KEY` itself.
22
+
23
+ A development key reads real data, but a collection its manifest may write is read and written in
24
+ the developer's own shadow, so trying the app never changes real records. The live key, given by an
25
+ admin, works on the real collections with the app's approved permissions. A call outside the manifest fails with `OrbiError` code
26
+ `app.permission_missing`.
27
+
28
+ ## Reading documents
29
+
30
+ With \`orbi.extraction\` in the manifest, \`extract\` reads the fields you ask for from a document
31
+ (PDF, image, DOCX, XLSX or text, at most 10 MB) and answers each with a value and a confidence:
32
+
33
+ \`\`\`ts
34
+ const result = await orbi.extract({
35
+ file, filename: 'receipt.jpg', mimeType: 'image/jpeg',
36
+ fields: [{ name: 'total', type: 'number', required: true }, { name: 'date', type: 'date' }],
37
+ });
38
+ if (result.needsReview) {
39
+ // a field is below 0.8 confidence, or a required one is empty: let a person confirm
40
+ }
41
+ \`\`\`
42
+
43
+ It spends the workspace's credits; with none left it throws \`OrbiError\` with code
44
+ \`app.extract_no_credits\`.
45
+
46
+ ## Sign in with Orbi
47
+
48
+ ```ts
49
+ const start = await orbi.signIn.start({ redirectUri: 'https://report.example.com/callback' });
50
+ // Redirect the person to start.url; keep start.codeVerifier and start.state in their session.
51
+ const { user, session } = await orbi.signIn.finish({ code, redirectUri, codeVerifier: start.codeVerifier });
52
+ const receipts = await orbi.asUser(session).collection('Receipts').list();
53
+ ```
54
+
55
+ Calls on behalf of a person carry a DPoP proof and reach only what both the app and the person may.
56
+
57
+ Licensed under Apache-2.0.
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
+ }