@ateam-ai-mobile/core 0.1.38 → 0.1.40
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 +52 -1
- package/dist/index.d.ts +52 -1
- package/dist/index.js +222 -34
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +216 -34
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/api/tenants.ts +2 -0
- package/src/chat/sideChat.ts +158 -0
- package/src/chat/sideChatPure.ts +59 -0
- package/src/chat/store.ts +5 -5
- package/src/chat/types.ts +2 -0
- package/src/index.ts +4 -0
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.40",
|
|
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",
|
package/src/api/tenants.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getConsumerAuthApiUrl, getToken, getConfig, type AdasSession } from '../config';
|
|
2
2
|
import { useChatStore, closeChatStream } from '../chat/store';
|
|
3
|
+
import { clearSideChats } from '../chat/sideChat';
|
|
3
4
|
|
|
4
5
|
export interface TenantMembership {
|
|
5
6
|
id: string;
|
|
@@ -136,6 +137,7 @@ export async function switchTenant(targetTenantId: string): Promise<AdasSession>
|
|
|
136
137
|
// against the new tenant on its next mount / loadConversation().
|
|
137
138
|
closeChatStream();
|
|
138
139
|
useChatStore.getState().clearChat();
|
|
140
|
+
clearSideChats();
|
|
139
141
|
|
|
140
142
|
return session;
|
|
141
143
|
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Side chat store — one per (workspace, page).
|
|
3
|
+
*
|
|
4
|
+
* A side chat is the person's ONE conversation seen through a topic (Docs/WIDGET_PROTOCOL.md, `open-side-chat`):
|
|
5
|
+
* - send → POST /api/chat, an ordinary chat turn whose triggerContext.pageContext is { page, chat: "page" }, which
|
|
6
|
+
* is how Core tags the turn with the page as its TOPIC and gives those turns their seats first;
|
|
7
|
+
* - open → GET /api/conversation?topic=<page id>, the turns said in this chat before.
|
|
8
|
+
* Same endpoints and rules as the web SideChatWindow; the job is followed by reading its status (no second socket), and its
|
|
9
|
+
* live line (humanStatus, liveProgress) comes from the same snapshot reader as the main chat.
|
|
10
|
+
*/
|
|
11
|
+
import { create } from 'zustand';
|
|
12
|
+
import type { StoreApi, UseBoundStore } from 'zustand';
|
|
13
|
+
import { getCoreApiUrl, getTenant, getUser } from '../config';
|
|
14
|
+
import { blocksToText } from './blockText';
|
|
15
|
+
import { coreHeaders, snapshotToProgress, isTerminalSnapshot, normalizeJobStatus, blocksToAttachments } from './store';
|
|
16
|
+
import { mergeSideChatHistory } from './sideChatPure';
|
|
17
|
+
import type { Message, JobProgress } from './types';
|
|
18
|
+
|
|
19
|
+
const HISTORY_TURNS = 20;
|
|
20
|
+
|
|
21
|
+
export interface SideChatState {
|
|
22
|
+
pageId: string;
|
|
23
|
+
messages: Message[];
|
|
24
|
+
/** A turn of this chat is running: Send waits (the web window does the same). */
|
|
25
|
+
loading: boolean;
|
|
26
|
+
loaded: boolean;
|
|
27
|
+
load: () => Promise<void>;
|
|
28
|
+
send: (text: string) => Promise<boolean>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type SideChatStore = UseBoundStore<StoreApi<SideChatState>>;
|
|
32
|
+
const stores = new Map<string, SideChatStore>();
|
|
33
|
+
|
|
34
|
+
/** The side chat for this page in the current workspace; reopened chats keep a running turn. */
|
|
35
|
+
export function getSideChatStore(pageId: string): SideChatStore {
|
|
36
|
+
const key = `${getTenant()}\u0000${pageId}`;
|
|
37
|
+
let s = stores.get(key);
|
|
38
|
+
if (!s) { s = createSideChatStore(pageId); stores.set(key, s); }
|
|
39
|
+
return s;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Forget every side chat (sign-out, workspace or environment switch). */
|
|
43
|
+
export function clearSideChats(): void { stores.clear(); }
|
|
44
|
+
|
|
45
|
+
function turnToMessages(turn: any): Message[] {
|
|
46
|
+
const out: Message[] = [];
|
|
47
|
+
const chainId = typeof turn?.chainId === 'string' ? turn.chainId : undefined;
|
|
48
|
+
const base = turn?.jobId || turn?.chainId || `${turn?.startedAt || Date.now()}`;
|
|
49
|
+
const userText = blocksToText(turn?.user?.blocks);
|
|
50
|
+
const userAtts = blocksToAttachments(turn?.user?.blocks);
|
|
51
|
+
if (userText || userAtts) {
|
|
52
|
+
out.push({ id: `user-${base}`, role: 'user', content: userText || '', timestamp: new Date(turn.startedAt || Date.now()), ...(userAtts ? { attachments: userAtts } : {}), ...(chainId ? { chainId } : {}) });
|
|
53
|
+
}
|
|
54
|
+
const answer = blocksToText(turn?.assistant?.blocks);
|
|
55
|
+
const actions = Array.isArray(turn?.assistant?.actions) && turn.assistant.actions.length ? turn.assistant.actions : undefined;
|
|
56
|
+
if (answer || actions) {
|
|
57
|
+
out.push({ id: `bot-${base}`, role: 'assistant', content: answer || '', timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), skillSlug: turn.skillSlug, ...(actions ? { actions } : {}), ...(chainId ? { chainId } : {}) });
|
|
58
|
+
} else if (turn?.status === 'failed') {
|
|
59
|
+
out.push({ id: `err-${base}`, role: 'system', content: turn.failReason || 'This turn failed.', timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), ...(chainId ? { chainId } : {}) });
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createSideChatStore(pageId: string): SideChatStore {
|
|
65
|
+
return create<SideChatState>((set, get) => {
|
|
66
|
+
const local = (m: Omit<Message, 'local'>): Message => ({ ...m, local: true });
|
|
67
|
+
const patchJob = (jobId: string, p: Partial<JobProgress>) =>
|
|
68
|
+
set(s => ({ messages: s.messages.map(m => (m.jobProgress?.jobId === jobId ? { ...m, jobProgress: { ...m.jobProgress, ...p } as JobProgress } : m)) }));
|
|
69
|
+
|
|
70
|
+
// Follow the job by reading its status until it ends (a hand-over keeps going), then read the saved turn.
|
|
71
|
+
async function follow(jobId: string, chainId: string) {
|
|
72
|
+
let ended: any = null;
|
|
73
|
+
for (let i = 0; !ended; i++) {
|
|
74
|
+
if (i > 0) await new Promise(r => setTimeout(r, i < 120 ? 1500 : 5000));
|
|
75
|
+
// The chat was cleared away (workspace switch): stop.
|
|
76
|
+
if (!get().messages.some(m => m.jobProgress?.jobId === jobId)) return;
|
|
77
|
+
try {
|
|
78
|
+
const res = await fetch(`${getCoreApiUrl()}/api/job/${encodeURIComponent(jobId)}/status`, { headers: coreHeaders() });
|
|
79
|
+
if (!res.ok) { if (res.status === 404) break; continue; }
|
|
80
|
+
const snap = await res.json();
|
|
81
|
+
const handoff = snap?.isHandoff || snap?.state?.handoffTransfer;
|
|
82
|
+
if (isTerminalSnapshot(snap) && !(normalizeJobStatus(snap) === 'done' && handoff)) ended = snap;
|
|
83
|
+
else patchJob(jobId, snapshotToProgress(snap, jobId));
|
|
84
|
+
} catch { /* a read failed: try again */ }
|
|
85
|
+
}
|
|
86
|
+
// The saved turn replaces the live bubble; give the server a moment to save it.
|
|
87
|
+
for (let t = 0; t < 5; t++) {
|
|
88
|
+
await get().load();
|
|
89
|
+
if (!get().messages.some(m => m.jobProgress?.jobId === jobId)) { set({ loading: false }); return; }
|
|
90
|
+
await new Promise(r => setTimeout(r, 800));
|
|
91
|
+
}
|
|
92
|
+
const failed = ended ? normalizeJobStatus(ended) === 'error' : false;
|
|
93
|
+
const fallback = ended?.result?.message || ended?.state?.finalReply || (failed ? 'Something went wrong. Please try again.' : 'Done.');
|
|
94
|
+
set(s => ({
|
|
95
|
+
loading: false,
|
|
96
|
+
messages: s.messages.map(m => (m.jobProgress?.jobId === jobId
|
|
97
|
+
? { ...m, id: `done-${jobId}`, content: fallback, jobProgress: { ...m.jobProgress, status: failed ? 'error' : 'done' } as JobProgress, chainId }
|
|
98
|
+
: m)),
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
pageId,
|
|
104
|
+
messages: [],
|
|
105
|
+
loading: false,
|
|
106
|
+
loaded: false,
|
|
107
|
+
|
|
108
|
+
load: async () => {
|
|
109
|
+
try {
|
|
110
|
+
const res = await fetch(`${getCoreApiUrl()}/api/conversation?topic=${encodeURIComponent(pageId)}&page_size=${HISTORY_TURNS}`, { headers: coreHeaders() });
|
|
111
|
+
if (!res.ok) { set({ loaded: true }); return; }
|
|
112
|
+
const json = await res.json();
|
|
113
|
+
const items: any[] = Array.isArray(json?.items) ? [...json.items].reverse() : [];
|
|
114
|
+
const seen = new Set<string>();
|
|
115
|
+
const saved = items.filter(t => { const k = t?.jobId; if (!k) return true; if (seen.has(k)) return false; seen.add(k); return true; }).flatMap(turnToMessages);
|
|
116
|
+
set(s => ({ messages: mergeSideChatHistory(saved, s.messages), loaded: true }));
|
|
117
|
+
} catch { set({ loaded: true }); }
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
send: async (text: string) => {
|
|
121
|
+
const t = text.trim();
|
|
122
|
+
if (!t || get().loading) return false;
|
|
123
|
+
const echo = local({ id: `user-${Date.now()}`, role: 'user', content: t, timestamp: new Date() });
|
|
124
|
+
set(s => ({ messages: [...s.messages, echo], loading: true }));
|
|
125
|
+
const fail = (msg: string) => set(s => ({ loading: false, messages: [...s.messages, local({ id: `error-${Date.now()}`, role: 'system', content: msg, timestamp: new Date() })] }));
|
|
126
|
+
try {
|
|
127
|
+
const actor = getUser();
|
|
128
|
+
const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
|
|
129
|
+
method: 'POST',
|
|
130
|
+
headers: coreHeaders(),
|
|
131
|
+
body: JSON.stringify({
|
|
132
|
+
goal: t,
|
|
133
|
+
triggerContext: {
|
|
134
|
+
channel: 'mobile',
|
|
135
|
+
replyContext: { chatId: actor?.actorId || 'unknown' },
|
|
136
|
+
pageContext: { page: pageId, chat: 'page' },
|
|
137
|
+
},
|
|
138
|
+
}),
|
|
139
|
+
});
|
|
140
|
+
const json = await res.json().catch(() => null);
|
|
141
|
+
const jobId = json?.jobId || json?.id;
|
|
142
|
+
if (!res.ok || !jobId) { fail(json?.error || `Could not start (${res.status}).`); return false; }
|
|
143
|
+
const chainId: string = json.job?.chainId || jobId; // what the saved turn is filed under
|
|
144
|
+
const bubble = local({
|
|
145
|
+
id: `job-${jobId}`, role: 'assistant', content: 'Working on it...', timestamp: new Date(), chainId,
|
|
146
|
+
jobProgress: { jobId, actorId: actor?.actorId, status: 'running', subStatus: 'Starting...', chainStartedAt: Date.now() },
|
|
147
|
+
});
|
|
148
|
+
set(s => ({ messages: [...s.messages.map(m => (m.id === echo.id ? { ...m, chainId } : m)), bubble] }));
|
|
149
|
+
void follow(jobId, chainId);
|
|
150
|
+
return true;
|
|
151
|
+
} catch (e: any) {
|
|
152
|
+
fail(`Request failed: ${e?.message || e}`);
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
});
|
|
158
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Side chat — the pure rules (no imports of the SDK, so they run under plain node tests).
|
|
3
|
+
*
|
|
4
|
+
* A builder's page asks for a side chat with the widget message `open-side-chat`. The look it may give the chat is
|
|
5
|
+
* cleaned here (same limits and shape as the web host: ai-dev-assistant packages/widget-surface/src/sideChatOptions.js),
|
|
6
|
+
* and the chat's saved turns are merged with the messages this phone sent that the server has not saved yet.
|
|
7
|
+
*/
|
|
8
|
+
import type { Message } from './types';
|
|
9
|
+
|
|
10
|
+
export const SIDE_CHAT_LIMITS = { title: 60, header: 40, welcome: 200, placeholder: 60 } as const;
|
|
11
|
+
const HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
|
12
|
+
|
|
13
|
+
export interface SideChatOptions {
|
|
14
|
+
title: string;
|
|
15
|
+
header: string;
|
|
16
|
+
welcome: string;
|
|
17
|
+
placeholder: string;
|
|
18
|
+
accent: string | null;
|
|
19
|
+
side: 'left' | 'right';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const text = (v: unknown, max: number): string =>
|
|
23
|
+
(typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '');
|
|
24
|
+
|
|
25
|
+
/** What the page asked for, cleaned: plain text cut to a length, one hex color, `left`/`right`. A widget is not trusted with markup. */
|
|
26
|
+
export function sideChatOptions(payload: unknown): SideChatOptions {
|
|
27
|
+
const p: any = payload && typeof payload === 'object' ? payload : {};
|
|
28
|
+
return {
|
|
29
|
+
title: text(p.title, SIDE_CHAT_LIMITS.title),
|
|
30
|
+
header: text(p.header, SIDE_CHAT_LIMITS.header),
|
|
31
|
+
welcome: text(p.welcome, SIDE_CHAT_LIMITS.welcome),
|
|
32
|
+
placeholder: text(p.placeholder, SIDE_CHAT_LIMITS.placeholder),
|
|
33
|
+
accent: typeof p.accent === 'string' && HEX.test(p.accent.trim()) ? p.accent.trim() : null,
|
|
34
|
+
side: p.side === 'left' ? 'left' : 'right',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const SHORT = new Set(['ui', 'ai', 'mcp', 'api', 'crm', 'sms', 'pa']);
|
|
39
|
+
const nameOf = (slug: string): string =>
|
|
40
|
+
slug.split(/[-_]+/).filter(Boolean)
|
|
41
|
+
.map(w => (SHORT.has(w.toLowerCase()) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1))).join(' ');
|
|
42
|
+
|
|
43
|
+
/** The words in the TOPIC tag: the title the page gave, else the last part of its page id ("mcp:crm:deal-board" → "Deal Board"). */
|
|
44
|
+
export function topicLabel(pageId: string, title?: string): string {
|
|
45
|
+
if (title) return title;
|
|
46
|
+
const last = String(pageId || '').split(':').pop() || '';
|
|
47
|
+
return nameOf(last) || 'Side chat';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The chat's messages: the server's saved turns (oldest first), then this phone's own messages of a turn the server does
|
|
52
|
+
* not hold yet. A local message carries `chainId`; it is dropped once a saved message of that chain is there. A local
|
|
53
|
+
* message with no chain (a send that never started, an error) stays. So a turn is drawn once.
|
|
54
|
+
*/
|
|
55
|
+
export function mergeSideChatHistory(saved: Message[], current: Message[]): Message[] {
|
|
56
|
+
const savedChains = new Set(saved.map(m => m.chainId).filter(Boolean) as string[]);
|
|
57
|
+
const keep = current.filter(m => m.local && !(m.chainId && savedChains.has(m.chainId)));
|
|
58
|
+
return [...saved, ...keep];
|
|
59
|
+
}
|
package/src/chat/store.ts
CHANGED
|
@@ -48,7 +48,7 @@ interface ChatState {
|
|
|
48
48
|
// Helpers
|
|
49
49
|
// ---------------------------------------------------------------------------
|
|
50
50
|
|
|
51
|
-
function coreHeaders(): Record<string, string> {
|
|
51
|
+
export function coreHeaders(): Record<string, string> {
|
|
52
52
|
const token = getToken();
|
|
53
53
|
const headers: Record<string, string> = {
|
|
54
54
|
'Content-Type': 'application/json',
|
|
@@ -62,7 +62,7 @@ function isTerminalStatus(status?: unknown): boolean {
|
|
|
62
62
|
return s === 'done' || s === 'error' || s === 'failed' || s === 'completed';
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
function normalizeJobStatus(snap: any): JobProgress['status'] {
|
|
65
|
+
export function normalizeJobStatus(snap: any): JobProgress['status'] {
|
|
66
66
|
const status = typeof snap?.status === 'string' ? snap.status.toLowerCase() : '';
|
|
67
67
|
if (status === 'done' || status === 'completed') return 'done';
|
|
68
68
|
if (status === 'error' || status === 'failed') return 'error';
|
|
@@ -115,7 +115,7 @@ function extractCurrentTool(state: any): string | undefined {
|
|
|
115
115
|
return (last?.tool || last?.phase) as string | undefined;
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
-
function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress> {
|
|
118
|
+
export function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress> {
|
|
119
119
|
const pq = extractPendingQuestion(snap);
|
|
120
120
|
const progress: Partial<JobProgress> = {
|
|
121
121
|
jobId: rootJobId,
|
|
@@ -148,13 +148,13 @@ function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress>
|
|
|
148
148
|
return progress;
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
-
function isTerminalSnapshot(snap: any): boolean {
|
|
151
|
+
export function isTerminalSnapshot(snap: any): boolean {
|
|
152
152
|
if (extractPendingQuestion(snap)) return false;
|
|
153
153
|
return snap?.done === true || isTerminalStatus(snap?.status);
|
|
154
154
|
}
|
|
155
155
|
|
|
156
156
|
/** Extract image/file attachments from conversation blocks */
|
|
157
|
-
function blocksToAttachments(blocks?: Array<{ kind: string; hash?: string; url?: string; mimeType?: string; name?: string }>): MessageAttachment[] | undefined {
|
|
157
|
+
export function blocksToAttachments(blocks?: Array<{ kind: string; hash?: string; url?: string; mimeType?: string; name?: string }>): MessageAttachment[] | undefined {
|
|
158
158
|
if (!blocks || blocks.length === 0) return undefined;
|
|
159
159
|
const atts: MessageAttachment[] = [];
|
|
160
160
|
for (const b of blocks) {
|
package/src/chat/types.ts
CHANGED
|
@@ -81,4 +81,6 @@ export interface Message {
|
|
|
81
81
|
chainId?: string;
|
|
82
82
|
/** Turn variant. 'notification' = proactive/system-initiated. */
|
|
83
83
|
kind?: 'notification' | string;
|
|
84
|
+
/** A side chat's own message this phone sent that the server has not saved yet (see chat/sideChat.ts). */
|
|
85
|
+
local?: boolean;
|
|
84
86
|
}
|
package/src/index.ts
CHANGED
|
@@ -147,6 +147,10 @@ export {
|
|
|
147
147
|
useChatStore,
|
|
148
148
|
closeChatStream,
|
|
149
149
|
} from './chat/store';
|
|
150
|
+
export { getSideChatStore, clearSideChats } from './chat/sideChat';
|
|
151
|
+
export type { SideChatState } from './chat/sideChat';
|
|
152
|
+
export { sideChatOptions, topicLabel, mergeSideChatHistory, SIDE_CHAT_LIMITS } from './chat/sideChatPure';
|
|
153
|
+
export type { SideChatOptions } from './chat/sideChatPure';
|
|
150
154
|
export {
|
|
151
155
|
blocksToText,
|
|
152
156
|
splitBlockSegments,
|