@nauticana/sail 1.1.34 → 1.1.35

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.
Files changed (43) hide show
  1. package/README.md +22 -15
  2. package/package.json +1 -1
  3. package/src/agent/component/approval_inbox.html +49 -2
  4. package/src/agent/component/approval_inbox.ts +54 -16
  5. package/src/agent/component/assistant_activity.html +28 -0
  6. package/src/agent/component/assistant_activity.ts +40 -0
  7. package/src/agent/component/studio_page.html +35 -1
  8. package/src/agent/component/studio_page.ts +67 -10
  9. package/src/agent/component/turn_thread.html +27 -0
  10. package/src/agent/component/turn_thread.ts +83 -0
  11. package/src/agent/index.ts +2 -0
  12. package/src/agent/model/agent_studio.ts +63 -0
  13. package/src/agent/model/approval.ts +37 -1
  14. package/src/agent/model/conversation.ts +31 -0
  15. package/src/agent/model/decision.ts +12 -8
  16. package/src/agent/service/agent_studio.service.ts +29 -0
  17. package/src/agent/service/approval.service.ts +24 -4
  18. package/src/agent/service/conversation.service.ts +10 -0
  19. package/src/component/agency/agency_earnings_summary.html +3 -3
  20. package/src/component/agency/agency_earnings_summary.ts +2 -2
  21. package/src/component/agency/agency_payout_history.html +1 -1
  22. package/src/component/agency/agency_payout_history.ts +2 -3
  23. package/src/component/agency/commission_ledger.html +1 -1
  24. package/src/component/agency/commission_ledger.ts +2 -3
  25. package/src/component/billing/plan_selector.ts +1 -1
  26. package/src/component/billing/price_selector.ts +5 -5
  27. package/src/component/payout/bank_info_form.html +15 -6
  28. package/src/component/payout/bank_info_form.ts +28 -72
  29. package/src/component/security/api_keys.html +78 -0
  30. package/src/component/security/api_keys.ts +90 -0
  31. package/src/component/security/connected_apps.html +25 -0
  32. package/src/component/security/connected_apps.ts +40 -0
  33. package/src/index.ts +7 -0
  34. package/src/model/access.ts +28 -0
  35. package/src/model/appdata.ts +41 -67
  36. package/src/model/geo.ts +12 -0
  37. package/src/service/access.service.ts +57 -0
  38. package/src/service/caption_pipe.ts +8 -2
  39. package/src/service/currency.service.ts +51 -0
  40. package/src/service/money_pipe.ts +27 -0
  41. package/src/service/rest_service.ts +1 -1
  42. package/src/service/rest_url.ts +3 -0
  43. package/src/util/money.ts +18 -34
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  A shared Angular component library for building CRUD-based admin frontends. Provides table management, form handling, navigation, authentication, two-factor authentication, and trusted device management — all driven by metadata from a [keel](https://github.com/nauticana/keel) Go backend.
4
4
 
5
- > **Compatibility:** sail and keel are versioned in lock-step. The current line is **sail v1.1.x ↔ keel v1.2.x**; sail v1.1.33 adopts keel v1.2.106 (`prompt` on the login page, new-device step-up, sign-in sessions), sail v1.1.32 adopts keel v1.2.101 (the OAuth connect callback ticket), sail v1.1.31 adopts keel v1.2.100 (tenant single sign-on, DNS and HTTP-file domain verification), sail v1.1.30 adopts keel v1.2.99 (password routes; a password change signs out), sail v1.1.29 adopts keel v1.2.94 (signup: confirmation signs in, partner setup, sign-in hand-off code), sail v1.1.28 adopts keel v1.2.93 (absolute `return` for the OAuth hand-off), sail v1.1.18 adopts keel v1.2.58 (refresh-token rotation, `/public/logout`, setup intents, the realtime hub), the agency components in sail v1.1.14 require keel v1.2.41 (sail v1.1.9 needs keel v1.2.16 for the OAuth-connect layer). Earlier lines: **sail v0.5.x ↔ keel v0.5.x**, **sail v0.6.x / v0.7.x ↔ keel v0.7.x**, **sail v0.8.x ↔ keel v0.8.x**, **sail v0.9.x ↔ keel v0.9.x**. Newer sail releases extend the contract — older keel servers reject unknown endpoints with HTTP 404 / 400. The v0.8.x line additionally ships the `table_action` framework (per-table custom buttons surfaced in `TableList` / `TableSearch` / `TableEdit` / `TableDetail`); see the [Migrating to v0.7.0 §5 — TableAction](#migrating-to-v070--payout-user-payment-methods-table-actions) section for the seed shape (basis `table_action` + `authorization_object` + `authorization_object_action` rows) and the [keel/README Table Actions](https://github.com/nauticana/keel#table-actions) section for backend wiring via `handler.WrapTableAction`.
5
+ > **Compatibility:** sail and keel are versioned in lock-step. The current line is **sail v1.1.x ↔ keel v1.2.x**; sail v1.1.35 adopts keel v1.2.112 (minor-unit money, the `currency` catalog, OAuth grant routes), sail v1.1.33 adopts keel v1.2.106 (`prompt` on the login page, new-device step-up, sign-in sessions), sail v1.1.32 adopts keel v1.2.101 (the OAuth connect callback ticket), sail v1.1.31 adopts keel v1.2.100 (tenant single sign-on, DNS and HTTP-file domain verification), sail v1.1.30 adopts keel v1.2.99 (password routes; a password change signs out), sail v1.1.29 adopts keel v1.2.94 (signup: confirmation signs in, partner setup, sign-in hand-off code), sail v1.1.28 adopts keel v1.2.93 (absolute `return` for the OAuth hand-off), sail v1.1.18 adopts keel v1.2.58 (refresh-token rotation, `/public/logout`, setup intents, the realtime hub), the agency components in sail v1.1.14 require keel v1.2.41 (sail v1.1.9 needs keel v1.2.16 for the OAuth-connect layer). Earlier lines: **sail v0.5.x ↔ keel v0.5.x**, **sail v0.6.x / v0.7.x ↔ keel v0.7.x**, **sail v0.8.x ↔ keel v0.8.x**, **sail v0.9.x ↔ keel v0.9.x**. Newer sail releases extend the contract — older keel servers reject unknown endpoints with HTTP 404 / 400. The v0.8.x line additionally ships the `table_action` framework (per-table custom buttons surfaced in `TableList` / `TableSearch` / `TableEdit` / `TableDetail`); see the [Migrating to v0.7.0 §5 — TableAction](#migrating-to-v070--payout-user-payment-methods-table-actions) section for the seed shape (basis `table_action` + `authorization_object` + `authorization_object_action` rows) and the [keel/README Table Actions](https://github.com/nauticana/keel#table-actions) section for backend wiring via `handler.WrapTableAction`.
6
6
 
7
7
  **Recent additions:** `BaseAuthService.acceptToken(jwt)` — adopt an externally-minted JWT (registration / SSO-handoff flows) and run the full post-login sequence (store under the canonical `jwt` key, load appdata, init routes); apps must use this instead of writing `localStorage` directly. `BaseRestService.analytic<T>(endpoint, params?)` — GET a keel `analytic/<endpoint>` report and return its rows. `passwordPolicyValidator` + `BaseAuthService.ensurePasswordPolicy()` — validate passwords against keel's policy (via `SailGuiConfig.passwordPolicyUrl`); see Configuration reference.
8
8
 
@@ -16,7 +16,7 @@ A shared Angular component library for building CRUD-based admin frontends. Prov
16
16
  | **Form components** | `DynamicField`, `RecordForm`, `TableForm` |
17
17
  | **Navigation** | `Navigation` (sidenav + toolbar with menu, responsive) |
18
18
  | **Login** | `LoginComponent`, `RegisterComponent`, `ChpassComponent`, `ConfirmRegisterComponent`, `ConfirmChpassComponent` |
19
- | **Security** | `TwoFactorSetupComponent`, `TwoFactorVerifyComponent`, `TrustedDevicesComponent`, `SessionsComponent`, `AccountDeletionComponent` |
19
+ | **Security** | `TwoFactorSetupComponent`, `TwoFactorVerifyComponent`, `TrustedDevicesComponent`, `SessionsComponent`, `ApiKeysComponent`, `ConnectedAppsComponent`, `AccountDeletionComponent` |
20
20
  | **Account** | `MyAccountComponent` (self-service hub), `ProfileEditorComponent` (name/locale immediate; email/phone verify-before-apply) |
21
21
  | **Auth** | `ConsentGateComponent`, `OtpInputComponent`, `SocialLoginComponent`, `SsoLoginComponent`, `SsoReturnComponent` |
22
22
  | **Billing** | `PlanSelectorComponent`, `PriceSelectorComponent`, `CheckoutButtonComponent`, `PaymentMethodsComponent`, `PortalButtonComponent`, `UsageMeterComponent`, `StatusChipComponent`, `TrialBannerComponent`, `SeatSelectorComponent`, `DunningBannerComponent` |
@@ -29,9 +29,9 @@ A shared Angular component library for building CRUD-based admin frontends. Prov
29
29
  | **Services** | `BaseAuthService` (OTP / social / push / deleteAccount / logoutEverywhere / profile: `getProfile`, `updateProfile`, `request`+`confirmEmailChange`, `request`+`confirmPhoneChange`), `BillingService`, `AgencyService`, `BackendService`, `PayoutService`, `UserPaymentMethodService`, `PartnerDocumentService`, `NotificationInboxService`, `loadScript()`, `authInterceptor`, `apiResponseInterceptor` |
30
30
  | **Abstracts** | `BaseTable`, `BaseForm`, `BaseView`, `AbstractEditableView`, `BaseAsync`, `BaseRestService` |
31
31
  | **Config** | `SAIL_GUI_CONFIG`, `SailGuiConfig`, `configureRestUrls()` |
32
- | **Models** | `ApplicationData`, `TableDefinition`, `SiudAction`, `ApplicationMenu`, `ConstantValue`, `UserAccount`, `RestReport`, `ReportParam`, `TrustedDevice`, `PublicPlan`, `PlanPrice`, `PaymentMethod`, `Subscription`, `Invoice`, `CheckoutRequest`/`CheckoutResponse`, `PortalResponse`, `UsageMeter`, `ChargeResult`, `UserPaymentMethod`, `TableAction`, `TableActionParameter`, `ReusableAccount`, `PayoutOnboardingSession`, `BankInfoFormValue`, `CountryProfile`, `OtpRequest`/`OtpResponse`, `SignupConsent`, `ConsentState`, `ConsentOption`, `SocialProvider`, `PushPlatform`, `InboxMessage`/`InboxPage`, `PartnerDocument`/`DocumentUploadRequest`, 2FA types, etc. |
32
+ | **Models** | `ApplicationData`, `TableDefinition`, `SiudAction`, `ApplicationMenu`, `ConstantValue`, `UserAccount`, `RestReport`, `ReportParam`, `TrustedDevice`, `PublicPlan`, `PlanPrice`, `PaymentMethod`, `Subscription`, `Invoice`, `CheckoutRequest`/`CheckoutResponse`, `PortalResponse`, `UsageMeter`, `ChargeResult`, `UserPaymentMethod`, `TableAction`, `TableActionParameter`, `ReusableAccount`, `PayoutOnboardingSession`, `BankInfoFormValue`, `Currency`, `Country`, `OtpRequest`/`OtpResponse`, `SignupConsent`, `ConsentState`, `ConsentOption`, `SocialProvider`, `PushPlatform`, `InboxMessage`/`InboxPage`, `PartnerDocument`/`DocumentUploadRequest`, 2FA types, etc. |
33
33
  | **Decorators** | `@IsSailString()`, `@IsSailNumeric()` (class-validator based) |
34
- | **Utils** | `titleCase()`, `fromPriceLabel()`, `formatMinorCurrency()` |
34
+ | **Utils** | `titleCase()`, `fromPriceLabel()`, `formatMinor()`, `CurrencyService`, `sailMoney` pipe |
35
35
 
36
36
  ## Quick start
37
37
 
@@ -262,6 +262,10 @@ this.backend.listPaginated<MyRow>('orders', { Status: 'open' }, {
262
262
 
263
263
  Default page size is 100, capped at 1000 server-side. Sail maps `limit`, `offset`, and `orderBy` to keel's `_limit`, `_offset`, and `_order` query controls. Existing callers that put those string controls in the filter map remain compatible; explicit `PageRequest` values take precedence.
264
264
 
265
+ ## Money
266
+
267
+ keel stores money as integer minor units and serves the `currency` table (`code`, `caption`, `exponent`) as the only source of exponents. `formatMinor(minor, currency, exponent)` renders an amount; `Intl` supplies the symbol and grouping only. Billing payloads (`PlanPrice`, `Subscription`, `Invoice`) carry `exponent` beside their `…Minor` fields, so they render without a catalog: `{{ invoice.totalMinor | sailMoney:invoice.currency:invoice.exponent }}`. Amounts without an exponent, such as the agency ledger, use `{{ minor | sailMoney:currency }}`: the pipe loads the catalog once through `CurrencyService` (generic REST `currency`, so the role needs `TABLE SELECT currency`), renders `''` until it arrives, and throws for a code the catalog lacks rather than guessing decimals.
268
+
265
269
  ## Backend-driven constant captions
266
270
 
267
271
  `LabelService` loads one caption map from the backend-provided `ApplicationData`: a keel `constant_value` domain from `ConstantCache` by constant id, or a catalog table registered in `foreign_key_lookup` from `TableCache` by table name. `sailCaption` is the pipe form: `{{ code | sailCaption:'constant_id' }}`. The domain is the backend `constant_id` (for example `ride_type`), not a locale: keel's constant catalogue does not contain a language column. It does not call generic `constant_value` CRUD, which is normally restricted to administrative roles.
@@ -410,6 +414,8 @@ The login flow redirects `twoFactorRequired` responses to `/login/2fa`. With `tw
410
414
 
411
415
  `SessionsComponent` (`<sail-sessions>`) lists the sessions with their `sign_in_method` captions, marks the current one, and signs out any other.
412
416
 
417
+ `ApiKeysComponent` (`<sail-api-keys [scopes]>`) lists the partner's keys and uses the backend-provided `generate` and `restrict` table actions; controls appear only for granted actions. Pass the scopes the app offers (`LabelOption[]`) after filtering out scopes the caller may not mint. The role also needs generic `SELECT` and `DELETE` grants to list and revoke keys. `ConnectedAppsComponent` (`<sail-connected-apps>`) lists and disconnects OAuth clients through keel's `GrantHandler` routes (v1.2.112, `RestURL.oauthGrantsURL` and `oauthGrantRevokeURL`).
418
+
413
419
  ### Cross-origin cookie requirement
414
420
 
415
421
  The "trust this device" feature (keel v0.9+) is backed by a server-set HttpOnly cookie named `keel_td`. The lifecycle is entirely server-driven:
@@ -498,9 +504,8 @@ unless the user holds `PARTNER_PLAN_SUBSCRIPTION` `CANCEL` / `CHANGE` / `PORTAL`
498
504
  </sail-price-selector>
499
505
  ```
500
506
 
501
- `<sail-price-selector>` is presentational (a `radiogroup` of offers), formats each amount with `Intl` from the offer's currency (so JPY/BHD render with the right number of decimals), and maps PERIOD_TYPE codes to copy via `[cycleLabels]`. It emits the full `PlanPrice` so you keep the chosen terms, not just the id.
507
+ `<sail-price-selector>` is presentational (a `radiogroup` of offers), formats each `amountMinor` at the offer's `exponent`, and maps PERIOD_TYPE codes to copy via `[cycleLabels]`. It emits the full `PlanPrice` so you keep the chosen terms, not just the id.
502
508
 
503
- > **Migration.** The flat `PublicPlan.priceId` is deprecated (keel v1.0.5 dropped `subscription_plan.provider_price_id`) — read the id from the selected offer (`offer().priceId`). **keel v1.0.7 also removed `PublicPlan.monthlyCost`/`annualCost`** from both `/public/plans` and the billing catalog, so any plan-card code reading them now gets `undefined`. Derive a display price from the offers with `fromPriceLabel(plan.prices)` (used by `<sail-plan-selector>`), or render the per-offer amounts via `<sail-price-selector>`. These fields are removed from sail's `PublicPlan` type so the compiler flags any remaining references.
504
509
 
505
510
  **Checkout button** — calls `createCheckout()` and redirects to the provider-hosted URL. Feed it the chosen offer's `priceId`:
506
511
  ```html
@@ -684,7 +689,7 @@ A complete screen is the pieces above assembled over `BillingService` — no met
684
689
 
685
690
  ## Agent UI (v1.1.20)
686
691
 
687
- Agent Studio and agent-conversation UI live in a secondary entry point, `@nauticana/sail/agent`. Nothing in it is exported from `@nauticana/sail`, so an app that never imports it bundles none of it. It needs no additional peer dependency. The wire types match Scout v1.2.8.
692
+ Agent Studio and agent-conversation UI live in a secondary entry point, `@nauticana/sail/agent`. Nothing in it is exported from `@nauticana/sail`, so an app that never imports it bundles none of it. It needs no additional peer dependency. The wire types match Scout v1.2.13.
688
693
 
689
694
  ```ts
690
695
  import { AgentStudioService, PromptLanguageEditorComponent, TurnStream } from '@nauticana/sail/agent';
@@ -694,7 +699,10 @@ import { AgentStudioService, PromptLanguageEditorComponent, TurnStream } from '@
694
699
  |---|---|
695
700
  | `AgentStudioService` | Client for Scout's core Studio routes under `/api/agent-studio/` (fixed, unversioned paths): the `features` manifest, list, draft, settings, create, rename, archive, enable, test, publish, restore, reset, default, history, audit, release sections, models. Models mirror the backend's JSON names. |
696
701
  | `sail-studio-page` | Embeddable Studio: an agent rail grouped by `[groupBy]` (agent type by default; pass a function for workflow or position), and Overview, Prompts, Settings (scoped bindings and what they resolve to), Test, and History (diff, restore, audit) tabs. Product tabs are `<ng-template sailStudioTab="id" label="Label" let-agent>`. A control shows only when the `agents` feature lists its action and the caller holds the `AGENT_STUDIO` grant at `agent:<name>` (`agent_type:<type>` for create); hiding is never the authorization. `hasUnsavedChanges()` serves a `canDeactivate` guard. |
697
- | `sail-approval-inbox` / `ApprovalService` | The signed-in person's pending approvals (`GET /api/approval/pending`) and a decision view: approve, reject, or edit a tool call's arguments (`POST /api/approval/resolve`). A `409` reloads the list; `(decided)` emits the result. |
702
+ | `sail-studio-page` Guardrails tab | Shown when the `features` manifest lists `guardrails`: inherited layers read-only, the agent's own rules as an editable JSON array saved against `expected_agent_revision`, and its safety events paged by `before`. Edit needs the feature's `EDIT` action. The rail captions Scout's fixed readiness values (`AGENT_READINESS_CAPTIONS`). |
703
+ | `sail-assistant-activity` | The tenant's decision records from Scout's `decisions` feature (`GET /api/agent-studio/decisions`, `AGENT_AUDIT` `VIEW`), newest first and paged by `next_before`: when, action, resource, outcome caption, who (`[who]` names a principal), app (`client_ref`), and whom it acted for. `[category]` and `[outcome]` filter. |
704
+ | `sail-turn-thread` | The signed-in person's turns from `GET {base}turns` (`ConversationService.turns`), newest first, paged by `next_before` and optionally narrowed to `[workRef]`: `turn_status` caption, settled cost in minor units with its exponent, agent and release version. Each `task_kind` renders its result through `<ng-template sailTurnResult="kind" let-turn>`; the first page reloads every `[pollMs]` while a turn is nonterminal. |
705
+ | `sail-approval-inbox` / `ApprovalService` | The signed-in person's pending approvals (`GET /api/approval/pending`) and MCP confirmations (`GET /api/approval/confirmations`) in one list. Approvals are approved, rejected, or edited (`POST /api/approval/resolve`); confirmations are confirmed, declined, withdrawn, or reconciled as executed or failed through `/api/approval/confirmation/*`, each control shown only when Scout says the person may. A `409` reloads the list; `(decided)` and `(confirmationChanged)` emit the result. |
698
706
  | `studioErrorMessage(err)` | One message for a failed Studio call: the conflict cause, the field errors, or the detail. |
699
707
  | `studioConflictCause(err)` | `'revision'` (reload the draft), `'sealed'` (a layer sits under a sealed one) or `'other'` for a `409`. |
700
708
  | `studioFieldErrors(err)` / `retryAfterSeconds(err)` | Field errors of a `400`; `Retry-After` of a `429`/`503`. |
@@ -708,7 +716,7 @@ import { AgentStudioService, PromptLanguageEditorComponent, TurnStream } from '@
708
716
  | `ConversationService` | Transport for Scout's conversation bridge: `submit`, `stream(requestId, turnStream)`, `cancel`. Mount point injected through `CONVERSATION_BASE_PATH`. |
709
717
  | `SseParser` | Incremental `text/event-stream` parser: `push(chunk)` returns whole events out of chunks that split anywhere, including between the CR and LF of a CRLF; `finish()` flushes what the closing body left pending. |
710
718
 
711
- Map your audit rows onto `DecisionRecord` (outcome `A`, `D`, or `P`, captioned from `audit_decision_outcome`) to feed the timeline. Style the `.prompt-*`, `.release-*`, `.turn-*`, `.decision-*`, `.studio__*`, and `.approval-inbox__*` class hooks. Scout's short codes render through `sailCaption`, a pipe over the backend's constant captions.
719
+ `DecisionRecord` is Scout's `api.DecisionRecord` (outcome `A`, `D`, or `P`, captioned from `audit_decision_outcome`); the timeline takes the records of one request, the activity table pages the tenant's. Style the `.prompt-*`, `.release-*`, `.turn-*`, `.decision-*`, `.studio__*`, and `.approval-inbox__*` class hooks. Scout's short codes render through `sailCaption`, a pipe over the backend's constant captions.
712
720
 
713
721
  ### Conversation transport (v1.1.22)
714
722
 
@@ -816,10 +824,9 @@ pending profile. The ledger and payout-history components show default empty
816
824
  messages; pass `[emptyMessage]="''"` when a composed page should omit empty
817
825
  regions entirely.
818
826
 
819
- All accounting values are integer minor units. `formatMinorCurrency()` uses the
820
- currency exponent reported by `Intl.NumberFormat`, so zero- and three-decimal
821
- currencies render correctly; earnings stay separated by currency rather than
822
- being summed into a misleading total.
827
+ All accounting values are integer minor units rendered through the `sailMoney` pipe at the
828
+ exponent of keel's `currency` catalog (see [Money](#money)); earnings stay separated by
829
+ currency rather than being summed into a misleading total.
823
830
 
824
831
  **Delegation roles (v1.1.27, keel v1.2.89).** `AgencyDelegation.roles` (always present) and
825
832
  `AgencyClient.roles` carry `AgencyRoleGrant { role, expiresAt? }`; no `expiresAt` is
@@ -1607,10 +1614,10 @@ The v0.6 / v0.7 line introduced three additive feature groups against keel v0.7.
1607
1614
  |---|---|---|
1608
1615
  | `@nauticana/sail` | `PayoutService` | keel/payout API client — onboarding, reuse, status, bank-version replacement, beneficiary registration |
1609
1616
  | `@nauticana/sail` | `PayoutProviderOnboardingComponent` (`<sail-payout-provider-onboarding>`) | Drop-in onboarding step with reuse picker, hosted-KYC handoff, and asynchronous-confirmation output |
1610
- | `@nauticana/sail` | `PayoutBankInfoFormComponent` (`<sail-payout-bank-info-form>`) | Tax + payout details form (country / currency / tax ID / billing address / agreement) |
1617
+ | `@nauticana/sail` | `PayoutBankInfoFormComponent` (`<sail-payout-bank-info-form>`) | Tax + payout details form; countries from keel's `country` table, tax-id types from the `tax_id_type` domain |
1611
1618
  | `@nauticana/sail` | `UserPaymentMethodService` | Saved-card list / remove / set-default API client |
1612
1619
  | `@nauticana/sail` | `UserPaymentMethodsComponent` (`<sail-user-payment-methods>`) | List of saved cards/wallets with set-default + remove |
1613
- | `@nauticana/sail` | `TableAction`, `ReusableAccount`, `PayoutOnboardingSession`, `BankInfoFormValue`, `CountryProfile`, `UserPaymentMethod`, `DEFAULT_COUNTRY_PROFILES` | Model types / defaults |
1620
+ | `@nauticana/sail` | `TableAction`, `ReusableAccount`, `PayoutOnboardingSession`, `BankInfoFormValue`, `UserPaymentMethod` | Model types |
1614
1621
 
1615
1622
  ### 2. New keel endpoints
1616
1623
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nauticana/sail",
3
- "version": "1.1.34",
3
+ "version": "1.1.35",
4
4
  "description": "Metadata-driven Angular component library for CRUD admin frontends backed by the keel Go backend. Tables, forms, navigation, OTP/2FA/social auth, billing, payout onboarding.",
5
5
  "main": "src/index.ts",
6
6
  "exports": {
@@ -1,13 +1,13 @@
1
1
  <div class="approval-inbox">
2
2
  <section class="approval-inbox__list" aria-label="Pending approvals">
3
- @if (requests().length === 0 && !loading()) {
3
+ @if (requests().length === 0 && confirmations().length === 0 && !loading()) {
4
4
  <p class="approval-inbox__empty">Nothing is waiting for your decision.</p>
5
5
  }
6
6
  <ul>
7
7
  @for (request of requests(); track key(request)) {
8
8
  <li>
9
9
  <button type="button" class="approval-inbox__item" [class.selected]="key(request) === selectedKey()"
10
- [attr.aria-current]="key(request) === selectedKey()" (click)="select(request)">
10
+ [attr.aria-current]="key(request) === selectedKey()" (click)="select(key(request))">
11
11
  <span class="approval-inbox__summary">{{ request.summary || request.action }}</span>
12
12
  @if (request.deadline_at) {
13
13
  <span class="approval-inbox__deadline">Due {{ request.deadline_at | date: 'medium' }}</span>
@@ -15,6 +15,17 @@
15
15
  </button>
16
16
  </li>
17
17
  }
18
+ @for (c of confirmations(); track confirmationKey(c)) {
19
+ <li>
20
+ <button type="button" class="approval-inbox__item" [class.selected]="confirmationKey(c) === selectedKey()"
21
+ [attr.aria-current]="confirmationKey(c) === selectedKey()" (click)="select(confirmationKey(c))">
22
+ <span class="approval-inbox__summary">{{ c.tool }} · {{ c.status | sailCaption:'mcp_confirmation_status' }}</span>
23
+ @if (c.status === 'P') {
24
+ <span class="approval-inbox__deadline">Expires {{ c.expires_at | date: 'medium' }}</span>
25
+ }
26
+ </button>
27
+ </li>
28
+ }
18
29
  </ul>
19
30
  <button matButton type="button" [disabled]="loading()" (click)="load()">Refresh</button>
20
31
  </section>
@@ -57,6 +68,42 @@
57
68
  </section>
58
69
  }
59
70
 
71
+ @if (selectedConfirmation(); as c) {
72
+ <section class="approval-inbox__decision" aria-label="Confirmation">
73
+ <h3>{{ c.tool }}</h3>
74
+ <dl>
75
+ <dt>Status</dt><dd>{{ c.status | sailCaption:'mcp_confirmation_status' }}@if (c.expired) { (expired) }</dd>
76
+ <dt>Requested by</dt><dd>{{ c.maker.kind }} {{ c.maker.id }}@if (c.client_ref) { through {{ c.client_ref }} }</dd>
77
+ <dt>Requested</dt><dd>{{ c.created_at | date: 'medium' }} · expires {{ c.expires_at | date: 'medium' }}</dd>
78
+ @if (c.approval_required) { <dt>Maker-checker</dt><dd>A second person must approve</dd> }
79
+ @if (c.decider; as d) { <dt>Decided</dt><dd>{{ d.kind }} {{ d.id }} · {{ c.decided_at | date: 'medium' }} {{ c.decision_note }}</dd> }
80
+ @if (c.reconciler; as r) { <dt>Reconciled</dt><dd>{{ r.kind }} {{ r.id }} {{ c.reconcile_note }}</dd> }
81
+ @if (c.error) { <dt>Error</dt><dd>{{ c.error }}</dd> }
82
+ </dl>
83
+ @if (c.preview !== undefined) { <pre class="approval-inbox__preview">{{ c.preview | json }}</pre> }
84
+
85
+ @if (c.can_decide || c.can_reconcile) {
86
+ <mat-form-field>
87
+ <mat-label>Note (optional)</mat-label>
88
+ <textarea matInput rows="2" [value]="reason()" (input)="reason.set($any($event.target).value)"></textarea>
89
+ </mat-form-field>
90
+ }
91
+ <div class="approval-inbox__actions">
92
+ @if (c.can_decide) {
93
+ <button matButton="elevated" type="button" [disabled]="loading()" (click)="confirm(true)">Confirm</button>
94
+ <button matButton type="button" class="warn" [disabled]="loading()" (click)="confirm(false)">Decline</button>
95
+ }
96
+ @if (c.can_withdraw) {
97
+ <button matButton type="button" [disabled]="loading()" (click)="withdraw()">Withdraw</button>
98
+ }
99
+ @if (c.can_reconcile) {
100
+ <button matButton type="button" [disabled]="loading()" (click)="reconcile('D')">Mark executed</button>
101
+ <button matButton type="button" [disabled]="loading()" (click)="reconcile('F')">Mark failed</button>
102
+ }
103
+ </div>
104
+ </section>
105
+ }
106
+
60
107
  @if (errorMessage()) {
61
108
  <p class="approval-inbox__error" role="alert">{{ errorMessage() }}</p>
62
109
  }
@@ -1,52 +1,88 @@
1
- import { DatePipe } from '@angular/common';
1
+ import { DatePipe, JsonPipe } from '@angular/common';
2
2
  import { ChangeDetectionStrategy, Component, OnInit, computed, inject, output, signal } from '@angular/core';
3
3
  import { MatButtonModule } from '@angular/material/button';
4
4
  import { MatFormFieldModule } from '@angular/material/form-field';
5
5
  import { MatInputModule } from '@angular/material/input';
6
+ import { Observable, forkJoin } from 'rxjs';
6
7
  import { BaseAsync } from '../../component/abstract/base_async';
7
8
  import { CaptionPipe } from '../../service/caption_pipe';
8
- import { ApprovalRequest, ApprovalVerdict } from '../model/approval';
9
+ import { ApprovalRequest, ApprovalVerdict, Confirmation } from '../model/approval';
9
10
  import { ApprovalService } from '../service/approval.service';
10
11
 
11
12
  /**
12
- * The signed-in person's pending approvals and a decision view: approve, reject, or edit a
13
- * tool call's arguments. A 409 (reassigned or decided elsewhere) reloads the list.
13
+ * The signed-in person's pending approvals and MCP confirmations with a decision view: approve,
14
+ * reject, or edit a tool call's arguments; confirm, decline, withdraw, or reconcile a confirmation.
15
+ * A 409 (reassigned or decided elsewhere) reloads the list.
14
16
  * Selector: <sail-approval-inbox>.
15
17
  */
16
18
  @Component({
17
19
  selector: 'sail-approval-inbox',
18
20
  changeDetection: ChangeDetectionStrategy.OnPush,
19
- imports: [DatePipe, MatButtonModule, MatFormFieldModule, MatInputModule, CaptionPipe],
21
+ imports: [DatePipe, JsonPipe, MatButtonModule, MatFormFieldModule, MatInputModule, CaptionPipe],
20
22
  templateUrl: './approval_inbox.html',
21
23
  })
22
24
  export class ApprovalInboxComponent extends BaseAsync implements OnInit {
23
25
  private readonly approvals = inject(ApprovalService);
24
26
 
25
27
  readonly decided = output<ApprovalRequest>();
28
+ readonly confirmationChanged = output<Confirmation>();
26
29
 
27
30
  readonly requests = signal<ApprovalRequest[]>([]);
31
+ readonly confirmations = signal<Confirmation[]>([]);
28
32
  readonly selectedKey = signal('');
29
33
  readonly reason = signal('');
30
34
  readonly revisedArguments = signal('');
31
35
  readonly selected = computed(() => this.requests().find((r) => this.key(r) === this.selectedKey()));
36
+ readonly selectedConfirmation = computed(() => this.confirmations().find((c) => this.confirmationKey(c) === this.selectedKey()));
32
37
 
33
38
  ngOnInit(): void {
34
39
  this.load();
35
40
  }
36
41
 
37
42
  load(): void {
38
- this.run(this.approvals.pending(), (rows) => {
39
- this.requests.set(rows);
40
- if (!this.selected()) this.select(rows[0]);
43
+ this.run(forkJoin([this.approvals.pending(), this.approvals.confirmations()]), ([requests, confirmations]) => {
44
+ this.requests.set(requests);
45
+ this.confirmations.set(confirmations);
46
+ if (!this.selected() && !this.selectedConfirmation()) this.select(requests[0] ? this.key(requests[0]) : confirmations[0] ? this.confirmationKey(confirmations[0]) : '');
41
47
  }, 'Failed to load approvals.');
42
48
  }
43
49
 
44
- select(request: ApprovalRequest | undefined): void {
45
- this.selectedKey.set(request ? this.key(request) : '');
50
+ select(key: string): void {
51
+ this.selectedKey.set(key);
46
52
  this.reason.set('');
47
53
  this.revisedArguments.set('');
48
54
  }
49
55
 
56
+ confirm(approve: boolean): void {
57
+ const c = this.selectedConfirmation();
58
+ if (!c) return;
59
+ this.applyConfirmation(this.approvals.decideConfirmation(c, approve, this.reason().trim()));
60
+ }
61
+
62
+ withdraw(): void {
63
+ const c = this.selectedConfirmation();
64
+ if (!c || !window.confirm('Withdraw this confirmation?')) return;
65
+ this.run(this.approvals.withdrawConfirmation(c), () => this.load(), 'Failed to withdraw the confirmation.');
66
+ }
67
+
68
+ reconcile(outcome: 'D' | 'F'): void {
69
+ const c = this.selectedConfirmation();
70
+ if (!c) return;
71
+ this.applyConfirmation(this.approvals.reconcileConfirmation(c, outcome, this.reason().trim()));
72
+ }
73
+
74
+ private applyConfirmation(request: Observable<Confirmation>): void {
75
+ this.run(request, (result) => {
76
+ this.confirmations.update((rows) => rows.map((c) => c.id === result.id && c.tenant_id === result.tenant_id ? result : c));
77
+ this.reason.set('');
78
+ this.confirmationChanged.emit(result);
79
+ }, 'Failed to record the decision.', (err) => this.reloadOnConflict(err));
80
+ }
81
+
82
+ confirmationKey(c: Confirmation): string {
83
+ return `${c.tenant_id}/${c.id}`;
84
+ }
85
+
50
86
  decide(verdict: ApprovalVerdict): void {
51
87
  const request = this.selected();
52
88
  if (!request) return;
@@ -67,13 +103,15 @@ export class ApprovalInboxComponent extends BaseAsync implements OnInit {
67
103
  revised_arguments: revised,
68
104
  }), (result) => {
69
105
  this.requests.update((rows) => rows.filter((r) => this.key(r) !== this.key(request)));
70
- this.select(this.requests()[0]);
106
+ this.select(this.requests()[0] ? this.key(this.requests()[0]) : '');
71
107
  this.decided.emit(result);
72
- }, 'Failed to record the decision.', (err) => {
73
- if ((err as { status?: number })?.status !== 409) return;
74
- this.load();
75
- this.errorMessage.set('This request was reassigned or decided elsewhere; the list was refreshed.');
76
- });
108
+ }, 'Failed to record the decision.', (err) => this.reloadOnConflict(err));
109
+ }
110
+
111
+ private reloadOnConflict(err: unknown): void {
112
+ if ((err as { status?: number })?.status !== 409) return;
113
+ this.load();
114
+ this.errorMessage.set('This request was reassigned or decided elsewhere; the list was refreshed.');
77
115
  }
78
116
 
79
117
  key(request: ApprovalRequest): string {
@@ -0,0 +1,28 @@
1
+ <div class="assistant-activity">
2
+ @if (records().length > 0) {
3
+ <table class="assistant-activity__table">
4
+ <thead>
5
+ <tr><th>When</th><th>Action</th><th>Resource</th><th>Outcome</th><th>By</th><th>App</th><th>Acting for</th></tr>
6
+ </thead>
7
+ <tbody>
8
+ @for (record of records(); track record.id) {
9
+ <tr [class]="'assistant-activity__row assistant-activity__row--' + record.outcome">
10
+ <td>{{ record.occurred_at | date: 'medium' }}</td>
11
+ <td><code>{{ record.action }}</code></td>
12
+ <td>{{ record.resource }}</td>
13
+ <td>{{ record.outcome | sailCaption:'audit_decision_outcome' }}@if (record.reason) { <span class="assistant-activity__reason">({{ record.reason }})</span> }</td>
14
+ <td>{{ who()(record) }}</td>
15
+ <td>{{ record.client_ref }}</td>
16
+ <td>@if (record.authority; as a) { {{ a.subject.kind }} {{ a.subject.id }} }</td>
17
+ </tr>
18
+ }
19
+ </tbody>
20
+ </table>
21
+ } @else if (!loading()) {
22
+ <p class="assistant-activity__empty">No assistant activity yet.</p>
23
+ }
24
+ @if (nextBefore()) {
25
+ <button matButton type="button" [disabled]="loading()" (click)="load(nextBefore())">Load more</button>
26
+ }
27
+ @if (errorMessage()) { <p class="assistant-activity__error" role="alert">{{ errorMessage() }}</p> }
28
+ </div>
@@ -0,0 +1,40 @@
1
+ import { DatePipe } from '@angular/common';
2
+ import { ChangeDetectionStrategy, Component, OnInit, inject, input, signal } from '@angular/core';
3
+ import { MatButtonModule } from '@angular/material/button';
4
+ import { BaseAsync } from '../../component/abstract/base_async';
5
+ import { CaptionPipe } from '../../service/caption_pipe';
6
+ import { DecisionOutcome, DecisionRecord } from '../model/decision';
7
+ import { AgentStudioService } from '../service/agent_studio.service';
8
+
9
+ /**
10
+ * What assistants did in the tenant: Scout's decision records (`decisions` feature, `AGENT_AUDIT`
11
+ * `VIEW`), newest first and paged by `next_before`. Selector: <sail-assistant-activity>.
12
+ */
13
+ @Component({
14
+ selector: 'sail-assistant-activity',
15
+ changeDetection: ChangeDetectionStrategy.OnPush,
16
+ imports: [DatePipe, MatButtonModule, CaptionPipe],
17
+ templateUrl: './assistant_activity.html',
18
+ })
19
+ export class AssistantActivityComponent extends BaseAsync implements OnInit {
20
+ private readonly studio = inject(AgentStudioService);
21
+
22
+ readonly category = input('');
23
+ readonly outcome = input<DecisionOutcome | undefined>(undefined);
24
+ /** Who acted, as the app names its principals; kind and id by default. */
25
+ readonly who = input<(record: DecisionRecord) => string>((r) => `${r.principal.kind} ${r.principal.id}`);
26
+
27
+ readonly records = signal<DecisionRecord[]>([]);
28
+ readonly nextBefore = signal(0);
29
+
30
+ ngOnInit(): void {
31
+ this.load();
32
+ }
33
+
34
+ load(before = 0): void {
35
+ this.run(this.studio.decisions(before, 0, this.category(), this.outcome()), (page) => {
36
+ this.records.update((rows) => before ? [...rows, ...page.records] : page.records);
37
+ this.nextBefore.set(page.next_before ?? 0);
38
+ }, 'Failed to load assistant activity.');
39
+ }
40
+ }
@@ -10,7 +10,7 @@
10
10
  <button type="button" class="studio__agent" [class.selected]="agent.agent_name === selectedName()"
11
11
  [attr.aria-current]="agent.agent_name === selectedName()" (click)="select(agent.agent_name)">
12
12
  <span class="studio__agent-name">{{ agent.display_name }}</span>
13
- <span [class]="'studio__readiness studio__readiness--' + agent.readiness">{{ agent.readiness }}</span>
13
+ <span [class]="'studio__readiness studio__readiness--' + agent.readiness">{{ readinessCaption(agent.readiness) }}</span>
14
14
  <span class="studio__agent-meta">
15
15
  @if (agent.is_default) { <span>Default</span> }
16
16
  @if (agent.archived) { <span>Archived</span> }
@@ -232,6 +232,40 @@
232
232
  </ul>
233
233
  }
234
234
  }
235
+ @case ('guardrails') {
236
+ @if (guardrails(); as g) {
237
+ @if (g.problem) { <p class="studio__error" role="alert">{{ g.problem }}</p> }
238
+ @for (layer of g.inherited; track layer.layer) {
239
+ <h3>Inherited · layer {{ layer.layer }}@if (layer.digest) { · {{ layer.digest.slice(0, 12) }} }</h3>
240
+ <pre class="studio__rules">{{ layer.rules | json }}</pre>
241
+ }
242
+ <h3>This agent's rules</h3>
243
+ <p>Rules only add to the inherited ones or tighten a rule of the same id.</p>
244
+ <mat-form-field class="studio__rules-editor">
245
+ <mat-label>Rules (JSON array)</mat-label>
246
+ <textarea matInput rows="10" #rules [value]="g.rules | json" [disabled]="!can('EDIT', undefined, 'guardrails')"></textarea>
247
+ </mat-form-field>
248
+ @if (can('EDIT', undefined, 'guardrails')) {
249
+ <button matButton="elevated" type="button" [disabled]="busy()" (click)="saveGuardrails(rules.value)">Save rules</button>
250
+ }
251
+ <h3>Safety events</h3>
252
+ <ul class="studio__safety-events">
253
+ @for (event of safetyEvents(); track event.id) {
254
+ <li>
255
+ {{ event.occurred_at | date: 'medium' }} · {{ event.stage }} · layer {{ event.layer }} · {{ event.action }} ({{ event.severity }})
256
+ · rules {{ event.rule_ids.join(', ') }}
257
+ @if (event.version) { · v{{ event.version }} }
258
+ @if (event.actor_kind) { · {{ event.actor_kind }} {{ event.actor_id }} }
259
+ </li>
260
+ } @empty {
261
+ <li>No safety event recorded.</li>
262
+ }
263
+ </ul>
264
+ @if (!safetyExhausted()) {
265
+ <button matButton type="button" [disabled]="busy()" (click)="loadSafetyEvents()">Load more</button>
266
+ }
267
+ }
268
+ }
235
269
  @default {
236
270
  @if (productTab(); as t) {
237
271
  @if (selected(); as agent) {
@@ -13,8 +13,9 @@ import { BaseAuthService } from '../../service/auth.service';
13
13
  import { CaptionPipe } from '../../service/caption_pipe';
14
14
  import { LabelOption, LabelService } from '../../service/label.service';
15
15
  import {
16
- AgentAuditEvent, AgentDraft, AgentLanguageDraft, AgentMergeMode, AgentModelSelection, AgentRelease, AgentSetting,
17
- AgentSettings, AgentSummary, AgentTestResult, StudioFeature, StudioModel,
16
+ AGENT_READINESS_CAPTIONS, AgentAuditEvent, AgentDraft, AgentGuardrails, AgentLanguageDraft, AgentMergeMode,
17
+ AgentModelSelection, AgentRelease, AgentSetting, AgentSettings, AgentSummary, AgentTestResult, GuardrailRule,
18
+ SafetyEvent, StudioFeature, StudioModel,
18
19
  } from '../model/agent_studio';
19
20
  import { AgentStudioService } from '../service/agent_studio.service';
20
21
  import { ReleaseSectionDiff, diffReleaseSections } from '../util/release_diff';
@@ -29,11 +30,12 @@ const CORE_TABS = [
29
30
  { id: 'test', label: 'Test' },
30
31
  { id: 'history', label: 'History' },
31
32
  ];
33
+ const GUARDRAILS_TAB = { id: 'guardrails', label: 'Guardrails' };
32
34
 
33
35
  /**
34
36
  * Embeddable Agent Studio over Scout's core `agents` feature: a grouped agent rail and tabs
35
- * for the draft, prompts, scoped settings, tests, and release history, plus product tabs
36
- * declared with `sailStudioTab`. A control shows only when the feature manifest lists its
37
+ * for the draft, prompts, scoped settings, tests, and release history, a Guardrails tab when the
38
+ * manifest lists that feature, plus product tabs declared with `sailStudioTab`. A control shows only when the feature manifest lists its
37
39
  * action and the caller holds the grant; hiding is never the authorization, Scout decides.
38
40
  * Selector: <sail-studio-page>.
39
41
  */
@@ -66,6 +68,9 @@ export class StudioPageComponent implements OnInit {
66
68
  readonly settings = signal<AgentSettings | null>(null);
67
69
  readonly releases = signal<AgentRelease[]>([]);
68
70
  readonly audit = signal<AgentAuditEvent[]>([]);
71
+ readonly guardrails = signal<AgentGuardrails | null>(null);
72
+ readonly safetyEvents = signal<SafetyEvent[]>([]);
73
+ readonly safetyExhausted = signal(true);
69
74
  readonly diff = signal<{ version: number; previous: number; rows: ReleaseSectionDiff[] } | null>(null);
70
75
  readonly testResult = signal<AgentTestResult | null>(null);
71
76
  readonly tab = signal('overview');
@@ -79,7 +84,10 @@ export class StudioPageComponent implements OnInit {
79
84
  private readonly pending = signal(0);
80
85
  readonly busy = computed(() => this.pending() > 0);
81
86
 
82
- readonly tabs = computed(() => [...CORE_TABS, ...this.productTabs().map((t) => ({ id: t.id(), label: t.label() }))]);
87
+ readonly tabs = computed(() => [
88
+ ...CORE_TABS, ...(this.feature('guardrails') ? [GUARDRAILS_TAB] : []),
89
+ ...this.productTabs().map((t) => ({ id: t.id(), label: t.label() })),
90
+ ]);
83
91
  readonly productTab = computed(() => this.productTabs().find((t) => t.id() === this.tab()));
84
92
  readonly selected = computed(() => this.summaries().find((a) => a.agent_name === this.selectedName()));
85
93
  readonly dirty = computed(() => this.draft() !== null && JSON.stringify(this.draft()) !== this.baseline());
@@ -97,7 +105,6 @@ export class StudioPageComponent implements OnInit {
97
105
  }
98
106
  return [...groups].map(([name, agents]) => ({ name, agents }));
99
107
  });
100
- private readonly core = computed(() => this.features().find((f) => f.id === 'agents'));
101
108
 
102
109
  ngOnInit(): void {
103
110
  this.call(this.studio.features(), (features) => this.features.set(features));
@@ -110,10 +117,18 @@ export class StudioPageComponent implements OnInit {
110
117
  return this.dirty();
111
118
  }
112
119
 
113
- /** Whether the manifest serves `action` and the caller holds it at `value` (the selected agent by default). */
114
- can(action: string, value = `agent:${this.selectedName()}`): boolean {
115
- const core = this.core();
116
- return !!core?.actions.includes(action) && this.auth.hasPermission(core.object || 'AGENT_STUDIO', action, value);
120
+ /** Whether `feature` serves `action` and the caller holds it at `value` (the selected agent by default). */
121
+ can(action: string, value = `agent:${this.selectedName()}`, feature = 'agents'): boolean {
122
+ const f = this.feature(feature);
123
+ return !!f?.actions.includes(action) && this.auth.hasPermission(f.object || 'AGENT_STUDIO', action, value);
124
+ }
125
+
126
+ private feature(id: string): StudioFeature | undefined {
127
+ return this.features().find((f) => f.id === id);
128
+ }
129
+
130
+ readinessCaption(code: string): string {
131
+ return AGENT_READINESS_CAPTIONS[code] ?? code;
117
132
  }
118
133
 
119
134
  modelsOf(type: string): StudioModel[] {
@@ -136,6 +151,8 @@ export class StudioPageComponent implements OnInit {
136
151
  this.settings.set(null);
137
152
  this.releases.set([]);
138
153
  this.audit.set([]);
154
+ this.guardrails.set(null);
155
+ this.safetyEvents.set([]);
139
156
  this.diff.set(null);
140
157
  this.testResult.set(null);
141
158
  this.errorMessage.set('');
@@ -146,6 +163,7 @@ export class StudioPageComponent implements OnInit {
146
163
  openTab(id: string): void {
147
164
  this.tab.set(id);
148
165
  if (id === 'history') this.loadHistory();
166
+ if (id === 'guardrails') this.loadGuardrails();
149
167
  }
150
168
 
151
169
  private loadAgent(): void {
@@ -153,6 +171,7 @@ export class StudioPageComponent implements OnInit {
153
171
  this.call(this.studio.getDraft(name), (draft) => this.applyDraft(draft), name);
154
172
  this.call(this.studio.settings(name), (settings) => this.settings.set(settings), name);
155
173
  if (this.tab() === 'history') this.loadHistory();
174
+ if (this.tab() === 'guardrails') this.loadGuardrails();
156
175
  }
157
176
 
158
177
  private applyDraft(draft: AgentDraft): void {
@@ -312,6 +331,44 @@ export class StudioPageComponent implements OnInit {
312
331
  }, name);
313
332
  }
314
333
 
334
+ loadGuardrails(): void {
335
+ const name = this.selectedName();
336
+ this.safetyEvents.set([]);
337
+ this.call(this.studio.guardrails(name), (g) => this.guardrails.set(g), name);
338
+ this.loadSafetyEvents();
339
+ }
340
+
341
+ loadSafetyEvents(): void {
342
+ const name = this.selectedName();
343
+ const before = this.safetyEvents().at(-1)?.id ?? 0;
344
+ this.call(this.studio.safetyEvents(name, before), (events) => {
345
+ this.safetyEvents.update((rows) => [...rows, ...events]);
346
+ this.safetyExhausted.set(events.length < 50);
347
+ }, name);
348
+ }
349
+
350
+ /** Replaces the agent's own rules with the JSON array typed in. */
351
+ saveGuardrails(rulesText: string): void {
352
+ const g = this.guardrails();
353
+ if (!g) return;
354
+ let rules: GuardrailRule[];
355
+ try {
356
+ rules = JSON.parse(rulesText.trim() || '[]') as GuardrailRule[];
357
+ } catch {
358
+ this.errorMessage.set('The rules must be a JSON array.');
359
+ return;
360
+ }
361
+ if (!Array.isArray(rules)) {
362
+ this.errorMessage.set('The rules must be a JSON array.');
363
+ return;
364
+ }
365
+ this.act(this.studio.saveGuardrails({ agent_name: g.agent_name, rules, expected_agent_revision: g.expected_agent_revision }), (saved) => {
366
+ this.guardrails.set(saved);
367
+ this.applyRevisions(saved.expected_agent_revision);
368
+ this.successMessage.set('Guardrails saved.');
369
+ }, g.agent_name);
370
+ }
371
+
315
372
  previousVersion(version: number): number {
316
373
  return this.releases().reduce((best, r) => r.version < version && r.version > best ? r.version : best, 0);
317
374
  }