@applica-software-guru/persona-sdk 0.1.114 → 0.1.116

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.
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Decisions: typed questions about a state, answered with probabilities by a decision
3
+ * model (TypeSafe Jev, Cloudflare Clef). Mirrors `POST /decisions` of persona-core.
4
+ */
5
+
6
+ export type DecisionQuestionType = 'noul' | 'choice' | 'score' | 'box';
7
+
8
+ /** Yes/no question; `criteria` optionally describes the two sides. */
9
+ export interface NoulQuestion {
10
+ type: 'noul';
11
+ instructions: string | Record<string, unknown> | unknown[];
12
+ criteria?: { true?: string; false?: string } | null;
13
+ }
14
+
15
+ /** One of the options: `criteria` maps option keys to their descriptions. */
16
+ export interface ChoiceQuestion {
17
+ type: 'choice';
18
+ instructions: string | Record<string, unknown> | unknown[];
19
+ criteria: Record<string, string | null>;
20
+ }
21
+
22
+ /** An ordered rubric: `criteria` lists the levels, lowest first (at least 2). */
23
+ export interface ScoreQuestion {
24
+ type: 'score';
25
+ instructions: string | Record<string, unknown> | unknown[];
26
+ criteria: string[];
27
+ }
28
+
29
+ export type DecisionQuestion = NoulQuestion | ChoiceQuestion | ScoreQuestion;
30
+
31
+ export interface DecisionRequest {
32
+ /** `"<provider>/<model>"` (e.g. `typesafe/jev-latest`) or `alias:<name>`. */
33
+ model: string;
34
+ /** What to decide about: text, an object or a list. */
35
+ state: unknown;
36
+ questions: Record<string, DecisionQuestion>;
37
+ /** Trace: code of the session the decision is stored in. */
38
+ sessionCode?: string;
39
+ /** Trace: parent session (e.g. a workflow execution). */
40
+ parentSessionId?: string;
41
+ userId?: string;
42
+ }
43
+
44
+ export interface NoulAnswer {
45
+ type: 'noul';
46
+ /** Probability of yes (0-1). */
47
+ noul: number;
48
+ }
49
+
50
+ export interface ChoiceAnswer {
51
+ type: 'choice';
52
+ /** The winning option key. */
53
+ choice: string;
54
+ probabilities: Record<string, number>;
55
+ /** Normalized entropy (0-1), not the winning probability. */
56
+ confidence: number;
57
+ }
58
+
59
+ export interface ScoreAnswer {
60
+ type: 'score';
61
+ /** Expected zero-based level index (may be fractional). */
62
+ score: number;
63
+ probabilities: Record<string, number>;
64
+ confidence: number;
65
+ legend?: Record<string, unknown>;
66
+ }
67
+
68
+ export interface RefusalAnswer {
69
+ type: 'refusal';
70
+ }
71
+
72
+ export type DecisionAnswer = NoulAnswer | ChoiceAnswer | ScoreAnswer | RefusalAnswer;
73
+
74
+ export interface DecisionUsage {
75
+ inputTokens: number;
76
+ outputTokens: number;
77
+ }
78
+
79
+ export interface DecisionResponse {
80
+ sessionId: string;
81
+ sessionCode: string;
82
+ /** The resolved model version that answered (e.g. `jev-1.14.0`). */
83
+ model: string;
84
+ answers: Record<string, DecisionAnswer>;
85
+ usage: DecisionUsage;
86
+ }
87
+
88
+ export interface DecisionModelInfo {
89
+ id: string;
90
+ provider: string;
91
+ maxInputTokens?: number | null;
92
+ inputCostPerToken?: number | null;
93
+ outputCostPerToken?: number | null;
94
+ }
package/src/index.ts CHANGED
@@ -180,6 +180,43 @@ export { MarkupRulesApi } from './markup-rules/markup-rules-api';
180
180
  export type { MarkupRule } from './markup-rules/types';
181
181
  export { ProvidersApi } from './providers/providers-api';
182
182
  export type { Provider, ProviderModel } from './providers/types';
183
+ export { ModelAliasesApi } from './model-aliases/model-aliases-api';
184
+ export { ALIAS_PREFIX, isAliasRef, aliasNameFromRef, aliasRef } from './model-aliases/references';
185
+ export type {
186
+ ModelAlias,
187
+ ModelAliasInput,
188
+ ModelAliasDefaults,
189
+ ModelAliasHealth,
190
+ ModelAliasHealthStatus,
191
+ ModelAliasIssue,
192
+ ModelAliasIssueRole,
193
+ ModelAliasChange,
194
+ AliasImpact,
195
+ AliasUsage,
196
+ AliasSuggestions,
197
+ ModelSuggestion,
198
+ ModelProfile,
199
+ ModelCapability,
200
+ } from './model-aliases/types';
201
+ export { NotificationsApi } from './notifications/notifications-api';
202
+ export type { Notification, NotificationSeverity, NotificationListParams } from './notifications/types';
203
+ export { DecisionsApi } from './decisions/decisions-api';
204
+ export type {
205
+ DecisionQuestionType,
206
+ DecisionQuestion,
207
+ NoulQuestion,
208
+ ChoiceQuestion,
209
+ ScoreQuestion,
210
+ DecisionRequest,
211
+ DecisionAnswer,
212
+ NoulAnswer,
213
+ ChoiceAnswer,
214
+ ScoreAnswer,
215
+ RefusalAnswer,
216
+ DecisionUsage,
217
+ DecisionResponse,
218
+ DecisionModelInfo,
219
+ } from './decisions/types';
183
220
  export type { Revision as RevisionType } from './revisions/types';
184
221
  export { BillingClient } from './billing/billing-client';
185
222
  export { ValuesApi } from './values/values-api';
@@ -200,6 +237,7 @@ export type {
200
237
  UsageTotals,
201
238
  UsageDailyEntry,
202
239
  UsageModelEntry,
240
+ UsageAliasEntry,
203
241
  UsageDetail,
204
242
  UsagePage,
205
243
  } from './billing/types';
@@ -0,0 +1,94 @@
1
+ import { HttpApi } from '../http-api';
2
+ import { Paginated } from '../paginated';
3
+ import { AuthenticationProvider } from '../auth/authentication-provider';
4
+ import { ApiException } from '../exceptions';
5
+ import { AliasImpact, AliasSuggestions, ModelAlias, ModelAliasInput } from './types';
6
+
7
+ /**
8
+ * Model aliases: named indirections (`alias:<name>`) to a concrete model, with
9
+ * ordered fallbacks. Global aliases are managed by super admins; project aliases by
10
+ * super admins, project admins and the project API key (not plain users, nor agent
11
+ * keys). Everyone in a project can read its aliases and the global ones.
12
+ */
13
+ export class ModelAliasesApi extends HttpApi {
14
+ constructor(baseUrl: string, auth: string | AuthenticationProvider) {
15
+ super(baseUrl, auth);
16
+ }
17
+
18
+ /**
19
+ * Aliases visible to the caller (their project's and the global ones). Super admins
20
+ * can pass `projectId` to see another project's view.
21
+ */
22
+ async list(
23
+ projectId?: string | null,
24
+ keyword?: string | null,
25
+ page?: number,
26
+ size?: number
27
+ ): Promise<Paginated<ModelAlias>> {
28
+ const { page: p, size: s } = this.normalizePageParams(page, size);
29
+ const params: Record<string, unknown> = { page: p, size: s };
30
+ if (projectId) params.projectId = projectId;
31
+ if (keyword) params.keyword = keyword;
32
+ return this.httpGet<Paginated<ModelAlias>>('/model-aliases', params);
33
+ }
34
+
35
+ async get(id: string): Promise<ModelAlias> {
36
+ return this.httpGet<ModelAlias>('/model-aliases/' + id);
37
+ }
38
+
39
+ /** Create an alias. Non-super-admins always create in their own project. */
40
+ async create(alias: ModelAliasInput): Promise<ModelAlias> {
41
+ return this.httpPost<ModelAlias>('/model-aliases', alias);
42
+ }
43
+
44
+ /** Change target, fallbacks, defaults and description. `name` and the scope are immutable. */
45
+ async update(id: string, alias: ModelAliasInput): Promise<ModelAlias> {
46
+ return this.httpPut<ModelAlias>('/model-aliases/' + id, alias);
47
+ }
48
+
49
+ /**
50
+ * Delete an alias. Refused with a 409 while agents still reference it: use
51
+ * {@link ModelAliasesApi.inUse} on the error to read which ones.
52
+ */
53
+ async remove(id: string): Promise<void> {
54
+ await this.httpDelete('/model-aliases/' + id);
55
+ }
56
+
57
+ /** Agents that reference the alias, and in which model slot. */
58
+ async impact(id: string): Promise<AliasImpact> {
59
+ return this.httpGet<AliasImpact>('/model-aliases/' + id + '/impact');
60
+ }
61
+
62
+ /**
63
+ * Run the health check now (registry, announced retirements, credentials). Stores the
64
+ * result in `health` and updates the notifications; it never changes the alias.
65
+ */
66
+ async check(id: string): Promise<ModelAlias> {
67
+ return this.httpPost<ModelAlias>('/model-aliases/' + id + '/check');
68
+ }
69
+
70
+ /**
71
+ * Replacement and fallback candidates for the alias' target, or for `model` (e.g. a
72
+ * fallback that went missing). A proposal only: nothing is applied.
73
+ */
74
+ async suggestions(id: string, model?: string | null, limit?: number): Promise<AliasSuggestions> {
75
+ const params: Record<string, unknown> = {};
76
+ if (model) params.model = model;
77
+ if (limit !== undefined) params.limit = limit;
78
+ return this.httpGet<AliasSuggestions>('/model-aliases/' + id + '/suggestions', params);
79
+ }
80
+
81
+ /**
82
+ * The agents blocking a delete, when `error` is the 409 of {@link ModelAliasesApi.remove};
83
+ * `null` for any other error.
84
+ */
85
+ static inUse(error: unknown): AliasImpact | null {
86
+ if (!(error instanceof ApiException) || error.statusCode !== 409) return null;
87
+ try {
88
+ const impact = JSON.parse(error.body)?.detail?.impact;
89
+ return impact && typeof impact.total === 'number' ? (impact as AliasImpact) : null;
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,20 @@
1
+ /** Prefix of a model name that references a model alias. */
2
+ export const ALIAS_PREFIX = 'alias:';
3
+
4
+ /** True when `modelName` is an `alias:<name>` reference. */
5
+ export function isAliasRef(modelName?: string | null): boolean {
6
+ return !!modelName && modelName.trim().toLowerCase().startsWith(ALIAS_PREFIX);
7
+ }
8
+
9
+ /** `"alias:smart"` -> `"smart"`. Throws when `modelName` is not a reference. */
10
+ export function aliasNameFromRef(modelName: string): string {
11
+ if (!isAliasRef(modelName)) {
12
+ throw new Error(`Not a model alias reference: ${JSON.stringify(modelName)}`);
13
+ }
14
+ return modelName.trim().slice(ALIAS_PREFIX.length).trim();
15
+ }
16
+
17
+ /** `"smart"` -> `"alias:smart"`, to set as the `modelName` of an agent. */
18
+ export function aliasRef(name: string): string {
19
+ return ALIAS_PREFIX + name.trim();
20
+ }
@@ -0,0 +1,125 @@
1
+ import type { ReasoningEffort } from '../agents/types';
2
+
3
+ /** Applied only to the fields an agent leaves empty. `temperature` is not here on purpose. */
4
+ export interface ModelAliasDefaults {
5
+ reasoningEffort?: ReasoningEffort | null;
6
+ maxOutputTokens?: number | null;
7
+ contextWindow?: number | null;
8
+ }
9
+
10
+ export type ModelAliasHealthStatus = 'unknown' | 'ok' | 'deprecating' | 'missing' | 'no_credentials';
11
+ export type ModelAliasIssueRole = 'target' | 'fallback';
12
+
13
+ /** A problem found by the health check on one of the alias' models. */
14
+ export interface ModelAliasIssue {
15
+ model: string;
16
+ role: ModelAliasIssueRole;
17
+ status: ModelAliasHealthStatus;
18
+ detail?: string | null;
19
+ /** Provider-announced retirement date (`YYYY-MM-DD`), when known. */
20
+ deprecationDate?: string | null;
21
+ }
22
+
23
+ export interface ModelAliasHealth {
24
+ status: ModelAliasHealthStatus;
25
+ checkedAt?: string | null;
26
+ issues: ModelAliasIssue[];
27
+ }
28
+
29
+ /** Audit entry: one changed field of the alias (the last 50 are kept). */
30
+ export interface ModelAliasChange {
31
+ at: string;
32
+ by?: string | null;
33
+ field: 'target' | 'fallbacks' | 'defaults';
34
+ old?: unknown;
35
+ new?: unknown;
36
+ }
37
+
38
+ /**
39
+ * A named indirection to a concrete `<provider>/<model>`. An agent references it as
40
+ * `alias:<name>` (see {@link aliasRef}); editing the alias moves every agent using it.
41
+ */
42
+ export interface ModelAlias {
43
+ id: string;
44
+ /** Lowercase slug used in `alias:<name>`. Immutable. */
45
+ name: string;
46
+ /** null => global (super admins only); set => per-project. Immutable. */
47
+ projectId?: string | null;
48
+ description?: string | null;
49
+ /** Concrete litellm-style `<provider>/<model>`, never another alias. */
50
+ target: string;
51
+ /** Ordered alternatives, used at runtime when the target cannot serve a call. */
52
+ fallbacks: string[];
53
+ defaults: ModelAliasDefaults;
54
+ /** Result of the last health check. Managed by the server. */
55
+ health: ModelAliasHealth;
56
+ /** Managed by the server. */
57
+ history: ModelAliasChange[];
58
+ createdAt?: string;
59
+ updatedAt?: string;
60
+ updatedBy?: string | null;
61
+ }
62
+
63
+ /**
64
+ * What to send to create or update an alias. The server-managed fields (`health`,
65
+ * `history`, timestamps) are not part of it; `name` is required but immutable, and
66
+ * the scope can only be chosen (via `projectId`) by super admins when creating.
67
+ */
68
+ export interface ModelAliasInput {
69
+ name: string;
70
+ target: string;
71
+ projectId?: string | null;
72
+ description?: string | null;
73
+ fallbacks?: string[];
74
+ defaults?: ModelAliasDefaults;
75
+ }
76
+
77
+ /** An agent that references an alias, and in which model slots. */
78
+ export interface AliasUsage {
79
+ agentId: string;
80
+ agentName?: string | null;
81
+ projectId?: string | null;
82
+ /** `model`, `compaction`, `loopRecovery`, `attachmentsPreprocessor`, `knowledge`. */
83
+ usedIn: string[];
84
+ }
85
+
86
+ /** Agents referencing an alias; also the detail of the 409 returned when deleting one in use. */
87
+ export interface AliasImpact {
88
+ aliasId: string;
89
+ aliasName: string;
90
+ /** May exceed `usages.length` when the list is capped. */
91
+ total: number;
92
+ usages: AliasUsage[];
93
+ }
94
+
95
+ export type ModelCapability = 'function_calling' | 'vision' | 'audio_input' | 'pdf_input' | 'reasoning';
96
+
97
+ /** What litellm's registry knows about a model. */
98
+ export interface ModelProfile {
99
+ model: string;
100
+ contextWindow?: number | null;
101
+ /** USD per million tokens. */
102
+ inputCostPerMillion?: number | null;
103
+ outputCostPerMillion?: number | null;
104
+ capabilities: ModelCapability[];
105
+ }
106
+
107
+ /** A candidate to replace a model, or to add as a fallback. */
108
+ export interface ModelSuggestion extends ModelProfile {
109
+ provider: string;
110
+ sameProvider: boolean;
111
+ /** e.g. a smaller context window, a much higher price. */
112
+ warnings: string[];
113
+ }
114
+
115
+ /** A proposal only: nothing is applied, the alias is edited by hand. */
116
+ export interface AliasSuggestions {
117
+ aliasId?: string | null;
118
+ /** The model the suggestions are measured against (the alias' target by default). */
119
+ referenceModel: string;
120
+ /** null when the registry does not know the reference model (e.g. already retired). */
121
+ reference?: ModelProfile | null;
122
+ notes: string[];
123
+ replacements: ModelSuggestion[];
124
+ fallbacks: ModelSuggestion[];
125
+ }
@@ -0,0 +1,42 @@
1
+ import { HttpApi } from '../http-api';
2
+ import { Paginated } from '../paginated';
3
+ import { AuthenticationProvider } from '../auth/authentication-provider';
4
+ import { Notification, NotificationListParams } from './types';
5
+
6
+ /**
7
+ * In-platform notifications. A project sees its own; platform-wide ones (no project)
8
+ * are for super admins. Agent API keys have no access. Read state is shared by
9
+ * everyone who can see a notification.
10
+ */
11
+ export class NotificationsApi extends HttpApi {
12
+ constructor(baseUrl: string, auth: string | AuthenticationProvider) {
13
+ super(baseUrl, auth);
14
+ }
15
+
16
+ async list(params: NotificationListParams = {}): Promise<Paginated<Notification>> {
17
+ const { page, size } = this.normalizePageParams(params.page, params.size);
18
+ const query: Record<string, unknown> = { page, size };
19
+ if (params.unreadOnly) query.unreadOnly = true;
20
+ if (params.includeResolved) query.includeResolved = true;
21
+ if (params.projectId) query.projectId = params.projectId;
22
+ return this.httpGet<Paginated<Notification>>('/notifications', query);
23
+ }
24
+
25
+ /** Open, unread notifications: the value of the badge. */
26
+ async unreadCount(projectId?: string | null): Promise<number> {
27
+ const result = await this.httpGet<{ count: number }>(
28
+ '/notifications/unread-count',
29
+ projectId ? { projectId } : undefined
30
+ );
31
+ return result.count;
32
+ }
33
+
34
+ async markRead(id: string): Promise<Notification> {
35
+ return this.httpPost<Notification>('/notifications/' + id + '/read');
36
+ }
37
+
38
+ /** Mark as read everything the caller can see. */
39
+ async markAllRead(projectId?: string | null): Promise<void> {
40
+ await this.httpPost<void>('/notifications/read-all', undefined, projectId ? { projectId } : undefined);
41
+ }
42
+ }
@@ -0,0 +1,39 @@
1
+ export type NotificationSeverity = 'info' | 'warning' | 'critical';
2
+
3
+ /**
4
+ * An in-platform notification (badge + banner). `title` and `message` are an English
5
+ * fallback: clients localize from `code` and `data`.
6
+ */
7
+ export interface Notification {
8
+ id: string;
9
+ /** null => platform-wide, visible to super admins only. */
10
+ projectId?: string | null;
11
+ /** Producer area, e.g. `model_alias`. */
12
+ type: string;
13
+ /** Stable machine code, e.g. `model_alias.missing`, `model_alias.runtime_fallback`. */
14
+ code: string;
15
+ severity: NotificationSeverity;
16
+ title: string;
17
+ message: string;
18
+ /** What it is about, for deep links. */
19
+ entityType?: string | null;
20
+ entityId?: string | null;
21
+ dedupeKey?: string | null;
22
+ data: Record<string, unknown>;
23
+ createdAt?: string;
24
+ readAt?: string | null;
25
+ readBy?: string | null;
26
+ /** Set when the problem it describes no longer applies. */
27
+ resolvedAt?: string | null;
28
+ }
29
+
30
+ export interface NotificationListParams {
31
+ /** Only the ones not read yet. */
32
+ unreadOnly?: boolean;
33
+ /** Include the ones whose problem is gone (hidden by default). */
34
+ includeResolved?: boolean;
35
+ /** Super admins: the view of this project (plus platform-wide ones). */
36
+ projectId?: string | null;
37
+ page?: number;
38
+ size?: number;
39
+ }
@@ -13,6 +13,9 @@ import { SessionsApi } from './sessions/sessions-api';
13
13
  import { MissionsApi } from './missions/missions-api';
14
14
  import { BillingClient } from './billing/billing-client';
15
15
  import { ValuesApi } from './values/values-api';
16
+ import { ModelAliasesApi } from './model-aliases/model-aliases-api';
17
+ import { NotificationsApi } from './notifications/notifications-api';
18
+ import { DecisionsApi } from './decisions/decisions-api';
16
19
 
17
20
  export class PersonaSdk {
18
21
  private readonly baseUrl: string;
@@ -103,6 +106,24 @@ export class PersonaSdk {
103
106
  return new BillingClient(this.billingBaseUrl, auth);
104
107
  }
105
108
 
109
+ modelAliases(apiKey: string): ModelAliasesApi;
110
+ modelAliases(authProvider: AuthenticationProvider): ModelAliasesApi;
111
+ modelAliases(auth: string | AuthenticationProvider): ModelAliasesApi {
112
+ return new ModelAliasesApi(this.baseUrl, auth);
113
+ }
114
+
115
+ notifications(apiKey: string): NotificationsApi;
116
+ notifications(authProvider: AuthenticationProvider): NotificationsApi;
117
+ notifications(auth: string | AuthenticationProvider): NotificationsApi {
118
+ return new NotificationsApi(this.baseUrl, auth);
119
+ }
120
+
121
+ decisions(apiKey: string): DecisionsApi;
122
+ decisions(authProvider: AuthenticationProvider): DecisionsApi;
123
+ decisions(auth: string | AuthenticationProvider): DecisionsApi {
124
+ return new DecisionsApi(this.baseUrl, auth);
125
+ }
126
+
106
127
  values(apiKey: string): ValuesApi;
107
128
  values(authProvider: AuthenticationProvider): ValuesApi;
108
129
  values(auth: string | AuthenticationProvider): ValuesApi {
@@ -84,6 +84,8 @@ export interface UsageCost {
84
84
  price?: number;
85
85
  credits?: number;
86
86
  unit?: string;
87
+ /** Name of the model alias the usage went through, if any. `service` names the concrete model that served it. */
88
+ alias?: string | null;
87
89
  }
88
90
 
89
91
  export interface CommittedUsage {
@@ -0,0 +1,71 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { BillingClient } from '../dist/bundle.es.js';
5
+
6
+ function recordFetch(context, body) {
7
+ const originalFetch = globalThis.fetch;
8
+ context.after(() => {
9
+ globalThis.fetch = originalFetch;
10
+ });
11
+ const calls = [];
12
+ globalThis.fetch = async (url, init) => {
13
+ calls.push({ url: new URL(String(url)), method: init.method });
14
+ return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } });
15
+ };
16
+ return calls;
17
+ }
18
+
19
+ const client = () => new BillingClient('https://billing.test', 'api-key');
20
+
21
+ test('usage stats carry the breakdown by alias', async (context) => {
22
+ const stats = {
23
+ totals: { creditsUsed: 5100, usageCount: 15 },
24
+ daily: [],
25
+ byModel: [],
26
+ byAlias: [
27
+ { alias: 'smart', credits: 5000, count: 12, totalCost: 0.5, totalPrice: 5 },
28
+ { alias: 'cheap', credits: 100, count: 3 },
29
+ ],
30
+ availableModels: [],
31
+ };
32
+ const calls = recordFetch(context, stats);
33
+
34
+ const result = await client().getUsageStats('p1', '2026-11-01', '2026-11-30');
35
+
36
+ assert.equal(calls[0].url.pathname, '/projects/p1/subscription/usage-stats');
37
+ assert.deepEqual(result.byAlias, stats.byAlias);
38
+ });
39
+
40
+ test('listUsages filters by alias, one parameter per alias', async (context) => {
41
+ const calls = recordFetch(context, { content: [], totalElements: 0, totalPages: 0, page: 0, size: 20 });
42
+
43
+ await client().listUsages('p1', undefined, undefined, undefined, undefined, 0, 20, ['smart', 'my alias']);
44
+
45
+ assert.equal(calls[0].url.pathname, '/projects/p1/subscription/usages');
46
+ assert.deepEqual(calls[0].url.searchParams.getAll('alias'), ['smart', 'my alias']);
47
+ assert.equal(calls[0].url.searchParams.get('page'), '0');
48
+ });
49
+
50
+ test('listUsages without aliases sends no alias parameter', async (context) => {
51
+ const calls = recordFetch(context, { content: [], totalElements: 0, totalPages: 0, page: 0, size: 20 });
52
+
53
+ await client().listUsages('p1', undefined, undefined, ['gpt-5']);
54
+ await client().listUsages('p1', undefined, undefined, undefined, undefined, undefined, undefined, []);
55
+
56
+ for (const call of calls) assert.equal(call.url.searchParams.has('alias'), false);
57
+ assert.deepEqual(calls[0].url.searchParams.getAll('model'), ['gpt-5']);
58
+ });
59
+
60
+ test('usage details keep the alias a line went through', async (context) => {
61
+ const usage = {
62
+ id: 'u1',
63
+ creditsUsed: 200,
64
+ details: [{ service: 'model.openai.gpt-5.prompt_tokens', credits: 200, unit: 'tokens', alias: 'smart' }],
65
+ };
66
+ recordFetch(context, { content: [usage], totalElements: 1, totalPages: 1, page: 0, size: 20 });
67
+
68
+ const page = await client().listUsages('p1', undefined, undefined, undefined, undefined, 0, 20, ['smart']);
69
+
70
+ assert.equal(page.content[0].details[0].alias, 'smart');
71
+ });
@@ -0,0 +1,57 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { DecisionsApi, PersonaSdk } from '../dist/bundle.es.js';
5
+
6
+ const BASE = 'https://core.test';
7
+
8
+ function recordFetch(context, respond) {
9
+ const originalFetch = globalThis.fetch;
10
+ context.after(() => {
11
+ globalThis.fetch = originalFetch;
12
+ });
13
+ const calls = [];
14
+ globalThis.fetch = async (url, init) => {
15
+ calls.push({ url: new URL(String(url)), method: init.method, body: init.body });
16
+ const { status, body } = respond(calls.length);
17
+ return new Response(JSON.stringify(body), {
18
+ status,
19
+ headers: { 'Content-Type': 'application/json' },
20
+ });
21
+ };
22
+ return calls;
23
+ }
24
+
25
+ const REPLY = {
26
+ sessionId: 's1',
27
+ sessionCode: 'c1',
28
+ model: 'jev-1.14.0',
29
+ answers: { urgent: { type: 'noul', noul: 0.9 } },
30
+ usage: { inputTokens: 10, outputTokens: 1 },
31
+ };
32
+
33
+ test('decide posts the request and returns the answers', async (context) => {
34
+ const calls = recordFetch(context, () => ({ status: 200, body: REPLY }));
35
+ const request = {
36
+ model: 'typesafe/jev-latest',
37
+ state: { days: 40 },
38
+ questions: {
39
+ urgent: { type: 'noul', instructions: 'Urgent?' },
40
+ refund: { type: 'choice', instructions: 'Approve?', criteria: { approve: 'ok', reject: 'no' } },
41
+ },
42
+ };
43
+
44
+ const response = await new DecisionsApi(BASE, 'api-key').decide(request);
45
+
46
+ assert.equal(calls[0].method, 'POST');
47
+ assert.equal(calls[0].url.pathname, '/decisions');
48
+ assert.deepEqual(JSON.parse(calls[0].body), request);
49
+ assert.equal(response.answers.urgent.noul, 0.9);
50
+ });
51
+
52
+ test('listModels and the sdk facade', async (context) => {
53
+ const calls = recordFetch(context, () => ({ status: 200, body: [{ id: 'typesafe/jev-latest', provider: 'typesafe' }] }));
54
+ const models = await new PersonaSdk(BASE).decisions('api-key').listModels();
55
+ assert.equal(calls[0].url.pathname, '/decision-models');
56
+ assert.equal(models[0].id, 'typesafe/jev-latest');
57
+ });