@ohoooho/taoxian-runtime-sdk 0.0.0-stage → 0.1.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/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +146 -2
- package/api-key-verifier.mjs +166 -0
- package/browser.mjs +101 -0
- package/examples/browser-mobile.mjs +14 -0
- package/examples/fenshen-express.mjs +27 -0
- package/fenshen.mjs +124 -0
- package/index.mjs +5 -0
- package/package.json +55 -4
- package/runtime-client.mjs +510 -0
- package/types/api-key.d.ts +40 -0
- package/types/browser.d.ts +29 -0
- package/types/fenshen.d.ts +37 -0
- package/types/index.d.ts +3 -0
- package/types/runtime.d.ts +144 -0
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
|
|
6
|
+
// Shared client for fenshen apps and agent bases. It intentionally knows only
|
|
7
|
+
// the Runtime contract: discovery, health, version compatibility and lifecycle
|
|
8
|
+
// commands. It never starts a second database or a second Runtime process.
|
|
9
|
+
export const RUNTIME_SERVICE_NAME = 'taoxian-runtime';
|
|
10
|
+
export const RUNTIME_API_VERSION = 1;
|
|
11
|
+
export const DEFAULT_RUNTIME_URL = 'http://127.0.0.1:4319';
|
|
12
|
+
export const DEFAULT_RUNTIME_HOME = path.join(os.homedir(), '.taoxian');
|
|
13
|
+
|
|
14
|
+
export class RuntimeUnavailableError extends Error {
|
|
15
|
+
constructor(message, cause) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'RuntimeUnavailableError';
|
|
18
|
+
this.code = 'runtime_unavailable';
|
|
19
|
+
this.cause = cause;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class RuntimeIncompatibleError extends Error {
|
|
24
|
+
constructor(message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = 'RuntimeIncompatibleError';
|
|
27
|
+
this.code = 'runtime_incompatible';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class RuntimeApiError extends Error {
|
|
32
|
+
constructor(message, { status = 0, code = 'runtime_api_error', body = null } = {}) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = 'RuntimeApiError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.body = body;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function trimUrl(value) {
|
|
42
|
+
return String(value || '').replace(/\/+$/, '');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function defaultRuntimeUrl(env = process.env) {
|
|
46
|
+
if (env.TAOXIAN_RUNTIME_URL) return trimUrl(env.TAOXIAN_RUNTIME_URL);
|
|
47
|
+
if (env.TAOXIAN_RUNTIME_PORT) return `http://127.0.0.1:${env.TAOXIAN_RUNTIME_PORT}`;
|
|
48
|
+
return DEFAULT_RUNTIME_URL;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseVersion(value) {
|
|
52
|
+
const match = String(value || '').match(/^(\d+)\.(\d+)\.(\d+)/);
|
|
53
|
+
return match ? match.slice(1).map(Number) : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function compareRuntimeVersions(a, b) {
|
|
57
|
+
const left = parseVersion(a);
|
|
58
|
+
const right = parseVersion(b);
|
|
59
|
+
if (!left || !right) return null;
|
|
60
|
+
for (let i = 0; i < 3; i += 1) {
|
|
61
|
+
if (left[i] > right[i]) return 1;
|
|
62
|
+
if (left[i] < right[i]) return -1;
|
|
63
|
+
}
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function runtimeDescriptorPath({ homeDir = process.env.TAOXIAN_HOME || DEFAULT_RUNTIME_HOME } = {}) {
|
|
68
|
+
return path.join(homeDir, 'runtime.json');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// runtime.json contains only discovery metadata, never secrets:
|
|
72
|
+
// { url, port, host, pid, version, api_version, started_at, health_path,
|
|
73
|
+
// mobile_path, lan_urls, lan_mobile_urls, lan_enabled }
|
|
74
|
+
export async function readRuntimeDescriptor({
|
|
75
|
+
homeDir = process.env.TAOXIAN_HOME || DEFAULT_RUNTIME_HOME,
|
|
76
|
+
env = process.env,
|
|
77
|
+
fsImpl = fs,
|
|
78
|
+
} = {}) {
|
|
79
|
+
if (env.TAOXIAN_RUNTIME_URL) {
|
|
80
|
+
return { url: trimUrl(env.TAOXIAN_RUNTIME_URL), source: 'env' };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const file = runtimeDescriptorPath({ homeDir });
|
|
84
|
+
const fallbackUrl = defaultRuntimeUrl(env);
|
|
85
|
+
try {
|
|
86
|
+
const raw = await fsImpl.readFile(file, 'utf8');
|
|
87
|
+
const parsed = JSON.parse(raw);
|
|
88
|
+
if (!parsed?.url) return { url: fallbackUrl, source: 'default', descriptor_path: file };
|
|
89
|
+
return { ...parsed, url: trimUrl(parsed.url), source: 'descriptor', descriptor_path: file };
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error?.code === 'ENOENT') {
|
|
92
|
+
return { url: fallbackUrl, source: 'default', descriptor_path: file };
|
|
93
|
+
}
|
|
94
|
+
throw new RuntimeUnavailableError('cannot read Taoxian Runtime descriptor', error);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function normalizeStatus(data, url) {
|
|
99
|
+
if (!data || data.ok !== true) {
|
|
100
|
+
throw new RuntimeUnavailableError('Taoxian Runtime health check did not report ok=true');
|
|
101
|
+
}
|
|
102
|
+
if (data.service && data.service !== RUNTIME_SERVICE_NAME) {
|
|
103
|
+
throw new RuntimeUnavailableError(`unexpected runtime service: ${data.service}`);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
ok: true,
|
|
107
|
+
url,
|
|
108
|
+
service: data.service || RUNTIME_SERVICE_NAME,
|
|
109
|
+
version: data.version || null,
|
|
110
|
+
apiVersion: Number(data.api_version ?? data.apiVersion ?? 0) || null,
|
|
111
|
+
pid: data.pid ?? null,
|
|
112
|
+
startedAt: data.started_at ?? data.startedAt ?? null,
|
|
113
|
+
host: data.host ?? null,
|
|
114
|
+
lanEnabled: Boolean(data.lan_enabled),
|
|
115
|
+
db: {
|
|
116
|
+
ready: Boolean(data.db?.ready),
|
|
117
|
+
schemaVersion: data.db?.schema_version ?? data.db?.schemaVersion ?? null,
|
|
118
|
+
},
|
|
119
|
+
mcp: {
|
|
120
|
+
servers: Number(data.mcp?.servers ?? 0),
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function getRuntimeStatus({
|
|
126
|
+
url,
|
|
127
|
+
descriptor,
|
|
128
|
+
homeDir,
|
|
129
|
+
env = process.env,
|
|
130
|
+
timeoutMs = 1500,
|
|
131
|
+
fetchImpl = globalThis.fetch,
|
|
132
|
+
} = {}) {
|
|
133
|
+
let resolvedDescriptor = descriptor;
|
|
134
|
+
if (!url && !resolvedDescriptor) {
|
|
135
|
+
resolvedDescriptor = await readRuntimeDescriptor({ homeDir, env });
|
|
136
|
+
}
|
|
137
|
+
const base = trimUrl(url || resolvedDescriptor?.url || defaultRuntimeUrl(env));
|
|
138
|
+
const controller = new AbortController();
|
|
139
|
+
const timer = setTimeout(() => controller.abort(new Error('runtime_health_timeout')), timeoutMs);
|
|
140
|
+
timer.unref?.();
|
|
141
|
+
try {
|
|
142
|
+
const response = await fetchImpl(`${base}/healthz`, {
|
|
143
|
+
method: 'GET',
|
|
144
|
+
headers: { Accept: 'application/json' },
|
|
145
|
+
cache: 'no-store',
|
|
146
|
+
signal: controller.signal,
|
|
147
|
+
});
|
|
148
|
+
if (!response.ok) {
|
|
149
|
+
throw new RuntimeUnavailableError(`Taoxian Runtime health returned HTTP ${response.status}`);
|
|
150
|
+
}
|
|
151
|
+
let data;
|
|
152
|
+
try {
|
|
153
|
+
data = await response.json();
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new RuntimeUnavailableError('Taoxian Runtime health returned invalid JSON', error);
|
|
156
|
+
}
|
|
157
|
+
return normalizeStatus(data, base);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if (error instanceof RuntimeUnavailableError) throw error;
|
|
160
|
+
throw new RuntimeUnavailableError('Taoxian Runtime is not reachable', error);
|
|
161
|
+
} finally {
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function assertRuntimeCompatible(status, {
|
|
167
|
+
minVersion = null,
|
|
168
|
+
apiVersion = RUNTIME_API_VERSION,
|
|
169
|
+
} = {}) {
|
|
170
|
+
if (!status?.ok) throw new RuntimeUnavailableError('Taoxian Runtime is not ready');
|
|
171
|
+
if (apiVersion != null && Number(status.apiVersion) !== Number(apiVersion)) {
|
|
172
|
+
throw new RuntimeIncompatibleError(
|
|
173
|
+
`Taoxian Runtime API version ${status.apiVersion} is not compatible with required ${apiVersion}`
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
if (minVersion) {
|
|
177
|
+
const comparison = compareRuntimeVersions(status.version, minVersion);
|
|
178
|
+
if (comparison == null) {
|
|
179
|
+
throw new RuntimeIncompatibleError(`cannot compare runtime version ${status.version} with ${minVersion}`);
|
|
180
|
+
}
|
|
181
|
+
if (comparison < 0) {
|
|
182
|
+
throw new RuntimeIncompatibleError(
|
|
183
|
+
`Taoxian Runtime ${status.version} is older than required ${minVersion}`
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return status;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function runtimeRequest({
|
|
191
|
+
path: requestPath,
|
|
192
|
+
method = 'GET',
|
|
193
|
+
body,
|
|
194
|
+
token,
|
|
195
|
+
headers: extraHeaders = {},
|
|
196
|
+
url,
|
|
197
|
+
descriptor,
|
|
198
|
+
homeDir,
|
|
199
|
+
env = process.env,
|
|
200
|
+
timeoutMs = 3_000,
|
|
201
|
+
fetchImpl = globalThis.fetch,
|
|
202
|
+
} = {}) {
|
|
203
|
+
let resolvedDescriptor = descriptor;
|
|
204
|
+
if (!url && !resolvedDescriptor) {
|
|
205
|
+
resolvedDescriptor = await readRuntimeDescriptor({ homeDir, env });
|
|
206
|
+
}
|
|
207
|
+
const base = trimUrl(url || resolvedDescriptor?.url || defaultRuntimeUrl(env));
|
|
208
|
+
const controller = new AbortController();
|
|
209
|
+
const timer = setTimeout(() => controller.abort(new Error('runtime_request_timeout')), timeoutMs);
|
|
210
|
+
timer.unref?.();
|
|
211
|
+
try {
|
|
212
|
+
const headers = { Accept: 'application/json', ...extraHeaders };
|
|
213
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
214
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
215
|
+
const response = await fetchImpl(`${base}${requestPath}`, {
|
|
216
|
+
method,
|
|
217
|
+
headers,
|
|
218
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
219
|
+
cache: 'no-store',
|
|
220
|
+
signal: controller.signal,
|
|
221
|
+
});
|
|
222
|
+
let data = null;
|
|
223
|
+
try { data = await response.json(); } catch { /* keep error readable */ }
|
|
224
|
+
if (!response.ok) {
|
|
225
|
+
throw new RuntimeApiError(
|
|
226
|
+
data?.error ? `Taoxian Runtime API error: ${data.error}` : `Taoxian Runtime API returned HTTP ${response.status}`,
|
|
227
|
+
{ status: response.status, code: data?.error || 'runtime_api_error', body: data }
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
return data;
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error instanceof RuntimeApiError) throw error;
|
|
233
|
+
throw new RuntimeUnavailableError('Taoxian Runtime API is not reachable', error);
|
|
234
|
+
} finally {
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export async function initFenshen(payload, options = {}) {
|
|
240
|
+
return runtimeRequest({
|
|
241
|
+
...options,
|
|
242
|
+
path: '/api/v1/runtime/fenshen/init',
|
|
243
|
+
method: 'POST',
|
|
244
|
+
body: payload,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export async function listFenshens(options = {}) {
|
|
249
|
+
const data = await runtimeRequest({ ...options, path: '/api/v1/runtime/fenshen' });
|
|
250
|
+
return Array.isArray(data?.fenshens) ? data.fenshens : [];
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export async function getFenshen(id, options = {}) {
|
|
254
|
+
const data = await runtimeRequest({
|
|
255
|
+
...options,
|
|
256
|
+
path: `/api/v1/runtime/fenshen/${encodeURIComponent(String(id || ''))}`,
|
|
257
|
+
});
|
|
258
|
+
return data?.fenshen || null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export async function listMcpServers(options = {}) {
|
|
262
|
+
const data = await runtimeRequest({ ...options, path: '/api/v1/runtime/mcp/servers' });
|
|
263
|
+
return Array.isArray(data?.servers) ? data.servers : [];
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export async function getLocalAuthStatus(options = {}) {
|
|
267
|
+
return runtimeRequest({ ...options, path: '/api/v1/runtime/auth/status' });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export async function setupLocalIdentity(payload, options = {}) {
|
|
271
|
+
return runtimeRequest({
|
|
272
|
+
...options,
|
|
273
|
+
path: '/api/v1/runtime/auth/setup',
|
|
274
|
+
method: 'POST',
|
|
275
|
+
body: payload,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export async function loginLocal(payload, options = {}) {
|
|
280
|
+
return runtimeRequest({
|
|
281
|
+
...options,
|
|
282
|
+
path: '/api/v1/runtime/auth/login',
|
|
283
|
+
method: 'POST',
|
|
284
|
+
body: payload,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export async function logoutLocal(sessionToken, options = {}) {
|
|
289
|
+
return runtimeRequest({
|
|
290
|
+
...options,
|
|
291
|
+
path: '/api/v1/runtime/auth/logout',
|
|
292
|
+
method: 'POST',
|
|
293
|
+
body: {},
|
|
294
|
+
token: sessionToken,
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export async function getLocalUser(sessionToken, options = {}) {
|
|
299
|
+
return runtimeRequest({
|
|
300
|
+
...options,
|
|
301
|
+
path: '/api/v1/runtime/auth/me',
|
|
302
|
+
token: sessionToken,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Fenshen backends should call this with the browser's raw Cookie header. The
|
|
307
|
+
// Runtime cookie is host-scoped, not port-scoped, so a fenshen on another port
|
|
308
|
+
// of the same host receives it. Never forward this cookie to browser JS.
|
|
309
|
+
export async function getLocalUserFromCookie(cookie, options = {}) {
|
|
310
|
+
return runtimeRequest({
|
|
311
|
+
...options,
|
|
312
|
+
path: '/api/v1/runtime/auth/me',
|
|
313
|
+
headers: cookie ? { Cookie: String(cookie) } : {},
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export async function getMobileAccess(sessionToken, options = {}) {
|
|
318
|
+
return runtimeRequest({
|
|
319
|
+
...options,
|
|
320
|
+
path: '/api/v1/runtime/mobile/access',
|
|
321
|
+
token: sessionToken,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export async function createMobilePairing(sessionToken, payload = {}, options = {}) {
|
|
326
|
+
return runtimeRequest({
|
|
327
|
+
...options,
|
|
328
|
+
path: '/api/v1/runtime/mobile/pairing',
|
|
329
|
+
method: 'POST',
|
|
330
|
+
token: sessionToken,
|
|
331
|
+
body: payload,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export async function redeemMobilePairing(payload, options = {}) {
|
|
336
|
+
return runtimeRequest({
|
|
337
|
+
...options,
|
|
338
|
+
path: '/api/v1/runtime/mobile/pair',
|
|
339
|
+
method: 'POST',
|
|
340
|
+
body: payload,
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export async function listLocalApiKeys(sessionToken, options = {}) {
|
|
345
|
+
const data = await runtimeRequest({
|
|
346
|
+
...options,
|
|
347
|
+
path: '/api/v1/runtime/api-keys',
|
|
348
|
+
token: sessionToken,
|
|
349
|
+
});
|
|
350
|
+
return Array.isArray(data?.api_keys) ? data.api_keys : [];
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export async function createLocalApiKey(sessionToken, payload, options = {}) {
|
|
354
|
+
return runtimeRequest({
|
|
355
|
+
...options,
|
|
356
|
+
path: '/api/v1/runtime/api-keys',
|
|
357
|
+
method: 'POST',
|
|
358
|
+
token: sessionToken,
|
|
359
|
+
body: payload,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export async function revokeLocalApiKey(sessionToken, id, options = {}) {
|
|
364
|
+
return runtimeRequest({
|
|
365
|
+
...options,
|
|
366
|
+
path: `/api/v1/runtime/api-keys/${encodeURIComponent(String(id || ''))}`,
|
|
367
|
+
method: 'DELETE',
|
|
368
|
+
token: sessionToken,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export async function verifyLocalApiKey(key, options = {}) {
|
|
373
|
+
const { serviceToken, ...requestOptions } = options;
|
|
374
|
+
return runtimeRequest({
|
|
375
|
+
...requestOptions,
|
|
376
|
+
path: '/api/v1/runtime/api-keys/verify',
|
|
377
|
+
method: 'POST',
|
|
378
|
+
body: { key },
|
|
379
|
+
headers: serviceToken ? { 'X-Taoxian-Service-Token': serviceToken } : undefined,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function runLifecycleCommand({
|
|
384
|
+
command = 'taoxian-runtime',
|
|
385
|
+
args = [],
|
|
386
|
+
timeoutMs = 10_000,
|
|
387
|
+
spawnImpl = spawn,
|
|
388
|
+
env = process.env,
|
|
389
|
+
cwd = process.cwd(),
|
|
390
|
+
} = {}) {
|
|
391
|
+
return new Promise((resolve, reject) => {
|
|
392
|
+
let settled = false;
|
|
393
|
+
let child;
|
|
394
|
+
try {
|
|
395
|
+
child = spawnImpl(command, args, {
|
|
396
|
+
cwd,
|
|
397
|
+
env,
|
|
398
|
+
stdio: 'ignore',
|
|
399
|
+
windowsHide: true,
|
|
400
|
+
detached: true,
|
|
401
|
+
});
|
|
402
|
+
} catch (error) {
|
|
403
|
+
reject(new RuntimeUnavailableError(`cannot start runtime command: ${command}`, error));
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const timer = setTimeout(() => {
|
|
408
|
+
if (settled) return;
|
|
409
|
+
settled = true;
|
|
410
|
+
try { child.kill?.(); } catch { /* best effort */ }
|
|
411
|
+
reject(new RuntimeUnavailableError(`runtime command timed out: ${command} ${args.join(' ')}`));
|
|
412
|
+
}, timeoutMs);
|
|
413
|
+
timer.unref?.();
|
|
414
|
+
|
|
415
|
+
child.once?.('error', (error) => {
|
|
416
|
+
if (settled) return;
|
|
417
|
+
settled = true;
|
|
418
|
+
clearTimeout(timer);
|
|
419
|
+
reject(new RuntimeUnavailableError(`runtime command failed: ${command}`, error));
|
|
420
|
+
});
|
|
421
|
+
child.once?.('exit', (code, signal) => {
|
|
422
|
+
if (settled) return;
|
|
423
|
+
settled = true;
|
|
424
|
+
clearTimeout(timer);
|
|
425
|
+
child.unref?.();
|
|
426
|
+
if (code === 0) resolve({ code, signal, pid: child.pid ?? null });
|
|
427
|
+
else reject(new RuntimeUnavailableError(`runtime command exited ${code ?? signal}: ${command} ${args.join(' ')}`));
|
|
428
|
+
});
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export async function startRuntime(options = {}) {
|
|
433
|
+
return runLifecycleCommand({ ...options, args: options.args || ['start'] });
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export async function stopRuntime(options = {}) {
|
|
437
|
+
return runLifecycleCommand({ ...options, args: options.args || ['stop'] });
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export async function restartRuntime(options = {}) {
|
|
441
|
+
return runLifecycleCommand({ ...options, args: options.args || ['restart'] });
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export async function waitForRuntime({
|
|
445
|
+
url,
|
|
446
|
+
descriptor,
|
|
447
|
+
homeDir,
|
|
448
|
+
env = process.env,
|
|
449
|
+
waitMs = 10_000,
|
|
450
|
+
intervalMs = 250,
|
|
451
|
+
timeoutMs = 1500,
|
|
452
|
+
fetchImpl = globalThis.fetch,
|
|
453
|
+
} = {}) {
|
|
454
|
+
const deadline = Date.now() + waitMs;
|
|
455
|
+
let lastError;
|
|
456
|
+
while (Date.now() <= deadline) {
|
|
457
|
+
try {
|
|
458
|
+
return await getRuntimeStatus({ url, descriptor, homeDir, env, timeoutMs, fetchImpl });
|
|
459
|
+
} catch (error) {
|
|
460
|
+
lastError = error;
|
|
461
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
throw new RuntimeUnavailableError('Taoxian Runtime did not become ready in time', lastError);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// The standard entry for fenshen apps and agent bases:
|
|
468
|
+
// - if Runtime is already healthy, return status
|
|
469
|
+
// - if it is down and autoStart=true, run `taoxian-runtime start` once and poll
|
|
470
|
+
// - never starts a second database; Runtime owns that lifecycle
|
|
471
|
+
export async function ensureRuntime({
|
|
472
|
+
autoStart = false,
|
|
473
|
+
startOptions = {},
|
|
474
|
+
waitMs = 10_000,
|
|
475
|
+
intervalMs = 250,
|
|
476
|
+
minVersion = null,
|
|
477
|
+
apiVersion = RUNTIME_API_VERSION,
|
|
478
|
+
url,
|
|
479
|
+
descriptor,
|
|
480
|
+
homeDir,
|
|
481
|
+
env = process.env,
|
|
482
|
+
fetchImpl = globalThis.fetch,
|
|
483
|
+
} = {}) {
|
|
484
|
+
let status = null;
|
|
485
|
+
try {
|
|
486
|
+
status = await getRuntimeStatus({ url, descriptor, homeDir, env, fetchImpl });
|
|
487
|
+
} catch {
|
|
488
|
+
// fall through to autoStart
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (status) return assertRuntimeCompatible(status, { minVersion, apiVersion });
|
|
492
|
+
|
|
493
|
+
if (!autoStart) {
|
|
494
|
+
throw new RuntimeUnavailableError(
|
|
495
|
+
'Taoxian Runtime is not running. Start it with `taoxian-runtime start` or enable autoStart.'
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
await startRuntime({ ...startOptions, env: startOptions.env || env });
|
|
500
|
+
const ready = await waitForRuntime({
|
|
501
|
+
url,
|
|
502
|
+
descriptor,
|
|
503
|
+
homeDir,
|
|
504
|
+
env,
|
|
505
|
+
waitMs,
|
|
506
|
+
intervalMs,
|
|
507
|
+
fetchImpl,
|
|
508
|
+
});
|
|
509
|
+
return assertRuntimeCompatible(ready, { minVersion, apiVersion });
|
|
510
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { FetchLike } from './runtime.js';
|
|
2
|
+
|
|
3
|
+
export interface ApiKeyVerifierOptions {
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
serviceToken: string;
|
|
6
|
+
ttlMs?: number;
|
|
7
|
+
negativeTtlMs?: number;
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
maxCacheEntries?: number;
|
|
10
|
+
fetchImpl?: FetchLike;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ApiKeyVerification {
|
|
14
|
+
active: boolean;
|
|
15
|
+
reason?: string;
|
|
16
|
+
logtoUserId?: string;
|
|
17
|
+
keyId?: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
expiresAt?: string | null;
|
|
20
|
+
lastUsedAt?: string | null;
|
|
21
|
+
cached?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ApiKeyVerifier {
|
|
25
|
+
verify(rawKey: string, options?: { signal?: AbortSignal }): Promise<ApiKeyVerification>;
|
|
26
|
+
clearCache(): void;
|
|
27
|
+
readonly cacheSize: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class ApiKeyVerifierConfigError extends Error {
|
|
31
|
+
code: 'api_key_verifier_config_error';
|
|
32
|
+
}
|
|
33
|
+
export class ApiKeyVerifyUnavailableError extends Error {
|
|
34
|
+
code: 'api_key_verify_unavailable';
|
|
35
|
+
cause?: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const API_KEY_PATTERN: RegExp;
|
|
39
|
+
export function isApiKeyFormat(value: unknown): boolean;
|
|
40
|
+
export function createApiKeyVerifier(options: ApiKeyVerifierOptions): ApiKeyVerifier;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { FetchLike, FenshenRecord, LocalAuthStatus, LocalUser } from './runtime.js';
|
|
2
|
+
|
|
3
|
+
export interface RuntimeBrowserOptions {
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
fetchImpl?: FetchLike;
|
|
6
|
+
credentials?: 'same-origin' | 'include';
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface RuntimeBrowserClient {
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
getAuthStatus(): Promise<LocalAuthStatus>;
|
|
13
|
+
getMe(): Promise<{ ok: true; user: LocalUser; session: { id: string; expires_at: string } }>;
|
|
14
|
+
getStatus(): Promise<any>;
|
|
15
|
+
getMobileAccess(): Promise<any>;
|
|
16
|
+
listFenshens(): Promise<{ fenshens: FenshenRecord[] }>;
|
|
17
|
+
logout(): Promise<{ ok: true; revoked: boolean }>;
|
|
18
|
+
createPairing(options?: { label?: string; ttlSeconds?: number }): Promise<any>;
|
|
19
|
+
redeemPairing(code: string): Promise<any>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class RuntimeBrowserError extends Error {
|
|
23
|
+
code: string;
|
|
24
|
+
status: number;
|
|
25
|
+
body: any;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createRuntimeBrowserClient(options?: RuntimeBrowserOptions): RuntimeBrowserClient;
|
|
29
|
+
export function resolveFenshenUiUrl(fenshen: FenshenRecord, options?: { hostname?: string }): string | null;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { FetchLike, LocalUser } from './runtime.js';
|
|
2
|
+
|
|
3
|
+
export interface FenshenAuthOptions {
|
|
4
|
+
runtimeUrl?: string;
|
|
5
|
+
timeoutMs?: number;
|
|
6
|
+
fetchImpl?: FetchLike;
|
|
7
|
+
trustProxy?: boolean;
|
|
8
|
+
onUnauthorized?: (req: any, res: any) => any;
|
|
9
|
+
onUnavailable?: (req: any, res: any, error: unknown) => any;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface FenshenAuth {
|
|
13
|
+
runtimeUrl: string;
|
|
14
|
+
authenticate(req: any): Promise<LocalUser | null>;
|
|
15
|
+
middleware(req: any, res: any, next?: () => void): Promise<any>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RuntimePublicUrlOptions {
|
|
19
|
+
runtimeUrl?: string;
|
|
20
|
+
runtimePort?: string | number;
|
|
21
|
+
trustProxy?: boolean;
|
|
22
|
+
path?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface RuntimeLoginUrlOptions extends Omit<RuntimePublicUrlOptions, 'path'> {
|
|
26
|
+
nextPath?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class FenshenAuthError extends Error {
|
|
30
|
+
code: string;
|
|
31
|
+
cause?: unknown;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function runtimePublicUrl(req: any, options?: RuntimePublicUrlOptions): string;
|
|
35
|
+
export function runtimeLoginUrl(req: any, options?: RuntimeLoginUrlOptions): string;
|
|
36
|
+
export function getFenshenUser(req: any, options?: Omit<FenshenAuthOptions, 'trustProxy' | 'onUnauthorized' | 'onUnavailable'>): Promise<LocalUser | null>;
|
|
37
|
+
export function createFenshenAuth(options?: FenshenAuthOptions): FenshenAuth;
|
package/types/index.d.ts
ADDED