@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 CHANGED
@@ -1,5 +1,32 @@
1
1
  # @skaile/forge-layer-core
2
2
 
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 97d3c66: The assistant gets a third engine, `app`, and the owner decides which engine answers and what the chat reaches.
8
+
9
+ - `AssistantMode` is `'app' | 'skaile' | 'byok'`: `app` is the chat in the app server on the app's model (registered by `@skaile/forge-layer-chat` 3). `chat_threads.transport` accepts `app`; no migration.
10
+ - `assistant-policy` (Settings › Agents) has two new fields: `engine` (`app`, the default, or `skaile`: what a new conversation runs on when both can; the other steps in when the chosen one cannot run) and `chatAccess` (`actions`, the default: the chat in the app server reaches every action a model may call, with the rights of the person; `document`: only the record the page shows, changes are proposals). New helpers `preferredAssistantEngine()` and `chatAccess()`.
11
+ - `effectiveAssistantMode` follows `engine`. With `app`: `byok` for a person who chose their own key, else `app`, else `skaile`. With `skaile`: `skaile`, else `byok` for a person who chose their own key, else `app`. An app whose layers register no `app` engine behaves as before.
12
+ - `assistant.account.get|update` answer `chatAccess` too. A person's `mode` stays `skaile` ("App's model") or `byok` (`AssistantAccountMode`, `ASSISTANT_ACCOUNT_MODES`); "App's model" is accepted when the `app` or the `skaile` engine is installed. Settings › Profile offers it accordingly.
13
+ - `resolveRoleModel(roleId, { sdkModel: true })` resolves an AI SDK model in this process also for a role registered with `sdkModel: false`.
14
+ - 913a9b9: Sign-in by mail: the new auth mode `APP_AUTH_MODE=email`. The sign-in page asks for the address and mails a six-digit code and a one-click link (`<APP_URL>/login/verify?token=…&next=…`), both valid 10 minutes and once. The defaults stay (`password` with `DATABASE_URL`, `local` without); the modes `local`, `password` and `passkey` are unchanged.
15
+
16
+ - **Limits.** 5 codes per address within an hour (429), a new code ends the earlier ones, the fifth wrong entry ends the code (429), an expired code answers 410. Every address gets the same answer after the same minimum time, known or not, and only people in `users` get a mail. Only hashes are stored.
17
+ - **Actions and route.** `auth.code.request` and `auth.code.verify` (audience `user`) are in the core catalogue; they are the only actions a same-origin request without a session may call (`SIGN_IN_ACTION_IDS`, `signInPrincipal()`). The link is the server route `GET /login/verify`; a dead link comes back to `/login?link=expired|invalid`. Sessions open through `startUserSession`.
18
+ - **Mail.** `sendMail()` in `server/utils/mail.ts` sends over `SMTP_URL` with nodemailer from `MAIL_FROM` (default `noreply@<SMTP host>`), retries once and then throws `MailSendError`. `setMailSender()` and `createMemoryMailSender()` replace the transport in tests. The sign-in mail comes in the app's language (`core.login.mail*`, English and German) and names the app by the `app` settings' `appName`.
19
+ - **Environment.** `SMTP_URL`, `APP_URL` (the root of every mailed link, `appBaseUrl()`; never the request's Host header) and `MAIL_FROM`. The server refuses to start in email mode without `SMTP_URL` or `APP_URL`, with `SMTP_URL` set but no `APP_URL` in any mode, and with an unknown `APP_AUTH_MODE` (before: the first request failed).
20
+ - **Invitations.** `createSignInLink({ userId, ttlMs, next })` (`server/utils/login-codes.ts`, email mode) stores a link without a code and returns `{ link, id, expiresAt, discard }`; the app writes and sends its own mail and calls `discard()` when the send fails. `assertSignInLinkAllowed(userId)` answers 429 after 5 links for one person within an hour.
21
+ - **Database.** Migration `0004_email_sign_in`: the table `login_codes` and the nullable column `users.last_sign_in_at`, set on a sign-in by code or link (hidden from `data.*`).
22
+ - **Dependencies.** `nodemailer`, `@types/nodemailer` and `ufo` are new dependencies.
23
+
24
+ ## 1.2.0
25
+
26
+ ### Minor Changes
27
+
28
+ - 7367ff9: Owners decide whether people may run the assistant on their own model: the settings scope `assistant-policy` (`ownModels`, default on, in Settings › Agents in the assistant's card; `ownModelsAllowed()`). Off, Profil shows no mode or key fields, just "The assistant uses the app's model", `assistant.account.update` refuses mode `byok` and own-key changes (403; removing a stored key still works) and stored keys are ignored, not deleted. New `personalModel(userId)` gives the person's provider, model, base URL and key when they chose "Own key" and the app allows it, so the SKAILE agent can run on it; `byokLanguageModel` builds on it and refuses while own models are off. `effectiveAssistantMode` now picks `skaile` whenever it is available to the person (with their own key under "Own key"), else `byok`. `assistant.account.get` reports `ownModels`. Profil names the modes "App's model" and "Own key", and offers "Own key" when either the SKAILE or the chat engine is installed. The Settings › Agents assistant card renders the form of every scope its parts name.
29
+
3
30
  ## 1.1.0
4
31
 
5
32
  ### Minor Changes
package/README.md CHANGED
@@ -24,7 +24,8 @@ Peers: `nuxt ^4`, `@nuxt/ui ^4.11`, `vue ^3.5`, `vue-router ^5`, `@vueuse/core ^
24
24
  | Where | What |
25
25
  | --- | --- |
26
26
  | Modules | `@nuxt/ui`, `@vueuse/nuxt`, `nuxt-auth-utils` (session cookie `skaile-app-session`, 7 days), `@skaile/forge-app-actions` (`/api/actions`, `/mcp`), `@skaile/forge-settings/nuxt` |
27
- | Sign-in | `APP_AUTH_MODE` `local` (one owner, no sign-in), `password` or `passkey` (see [Sign-in](#sign-in)); `server/api/auth/*`, `app/pages/login.vue`, `app/middleware/auth.global.ts` |
27
+ | Sign-in | `APP_AUTH_MODE` `local` (one owner, no sign-in), `password`, `passkey` or `email` (see [Sign-in](#sign-in)); `server/api/auth/*`, `server/utils/login-codes.ts`, `app/pages/login.vue`, `app/middleware/auth.global.ts` |
28
+ | Mail | `sendMail()` over `SMTP_URL` (`server/utils/mail.ts`, see [Mail](#mail)) |
28
29
  | Principals, tokens | `server/utils/{auth,principal,tokens,password,passkeys}.ts`, `CORE_SCOPES` in `shared/domain.ts` |
29
30
  | Action catalogue | `server/utils/actions/*` (`defineAppAction`, `registerActions`), authorization in `server/plugins/actions.ts` |
30
31
  | Data model | `server/db/{client,model,seed}.ts`, `server/db/schema/*`, `defineAppLayer` (`server/utils/app-layers.ts`), `data.*` (`server/utils/data.ts`) |
@@ -41,7 +42,7 @@ a file at the same path in the app.
41
42
  `APP_AUTH_MODE` is read at runtime; without it the app runs `local` without `DATABASE_URL` and `password` with it.
42
43
  Every mode ends in the same nuxt-auth-utils session (`startUserSession` in `server/utils/auth.ts`); the `users` table
43
44
  is the person record. On boot the server seeds the first owner from `APP_OWNER_EMAIL` / `APP_OWNER_NAME` /
44
- `APP_OWNER_PASSWORD` when the table is empty.
45
+ `APP_OWNER_PASSWORD` when the table is empty. An unknown `APP_AUTH_MODE` refuses to start.
45
46
 
46
47
  - `local`: every page request signs in as the owner. API and MCP still need a token.
47
48
  - `password`: email and password (`POST /api/auth/login`) against `users.password_hash`.
@@ -53,6 +54,51 @@ is the person record. On boot the server seeds the first owner from `APP_OWNER_E
53
54
  The relying party is the request's origin and host unless `NUXT_AUTH_ORIGIN`, `NUXT_AUTH_RP_ID` and
54
55
  `NUXT_AUTH_RP_NAME` say otherwise (set origin and id behind a proxy). Challenges live in process memory for five
55
56
  minutes, so several web replicas need sticky sessions.
57
+ - `email`: the sign-in page asks for the address and mails a six-digit code and a one-click link
58
+ (`<APP_URL>/login/verify?token=…&next=…`), both valid 10 minutes and once. Opt-in: set `APP_AUTH_MODE=email`,
59
+ `SMTP_URL` and `APP_URL`; the server refuses to start in this mode without either. There is no sign-up: only
60
+ people in `users` get a mail (in a fresh database the seeded owner, `APP_OWNER_EMAIL`), and every address gets the
61
+ same answer after the same minimum time (1.5 s), so the page does not tell which addresses exist. Limits
62
+ (`shared/sign-in.ts`): 5 codes per address and hour (429), a new code ends the earlier ones, the fifth wrong entry
63
+ ends the code (429), an expired one answers 410. Only hashes are stored (table `login_codes`); a sign-in sets
64
+ `users.last_sign_in_at`. The page calls the actions `auth.code.request` and `auth.code.verify` (audience `user`):
65
+ the only two a same-origin request without a session may call (`SIGN_IN_ACTION_IDS`); the link is the server route
66
+ `GET /login/verify`, which sends a dead link back to `/login?link=expired|invalid`. The mail comes in the app's
67
+ language and names the app by the `app` settings' `appName`. The unknown-address counter lives in process memory.
68
+
69
+ ### Sign-in links for invitations
70
+
71
+ `createSignInLink({ userId, ttlMs, next })` (`server/utils/login-codes.ts`, email mode) stores a link without a code
72
+ and returns `{ link, id, expiresAt, discard }`: following the link signs that person in once and opens `next`. The
73
+ app writes and sends the invitation mail itself; when the send fails, `discard()` revokes the link.
74
+ `assertSignInLinkAllowed(userId)` (also called by `createSignInLink`) answers 429 after 5 links for one person
75
+ within an hour. Code requests never end such a link, and no entered code can match it.
76
+
77
+ ```ts
78
+ import { createSignInLink } from '@skaile/forge-layer-core/server/utils/login-codes'
79
+ import { sendMail } from '@skaile/forge-layer-core/server/utils/mail'
80
+
81
+ const invite = await createSignInLink({ userId, ttlMs: 7 * 24 * 60 * 60_000, next: '/projects/42' })
82
+ try {
83
+ await sendMail({ to: email, subject: 'You are invited', text: `Sign in: ${invite.link}` })
84
+ } catch (error) {
85
+ await invite.discard()
86
+ throw error
87
+ }
88
+ ```
89
+
90
+ ## Mail
91
+
92
+ `sendMail({ to, subject, text, html? })` (`server/utils/mail.ts`) sends through nodemailer over `SMTP_URL`
93
+ (`smtp://` or `smtps://`, user and password in the URL) from `MAIL_FROM` (default `noreply@<SMTP host>`). A failed
94
+ send is retried once, then it throws `MailSendError`. Tests install `createMemoryMailSender()` with
95
+ `setMailSender()` and read `sender.sent`; `sender.fail = n` makes the next `n` sends fail.
96
+
97
+ | Variable | What |
98
+ | --- | --- |
99
+ | `SMTP_URL` | SMTP server for every mail, e.g. `smtps://user:password@smtp.example.com:465`. Required in email mode. |
100
+ | `APP_URL` | The app's public address, e.g. `https://app.example.com`: every link in a mail starts with it (`appBaseUrl()` in `server/utils/auth-mode.ts`), never with the request's `Host` header. Required in email mode and whenever `SMTP_URL` is set; the server refuses to start without it. |
101
+ | `MAIL_FROM` | Sender of the mails, e.g. `App <app@example.com>`. Default: `noreply@<host of SMTP_URL>`. |
56
102
 
57
103
  ## AI models
58
104
 
@@ -74,6 +120,34 @@ runner resolves the model itself, like the workspace agent) gets it as `source:
74
120
  failover; the runner builds its config from `NUXT_AI_FALLBACK_*` itself. When the fallback stands in for a broken
75
121
  assignment, `ai.status` gives owners (only them) a `warning` with the assignment's problem; the role stays available.
76
122
 
123
+ ## The assistant's model
124
+
125
+ The app has one assistant, the SKAILE workspace agent (`skaile` engine, from layer-workspace-agent). It runs on the
126
+ app's model (the `assistant` role above) unless the person uses their own:
127
+
128
+ - **Own models** (settings scope `assistant-policy`, field `ownModels`, default on; `server/utils/assistant/policy.ts`,
129
+ `ownModelsAllowed()`): owners switch it in Settings › Agents, in the assistant's card. On, each person may pick
130
+ "Own key" (mode `byok`) in Settings › Profile and store provider, model and key (sealed under `NUXT_APP_SECRET`).
131
+ Off, nobody can pick it (`assistant.account.update` answers 403; `clearKey` still works), stored keys are kept but
132
+ ignored, and Profile shows one line: the assistant uses the app's model.
133
+ - `personalModel(userId)` (`server/utils/assistant/account.ts`): the person's provider, model, absolute base URL and
134
+ unsealed key when own models are allowed, they chose `byok` and stored all of it, else `null`. The SKAILE engine
135
+ runs on it; `byokLanguageModel(userId)` builds the plain chat engine's model (layer-chat) and refuses while own
136
+ models are off.
137
+ - **Engine** (`assistant-policy.engine`, default `app`; `preferredAssistantEngine()`): what a new conversation runs
138
+ on when both can, the chat in the app server (`app`, layer-chat) or the SKAILE agent (`skaile`,
139
+ layer-workspace-agent). The other one steps in when the chosen one cannot run.
140
+ - **Access of the chat** (`assistant-policy.chatAccess`, default `actions`; `chatAccess()`): what the chat in the app
141
+ server (`app`, `byok`) reaches: every action a model may call, with the rights of the person, or with `document`
142
+ only the record the page shows, changes being proposals the person applies.
143
+ - `effectiveAssistantMode(principal)` (`server/utils/assistant/engines.ts`), the engine a new conversation uses. With
144
+ `engine: 'app'`: `byok` for a person who chose their own key (own models allowed), else `app`, else `skaile`. With
145
+ `engine: 'skaile'`: `skaile` whenever it is available to the person (on their own model when they chose it), else
146
+ `byok` for a person who chose their own key, else `app`. Last `byok` for anyone with a usable key, else `null`.
147
+ A person's choice in Settings › Profile stays "App's model" (`skaile`) or "Own key" (`byok`).
148
+ - `resolveRoleModel(roleId, { sdkModel: true })` resolves an AI SDK model in this process also for a role another
149
+ consumer registered with `sdkModel: false` (the chat in the app server on the role `assistant`).
150
+
77
151
  ## Importing core server code
78
152
 
79
153
  Other layers and the app's CLI and tests import through the package's `exports`, never `~~/server/...`:
@@ -3,11 +3,13 @@ import * as z from 'zod'
3
3
 
4
4
  /**
5
5
  * Settings › Profile › Assistant: how the app's assistant works for the signed-in person
6
- * (`assistant.account.get` / `assistant.account.update`). Mode `skaile` runs it with SKAILE on
7
- * the server, with full access to the app and the person's rights; mode `byok` ("Own key") runs
8
- * it on the person's own provider key and lets it see only the record of the open page. One
9
- * form, one explicit Save (EDIT-2); the key is write-only: the page only learns whether one is
10
- * saved (`hasKey`) and removes it through `clearKey`.
6
+ * (`assistant.account.get` / `assistant.account.update`). Whether people may pick their own model
7
+ * is the owner's call (`assistant-policy.ownModels`, Settings › Agents). Allowed: mode `skaile`
8
+ * ("App's model") runs the assistant on the app's model; mode `byok` ("Own key") runs it on the
9
+ * person's provider, model and key. Which engine answers (the chat in the app server or the SKAILE
10
+ * agent) is the owner's `assistant-policy.engine`. Not allowed: one line says the assistant uses the
11
+ * app's model, and a saved key can still be removed. One form, one explicit Save (EDIT-2); the key
12
+ * is write-only: the page only learns whether one is saved (`hasKey`) and removes it through `clearKey`.
11
13
  */
12
14
 
13
15
  const actions = useActions()
@@ -64,7 +66,8 @@ const labels = computed(
64
66
 
65
67
  // An account without a chosen mode shows the mode it gets anyway, so opening the page is no change.
66
68
  const stateOf = (value: Account | null | undefined): State => ({
67
- mode: value?.mode ?? value?.effectiveMode ?? undefined,
69
+ // Not chosen: what a new conversation runs on, as one of the two choices (`app` is the app's model).
70
+ mode: value?.mode ?? (value?.effectiveMode ? (value.effectiveMode === 'byok' ? 'byok' : 'skaile') : undefined),
68
71
  preset: value?.byok.preset ?? undefined,
69
72
  model: value?.byok.model ?? '',
70
73
  baseUrl: value?.byok.baseUrl ?? '',
@@ -76,19 +79,39 @@ useLeaveGuard(dirty)
76
79
  const missing = computed(() => missingFields(schema.value, state, labels.value))
77
80
  const form = useTemplateRef('form')
78
81
 
79
- // A mode that is not installed cannot be chosen; "Own key" stays choosable without a key,
80
- // because this form is where the key is entered (so its reason, which points here, is not repeated).
81
- const modeItems = computed(() =>
82
- (account.value?.modes ?? []).map(({ mode, available, installed, reason }) => {
83
- const hint = t(`core.assistant.modeHint.${mode}`)
84
- return {
85
- value: mode,
86
- label: t(`core.assistant.mode.${mode}`),
87
- description: available || !reason || mode === 'byok' ? hint : `${hint} ${reason}`,
88
- disabled: !installed || (!available && mode !== 'byok'),
89
- }
90
- }),
91
- )
82
+ // "App's model" runs on the chat in the app server or the SKAILE agent, "Own key" on the SKAILE agent or the
83
+ // chat's own-key engine: each is offered when one of its engines is installed. "Own key" stays choosable without
84
+ // a key, because this form is where the key is entered (so its reason, which points here, is not repeated).
85
+ const modeItems = computed(() => {
86
+ const modes = account.value?.modes ?? []
87
+ const engine = (mode: Mode) => modes.find(entry => entry.mode === mode)
88
+ const skaile = engine('skaile')
89
+ const appModel = [engine('app'), skaile].filter(entry => entry?.installed)
90
+ const appModelReady = appModel.some(entry => entry?.available)
91
+ const appModelReason = appModel.find(entry => entry?.reason)?.reason
92
+ const appModelHint = t('core.assistant.modeHint.skaile')
93
+ const byokInstalled = Boolean(skaile?.installed || engine('byok')?.installed)
94
+ return [
95
+ {
96
+ value: 'skaile' as const,
97
+ label: t('core.assistant.mode.skaile'),
98
+ description: !appModel.length
99
+ ? `${appModelHint} ${t('core.assistant.notInstalled')}`
100
+ : appModelReady || !appModelReason
101
+ ? appModelHint
102
+ : `${appModelHint} ${appModelReason}`,
103
+ disabled: !appModelReady,
104
+ },
105
+ {
106
+ value: 'byok' as const,
107
+ label: t('core.assistant.mode.byok'),
108
+ description: byokInstalled
109
+ ? t(skaile?.installed ? 'core.assistant.modeHint.byok' : 'core.assistant.modeHint.byokChat')
110
+ : `${t('core.assistant.modeHint.byok')} ${t('core.assistant.notInstalled')}`,
111
+ disabled: !byokInstalled,
112
+ },
113
+ ]
114
+ })
92
115
  const presetItems = computed(() =>
93
116
  PRESETS.map(({ value, label }) => ({
94
117
  value,
@@ -178,7 +201,17 @@ async function removeKey() {
178
201
  @submit="onSave"
179
202
  @error="focusFirstError"
180
203
  >
181
- <UFormField name="mode">
204
+ <p
205
+ v-if="!account.ownModels"
206
+ class="text-sm text-muted"
207
+ data-testid="assistant-app-model-only"
208
+ >
209
+ {{ t('core.assistant.appModelOnly') }}
210
+ </p>
211
+ <UFormField
212
+ v-else
213
+ name="mode"
214
+ >
182
215
  <URadioGroup
183
216
  v-model="state.mode"
184
217
  :items="modeItems"
@@ -188,7 +221,7 @@ async function removeKey() {
188
221
  />
189
222
  </UFormField>
190
223
 
191
- <template v-if="state.mode === 'byok'">
224
+ <template v-if="account.ownModels && state.mode === 'byok'">
192
225
  <UFormField
193
226
  name="preset"
194
227
  :label="labels.preset"
@@ -271,6 +304,7 @@ async function removeKey() {
271
304
  </div>
272
305
 
273
306
  <SettingsSave
307
+ v-if="account?.ownModels"
274
308
  :dirty="dirty"
275
309
  :loading="saving"
276
310
  :missing="missing"
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Password and passkey mode: pages need a session, otherwise → /login. In
2
+ * Password, passkey and email mode: pages need a session, otherwise → /login. In
3
3
  * local mode the server signs every page request in as the owner, so this
4
4
  * never redirects.
5
5
  */
@@ -2,9 +2,11 @@
2
2
  import type { AuthFormField, FormSubmitEvent } from '@nuxt/ui'
3
3
  import * as z from 'zod'
4
4
  import { signInEmailSchema } from '../../shared/domain'
5
+ import { LOGIN_CODE_LENGTH, LOGIN_CODE_TTL_MINUTES, RESEND_AFTER_SECONDS, safeNextPath } from '../../shared/sign-in'
5
6
 
6
- // Sign-in of password mode (email + password) and passkey mode (the device's
7
- // screen lock). In passkey mode the owner is claimed here with the first passkey.
7
+ // Sign-in of password mode (email + password), passkey mode (the device's
8
+ // screen lock) and email mode (a mailed code or link). In passkey mode the
9
+ // owner is claimed here with the first passkey.
8
10
  definePageMeta({ layout: false })
9
11
  const { t } = useCoreI18n()
10
12
  useHead({ title: () => t('core.login.title') })
@@ -86,6 +88,138 @@ function claimOwner() {
86
88
  })
87
89
  }
88
90
 
91
+ // Email mode: step 1 the address and "Send code", step 2 six digit fields that take a paste and sign in on the sixth
92
+ // digit, "Send the code again" after a minute, "Other address". The mailed link lands on `/login/verify` (server
93
+ // route); a dead link comes back here with `?link=expired|invalid`.
94
+ const actions = useActions()
95
+ const address = ref('')
96
+ const step = ref<'email' | 'code'>('email')
97
+ const digits = ref<string[]>([])
98
+ const sending = ref(false)
99
+ const checking = ref(false)
100
+ const addressError = ref<string>()
101
+ const resendError = ref<string>()
102
+ const codeError = ref<string>()
103
+ /** The code is past its ten minutes, or dead after five wrong entries: the fields stay disabled until a new one. */
104
+ const codeState = ref<'live' | 'expired' | 'dead'>('live')
105
+ const shaking = ref(false)
106
+ const pinBox = useTemplateRef<HTMLElement>('pinBox')
107
+ const linkError = computed(() =>
108
+ route.query.link === 'expired'
109
+ ? t('core.login.expiredLink')
110
+ : route.query.link === 'invalid'
111
+ ? t('core.login.invalidLink')
112
+ : undefined,
113
+ )
114
+
115
+ const codeHint = computed(() =>
116
+ t('core.login.codeHint', { email: address.value.trim(), minutes: LOGIN_CODE_TTL_MINUTES }),
117
+ )
118
+
119
+ const resendLeft = ref(0)
120
+ let timer: ReturnType<typeof setInterval> | undefined
121
+ function startCountdown(seconds: number) {
122
+ clearInterval(timer)
123
+ resendLeft.value = seconds
124
+ if (seconds <= 0) return
125
+ timer = setInterval(() => {
126
+ resendLeft.value = Math.max(0, resendLeft.value - 1)
127
+ if (resendLeft.value === 0) clearInterval(timer)
128
+ }, 1000)
129
+ }
130
+ onBeforeUnmount(() => clearInterval(timer))
131
+ const countdown = computed(
132
+ () => `${Math.floor(resendLeft.value / 60)}:${String(resendLeft.value % 60).padStart(2, '0')}`,
133
+ )
134
+ const resendLocked = computed(() => resendLeft.value > 0 && codeState.value === 'live')
135
+ const codeFieldError = computed(() =>
136
+ codeState.value === 'expired'
137
+ ? t('core.login.expiredCode')
138
+ : codeState.value === 'dead'
139
+ ? t('core.login.tooManyAttempts')
140
+ : codeError.value,
141
+ )
142
+
143
+ function statusOf(error: unknown): number | undefined {
144
+ return error && typeof error === 'object' && 'statusCode' in error && typeof error.statusCode === 'number'
145
+ ? error.statusCode
146
+ : undefined
147
+ }
148
+
149
+ /** Mails a new code; returns the error text to show, or nothing when it went out. */
150
+ async function send(): Promise<string | undefined> {
151
+ sending.value = true
152
+ try {
153
+ await actions.call('auth.code.request', {
154
+ email: address.value.trim(),
155
+ next: safeNextPath(route.query.redirect),
156
+ })
157
+ } catch (error) {
158
+ return actionErrorMessage(error)
159
+ } finally {
160
+ sending.value = false
161
+ }
162
+ digits.value = []
163
+ codeError.value = undefined
164
+ codeState.value = 'live'
165
+ startCountdown(RESEND_AFTER_SECONDS)
166
+ }
167
+
168
+ async function sendCode() {
169
+ addressError.value = undefined
170
+ if (!signInEmailSchema().safeParse(address.value).success) {
171
+ addressError.value = t('core.login.emailInvalid')
172
+ return
173
+ }
174
+ addressError.value = await send()
175
+ if (!addressError.value) step.value = 'code'
176
+ }
177
+
178
+ async function resendCode() {
179
+ resendError.value = await send()
180
+ }
181
+
182
+ async function wrongCode() {
183
+ digits.value = []
184
+ codeError.value = t('core.login.wrongCode')
185
+ shaking.value = true
186
+ setTimeout(() => {
187
+ shaking.value = false
188
+ }, 400)
189
+ await nextTick()
190
+ pinBox.value?.querySelector('input')?.focus()
191
+ }
192
+
193
+ async function verifyCode() {
194
+ const code = digits.value.join('')
195
+ if (code.length < LOGIN_CODE_LENGTH || codeState.value !== 'live' || checking.value) return
196
+ codeError.value = undefined
197
+ checking.value = true
198
+ try {
199
+ await actions.call('auth.code.verify', { email: address.value.trim(), code })
200
+ } catch (error) {
201
+ checking.value = false
202
+ const status = statusOf(error)
203
+ if (status === 401) return wrongCode()
204
+ if (status === 410 || status === 429) {
205
+ codeState.value = status === 410 ? 'expired' : 'dead'
206
+ digits.value = []
207
+ startCountdown(0)
208
+ return
209
+ }
210
+ codeError.value = actionErrorMessage(error)
211
+ return
212
+ }
213
+ await signedIn()
214
+ }
215
+
216
+ function otherAddress() {
217
+ step.value = 'email'
218
+ digits.value = []
219
+ codeError.value = undefined
220
+ resendError.value = undefined
221
+ }
222
+
89
223
  const baseURL = useRuntimeConfig().app.baseURL
90
224
  </script>
91
225
 
@@ -177,6 +311,122 @@ const baseURL = useRuntimeConfig().app.baseURL
177
311
  />
178
312
  </form>
179
313
  </div>
314
+ <div
315
+ v-else-if="status?.mode === 'email'"
316
+ class="flex flex-col gap-6"
317
+ data-testid="email-sign-in"
318
+ >
319
+ <form
320
+ v-if="step === 'email'"
321
+ class="flex flex-col gap-4"
322
+ novalidate
323
+ @submit.prevent="sendCode"
324
+ >
325
+ <div class="flex flex-col gap-1">
326
+ <h1 class="text-lg font-semibold text-highlighted">
327
+ {{ t('core.login.title') }}
328
+ </h1>
329
+ <p class="text-sm text-muted">
330
+ {{ t('core.login.emailModeHint') }}
331
+ </p>
332
+ </div>
333
+ <UAlert
334
+ v-if="linkError"
335
+ color="warning"
336
+ variant="subtle"
337
+ icon="i-tabler-link-off"
338
+ :description="linkError"
339
+ data-testid="email-sign-in-link-error"
340
+ />
341
+ <UFormField
342
+ :label="t('core.login.email')"
343
+ name="email"
344
+ :error="addressError"
345
+ required
346
+ >
347
+ <UInput
348
+ v-model="address"
349
+ type="email"
350
+ autocomplete="email"
351
+ :placeholder="t('core.login.emailPlaceholder')"
352
+ class="w-full"
353
+ :readonly="sending"
354
+ autofocus
355
+ />
356
+ </UFormField>
357
+ <UButton
358
+ type="submit"
359
+ :label="t('core.login.sendCode')"
360
+ block
361
+ :loading="sending"
362
+ data-testid="email-sign-in-send"
363
+ />
364
+ </form>
365
+ <form
366
+ v-else
367
+ class="flex flex-col gap-4"
368
+ novalidate
369
+ @submit.prevent="verifyCode"
370
+ >
371
+ <div class="flex flex-col gap-1">
372
+ <h1 class="text-lg font-semibold text-highlighted">
373
+ {{ t('core.login.codeTitle') }}
374
+ </h1>
375
+ <p class="text-sm text-muted">
376
+ {{ codeHint }}
377
+ </p>
378
+ </div>
379
+ <UFormField
380
+ :label="t('core.login.code')"
381
+ name="code"
382
+ :error="codeFieldError"
383
+ >
384
+ <div
385
+ ref="pinBox"
386
+ :class="{ 'login-shake': shaking }"
387
+ >
388
+ <UPinInput
389
+ v-model="digits"
390
+ :length="LOGIN_CODE_LENGTH"
391
+ otp
392
+ type="text"
393
+ placeholder="○"
394
+ size="lg"
395
+ :disabled="codeState !== 'live' || checking"
396
+ :aria-label="t('core.login.code')"
397
+ autofocus
398
+ @complete="verifyCode"
399
+ />
400
+ </div>
401
+ </UFormField>
402
+ <UAlert
403
+ v-if="resendError"
404
+ color="error"
405
+ variant="subtle"
406
+ icon="i-tabler-alert-octagon"
407
+ :description="resendError"
408
+ />
409
+ <div class="flex items-center justify-between gap-2 text-sm">
410
+ <UButton
411
+ :label="t('core.login.otherAddress')"
412
+ color="neutral"
413
+ variant="link"
414
+ class="px-0"
415
+ @click="otherAddress"
416
+ />
417
+ <UButton
418
+ :label="resendLocked ? t('core.login.resendCodeIn', { time: countdown }) : t('core.login.resendCode')"
419
+ color="neutral"
420
+ variant="link"
421
+ class="px-0"
422
+ :disabled="resendLocked"
423
+ :loading="sending"
424
+ data-testid="email-sign-in-resend"
425
+ @click="resendCode"
426
+ />
427
+ </div>
428
+ </form>
429
+ </div>
180
430
  <UAuthForm
181
431
  v-else
182
432
  :schema="schema"
@@ -197,3 +447,24 @@ const baseURL = useRuntimeConfig().app.baseURL
197
447
  </div>
198
448
  </div>
199
449
  </template>
450
+
451
+ <style scoped>
452
+ .login-shake {
453
+ animation: login-shake 0.4s ease-in-out;
454
+ }
455
+
456
+ @keyframes login-shake {
457
+ 0%,
458
+ 100% {
459
+ transform: translateX(0);
460
+ }
461
+ 20%,
462
+ 60% {
463
+ transform: translateX(-6px);
464
+ }
465
+ 40%,
466
+ 80% {
467
+ transform: translateX(6px);
468
+ }
469
+ }
470
+ </style>
@@ -1,5 +1,7 @@
1
1
  <script setup lang="ts">
2
2
  import { defineComponent, h } from 'vue'
3
+ // From `#components`, so an app's own `SettingsScopeForm` replaces the layer's here too.
4
+ import { SettingsScopeForm } from '#components'
3
5
  import type { AppShellSettingsSection } from '../../types/app-shell'
4
6
 
5
7
  /**
@@ -7,11 +9,15 @@ import type { AppShellSettingsSection } from '../../types/app-shell'
7
9
  * with this route): its model's status and checks, its settings and its own
8
10
  * content. The app has one assistant: every section of role or scope
9
11
  * `assistant` (the chat layer's settings, the SKAILE runs and tokens) is drawn
10
- * as one card, titled with the assistant's name. Models are chosen in
11
- * Settings › Harness. Owners edit; everyone else reads.
12
+ * as one card, titled with the assistant's name, with the form of every scope
13
+ * its parts name. The core's `assistant-policy` scope (whether people may use
14
+ * their own models) joins that card whenever there is one, so no layer has to
15
+ * contribute it. Models are chosen in Settings › Harness. Owners edit;
16
+ * everyone else reads.
12
17
  */
13
18
  const ROUTE = '/settings/agents'
14
19
  const ASSISTANT = 'assistant'
20
+ const ASSISTANT_POLICY = 'assistant-policy'
15
21
 
16
22
  const { t } = useCoreI18n()
17
23
  useHead({ title: () => t('core.agents.title') })
@@ -28,13 +34,37 @@ const onPage = computed(() =>
28
34
  )
29
35
  const isAssistant = (section: AppShellSettingsSection) => section.role === ASSISTANT || section.scope === ASSISTANT
30
36
  const assistantParts = computed(() => onPage.value.filter(isAssistant))
31
- // The parts' own components, one after another; its own computed, so a new name does not remount them.
37
+ // Every scope of the parts once, in their order, then the policy; the first is the card's own form.
38
+ const assistantScopes = computed(() => [
39
+ ...new Set([...assistantParts.value.flatMap(part => (part.scope ? [part.scope] : [])), ASSISTANT_POLICY]),
40
+ ])
41
+
42
+ // Unsaved state per form on the page (one card's form under its role or scope, further scope forms under their
43
+ // scope), so the leave guard asks once for all of them.
44
+ const sectionDirty = reactive<Record<string, boolean>>({})
45
+ useLeaveGuard(computed(() => Object.values(sectionDirty).some(Boolean)))
46
+
47
+ // The forms of the further scopes, then the parts' own components, one after another; its own computed, so a new
48
+ // name does not remount them.
32
49
  const assistantComponent = computed(() => {
50
+ const moreScopes = assistantScopes.value.slice(1)
33
51
  const components = assistantParts.value.flatMap(part => (part.component ? [part.component] : []))
34
- if (components.length < 2) return components[0]
52
+ if (moreScopes.length === 0 && components.length < 2) return components[0]
35
53
  return defineComponent({
36
54
  name: 'AssistantSectionParts',
37
- setup: () => () => components.map(component => h(component)),
55
+ setup: () => () => [
56
+ ...moreScopes.map(scope =>
57
+ h(SettingsScopeForm, {
58
+ key: scope,
59
+ scope,
60
+ readOnly: !canEdit.value,
61
+ onDirty: (value: boolean) => {
62
+ sectionDirty[scope] = value
63
+ },
64
+ }),
65
+ ),
66
+ ...components.map(component => h(component)),
67
+ ],
38
68
  })
39
69
  })
40
70
 
@@ -46,7 +76,7 @@ const sections = computed<AppShellSettingsSection[]>(() => {
46
76
  title: account.value?.name ?? parts[0]!.title,
47
77
  order: parts[0]!.order,
48
78
  role: parts.find(part => part.role)?.role,
49
- scope: parts.find(part => part.scope)?.scope,
79
+ scope: assistantScopes.value[0],
50
80
  component: assistantComponent.value,
51
81
  }
52
82
  return [assistant, ...onPage.value.filter(section => !isAssistant(section))].sort((a, b) => a.order - b.order)
@@ -54,9 +84,6 @@ const sections = computed<AppShellSettingsSection[]>(() => {
54
84
 
55
85
  const { data: status } = await useAsyncData('ai:status', () => actions.call('ai.status', {}))
56
86
  const statusOf = (roleId?: string) => (roleId ? status.value?.roles.find(role => role.id === roleId) : undefined)
57
-
58
- const sectionDirty = reactive<Record<string, boolean>>({})
59
- useLeaveGuard(computed(() => Object.values(sectionDirty).some(Boolean)))
60
87
  </script>
61
88
 
62
89
  <template>
package/nuxt.config.ts CHANGED
@@ -57,7 +57,7 @@ const coreSessionTypes = defineNuxtModule({
57
57
 
58
58
  // Layer: the base of an app built on forge-template-app, last in its `extends`.
59
59
  //
60
- // Sign-in (`APP_AUTH_MODE` local | password | passkey), principals and API tokens, settings
60
+ // Sign-in (`APP_AUTH_MODE` local | password | passkey | email), principals and API tokens, settings
61
61
  // scopes, the server-action catalogue on `/api/actions` and `/mcp`, the data model
62
62
  // (`defineAppLayer`, `data.*`), AI model roles and providers, the assistant's account,
63
63
  // engines and definition (`agents/app-assistant/`, the app's own folder wins), the