@ateam-ai-mobile/core 0.1.31 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +77 -3
- package/dist/index.d.ts +77 -3
- package/dist/index.js +121 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +118 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/chat/attachments.ts +139 -0
- package/src/chat/store.ts +18 -4
- package/src/chat/types.ts +2 -0
- package/src/config.ts +4 -1
- package/src/index.ts +6 -0
- package/src/storage/types.ts +57 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ateam-ai-mobile/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.33",
|
|
4
4
|
"description": "Headless ADAS SDK core — auth bridge, API client, chat/job streaming, MCP calls, theme tokens. No UI, no Expo dependencies.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning the attachments a user staged into what `POST /api/chat` takes.
|
|
3
|
+
*
|
|
4
|
+
* A file given by `uri` is uploaded first, as the raw request body of `POST /api/artifacts` (the same contract as the web
|
|
5
|
+
* client's uploadArtifact.js: `Content-Type: application/octet-stream`, the real type in `?mimeType=`, the name in `?name=`,
|
|
6
|
+
* the bearer token as the credential). Core stores it (up to 90 MiB) and answers `{ hash }`; the chat message then names the
|
|
7
|
+
* file by that hash. Nothing big ever rides inside the chat JSON.
|
|
8
|
+
*
|
|
9
|
+
* An OLD Core has no raw path: it parses the body as JSON and answers 400. For a file that still fits the old 10 MB base64
|
|
10
|
+
* path the attachment is then sent inline exactly as before; a bigger one fails with a plain message.
|
|
11
|
+
*/
|
|
12
|
+
import { getConfig, getCoreApiUrl, getToken, refreshToken, notifyAuthFailure } from '../config';
|
|
13
|
+
import { MAX_ATTACHMENT_BYTES, MAX_INLINE_ATTACHMENT_BYTES } from '../storage/types';
|
|
14
|
+
import type { OutgoingAttachment, FileUploader } from '../storage/types';
|
|
15
|
+
|
|
16
|
+
/** One attachment as `/api/chat` takes it: a stored file by hash, or small inline base64. */
|
|
17
|
+
export type WireAttachment =
|
|
18
|
+
| { hash: string; name: string; mimeType: string }
|
|
19
|
+
| { data: string; mimeType: string; name: string };
|
|
20
|
+
|
|
21
|
+
const mb = (bytes: number) => Math.round(bytes / 1024 / 1024);
|
|
22
|
+
|
|
23
|
+
/** base64 length of `bytes` raw bytes. */
|
|
24
|
+
const base64Length = (bytes: number) => Math.ceil(bytes / 3) * 4;
|
|
25
|
+
|
|
26
|
+
/** The most base64 characters all inline attachments of ONE message may add (see MAX_INLINE_ATTACHMENT_BYTES). */
|
|
27
|
+
const MAX_INLINE_CHARS = base64Length(MAX_INLINE_ATTACHMENT_BYTES);
|
|
28
|
+
|
|
29
|
+
function tooLarge(name: string): Error {
|
|
30
|
+
return new Error(`"${name}" is too large (max ${mb(MAX_ATTACHMENT_BYTES)} MB)`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function errorFrom(status: number, body: string, name: string): Error {
|
|
34
|
+
let message = '';
|
|
35
|
+
try { message = String(JSON.parse(body)?.error || ''); } catch { /* an HTML error page from a proxy */ }
|
|
36
|
+
if (status === 413) {
|
|
37
|
+
// Core's own 413 is JSON with the real limit; an nginx 413 (an old Core stops at 20 MB) is HTML and names nothing.
|
|
38
|
+
return new Error(message || `This server can't take files this big yet ("${name}")`);
|
|
39
|
+
}
|
|
40
|
+
if (status === 429) return new Error(message || 'Too many uploads: wait a moment and try again');
|
|
41
|
+
return new Error(message || `The upload of "${name}" failed (${status})`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function sendRaw(
|
|
45
|
+
uploader: FileUploader,
|
|
46
|
+
att: OutgoingAttachment,
|
|
47
|
+
onProgress: (fraction: number) => void,
|
|
48
|
+
): Promise<{ status: number; body: string }> {
|
|
49
|
+
const query = new URLSearchParams({ mimeType: att.mimeType || 'application/octet-stream', name: att.name || 'upload' });
|
|
50
|
+
const url = `${getCoreApiUrl()}/api/artifacts?${query.toString()}`;
|
|
51
|
+
const attempt = () => {
|
|
52
|
+
const token = getToken();
|
|
53
|
+
return uploader.upload({
|
|
54
|
+
url,
|
|
55
|
+
uri: att.uri as string,
|
|
56
|
+
headers: {
|
|
57
|
+
'Content-Type': 'application/octet-stream',
|
|
58
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
59
|
+
},
|
|
60
|
+
onProgress,
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
let res = await attempt();
|
|
64
|
+
if (res.status === 401 && getToken()) {
|
|
65
|
+
// Same semantics as apiFetch: refresh once and retry; only a dead session signs the user out.
|
|
66
|
+
const outcome = await refreshToken();
|
|
67
|
+
if (outcome.ok === 'ok') {
|
|
68
|
+
res = await attempt();
|
|
69
|
+
if (res.status === 401 || res.status === 403) {
|
|
70
|
+
notifyAuthFailure();
|
|
71
|
+
throw new Error('Session expired: sign in again to upload this file');
|
|
72
|
+
}
|
|
73
|
+
} else if (outcome.ok === 'auth_failed') {
|
|
74
|
+
notifyAuthFailure();
|
|
75
|
+
throw new Error('Session expired: sign in again to upload this file');
|
|
76
|
+
} else {
|
|
77
|
+
// A temporary failure (network, 5xx): the session is fine, the person can simply try again.
|
|
78
|
+
throw new Error('Could not reach the server to refresh your sign-in: check your connection and try again');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return res;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** `budget.chars` is what the message may still add inline; it is spent here when this file goes inline. */
|
|
85
|
+
async function uploadOne(att: OutgoingAttachment, onProgress: (fraction: number) => void, budget: { chars: number }): Promise<WireAttachment> {
|
|
86
|
+
const name = att.name || 'attachment';
|
|
87
|
+
if (att.data !== undefined) return { data: att.data, mimeType: att.mimeType, name: att.name };
|
|
88
|
+
if (!att.uri) throw new Error(`The attachment "${name}" has no file to send`);
|
|
89
|
+
if (att.size !== undefined && att.size > MAX_ATTACHMENT_BYTES) throw tooLarge(name);
|
|
90
|
+
|
|
91
|
+
const uploader = getConfig().fileUploader;
|
|
92
|
+
if (!uploader) throw new Error('This app cannot upload files yet: initAdas needs a fileUploader');
|
|
93
|
+
|
|
94
|
+
const res = await sendRaw(uploader, att, onProgress);
|
|
95
|
+
if (res.status >= 200 && res.status < 300) {
|
|
96
|
+
let parsed: { ok?: boolean; hash?: string; mimeType?: string } | null = null;
|
|
97
|
+
try { parsed = JSON.parse(res.body); } catch { /* fall through to the error below */ }
|
|
98
|
+
if (parsed?.ok && typeof parsed.hash === 'string') {
|
|
99
|
+
onProgress(1);
|
|
100
|
+
return { hash: parsed.hash, name: att.name, mimeType: parsed.mimeType || att.mimeType };
|
|
101
|
+
}
|
|
102
|
+
throw errorFrom(res.status, res.body, name);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (res.status === 400) {
|
|
106
|
+
// An old Core: POST /api/artifacts does not know a raw body. Fall back to base64 in the chat JSON, if it fits.
|
|
107
|
+
// Decide from the SIZE, before a byte is read: Core's 10 MB limit covers the whole chat body, all attachments together.
|
|
108
|
+
const size = att.size !== undefined ? att.size : await uploader.fileSize?.(att.uri);
|
|
109
|
+
if (size === undefined) {
|
|
110
|
+
throw new Error(`Cannot tell how big "${name}" is, and this server cannot take large files yet`);
|
|
111
|
+
}
|
|
112
|
+
if (base64Length(size) > budget.chars) {
|
|
113
|
+
throw new Error(`"${name}" is too big for this server, which cannot take more than ${mb(MAX_INLINE_ATTACHMENT_BYTES)} MB of files in one message yet`);
|
|
114
|
+
}
|
|
115
|
+
const data = await uploader.readBase64(att.uri);
|
|
116
|
+
budget.chars -= data.length;
|
|
117
|
+
onProgress(1);
|
|
118
|
+
return { data, mimeType: att.mimeType, name: att.name };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
throw errorFrom(res.status, res.body, name);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Upload what needs uploading and return the attachments as `/api/chat` takes them, in order.
|
|
126
|
+
* `onProgress` is the overall fraction 0..1 across all attachments.
|
|
127
|
+
*/
|
|
128
|
+
export async function prepareAttachments(
|
|
129
|
+
attachments: OutgoingAttachment[],
|
|
130
|
+
onProgress?: (fraction: number) => void,
|
|
131
|
+
): Promise<WireAttachment[]> {
|
|
132
|
+
// Inline attachments already in the message use up the old path's budget before any fallback does.
|
|
133
|
+
const budget = { chars: MAX_INLINE_CHARS - attachments.reduce((n, a) => n + (a.data !== undefined ? a.data.length : 0), 0) };
|
|
134
|
+
const out: WireAttachment[] = [];
|
|
135
|
+
for (let i = 0; i < attachments.length; i++) {
|
|
136
|
+
out.push(await uploadOne(attachments[i], f => onProgress?.((i + f) / attachments.length), budget));
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
package/src/chat/store.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { getCoreApiUrl, openCoreWs, getToken, getTenant, getUser, getConfig } fr
|
|
|
16
16
|
import { pluginCommandEmitter } from '../utils/emitter';
|
|
17
17
|
import { focusPlugin } from '../utils/hostIntents';
|
|
18
18
|
import type { OutgoingAttachment } from '../storage/types';
|
|
19
|
+
import { prepareAttachments } from './attachments';
|
|
19
20
|
import type { Message, MessageAttachment, JobProgress, UIAction } from './types';
|
|
20
21
|
|
|
21
22
|
// ---------------------------------------------------------------------------
|
|
@@ -494,8 +495,12 @@ export const useChatStore = create<ChatState>((set, get) => ({
|
|
|
494
495
|
attachments: attachments.map(a => ({
|
|
495
496
|
mimeType: a.mimeType,
|
|
496
497
|
name: a.name,
|
|
497
|
-
|
|
498
|
-
|
|
498
|
+
// An image on the phone previews from its own file; an inline one from its base64.
|
|
499
|
+
previewUri: !a.mimeType.startsWith('image/') ? undefined
|
|
500
|
+
: a.data !== undefined ? `data:${a.mimeType};base64,${a.data}` : a.uri,
|
|
501
|
+
})),
|
|
502
|
+
// A file on the phone is uploaded before the message is posted: the bubble shows how far along it is.
|
|
503
|
+
...(attachments.some(a => a.uri && a.data === undefined) ? { uploadProgress: 0 } : {}),
|
|
499
504
|
} : {}),
|
|
500
505
|
};
|
|
501
506
|
|
|
@@ -518,7 +523,16 @@ export const useChatStore = create<ChatState>((set, get) => ({
|
|
|
518
523
|
},
|
|
519
524
|
};
|
|
520
525
|
if (skillSlug) body.skillSlug = skillSlug;
|
|
521
|
-
if (attachments?.length)
|
|
526
|
+
if (attachments?.length) {
|
|
527
|
+
// Files on the phone go up first (raw body, POST /api/artifacts); the chat names them by hash.
|
|
528
|
+
let shown = 0;
|
|
529
|
+
body.attachments = await prepareAttachments(attachments, f => {
|
|
530
|
+
if (f - shown < 0.01 && f < 1) return;
|
|
531
|
+
shown = f;
|
|
532
|
+
set(s => ({ messages: s.messages.map(m => (m.id === userMsg.id && m.uploadProgress !== undefined ? { ...m, uploadProgress: f } : m)) }));
|
|
533
|
+
});
|
|
534
|
+
set(s => ({ messages: s.messages.map(m => (m.id === userMsg.id ? { ...m, uploadProgress: undefined } : m)) }));
|
|
535
|
+
}
|
|
522
536
|
|
|
523
537
|
const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
|
|
524
538
|
method: 'POST',
|
|
@@ -610,7 +624,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
|
|
|
610
624
|
streamJob(jobId, getTenant(), getToken());
|
|
611
625
|
} catch (err: any) {
|
|
612
626
|
set(s => ({
|
|
613
|
-
messages: [...s.messages, {
|
|
627
|
+
messages: [...s.messages.map(m => (m.id === userMsg.id && m.uploadProgress !== undefined ? { ...m, uploadProgress: undefined } : m)), {
|
|
614
628
|
id: `error-${Date.now()}`,
|
|
615
629
|
role: 'system' as const,
|
|
616
630
|
content: `Error: ${err.message}`,
|
package/src/chat/types.ts
CHANGED
|
@@ -72,6 +72,8 @@ export interface Message {
|
|
|
72
72
|
skillSlug?: string;
|
|
73
73
|
/** Attached images/files */
|
|
74
74
|
attachments?: MessageAttachment[];
|
|
75
|
+
/** 0..1 while this message's files are still uploading; absent once they are stored and the message is posted. */
|
|
76
|
+
uploadProgress?: number;
|
|
75
77
|
/** UI Action chips beneath assistant bubbles */
|
|
76
78
|
actions?: UIAction[];
|
|
77
79
|
/** Chain id from /api/conversation — used to attach live progress to the
|
package/src/config.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* too, and a second tenant/backend inside one app is not a supported v1 case.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import type { AttachmentCache } from './storage/types';
|
|
11
|
+
import type { AttachmentCache, FileUploader } from './storage/types';
|
|
12
12
|
import { tenantFromToken } from './jwt';
|
|
13
13
|
|
|
14
14
|
/** Result of a host-driven token refresh. Mirrors the semantics the API
|
|
@@ -74,6 +74,9 @@ export interface AdasConfig {
|
|
|
74
74
|
* survive app restarts. No-op when omitted (previews live in memory for
|
|
75
75
|
* the session only). @ateam-ai-mobile/ui ships an Expo/RN implementation. */
|
|
76
76
|
attachmentCache?: AttachmentCache;
|
|
77
|
+
/** Moves an attachment's bytes for `sendMessage` (raw upload of a file `uri`). Required to attach a file by `uri`;
|
|
78
|
+
* without it only base64 `data` attachments can be sent. `@ateam-ai-mobile/expo` ships `expoFileUploader`. */
|
|
79
|
+
fileUploader?: FileUploader;
|
|
77
80
|
/** Called by `switchTenant()` with the freshly-minted session for the
|
|
78
81
|
* target tenant. The host MUST persist it here (store the new JWT so
|
|
79
82
|
* tokenProvider.getToken() returns it, and update the active tenant) —
|
package/src/index.ts
CHANGED
|
@@ -163,7 +163,13 @@ export type {
|
|
|
163
163
|
AttachmentCache,
|
|
164
164
|
AttachmentPreview,
|
|
165
165
|
OutgoingAttachment,
|
|
166
|
+
UploadedArtifact,
|
|
167
|
+
FileUploader,
|
|
168
|
+
FileUploadRequest,
|
|
166
169
|
} from './storage/types';
|
|
170
|
+
export { MAX_ATTACHMENT_BYTES, MAX_INLINE_ATTACHMENT_BYTES } from './storage/types';
|
|
171
|
+
export { prepareAttachments } from './chat/attachments';
|
|
172
|
+
export type { WireAttachment } from './chat/attachments';
|
|
167
173
|
|
|
168
174
|
// Plugin command bus
|
|
169
175
|
export { pluginCommandEmitter, PluginCommandEmitter } from './utils/emitter';
|
package/src/storage/types.ts
CHANGED
|
@@ -3,11 +3,65 @@
|
|
|
3
3
|
* AsyncStorage imports) — hosts or @ateam-ai-mobile/ui plug in concrete implementations.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
/**
|
|
6
|
+
/** The most Core stores for one file (Core's MAX_ARTIFACT_BYTES, 90 MiB: Cloudflare allows 100 MB a request). */
|
|
7
|
+
export const MAX_ATTACHMENT_BYTES = 90 * 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* What the old base64-in-JSON path may carry in ONE chat message, in raw bytes (all inline attachments together). Core's
|
|
11
|
+
* express.json limit is 10 MB for the WHOLE /api/chat body and base64 adds a third (7 MiB becomes ~9.3 MiB), which leaves
|
|
12
|
+
* headroom for the text and the rest of the JSON.
|
|
13
|
+
*/
|
|
14
|
+
export const MAX_INLINE_ATTACHMENT_BYTES = 7 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* An attachment the user staged, as handed to `sendMessage`.
|
|
18
|
+
*
|
|
19
|
+
* A file on the phone is given by `uri` (+ `size`): it is uploaded as the raw request body to `POST /api/artifacts`, and
|
|
20
|
+
* `/api/chat` then names it by hash, so a 90 MB file never rides inside JSON. `data` (base64) is the older shape, kept for
|
|
21
|
+
* small inline attachments and as the fallback when the server is too old to take a raw upload (it answers 400).
|
|
22
|
+
*/
|
|
7
23
|
export interface OutgoingAttachment {
|
|
8
|
-
data: string;
|
|
9
24
|
mimeType: string;
|
|
10
25
|
name: string;
|
|
26
|
+
/** Base64 payload (inline path). Absent when the file is given by `uri`. */
|
|
27
|
+
data?: string;
|
|
28
|
+
/** Local file URI the host's `fileUploader` can read (e.g. a file:// path). */
|
|
29
|
+
uri?: string;
|
|
30
|
+
/** Size in bytes of the file at `uri`; used to refuse an oversize file early and to decide the old-server fallback. */
|
|
31
|
+
size?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What `POST /api/artifacts` answers for a stored file. */
|
|
35
|
+
export interface UploadedArtifact {
|
|
36
|
+
hash: string;
|
|
37
|
+
size: number;
|
|
38
|
+
mimeType: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One raw upload the host's `FileUploader` performs. The SDK builds the URL and the headers; the host only moves the bytes. */
|
|
42
|
+
export interface FileUploadRequest {
|
|
43
|
+
/** Absolute `POST` URL, query included. */
|
|
44
|
+
url: string;
|
|
45
|
+
/** Headers to send as given (bearer + `Content-Type: application/octet-stream`). */
|
|
46
|
+
headers: Record<string, string>;
|
|
47
|
+
/** The local file to send as the request BODY (not multipart). */
|
|
48
|
+
uri: string;
|
|
49
|
+
/** 0..1 as the bytes go out. */
|
|
50
|
+
onProgress?: (fraction: number) => void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The host's file I/O for attachments: streaming a local file as a request body and reading a small one as base64. Core has
|
|
55
|
+
* no filesystem or native imports, so `@ateam-ai-mobile/expo` supplies the Expo implementation (`expoFileUploader`).
|
|
56
|
+
*/
|
|
57
|
+
export interface FileUploader {
|
|
58
|
+
/** Send the file at `req.uri` as the raw body; resolve with the HTTP status and body text (any status). Reject only on a transport failure. */
|
|
59
|
+
upload(req: FileUploadRequest): Promise<{ status: number; body: string }>;
|
|
60
|
+
/** Read a local file as base64 (the old-server fallback, files within MAX_INLINE_ATTACHMENT_BYTES). */
|
|
61
|
+
readBase64(uri: string): Promise<string>;
|
|
62
|
+
/** Size in bytes of a local file, or undefined when it cannot be told. Used only when an attachment came without `size`,
|
|
63
|
+
* before any fallback read: without it a file of unknown size is refused rather than read whole. */
|
|
64
|
+
fileSize?(uri: string): Promise<number | undefined>;
|
|
11
65
|
}
|
|
12
66
|
|
|
13
67
|
/** Attachment as rendered in a message bubble (local or remote preview URI). */
|
|
@@ -24,6 +78,7 @@ export interface AttachmentPreview {
|
|
|
24
78
|
export interface AttachmentCache {
|
|
25
79
|
/** Resolve once the index is loaded — get() before this may return undefined. */
|
|
26
80
|
ready(): Promise<void>;
|
|
81
|
+
/** Keep a preview of each attachment (the bytes come from `data` or are copied from `uri`). */
|
|
27
82
|
save(jobId: string, attachments: OutgoingAttachment[]): Promise<void>;
|
|
28
83
|
get(jobId: string): AttachmentPreview[] | undefined;
|
|
29
84
|
}
|