@skaile/forge-layer-core 1.2.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.
@@ -29,6 +29,13 @@
29
29
  "when": 1795386008693,
30
30
  "tag": "0003_passkeys",
31
31
  "breakpoints": true
32
+ },
33
+ {
34
+ "idx": 4,
35
+ "version": "7",
36
+ "when": 1796502218851,
37
+ "tag": "0004_email_sign_in",
38
+ "breakpoints": true
32
39
  }
33
40
  ]
34
41
  }
@@ -21,6 +21,7 @@ export const userEntity = defineEntity(users, {
21
21
  fields: {
22
22
  email: { hidden: true },
23
23
  passwordHash: { hidden: true },
24
+ lastSignInAt: { hidden: true },
24
25
  createdAt: { hidden: true },
25
26
  updatedAt: { hidden: true },
26
27
  },
@@ -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
- /** The mode it started in and stays in: `byok` (AI SDK with the person's key) or `skaile` (skaile serve). Set on create. */
15
- transport: text('transport', { enum: ['byok', 'skaile'] }).notNull(),
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)],
@@ -1,5 +1,6 @@
1
1
  export * from './api-tokens.ts'
2
2
  export * from './chat.ts'
3
+ export * from './login-codes.ts'
3
4
  export * from './notifications.ts'
4
5
  export * from './passkeys.ts'
5
6
  export * from './settings.ts'
@@ -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
- /** People who sign in. `password_hash` is empty for the auto-signed-in owner of local mode. */
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
- return sessionPrincipal(event)
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,26 +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 { ASSISTANT_MODES, assistantModes, effectiveAssistantMode } from '../assistant/engines'
5
+ import { ASSISTANT_ACCOUNT_MODES, assistantModes, effectiveAssistantMode } from '../assistant/engines'
6
6
  import { assistantName } from '../assistant/name'
7
7
  // Importing the policy declares its scope, so `settings.get`/`settings.update` know "assistant-policy".
8
- import { ownModelsAllowed } from '../assistant/policy'
8
+ import { chatAccess, ownModelsAllowed } from '../assistant/policy'
9
9
  import { useCoreServerI18n } from '../i18n'
10
10
  import type { Principal } from '../principal'
11
11
  import { defineAppAction } from './define'
12
12
 
13
13
  /**
14
- * What both actions answer: the account without its key, the modes, the engine a new conversation
15
- * uses, and whether the app lets people choose their own model (`ownModels`).
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`).
16
17
  */
17
18
  async function accountView(principal: Principal, account: AssistantAccount) {
18
- const [name, modes, effectiveMode, ownModels] = await Promise.all([
19
+ const [name, modes, effectiveMode, ownModels, access] = await Promise.all([
19
20
  assistantName(),
20
21
  assistantModes(principal),
21
22
  effectiveAssistantMode(principal),
22
23
  ownModelsAllowed(),
24
+ chatAccess(),
23
25
  ])
24
- return { name, mode: account.mode, effectiveMode, modes, byok: account.byok, ownModels }
26
+ return { name, mode: account.mode, effectiveMode, modes, byok: account.byok, ownModels, chatAccess: access }
25
27
  }
26
28
 
27
29
  export const assistantActions = [
@@ -30,7 +32,7 @@ export const assistantActions = [
30
32
  kind: 'query',
31
33
  audience: ['user'],
32
34
  description:
33
- "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, every engine with whether it is installed and available to you, whether the app allows own models (ownModels), and your own-key provider, model and base URL (whether a key is stored, never the key).",
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).",
34
36
  input: z.object({}).strict(),
35
37
  authorize: (_input, ctx) => {
36
38
  if (ctx.principal.kind === 'system')
@@ -49,7 +51,11 @@ export const assistantActions = [
49
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.",
50
52
  input: z
51
53
  .object({
52
- mode: z.enum(ASSISTANT_MODES).nullable().optional().describe('skaile, byok, or null to let the app pick'),
54
+ mode: z
55
+ .enum(ASSISTANT_ACCOUNT_MODES)
56
+ .nullable()
57
+ .optional()
58
+ .describe('skaile, byok, or null to let the app pick'),
53
59
  byok: z
54
60
  .object({
55
61
  preset: z.enum(BYOK_PRESETS).describe('anthropic, openai, openrouter or openai-compatible'),
@@ -77,8 +83,9 @@ export const assistantActions = [
77
83
  if (input.mode) {
78
84
  const modes = await assistantModes(ctx.principal)
79
85
  const installed = (mode: string) => modes.some(entry => entry.mode === mode && entry.installed)
80
- // An own key runs the SKAILE agent, so `byok` needs either engine; the plain chat engine is only its fallback.
81
- if (!(installed(input.mode) || (input.mode === 'byok' && installed('skaile'))))
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')))
82
89
  throw createError({
83
90
  statusCode: 400,
84
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
  }
@@ -164,7 +164,12 @@ function narrowRegistry(registryView: MergedAIProviderRegistry, entryId: string)
164
164
  }
165
165
  }
166
166
 
167
- async function resolveAssigned(role: ModelRoleDefinition, assignment: string, env: Env): Promise<ResolvedRoleModel> {
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(roleId: string, options: { env?: Env } = {}): Promise<ResolvedRoleModel> {
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,7 @@ 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 { AssistantMode } from './engines'
10
+ import type { AssistantAccountMode } from './engines'
11
11
  import { ownModelsAllowed } from './policy'
12
12
 
13
13
  /**
@@ -30,7 +30,7 @@ const PRESET_BASE_URLS: Partial<Record<ByokPreset, string>> = {
30
30
 
31
31
  export interface AssistantAccount {
32
32
  /** `null`: not chosen, the app uses the first available mode. */
33
- mode: AssistantMode | null
33
+ mode: AssistantAccountMode | null
34
34
  byok: { preset: ByokPreset | null; model: string | null; baseUrl: string | null; hasKey: boolean }
35
35
  }
36
36
 
@@ -114,7 +114,7 @@ export async function getAssistantAccount(userId: string): Promise<AssistantAcco
114
114
  export async function updateAssistantAccount(
115
115
  userId: string,
116
116
  patch: {
117
- mode?: AssistantMode | null
117
+ mode?: AssistantAccountMode | null
118
118
  byok?: { preset: ByokPreset; model: string; baseUrl?: string | null; key?: string }
119
119
  clearKey?: boolean
120
120
  },
@@ -1,26 +1,35 @@
1
1
  import { coreMessages } from '../../../shared/messages'
2
2
  import { useForgeServerI18n } from '../i18n'
3
3
  import type { Principal } from '../principal'
4
- import { ownModelsAllowed } from './policy'
4
+ import { getAssistantAccount } from './account'
5
+ import { ownModelsAllowed, preferredAssistantEngine } from './policy'
5
6
 
6
7
  /**
7
- * The app has one assistant, the SKAILE workspace agent (`skaile`: a
8
- * `skaile serve` process per person, full access with the person's rights).
9
- * It runs on the app's model, or on the person's own model when the app
10
- * allows own models (`assistant-policy`) and they chose mode `byok` in
11
- * Settings › Profile. Only when the SKAILE engine cannot run does an own key
12
- * fall back to the plain chat engine (`byok`: the AI SDK, the open page only).
13
- * The layer that implements an engine registers it from a server plugin; an
14
- * engine no layer registers is not installed.
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.
15
17
  */
16
18
 
17
- export type AssistantMode = 'skaile' | 'byok'
19
+ export type AssistantMode = 'app' | 'skaile' | 'byok'
18
20
 
19
- /** Every mode, in order of preference. */
20
- 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']
21
30
 
22
31
  /** Shown for a mode no layer registered. */
23
- 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' }
24
33
 
25
34
  export interface AssistantEngine {
26
35
  mode: AssistantMode
@@ -73,14 +82,31 @@ export async function assistantModes(
73
82
  }
74
83
 
75
84
  /**
76
- * The engine a new conversation of this person uses: `skaile` whenever it is available to them (with
77
- * mode `byok` it runs on their own model), else `byok` when the app allows own models and the person
78
- * can use it, else `null` (nothing usable).
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.
79
91
  */
80
92
  export async function effectiveAssistantMode(principal: Principal): Promise<AssistantMode | null> {
81
- const modes = await assistantModes(principal)
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
+ ])
82
99
  const usable = (mode: AssistantMode) => modes.some(entry => entry.mode === mode && entry.available)
83
- if (usable('skaile')) return 'skaile'
84
- if (usable('byok') && (await ownModelsAllowed())) return 'byok'
85
- return null
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
86
112
  }
@@ -8,8 +8,21 @@ import { defineSettingsScope, getSettings } from '../settings'
8
8
  * `ownModels` decides whether people may run the assistant on their own
9
9
  * provider, model and key (Settings › Profile, mode `byok`). Off: nobody can
10
10
  * choose it, stored keys stay stored but are ignored, and everyone's
11
- * assistant runs on the app's model.
11
+ * assistant runs on the app's model. `engine` names what a new conversation
12
+ * runs on when both can: the plain chat in the app server (`app`) or the SKAILE
13
+ * agent (`skaile`). `chatAccess` is what the plain chat (`app` and `byok`)
14
+ * reaches: every action a model may call (`actions`), or only the record the
15
+ * page shows, with changes as proposals the person applies (`document`).
12
16
  */
17
+
18
+ /** What a new conversation prefers when both engines can run. */
19
+ export const ASSISTANT_ENGINES = ['app', 'skaile'] as const
20
+ export type AssistantEnginePreference = (typeof ASSISTANT_ENGINES)[number]
21
+
22
+ /** What the plain chat (`app`, `byok`) reaches. */
23
+ export const CHAT_ACCESS = ['actions', 'document'] as const
24
+ export type ChatAccess = (typeof CHAT_ACCESS)[number]
25
+
13
26
  export const assistantPolicy = defineSettingsScope(
14
27
  'assistant-policy',
15
28
  z
@@ -19,13 +32,23 @@ export const assistantPolicy = defineSettingsScope(
19
32
  .describe(
20
33
  "People may run the assistant on their own provider, model and key (Settings › Profile). Off: everyone uses the app's model",
21
34
  ),
35
+ engine: z
36
+ .enum(ASSISTANT_ENGINES)
37
+ .describe(
38
+ 'What a new conversation runs on when both can: app = the chat in the app server, skaile = the SKAILE agent. The other one steps in when the chosen one cannot run',
39
+ ),
40
+ chatAccess: z
41
+ .enum(CHAT_ACCESS)
42
+ .describe(
43
+ 'What the chat in the app server reaches: actions = every action a model may call, with the rights of the person; document = only the record the page shows, and changes are proposals the person applies',
44
+ ),
22
45
  })
23
46
  .strict(),
24
- // On by default: what apps did before the switch existed.
25
- { ownModels: true },
47
+ // Own models on: what apps did before the switch existed. The chat in the app server with every action is the default.
48
+ { ownModels: true, engine: 'app', chatAccess: 'actions' },
26
49
  {
27
- label: 'Assistant: models',
28
- description: 'Which models people may run the assistant on',
50
+ label: 'Assistant: models and engine',
51
+ description: 'Which models people may run the assistant on, what a conversation runs on and what it reaches',
29
52
  i18n: { catalogs: coreMessages, prefix: 'core.settings.assistantPolicy' },
30
53
  },
31
54
  )
@@ -34,3 +57,13 @@ export const assistantPolicy = defineSettingsScope(
34
57
  export async function ownModelsAllowed(): Promise<boolean> {
35
58
  return (await getSettings(assistantPolicy)).ownModels
36
59
  }
60
+
61
+ /** What a new conversation prefers when both engines can run (`assistant-policy.engine`). */
62
+ export async function preferredAssistantEngine(): Promise<AssistantEnginePreference> {
63
+ return (await getSettings(assistantPolicy)).engine
64
+ }
65
+
66
+ /** What the plain chat reaches (`assistant-policy.chatAccess`). */
67
+ export async function chatAccess(): Promise<ChatAccess> {
68
+ return (await getSettings(assistantPolicy)).chatAccess
69
+ }