@skaile/forge-layer-core 1.1.0 → 1.3.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 +27 -0
- package/README.md +76 -2
- package/app/components/AssistantAccountSettings.vue +55 -21
- package/app/middleware/auth.global.ts +1 -1
- package/app/pages/login.vue +273 -2
- package/app/pages/settings/agents.vue +36 -9
- package/nuxt.config.ts +1 -1
- package/package.json +5 -2
- package/server/db/migrations/0004_email_sign_in.sql +16 -0
- package/server/db/migrations/meta/0004_snapshot.json +884 -0
- package/server/db/migrations/meta/_journal.json +7 -0
- package/server/db/model.ts +1 -0
- package/server/db/schema/chat.ts +5 -2
- package/server/db/schema/index.ts +1 -0
- package/server/db/schema/login-codes.ts +31 -0
- package/server/db/schema/users.ts +6 -2
- package/server/plugins/00.auth-mode.ts +18 -0
- package/server/plugins/actions.ts +9 -4
- package/server/routes/login/verify.get.ts +30 -0
- package/server/utils/actions/assistant.ts +27 -9
- package/server/utils/actions/auth.ts +81 -0
- package/server/utils/actions/core.ts +3 -0
- package/server/utils/ai/roles.ts +15 -6
- package/server/utils/assistant/account.ts +56 -12
- package/server/utils/assistant/engines.ts +48 -16
- package/server/utils/assistant/policy.ts +69 -0
- package/server/utils/auth-mode.ts +44 -4
- package/server/utils/auth.ts +10 -1
- package/server/utils/login-codes.ts +368 -0
- package/server/utils/mail.ts +118 -0
- package/shared/messages/de.ts +43 -4
- package/shared/messages/en.ts +44 -4
- package/shared/sign-in.ts +28 -0
package/server/db/model.ts
CHANGED
package/server/db/schema/chat.ts
CHANGED
|
@@ -11,8 +11,11 @@ export const chatThreads = pgTable(
|
|
|
11
11
|
.notNull()
|
|
12
12
|
.references(() => users.id, { onDelete: 'cascade' }),
|
|
13
13
|
title: text('title').notNull().default('New conversation'),
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The engine it started in and stays in: `app` (AI SDK with the app's model), `byok` (AI SDK with the
|
|
16
|
+
* person's key) or `skaile` (skaile serve). Set on create.
|
|
17
|
+
*/
|
|
18
|
+
transport: text('transport', { enum: ['app', 'byok', 'skaile'] }).notNull(),
|
|
16
19
|
...timestamps(),
|
|
17
20
|
},
|
|
18
21
|
t => [index('chat_threads_user_idx').on(t.userId)],
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { index, integer, pgTable, text, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core'
|
|
2
|
+
import { id, timestamps } from './columns.ts'
|
|
3
|
+
import { users } from './users.ts'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Email mode (`APP_AUTH_MODE=email`): a six-digit code plus a one-click link
|
|
7
|
+
* token, mailed for one sign-in. Only hashes are stored. Valid until
|
|
8
|
+
* `expires_at`, used once (`used_at`), dead after five wrong entries
|
|
9
|
+
* (`attempts`). A row with an empty `code_hash` carries a link only
|
|
10
|
+
* (`createSignInLink`, e.g. an invitation): no entered code can match it.
|
|
11
|
+
* Internal: not exposed through `data.*`.
|
|
12
|
+
*/
|
|
13
|
+
export const loginCodes = pgTable(
|
|
14
|
+
'login_codes',
|
|
15
|
+
{
|
|
16
|
+
id: id(),
|
|
17
|
+
userId: uuid('user_id')
|
|
18
|
+
.notNull()
|
|
19
|
+
.references(() => users.id, { onDelete: 'cascade' }),
|
|
20
|
+
codeHash: text('code_hash').notNull(),
|
|
21
|
+
linkTokenHash: text('link_token_hash').notNull(),
|
|
22
|
+
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
|
|
23
|
+
usedAt: timestamp('used_at', { withTimezone: true }),
|
|
24
|
+
attempts: integer('attempts').notNull().default(0),
|
|
25
|
+
...timestamps(),
|
|
26
|
+
},
|
|
27
|
+
t => [
|
|
28
|
+
uniqueIndex('login_codes_link_token_unique').on(t.linkTokenHash),
|
|
29
|
+
index('login_codes_user_created_idx').on(t.userId, t.createdAt),
|
|
30
|
+
],
|
|
31
|
+
)
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { pgTable, text, uniqueIndex } from 'drizzle-orm/pg-core'
|
|
1
|
+
import { pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
|
|
2
2
|
import { USER_ROLES } from '../../../shared/domain.ts'
|
|
3
3
|
import { id, timestamps } from './columns.ts'
|
|
4
4
|
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* People who sign in. `password_hash` is empty for the auto-signed-in owner of local mode. `last_sign_in_at` is the
|
|
7
|
+
* last sign-in by a mailed code or link (`server/utils/login-codes.ts`); empty until the first one.
|
|
8
|
+
*/
|
|
6
9
|
export const users = pgTable(
|
|
7
10
|
'users',
|
|
8
11
|
{
|
|
@@ -11,6 +14,7 @@ export const users = pgTable(
|
|
|
11
14
|
name: text('name').notNull(),
|
|
12
15
|
role: text('role', { enum: USER_ROLES }).notNull().default('member'),
|
|
13
16
|
passwordHash: text('password_hash'),
|
|
17
|
+
lastSignInAt: timestamp('last_sign_in_at', { withTimezone: true }),
|
|
14
18
|
...timestamps(),
|
|
15
19
|
},
|
|
16
20
|
t => [uniqueIndex('users_email_unique').on(t.email)],
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { authModeConfigError } from '../utils/auth-mode'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Refuses to start when the sign-in mode cannot work: an unknown
|
|
5
|
+
* `APP_AUTH_MODE`, email mode without `SMTP_URL`, or mail (email mode or
|
|
6
|
+
* `SMTP_URL` set) without `APP_URL`. The message names the missing variable.
|
|
7
|
+
*/
|
|
8
|
+
export default defineNitroPlugin(() => {
|
|
9
|
+
let message: string | null
|
|
10
|
+
try {
|
|
11
|
+
message = authModeConfigError()
|
|
12
|
+
} catch (error) {
|
|
13
|
+
message = error instanceof Error ? error.message : String(error)
|
|
14
|
+
}
|
|
15
|
+
if (!message) return
|
|
16
|
+
console.error(`[app] ${message}`)
|
|
17
|
+
throw new Error(message)
|
|
18
|
+
})
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { HttpAuthorizeDecision } from '@skaile/forge-app-actions/http'
|
|
2
2
|
import type { McpAuthorizeDecision } from '@skaile/forge-app-actions/mcp'
|
|
3
3
|
import type { H3Event } from 'h3'
|
|
4
|
+
import { SIGN_IN_ACTION_IDS } from '../utils/actions/auth'
|
|
4
5
|
import { coreActions } from '../utils/actions/core'
|
|
5
6
|
import { findAction, registerActions } from '../utils/actions/registry'
|
|
6
|
-
import { bearerPrincipal, isSafeMethod, isSameOriginRequest, sessionPrincipal } from '../utils/auth'
|
|
7
|
+
import { bearerPrincipal, isSafeMethod, isSameOriginRequest, sessionPrincipal, signInPrincipal } from '../utils/auth'
|
|
7
8
|
|
|
8
9
|
/** The action id of a `POST /api/actions/<id>` request, if any. */
|
|
9
10
|
function actionIdOf(event: H3Event): string | undefined {
|
|
@@ -15,7 +16,9 @@ function actionIdOf(event: H3Event): string | undefined {
|
|
|
15
16
|
* `/api/actions` (user audience): an API token, or the session cookie of a
|
|
16
17
|
* signed-in person. With the cookie, effect actions must come from the app's
|
|
17
18
|
* own origin (CSRF); queries may also be called during SSR. A bearer that does
|
|
18
|
-
* not resolve never falls back to the cookie.
|
|
19
|
+
* not resolve never falls back to the cookie. Without a session, a same-origin
|
|
20
|
+
* request may call the sign-in actions (`SIGN_IN_ACTION_IDS`) and nothing else,
|
|
21
|
+
* as the rights-less `signInPrincipal()`.
|
|
19
22
|
*/
|
|
20
23
|
async function authorizeHttp(decision: HttpAuthorizeDecision): Promise<void> {
|
|
21
24
|
const { event } = decision
|
|
@@ -27,12 +30,14 @@ async function authorizeHttp(decision: HttpAuthorizeDecision): Promise<void> {
|
|
|
27
30
|
}
|
|
28
31
|
|
|
29
32
|
async function cookiePrincipal(event: H3Event) {
|
|
33
|
+
const id = actionIdOf(event)
|
|
30
34
|
if (!isSafeMethod(event.method)) {
|
|
31
|
-
const id = actionIdOf(event)
|
|
32
35
|
const kind = id ? findAction(id)?.kind : undefined
|
|
33
36
|
if (kind !== 'query' && !isSameOriginRequest(event)) return null
|
|
34
37
|
}
|
|
35
|
-
|
|
38
|
+
const principal = await sessionPrincipal(event)
|
|
39
|
+
if (principal) return principal
|
|
40
|
+
return id && SIGN_IN_ACTION_IDS.includes(id) && isSameOriginRequest(event) ? signInPrincipal() : null
|
|
36
41
|
}
|
|
37
42
|
|
|
38
43
|
/** `/mcp` (llm audience): API tokens only — MCP clients never hold a session. */
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { joinURL, withQuery } from 'ufo'
|
|
2
|
+
import { safeNextPath } from '../../../shared/sign-in'
|
|
3
|
+
import { startUserSession } from '../../utils/auth'
|
|
4
|
+
import { appAuthMode } from '../../utils/auth-mode'
|
|
5
|
+
import { verifyLinkToken } from '../../utils/login-codes'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The one-click link of a sign-in mail (email mode):
|
|
9
|
+
* `/login/verify?token=…&next=/projects/42`. A valid token signs in like the
|
|
10
|
+
* code and opens `next` (app paths only); otherwise `/login?link=expired|invalid`
|
|
11
|
+
* says why and keeps the path as the page's `redirect`.
|
|
12
|
+
*/
|
|
13
|
+
export default defineEventHandler(async event => {
|
|
14
|
+
const query = getQuery(event)
|
|
15
|
+
const base = useRuntimeConfig(event).app.baseURL
|
|
16
|
+
const next = safeNextPath(query.next)
|
|
17
|
+
const loginPage = (link?: 'expired' | 'invalid') =>
|
|
18
|
+
withQuery(joinURL(base, '/login'), { ...(link ? { link } : {}), ...(next === '/' ? {} : { redirect: next }) })
|
|
19
|
+
if (appAuthMode() !== 'email') return sendRedirect(event, loginPage())
|
|
20
|
+
try {
|
|
21
|
+
const user = await verifyLinkToken(typeof query.token === 'string' ? query.token : '', event)
|
|
22
|
+
await startUserSession(event, user)
|
|
23
|
+
} catch (error) {
|
|
24
|
+
const status = error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : undefined
|
|
25
|
+
if (status === 410) return sendRedirect(event, loginPage('expired'))
|
|
26
|
+
if (status === 401) return sendRedirect(event, loginPage('invalid'))
|
|
27
|
+
throw error
|
|
28
|
+
}
|
|
29
|
+
return sendRedirect(event, joinURL(base, next))
|
|
30
|
+
})
|
|
@@ -2,19 +2,28 @@ import { createError } from 'h3'
|
|
|
2
2
|
import * as z from 'zod'
|
|
3
3
|
import type { AssistantAccount } from '../assistant/account'
|
|
4
4
|
import { BYOK_PRESETS, getAssistantAccount, updateAssistantAccount } from '../assistant/account'
|
|
5
|
-
import {
|
|
5
|
+
import { ASSISTANT_ACCOUNT_MODES, assistantModes, effectiveAssistantMode } from '../assistant/engines'
|
|
6
6
|
import { assistantName } from '../assistant/name'
|
|
7
|
+
// Importing the policy declares its scope, so `settings.get`/`settings.update` know "assistant-policy".
|
|
8
|
+
import { chatAccess, ownModelsAllowed } from '../assistant/policy'
|
|
9
|
+
import { useCoreServerI18n } from '../i18n'
|
|
7
10
|
import type { Principal } from '../principal'
|
|
8
11
|
import { defineAppAction } from './define'
|
|
9
12
|
|
|
10
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* What both actions answer: the account without its key, the engines, the engine a new conversation
|
|
15
|
+
* uses, whether the app lets people choose their own model (`ownModels`) and what the chat in the app
|
|
16
|
+
* server reaches (`chatAccess`).
|
|
17
|
+
*/
|
|
11
18
|
async function accountView(principal: Principal, account: AssistantAccount) {
|
|
12
|
-
const [name, modes, effectiveMode] = await Promise.all([
|
|
19
|
+
const [name, modes, effectiveMode, ownModels, access] = await Promise.all([
|
|
13
20
|
assistantName(),
|
|
14
21
|
assistantModes(principal),
|
|
15
22
|
effectiveAssistantMode(principal),
|
|
23
|
+
ownModelsAllowed(),
|
|
24
|
+
chatAccess(),
|
|
16
25
|
])
|
|
17
|
-
return { name, mode: account.mode, effectiveMode, modes, byok: account.byok }
|
|
26
|
+
return { name, mode: account.mode, effectiveMode, modes, byok: account.byok, ownModels, chatAccess: access }
|
|
18
27
|
}
|
|
19
28
|
|
|
20
29
|
export const assistantActions = [
|
|
@@ -23,7 +32,7 @@ export const assistantActions = [
|
|
|
23
32
|
kind: 'query',
|
|
24
33
|
audience: ['user'],
|
|
25
34
|
description:
|
|
26
|
-
"Your assistant account: the assistant's name, the mode you chose (skaile, byok
|
|
35
|
+
"Your assistant account: the assistant's name, the mode you chose (skaile = the app's model, byok = your own key, null = not chosen), the engine new conversations use (effectiveMode: app = the chat in the app server on the app's model, skaile = the SKAILE agent, byok = the chat in the app server on your own key), every engine with whether it is installed and available to you, whether the app allows own models (ownModels), what the chat in the app server reaches (chatAccess: actions or document), and your own-key provider, model and base URL (whether a key is stored, never the key).",
|
|
27
36
|
input: z.object({}).strict(),
|
|
28
37
|
authorize: (_input, ctx) => {
|
|
29
38
|
if (ctx.principal.kind === 'system')
|
|
@@ -39,10 +48,14 @@ export const assistantActions = [
|
|
|
39
48
|
idempotent: true,
|
|
40
49
|
audience: ['user'],
|
|
41
50
|
description:
|
|
42
|
-
|
|
51
|
+
"Change your assistant account: mode (skaile = the app's model, byok = your own key, or null to let the app pick), your own-key provider, model, base URL (openai-compatible only) and key, or clearKey to remove the stored key. Mode byok and own-key changes are refused while the app does not allow own models (ownModels in assistant.account.get); clearKey always works. Changing provider or base URL without a new key removes the stored key. Returns the account like assistant.account.get.",
|
|
43
52
|
input: z
|
|
44
53
|
.object({
|
|
45
|
-
mode: z
|
|
54
|
+
mode: z
|
|
55
|
+
.enum(ASSISTANT_ACCOUNT_MODES)
|
|
56
|
+
.nullable()
|
|
57
|
+
.optional()
|
|
58
|
+
.describe('skaile, byok, or null to let the app pick'),
|
|
46
59
|
byok: z
|
|
47
60
|
.object({
|
|
48
61
|
preset: z.enum(BYOK_PRESETS).describe('anthropic, openai, openrouter or openai-compatible'),
|
|
@@ -65,9 +78,14 @@ export const assistantActions = [
|
|
|
65
78
|
throw createError({ statusCode: 403, statusMessage: 'The system principal has no assistant account' })
|
|
66
79
|
},
|
|
67
80
|
run: async (input, ctx) => {
|
|
81
|
+
if ((input.mode === 'byok' || input.byok) && !(await ownModelsAllowed()))
|
|
82
|
+
throw createError({ statusCode: 403, statusMessage: useCoreServerI18n().t('core.assistant.ownModelsOff') })
|
|
68
83
|
if (input.mode) {
|
|
69
|
-
const
|
|
70
|
-
|
|
84
|
+
const modes = await assistantModes(ctx.principal)
|
|
85
|
+
const installed = (mode: string) => modes.some(entry => entry.mode === mode && entry.installed)
|
|
86
|
+
// The app's model (`skaile`) runs on the SKAILE agent or the chat in the app server; an own key on the
|
|
87
|
+
// SKAILE agent or the chat's `byok` engine.
|
|
88
|
+
if (!(installed('skaile') || installed(input.mode === 'byok' ? 'byok' : 'app')))
|
|
71
89
|
throw createError({
|
|
72
90
|
statusCode: 400,
|
|
73
91
|
statusMessage: `The assistant mode ${input.mode} is not installed in this app`,
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { createError, isEvent } from 'h3'
|
|
2
|
+
import * as z from 'zod'
|
|
3
|
+
import { signInEmail } from '../../../shared/domain'
|
|
4
|
+
import { LOGIN_CODE_LENGTH } from '../../../shared/sign-in'
|
|
5
|
+
import { startUserSession } from '../auth'
|
|
6
|
+
import { appAuthMode, appBaseUrl } from '../auth-mode'
|
|
7
|
+
import { requestLoginCode, verifyLoginCode } from '../login-codes'
|
|
8
|
+
import { defineAppAction } from './define'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The actions a signed-out browser may call. `server/plugins/actions.ts` lets
|
|
12
|
+
* a same-origin request without a session run exactly these, as the
|
|
13
|
+
* rights-less `signInPrincipal()` (`server/utils/auth.ts`).
|
|
14
|
+
*/
|
|
15
|
+
export const SIGN_IN_ACTION_IDS: readonly string[] = ['auth.code.request', 'auth.code.verify']
|
|
16
|
+
|
|
17
|
+
function requireEmailMode(): void {
|
|
18
|
+
if (appAuthMode() !== 'email') {
|
|
19
|
+
throw createError({
|
|
20
|
+
statusCode: 400,
|
|
21
|
+
statusMessage: 'Sign-in by code is only used in email mode (APP_AUTH_MODE=email)',
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const authActions = [
|
|
27
|
+
defineAppAction({
|
|
28
|
+
id: 'auth.code.request',
|
|
29
|
+
kind: 'effect',
|
|
30
|
+
destructive: true,
|
|
31
|
+
audience: ['user'],
|
|
32
|
+
description:
|
|
33
|
+
'Sign-in, step 1 (email mode): mails the address a six-digit code and a one-click link, valid 10 minutes and once; earlier codes of the address stop working. Answers { ok, message } the same for every address, known or not. 429 after 5 codes per address within an hour, 503 when the mail cannot be sent.',
|
|
34
|
+
input: z
|
|
35
|
+
.object({
|
|
36
|
+
email: signInEmail.describe('The address to sign in with'),
|
|
37
|
+
next: z
|
|
38
|
+
.string()
|
|
39
|
+
.max(2000)
|
|
40
|
+
.optional()
|
|
41
|
+
.describe(
|
|
42
|
+
'App path the mailed link opens after sign-in, e.g. /settings/profile; anything but an app-relative path becomes /',
|
|
43
|
+
),
|
|
44
|
+
})
|
|
45
|
+
.strict(),
|
|
46
|
+
authorize: requireEmailMode,
|
|
47
|
+
run: (input, ctx) =>
|
|
48
|
+
requestLoginCode({
|
|
49
|
+
email: input.email,
|
|
50
|
+
baseUrl: appBaseUrl(),
|
|
51
|
+
next: input.next,
|
|
52
|
+
event: isEvent(ctx.event) ? ctx.event : undefined,
|
|
53
|
+
}),
|
|
54
|
+
}),
|
|
55
|
+
|
|
56
|
+
defineAppAction({
|
|
57
|
+
id: 'auth.code.verify',
|
|
58
|
+
kind: 'effect',
|
|
59
|
+
destructive: false,
|
|
60
|
+
audience: ['user'],
|
|
61
|
+
description:
|
|
62
|
+
'Sign-in, step 2 (email mode): checks the code mailed to the address and opens the session (cookie). Returns the signed-in user { id, email, name, role }. 401 wrong code, 410 expired, 429 after 5 wrong entries (ask for a new code).',
|
|
63
|
+
input: z
|
|
64
|
+
.object({
|
|
65
|
+
email: signInEmail.describe('The address the code was mailed to'),
|
|
66
|
+
code: z
|
|
67
|
+
.string()
|
|
68
|
+
.trim()
|
|
69
|
+
.regex(new RegExp(`^\\d{${LOGIN_CODE_LENGTH}}$`), 'Six digits')
|
|
70
|
+
.describe('The six-digit code from the mail'),
|
|
71
|
+
})
|
|
72
|
+
.strict(),
|
|
73
|
+
authorize: requireEmailMode,
|
|
74
|
+
run: async (input, ctx) => {
|
|
75
|
+
const event = isEvent(ctx.event) ? ctx.event : undefined
|
|
76
|
+
const user = await verifyLoginCode({ ...input, event })
|
|
77
|
+
if (event) await startUserSession(event, user)
|
|
78
|
+
return { user: { id: user.id, email: user.email, name: user.name, role: user.role } }
|
|
79
|
+
},
|
|
80
|
+
}),
|
|
81
|
+
] as const
|
|
@@ -2,6 +2,7 @@ import type { DataActions } from '../data'
|
|
|
2
2
|
import { dataActions } from '../data'
|
|
3
3
|
import { aiActions } from './ai'
|
|
4
4
|
import { assistantActions } from './assistant'
|
|
5
|
+
import { authActions } from './auth'
|
|
5
6
|
import { meActions } from './me'
|
|
6
7
|
import { notificationActions } from './notifications'
|
|
7
8
|
import { settingsActions } from './settings'
|
|
@@ -16,6 +17,7 @@ export type CoreActions = readonly [
|
|
|
16
17
|
...typeof meActions,
|
|
17
18
|
...typeof assistantActions,
|
|
18
19
|
...typeof notificationActions,
|
|
20
|
+
...typeof authActions,
|
|
19
21
|
]
|
|
20
22
|
|
|
21
23
|
/**
|
|
@@ -34,5 +36,6 @@ export function coreActions(): CoreActions {
|
|
|
34
36
|
...meActions,
|
|
35
37
|
...assistantActions,
|
|
36
38
|
...notificationActions,
|
|
39
|
+
...authActions,
|
|
37
40
|
] as const
|
|
38
41
|
}
|
package/server/utils/ai/roles.ts
CHANGED
|
@@ -164,7 +164,12 @@ function narrowRegistry(registryView: MergedAIProviderRegistry, entryId: string)
|
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
-
async function resolveAssigned(
|
|
167
|
+
async function resolveAssigned(
|
|
168
|
+
role: ModelRoleDefinition,
|
|
169
|
+
assignment: string,
|
|
170
|
+
env: Env,
|
|
171
|
+
sdk: boolean,
|
|
172
|
+
): Promise<ResolvedRoleModel> {
|
|
168
173
|
const place = providersPlace(env)
|
|
169
174
|
try {
|
|
170
175
|
const merged = loadRegistry(place)
|
|
@@ -177,7 +182,6 @@ async function resolveAssigned(role: ModelRoleDefinition, assignment: string, en
|
|
|
177
182
|
if (resolved.kind !== 'model')
|
|
178
183
|
throw new RoleNotConfigured(role.id, t('core.aiStatus.badSelector', { label: role.label, assignment }))
|
|
179
184
|
const { entryId } = resolved
|
|
180
|
-
const sdk = registry.get(role.id)?.sdkModel ?? true
|
|
181
185
|
const model = sdk ? (await resolveRegistryModel(place, assignment)).model : null
|
|
182
186
|
const narrowed = narrowRegistry(merged, entryId)
|
|
183
187
|
const delivery = registryCredentialEnv(narrowed, { env: providersEnv(place), policy: PROVIDER_POLICY })
|
|
@@ -322,7 +326,9 @@ function backedBy(roleId: string, primary: ResolvedRoleModel, fallback: Resolved
|
|
|
322
326
|
* The model that serves `roleId` right now: the registry selector assigned in
|
|
323
327
|
* Settings › Harness; without one, for a `chat` role the `NUXT_AI_*` environment
|
|
324
328
|
* (so a fresh clone with only `.env` still answers). `env` is where `NUXT_AI_*`
|
|
325
|
-
* and `AI_PROVIDERS_DIR` are read (default `process.env`).
|
|
329
|
+
* and `AI_PROVIDERS_DIR` are read (default `process.env`). `sdkModel` overrides what the role was registered
|
|
330
|
+
* with: a second consumer of a runner role (`sdkModel: false`) that calls `languageModel()` in this process
|
|
331
|
+
* (the chat in the app server on the role `assistant`) passes `true`.
|
|
326
332
|
*
|
|
327
333
|
* The operator's hidden fallback (`NUXT_AI_FALLBACK_*`) comes last: it answers when neither the assignment nor
|
|
328
334
|
* the environment gives a usable model (also when the assignment is broken). For a role that resolves an AI SDK
|
|
@@ -334,7 +340,10 @@ function backedBy(roleId: string, primary: ResolvedRoleModel, fallback: Resolved
|
|
|
334
340
|
* `image`, `tts` and `stt` roles get their resolver together with a consumer.
|
|
335
341
|
* @throws {RoleNotConfigured} the role is unknown, disabled or has no usable model.
|
|
336
342
|
*/
|
|
337
|
-
export async function resolveRoleModel(
|
|
343
|
+
export async function resolveRoleModel(
|
|
344
|
+
roleId: string,
|
|
345
|
+
options: { env?: Env; sdkModel?: boolean } = {},
|
|
346
|
+
): Promise<ResolvedRoleModel> {
|
|
338
347
|
const env = options.env ?? process.env
|
|
339
348
|
const registered = registry.get(roleId)
|
|
340
349
|
const role = registered?.definition
|
|
@@ -343,12 +352,12 @@ export async function resolveRoleModel(roleId: string, options: { env?: Env } =
|
|
|
343
352
|
if (role.kind !== 'chat' && role.kind !== 'decision') {
|
|
344
353
|
throw new RoleNotConfigured(roleId, t('core.aiStatus.noConsumer', { label: role.label, kind: role.kind }))
|
|
345
354
|
}
|
|
346
|
-
const sdk = registered?.sdkModel ?? true
|
|
355
|
+
const sdk = options.sdkModel ?? registered?.sdkModel ?? true
|
|
347
356
|
const fallback = resolveHiddenFallback(role, env)
|
|
348
357
|
const assignment = (await getSettings(aiSettings)).models[roleId]?.trim()
|
|
349
358
|
let primary: ResolvedRoleModel | null = null
|
|
350
359
|
try {
|
|
351
|
-
if (assignment) primary = await resolveAssigned(role, assignment, env)
|
|
360
|
+
if (assignment) primary = await resolveAssigned(role, assignment, env, sdk)
|
|
352
361
|
else if (role.kind === 'chat') primary = resolveFromEnv(role, env)
|
|
353
362
|
} catch (error) {
|
|
354
363
|
if (!(error instanceof RoleNotConfigured) || !fallback) throw error
|
|
@@ -7,7 +7,8 @@ import { createError } from 'h3'
|
|
|
7
7
|
import { assistantAccounts } from '../../db/schema'
|
|
8
8
|
import { useDb } from '../db'
|
|
9
9
|
import { useCoreServerI18n } from '../i18n'
|
|
10
|
-
import type {
|
|
10
|
+
import type { AssistantAccountMode } from './engines'
|
|
11
|
+
import { ownModelsAllowed } from './policy'
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* A person's assistant account (Settings › Profile): the mode they chose and,
|
|
@@ -20,18 +21,30 @@ export type ByokPreset = 'anthropic' | 'openai' | 'openrouter' | 'openai-compati
|
|
|
20
21
|
|
|
21
22
|
export const BYOK_PRESETS: readonly ByokPreset[] = ['anthropic', 'openai', 'openrouter', 'openai-compatible']
|
|
22
23
|
|
|
23
|
-
/** Base URL of
|
|
24
|
+
/** Base URL of each preset; `openai-compatible` brings its own. */
|
|
24
25
|
const PRESET_BASE_URLS: Partial<Record<ByokPreset, string>> = {
|
|
26
|
+
anthropic: 'https://api.anthropic.com',
|
|
25
27
|
openai: 'https://api.openai.com/v1',
|
|
26
28
|
openrouter: 'https://openrouter.ai/api/v1',
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
export interface AssistantAccount {
|
|
30
32
|
/** `null`: not chosen, the app uses the first available mode. */
|
|
31
|
-
mode:
|
|
33
|
+
mode: AssistantAccountMode | null
|
|
32
34
|
byok: { preset: ByokPreset | null; model: string | null; baseUrl: string | null; hasKey: boolean }
|
|
33
35
|
}
|
|
34
36
|
|
|
37
|
+
/** A person's own model, ready to call. Server only: it carries the unsealed key. */
|
|
38
|
+
export interface PersonalModel {
|
|
39
|
+
preset: ByokPreset
|
|
40
|
+
/** Provider model id as the person typed it. */
|
|
41
|
+
model: string
|
|
42
|
+
/** Absolute base URL of the provider's API (the preset's, or the person's for `openai-compatible`). */
|
|
43
|
+
baseUrl: string
|
|
44
|
+
/** Unsealed key. Never log, return or persist it. */
|
|
45
|
+
apiKey: string
|
|
46
|
+
}
|
|
47
|
+
|
|
35
48
|
/** The person cannot use `byok` yet; `reason` says what to set in Settings › Profile and never carries a key. */
|
|
36
49
|
export class AssistantNotConfigured extends Error {
|
|
37
50
|
constructor(
|
|
@@ -101,7 +114,7 @@ export async function getAssistantAccount(userId: string): Promise<AssistantAcco
|
|
|
101
114
|
export async function updateAssistantAccount(
|
|
102
115
|
userId: string,
|
|
103
116
|
patch: {
|
|
104
|
-
mode?:
|
|
117
|
+
mode?: AssistantAccountMode | null
|
|
105
118
|
byok?: { preset: ByokPreset; model: string; baseUrl?: string | null; key?: string }
|
|
106
119
|
clearKey?: boolean
|
|
107
120
|
},
|
|
@@ -134,13 +147,18 @@ export async function updateAssistantAccount(
|
|
|
134
147
|
return toAccount(row)
|
|
135
148
|
}
|
|
136
149
|
|
|
137
|
-
/**
|
|
138
|
-
|
|
139
|
-
|
|
150
|
+
/**
|
|
151
|
+
* The stored own model, whatever mode the person chose. Throws AssistantNotConfigured naming what is
|
|
152
|
+
* missing, so the `byok` engine can tell the person what to set.
|
|
153
|
+
*/
|
|
154
|
+
function storedModel(row: typeof assistantAccounts.$inferSelect | undefined): PersonalModel {
|
|
140
155
|
const preset = row?.byokPreset
|
|
141
156
|
if (!preset || !row.byokModel)
|
|
142
157
|
throw new AssistantNotConfigured('Choose a provider and model for your own key in Settings › Profile.')
|
|
143
158
|
if (!row.byokKeySealed) throw new AssistantNotConfigured('Enter your API key in Settings › Profile.')
|
|
159
|
+
const baseUrl = PRESET_BASE_URLS[preset] ?? row.byokBaseUrl
|
|
160
|
+
if (!baseUrl)
|
|
161
|
+
throw new AssistantNotConfigured('Enter the base URL of your OpenAI-compatible provider in Settings › Profile.')
|
|
144
162
|
let apiKey: string
|
|
145
163
|
try {
|
|
146
164
|
apiKey = unseal(row.byokKeySealed)
|
|
@@ -150,9 +168,35 @@ export async function byokLanguageModel(userId: string): Promise<LanguageModel>
|
|
|
150
168
|
{ cause: error },
|
|
151
169
|
)
|
|
152
170
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
171
|
+
return { preset, model: row.byokModel, baseUrl, apiKey }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The person's own model when it should be used: the app allows own models (`assistant-policy`), the
|
|
176
|
+
* person chose mode `byok`, and preset, model and key are stored. `null` otherwise, so the caller runs
|
|
177
|
+
* on the app's model. Read per call, so a changed account or policy needs no restart.
|
|
178
|
+
* @throws AssistantNotConfigured when the stored key cannot be unsealed (its reason is for people).
|
|
179
|
+
*/
|
|
180
|
+
export async function personalModel(userId: string): Promise<PersonalModel | null> {
|
|
181
|
+
if (!(await ownModelsAllowed())) return null
|
|
182
|
+
const row = await accountRow(userId)
|
|
183
|
+
if (row?.mode !== 'byok' || !row.byokPreset || !row.byokModel || !row.byokKeySealed) return null
|
|
184
|
+
if (row.byokPreset === 'openai-compatible' && !row.byokBaseUrl) return null
|
|
185
|
+
return storedModel(row)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The person's own model for the plain chat engine (`byok`), built per call so a changed account needs
|
|
190
|
+
* no restart. Unlike {@link personalModel} it does not ask for mode `byok`: the chat engine only runs
|
|
191
|
+
* when the SKAILE engine cannot, and then any stored key serves.
|
|
192
|
+
* @throws AssistantNotConfigured when own models are switched off or the account lacks a part.
|
|
193
|
+
*/
|
|
194
|
+
export async function byokLanguageModel(userId: string): Promise<LanguageModel> {
|
|
195
|
+
if (!(await ownModelsAllowed()))
|
|
196
|
+
throw new AssistantNotConfigured(useCoreServerI18n().t('core.assistant.ownModelsOff'))
|
|
197
|
+
const own = storedModel(await accountRow(userId))
|
|
198
|
+
if (own.preset === 'anthropic') return createAnthropic({ apiKey: own.apiKey })(own.model)
|
|
199
|
+
return createOpenAICompatible({ name: `byok-${own.preset}`, baseURL: own.baseUrl, apiKey: own.apiKey }).chatModel(
|
|
200
|
+
own.model,
|
|
201
|
+
)
|
|
158
202
|
}
|
|
@@ -2,23 +2,34 @@ import { coreMessages } from '../../../shared/messages'
|
|
|
2
2
|
import { useForgeServerI18n } from '../i18n'
|
|
3
3
|
import type { Principal } from '../principal'
|
|
4
4
|
import { getAssistantAccount } from './account'
|
|
5
|
+
import { ownModelsAllowed, preferredAssistantEngine } from './policy'
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
|
-
* The app has one assistant
|
|
8
|
-
*
|
|
9
|
-
* `skaile
|
|
10
|
-
* person's
|
|
11
|
-
*
|
|
12
|
-
* engine
|
|
8
|
+
* The app has one assistant, and three engines can run it:
|
|
9
|
+
* - `app`: the chat in the app server (the AI SDK) on the app's model;
|
|
10
|
+
* - `skaile`: the SKAILE workspace agent (a `skaile serve` process per person). It runs on the app's model, or
|
|
11
|
+
* on the person's own model when the app allows own models (`assistant-policy`) and they chose "Own key";
|
|
12
|
+
* - `byok`: the chat in the app server on the person's own key.
|
|
13
|
+
* Every engine acts with the rights of the person. What the chat in the app server reaches (`app`, `byok`) is the
|
|
14
|
+
* owner's call (`assistant-policy.chatAccess`), and so is which engine a new conversation prefers
|
|
15
|
+
* (`assistant-policy.engine`, see {@link effectiveAssistantMode}). The layer that implements an engine registers
|
|
16
|
+
* it from a server plugin; an engine no layer registers is not installed.
|
|
13
17
|
*/
|
|
14
18
|
|
|
15
|
-
export type AssistantMode = 'skaile' | 'byok'
|
|
19
|
+
export type AssistantMode = 'app' | 'skaile' | 'byok'
|
|
16
20
|
|
|
17
|
-
/** Every
|
|
18
|
-
export const ASSISTANT_MODES: readonly AssistantMode[] = ['skaile', 'byok']
|
|
21
|
+
/** Every engine. */
|
|
22
|
+
export const ASSISTANT_MODES: readonly AssistantMode[] = ['app', 'skaile', 'byok']
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What a person chooses in Settings › Profile: the app's model (`skaile`, whichever engine runs it) or their own
|
|
26
|
+
* key (`byok`). Stored in `assistant_accounts.mode`.
|
|
27
|
+
*/
|
|
28
|
+
export type AssistantAccountMode = 'skaile' | 'byok'
|
|
29
|
+
export const ASSISTANT_ACCOUNT_MODES: readonly AssistantAccountMode[] = ['skaile', 'byok']
|
|
19
30
|
|
|
20
31
|
/** Shown for a mode no layer registered. */
|
|
21
|
-
const DEFAULT_LABELS: Record<AssistantMode, string> = { skaile: 'SKAILE', byok: 'Own key' }
|
|
32
|
+
const DEFAULT_LABELS: Record<AssistantMode, string> = { app: 'App', skaile: 'SKAILE', byok: 'Own key' }
|
|
22
33
|
|
|
23
34
|
export interface AssistantEngine {
|
|
24
35
|
mode: AssistantMode
|
|
@@ -70,11 +81,32 @@ export async function assistantModes(
|
|
|
70
81
|
)
|
|
71
82
|
}
|
|
72
83
|
|
|
73
|
-
/**
|
|
84
|
+
/**
|
|
85
|
+
* The engine a new conversation of this person uses, `null` when none can run:
|
|
86
|
+
* - the owner prefers `app` (the default): the person's own key (`byok`) when they chose it and the app allows
|
|
87
|
+
* own models, else `app`, else `skaile`;
|
|
88
|
+
* - the owner prefers `skaile`: `skaile` (with "Own key" it runs on their own model), else `byok` when they
|
|
89
|
+
* chose their own key, else `app`.
|
|
90
|
+
* Last comes `byok` for anyone with a usable own key.
|
|
91
|
+
*/
|
|
74
92
|
export async function effectiveAssistantMode(principal: Principal): Promise<AssistantMode | null> {
|
|
75
|
-
const modes = await
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
93
|
+
const [modes, prefer, ownModels, account] = await Promise.all([
|
|
94
|
+
assistantModes(principal),
|
|
95
|
+
preferredAssistantEngine(),
|
|
96
|
+
ownModelsAllowed(),
|
|
97
|
+
principal.kind === 'system' ? null : getAssistantAccount(principal.id),
|
|
98
|
+
])
|
|
99
|
+
const usable = (mode: AssistantMode) => modes.some(entry => entry.mode === mode && entry.available)
|
|
100
|
+
const ownKey = ownModels && usable('byok')
|
|
101
|
+
const choseOwnKey = ownKey && account?.mode === 'byok'
|
|
102
|
+
if (prefer === 'skaile') {
|
|
103
|
+
if (usable('skaile')) return 'skaile'
|
|
104
|
+
if (choseOwnKey) return 'byok'
|
|
105
|
+
if (usable('app')) return 'app'
|
|
106
|
+
} else {
|
|
107
|
+
if (choseOwnKey) return 'byok'
|
|
108
|
+
if (usable('app')) return 'app'
|
|
109
|
+
if (usable('skaile')) return 'skaile'
|
|
110
|
+
}
|
|
111
|
+
return ownKey ? 'byok' : null
|
|
80
112
|
}
|