@nuwah/vertical-sdk 0.0.0-stage → 0.2.0-rc.1

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 (239) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +229 -2
  3. package/bin/nuwah-contract-check-rules.d.mts +41 -0
  4. package/bin/nuwah-contract-check-rules.mjs +333 -0
  5. package/bin/nuwah-contract-check.mjs +64 -0
  6. package/dist/accounting.d.ts +1417 -0
  7. package/dist/accounting.js +274 -0
  8. package/dist/active-org.d.ts +13 -0
  9. package/dist/active-org.js +59 -0
  10. package/dist/actors.d.ts +448 -0
  11. package/dist/actors.js +143 -0
  12. package/dist/ai.d.ts +359 -0
  13. package/dist/ai.js +229 -0
  14. package/dist/analytics.d.ts +37 -0
  15. package/dist/analytics.js +8 -0
  16. package/dist/atlas.d.ts +291 -0
  17. package/dist/atlas.js +78 -0
  18. package/dist/audit.d.ts +193 -0
  19. package/dist/audit.js +26 -0
  20. package/dist/authentication.d.ts +119 -0
  21. package/dist/authentication.js +83 -0
  22. package/dist/awards.d.ts +38 -0
  23. package/dist/awards.js +10 -0
  24. package/dist/blueprint/document.d.ts +178 -0
  25. package/dist/blueprint/document.js +17 -0
  26. package/dist/blueprint/index.d.ts +3 -0
  27. package/dist/blueprint/index.js +5 -0
  28. package/dist/blueprint/manifest.d.ts +105 -0
  29. package/dist/blueprint/manifest.js +11 -0
  30. package/dist/blueprint/validate.d.ts +14 -0
  31. package/dist/blueprint/validate.js +416 -0
  32. package/dist/bookings-directory.d.ts +118 -0
  33. package/dist/bookings-directory.js +289 -0
  34. package/dist/bookings-extra.d.ts +1448 -0
  35. package/dist/bookings-extra.js +582 -0
  36. package/dist/bookings.d.ts +1365 -0
  37. package/dist/bookings.js +305 -0
  38. package/dist/builder-code.d.ts +164 -0
  39. package/dist/builder-code.js +12 -0
  40. package/dist/builder-core-gaps.d.ts +83 -0
  41. package/dist/builder-core-gaps.js +8 -0
  42. package/dist/builder-repos.d.ts +73 -0
  43. package/dist/builder-repos.js +37 -0
  44. package/dist/builder.d.ts +730 -0
  45. package/dist/builder.js +105 -0
  46. package/dist/campaigns.d.ts +105 -0
  47. package/dist/campaigns.js +25 -0
  48. package/dist/catalogs.d.ts +188 -0
  49. package/dist/catalogs.js +36 -0
  50. package/dist/commerce-ai.d.ts +182 -0
  51. package/dist/commerce-ai.js +27 -0
  52. package/dist/connections.d.ts +278 -0
  53. package/dist/connections.js +96 -0
  54. package/dist/content-control.d.ts +121 -0
  55. package/dist/content-control.js +23 -0
  56. package/dist/contributions.d.ts +560 -0
  57. package/dist/contributions.js +140 -0
  58. package/dist/conversation-assist.d.ts +154 -0
  59. package/dist/conversation-assist.js +51 -0
  60. package/dist/conversation-info.d.ts +219 -0
  61. package/dist/conversation-info.js +43 -0
  62. package/dist/crm.d.ts +533 -0
  63. package/dist/crm.js +142 -0
  64. package/dist/dashboards.d.ts +119 -0
  65. package/dist/dashboards.js +22 -0
  66. package/dist/delegations.d.ts +161 -0
  67. package/dist/delegations.js +39 -0
  68. package/dist/docs.d.ts +289 -0
  69. package/dist/docs.js +49 -0
  70. package/dist/documents.d.ts +317 -0
  71. package/dist/documents.js +84 -0
  72. package/dist/drafts.d.ts +132 -0
  73. package/dist/drafts.js +56 -0
  74. package/dist/engagements.d.ts +133 -0
  75. package/dist/engagements.js +15 -0
  76. package/dist/event-stream.d.ts +54 -0
  77. package/dist/event-stream.js +228 -0
  78. package/dist/exchanges.d.ts +447 -0
  79. package/dist/exchanges.js +145 -0
  80. package/dist/exports.d.ts +113 -0
  81. package/dist/exports.js +81 -0
  82. package/dist/feeds.d.ts +228 -0
  83. package/dist/feeds.js +52 -0
  84. package/dist/files.d.ts +56 -0
  85. package/dist/files.js +55 -0
  86. package/dist/finance-insights.d.ts +41 -0
  87. package/dist/finance-insights.js +61 -0
  88. package/dist/fixed-assets.d.ts +155 -0
  89. package/dist/fixed-assets.js +28 -0
  90. package/dist/fulfilment-jobs.d.ts +405 -0
  91. package/dist/fulfilment-jobs.js +76 -0
  92. package/dist/fulfilment.d.ts +205 -0
  93. package/dist/fulfilment.js +39 -0
  94. package/dist/hr.d.ts +350 -0
  95. package/dist/hr.js +94 -0
  96. package/dist/http.d.ts +124 -0
  97. package/dist/http.js +392 -0
  98. package/dist/inbox.d.ts +206 -0
  99. package/dist/inbox.js +36 -0
  100. package/dist/index.d.ts +384 -0
  101. package/dist/index.js +294 -0
  102. package/dist/insights.d.ts +176 -0
  103. package/dist/insights.js +52 -0
  104. package/dist/inventory.d.ts +797 -0
  105. package/dist/inventory.js +120 -0
  106. package/dist/list-query.d.ts +211 -0
  107. package/dist/list-query.js +158 -0
  108. package/dist/listings.d.ts +381 -0
  109. package/dist/listings.js +173 -0
  110. package/dist/location-sharing.d.ts +83 -0
  111. package/dist/location-sharing.js +20 -0
  112. package/dist/marketplace.d.ts +268 -0
  113. package/dist/marketplace.js +59 -0
  114. package/dist/matching.d.ts +103 -0
  115. package/dist/matching.js +22 -0
  116. package/dist/media.d.ts +221 -0
  117. package/dist/media.js +239 -0
  118. package/dist/metrics.d.ts +125 -0
  119. package/dist/metrics.js +45 -0
  120. package/dist/moderation.d.ts +240 -0
  121. package/dist/moderation.js +40 -0
  122. package/dist/money.d.ts +41 -0
  123. package/dist/money.js +79 -0
  124. package/dist/my-data.d.ts +266 -0
  125. package/dist/my-data.js +32 -0
  126. package/dist/names.d.ts +14 -0
  127. package/dist/names.js +17 -0
  128. package/dist/occasions.d.ts +256 -0
  129. package/dist/occasions.js +40 -0
  130. package/dist/onboarding.d.ts +88 -0
  131. package/dist/onboarding.js +38 -0
  132. package/dist/pagination.d.ts +204 -0
  133. package/dist/pagination.js +141 -0
  134. package/dist/party-baseline-attributes.d.ts +245 -0
  135. package/dist/party-baseline-attributes.js +36 -0
  136. package/dist/party.d.ts +401 -0
  137. package/dist/party.js +56 -0
  138. package/dist/patient.d.ts +161 -0
  139. package/dist/patient.js +45 -0
  140. package/dist/payroll.d.ts +378 -0
  141. package/dist/payroll.js +60 -0
  142. package/dist/person-addresses.d.ts +88 -0
  143. package/dist/person-addresses.js +18 -0
  144. package/dist/person-cart.d.ts +250 -0
  145. package/dist/person-cart.js +63 -0
  146. package/dist/person-chat-assist.d.ts +47 -0
  147. package/dist/person-chat-assist.js +13 -0
  148. package/dist/person-data-webhooks.d.ts +72 -0
  149. package/dist/person-data-webhooks.js +86 -0
  150. package/dist/person-data.d.ts +212 -0
  151. package/dist/person-data.js +162 -0
  152. package/dist/person-locations.d.ts +54 -0
  153. package/dist/person-locations.js +6 -0
  154. package/dist/person-messaging.d.ts +405 -0
  155. package/dist/person-messaging.js +112 -0
  156. package/dist/person-notifications.d.ts +319 -0
  157. package/dist/person-notifications.js +164 -0
  158. package/dist/personalisation.d.ts +21 -0
  159. package/dist/personalisation.js +8 -0
  160. package/dist/platform.d.ts +63 -0
  161. package/dist/platform.js +45 -0
  162. package/dist/portfolio.d.ts +163 -0
  163. package/dist/portfolio.js +28 -0
  164. package/dist/pos.d.ts +743 -0
  165. package/dist/pos.js +129 -0
  166. package/dist/procurement.d.ts +664 -0
  167. package/dist/procurement.js +157 -0
  168. package/dist/promotions.d.ts +169 -0
  169. package/dist/promotions.js +39 -0
  170. package/dist/publications.d.ts +583 -0
  171. package/dist/publications.js +164 -0
  172. package/dist/ranking.d.ts +43 -0
  173. package/dist/ranking.js +34 -0
  174. package/dist/ratings.d.ts +293 -0
  175. package/dist/ratings.js +109 -0
  176. package/dist/reactions.d.ts +123 -0
  177. package/dist/reactions.js +41 -0
  178. package/dist/recipient-orders.d.ts +294 -0
  179. package/dist/recipient-orders.js +73 -0
  180. package/dist/relationships.d.ts +18 -0
  181. package/dist/relationships.js +8 -0
  182. package/dist/reporting.d.ts +107 -0
  183. package/dist/reporting.js +56 -0
  184. package/dist/sales.d.ts +270 -0
  185. package/dist/sales.js +66 -0
  186. package/dist/shares.d.ts +105 -0
  187. package/dist/shares.js +27 -0
  188. package/dist/shop.d.ts +993 -0
  189. package/dist/shop.js +215 -0
  190. package/dist/shopping-assistant.d.ts +65 -0
  191. package/dist/shopping-assistant.js +14 -0
  192. package/dist/spaces.d.ts +422 -0
  193. package/dist/spaces.js +118 -0
  194. package/dist/stored-value.d.ts +754 -0
  195. package/dist/stored-value.js +177 -0
  196. package/dist/types.d.ts +83 -0
  197. package/dist/types.js +2 -0
  198. package/dist/vault.d.ts +290 -0
  199. package/dist/vault.js +55 -0
  200. package/dist/vertical-runtime.d.ts +17 -0
  201. package/dist/vertical-runtime.js +8 -0
  202. package/dist/vite/build-manifest-plugin.d.ts +42 -0
  203. package/dist/vite/build-manifest-plugin.js +42 -0
  204. package/dist/vite/first-paint-plugin.d.ts +26 -0
  205. package/dist/vite/first-paint-plugin.js +57 -0
  206. package/dist/wishlists.d.ts +591 -0
  207. package/dist/wishlists.js +188 -0
  208. package/dist/workbench.d.ts +114 -0
  209. package/dist/workbench.js +22 -0
  210. package/dist/workspace.d.ts +190 -0
  211. package/dist/workspace.js +41 -0
  212. package/package.json +52 -4
  213. package/templates/extension-image.Dockerfile +38 -0
  214. package/templates/nuwah-vertical.yml +102 -0
  215. package/templates/vertical-app/.env.example +34 -0
  216. package/templates/vertical-app/README.md +108 -0
  217. package/templates/vertical-app/github/workflows/ci.yml +51 -0
  218. package/templates/vertical-app/gitignore +5 -0
  219. package/templates/vertical-app/index.html +12 -0
  220. package/templates/vertical-app/package.json +28 -0
  221. package/templates/vertical-app/src/App.tsx +64 -0
  222. package/templates/vertical-app/src/blueprint/blueprint.ts +45 -0
  223. package/templates/vertical-app/src/blueprint/screens.ts +15 -0
  224. package/templates/vertical-app/src/env.d.ts +18 -0
  225. package/templates/vertical-app/src/index.css +139 -0
  226. package/templates/vertical-app/src/lib/i18n.ts +5 -0
  227. package/templates/vertical-app/src/lib/iam.ts +19 -0
  228. package/templates/vertical-app/src/lib/operations.ts +93 -0
  229. package/templates/vertical-app/src/lib/router.ts +24 -0
  230. package/templates/vertical-app/src/lib/sdk.ts +21 -0
  231. package/templates/vertical-app/src/lib/theme.ts +18 -0
  232. package/templates/vertical-app/src/lib/words.ts +39 -0
  233. package/templates/vertical-app/src/main.tsx +25 -0
  234. package/templates/vertical-app/src/pages/AppScreens.tsx +71 -0
  235. package/templates/vertical-app/src/pages/AuthCallback.tsx +44 -0
  236. package/templates/vertical-app/src/pages/Home.tsx +36 -0
  237. package/templates/vertical-app/tsconfig.json +24 -0
  238. package/templates/vertical-app/vite.config.ts +23 -0
  239. package/templates/vertical-ci.yml +192 -0
package/dist/ai.d.ts ADDED
@@ -0,0 +1,359 @@
1
+ import { type Http, type NuwahClientConfig } from './http.js';
2
+ import { type RetryOptions } from './event-stream.js';
3
+ export interface AiBilingualText {
4
+ en: string;
5
+ ar: string;
6
+ }
7
+ export type AiSwitchValue = 'on' | 'off';
8
+ /** Where a policy value was decided: the level that set it, or `default`. */
9
+ export type AiDecisionLevel = 'platform' | 'vertical' | 'organisation' | 'actor' | 'default' | (string & {});
10
+ export interface AiAvailabilitySetting {
11
+ /** What this organisation chose itself; null = inherit. */
12
+ choice: AiSwitchValue | null;
13
+ /** What applies after every level is resolved (strictest wins). */
14
+ in_force: AiSwitchValue;
15
+ /** Which level decided `in_force`. */
16
+ decided_at: AiDecisionLevel;
17
+ }
18
+ export type AiTier = 'fast' | 'standard' | 'deep';
19
+ export type AiPayer = 'platform' | 'tenant' | 'developer' | 'person' | 'actor';
20
+ export interface AiFeatureSetting extends AiAvailabilitySetting {
21
+ key: string;
22
+ label: AiBilingualText;
23
+ tier: AiTier;
24
+ payer: AiPayer;
25
+ reads_person_data: boolean;
26
+ categories: string[];
27
+ minors_allowed: boolean;
28
+ /** The declaration's own default. */
29
+ default: AiSwitchValue;
30
+ /** A platform OFF is absolute: the organisation cannot turn it on. */
31
+ locked_by_platform: boolean;
32
+ }
33
+ export interface AiFeatureSettings {
34
+ availability: AiAvailabilitySetting;
35
+ features: AiFeatureSetting[];
36
+ }
37
+ export type AiBudgetMode = 'none' | 'soft_alert' | 'hard_cap';
38
+ export type AiBudgetScopeType = 'platform' | 'vertical' | 'organisation' | 'developer_org' | 'person' | 'builder_session' | 'actor';
39
+ /** Nano units: a JSON number, or a string where a server sends one past 2^53. */
40
+ export type AiNanoAmount = number | string;
41
+ export interface AiBudget {
42
+ scope_type: AiBudgetScopeType;
43
+ scope_id: string | null;
44
+ period: 'month' | 'session' | (string & {});
45
+ period_key: string;
46
+ cap_minor: number | null;
47
+ cap_nano: AiNanoAmount | null;
48
+ mode: AiBudgetMode;
49
+ mode_is_own: boolean;
50
+ alert_at_percent: number;
51
+ source: 'row' | 'default';
52
+ spent_minor: number;
53
+ spent_nano: AiNanoAmount;
54
+ remaining_minor: number | null;
55
+ remaining_nano: AiNanoAmount | null;
56
+ used_percent: number | null;
57
+ updated_by: string | null;
58
+ updated_at: string | null;
59
+ }
60
+ export interface AiBudgetChange {
61
+ /** Whole cents (minor units). Null clears the cap. */
62
+ cap_minor_units?: number | null;
63
+ mode?: AiBudgetMode | null;
64
+ alert_at_pct?: number;
65
+ }
66
+ export interface AiUsageTotals {
67
+ calls: number;
68
+ failed_calls: number;
69
+ input_tokens: number;
70
+ output_tokens: number;
71
+ recorded_cost_nano: AiNanoAmount;
72
+ estimated_cost_nano: AiNanoAmount;
73
+ recorded_cost_minor: number;
74
+ estimated_cost_minor: number;
75
+ }
76
+ export interface AiUsageMonth extends AiUsageTotals {
77
+ month: string;
78
+ by_purpose: Array<AiUsageTotals & {
79
+ purpose?: string;
80
+ }>;
81
+ by_model: Array<AiUsageTotals & {
82
+ provider?: string;
83
+ model?: string;
84
+ }>;
85
+ by_credential: Array<AiUsageTotals & Record<string, unknown>>;
86
+ by_feature: Array<AiUsageTotals & {
87
+ feature_key: string;
88
+ }>;
89
+ by_payer: Array<AiUsageTotals & {
90
+ scope_type: string;
91
+ scope_id: string | null;
92
+ }>;
93
+ }
94
+ export interface AiUsageReport {
95
+ tenant_id: string;
96
+ timezone: string;
97
+ /** ISO 4217 code of the cost currency. */
98
+ currency: string;
99
+ cost_unit: 'minor';
100
+ from: string;
101
+ to: string;
102
+ totals: AiUsageTotals;
103
+ months: AiUsageMonth[];
104
+ daily: Array<AiUsageTotals & {
105
+ date: string;
106
+ }>;
107
+ spend_counter: {
108
+ period: string;
109
+ spent_minor: number;
110
+ spent_nano: AiNanoAmount;
111
+ } & Record<string, unknown>;
112
+ }
113
+ export interface AiUsageQuery {
114
+ /** `YYYY-MM`. */
115
+ from?: string;
116
+ to?: string;
117
+ }
118
+ export interface PersonAiSettings {
119
+ person_id: string;
120
+ /** AI in private and group chats (translate, summarise, reply drafts). Off by default. */
121
+ private_chats: boolean;
122
+ /** The categories the person's own assistant may read. */
123
+ self_data_categories: string[];
124
+ /** The onboarding assistant. */
125
+ onboarder: boolean;
126
+ /** Feature keys this person turned off for themselves. */
127
+ features_off: string[];
128
+ /** False until the person saved anything (the values are the defaults). */
129
+ stored: boolean;
130
+ }
131
+ export type PersonAiSettingsChange = Partial<Pick<PersonAiSettings, 'private_chats' | 'self_data_categories' | 'onboarder' | 'features_off'>>;
132
+ /** The risks a proposal can carry. `read`, `person_data` run in the loop; `consent` is refused at registration. */
133
+ export type AiProposalRisk = 'write' | 'destructive' | 'money';
134
+ export type AiToolRisk = 'read' | 'person_data' | AiProposalRisk | 'consent';
135
+ export type AiProposalStatus = 'pending' | 'confirmed' | 'rejected' | 'expired';
136
+ export interface AiProposal {
137
+ id: string;
138
+ conversation_id: string | null;
139
+ tool: string;
140
+ risk: AiProposalRisk;
141
+ /** True exactly when `risk` is destructive: confirm must carry `acknowledge_destructive: true`. */
142
+ needs_acknowledgement: boolean;
143
+ summary: AiBilingualText;
144
+ /** What will change — a tool-specific object the card renders as plain key/value lines. */
145
+ preview: unknown;
146
+ status: AiProposalStatus;
147
+ expires_at: string | null;
148
+ executed_at: string | null;
149
+ result: unknown;
150
+ }
151
+ export interface AiProposalDecision {
152
+ proposal: AiProposal;
153
+ /** A double confirm replays the stored result instead of acting twice. */
154
+ replayed?: boolean;
155
+ }
156
+ /**
157
+ * Which store a proposal lives in, by who decides it: a business's staff assistant
158
+ * (`organisation`), the organisation setup assistant (`onboarding`: the same tenant store, decided
159
+ * at `/api/ai/onboarding/proposals` with `ai.onboarding.use`), or a person's own (`person`).
160
+ */
161
+ export type AiProposalStore = 'organisation' | 'onboarding' | 'person';
162
+ /** Anything but `completed` is a partial answer; `cancelled` = the client stopped the run. */
163
+ export type AiStopReason = 'completed' | 'step_limit' | 'tool_call_limit' | 'token_limit' | 'time_limit' | 'budget' | 'model_declined' | 'cancelled';
164
+ export interface AiAssistantAskRequest {
165
+ question: string;
166
+ conversation_id?: string | null;
167
+ /** Further fields the endpoint accepts (locale, context) pass through unchanged. */
168
+ [field: string]: unknown;
169
+ }
170
+ export interface AiPersonAskRequest {
171
+ question: string;
172
+ /** Continue one of the person's conversations; omitted, a new one starts (its id is in `run_started`). */
173
+ conversation_id?: string | null;
174
+ locale?: 'en' | 'ar';
175
+ }
176
+ export interface AiAssistantAnswer {
177
+ answer: string;
178
+ proposals: AiProposal[];
179
+ tools_used: string[];
180
+ usage?: {
181
+ prompt_tokens: number;
182
+ completion_tokens: number;
183
+ total_tokens: number;
184
+ };
185
+ conversation_id?: string | null;
186
+ citations?: AiCitation[];
187
+ /** Optional so older servers still parse. */
188
+ stop_reason?: AiStopReason;
189
+ /** True unless `stop_reason` is `completed`. */
190
+ partial?: boolean;
191
+ run_id?: string;
192
+ extraction?: unknown;
193
+ }
194
+ export interface AiCitation {
195
+ /** Stable id for keys. */
196
+ id?: string;
197
+ label: string | AiBilingualText;
198
+ /** A link the reader can open, when the source has one. */
199
+ href?: string | null;
200
+ /** What kind of source: `record`, `document`, `knowledge`, `web`, … */
201
+ kind?: string;
202
+ }
203
+ /**
204
+ * One step of a run as a screen renders it. The JSON turn yields `tool_finished` for each name in
205
+ * `tools_used`; the stream adds `tool_started`, each tool's `risk`, and for a person-data tool the
206
+ * labels of the categories it read (`dataRead`). A stream never carries a tool's arguments or
207
+ * results.
208
+ */
209
+ export type AiRunEvent = {
210
+ type: 'run_started';
211
+ runId: string | null;
212
+ conversationId: string | null;
213
+ } | {
214
+ type: 'token';
215
+ text: string;
216
+ } | {
217
+ type: 'tool_started';
218
+ callId: string;
219
+ tool: string;
220
+ risk?: AiToolRisk;
221
+ summary?: AiBilingualText;
222
+ } | {
223
+ type: 'tool_finished';
224
+ callId: string;
225
+ tool: string;
226
+ outcome: AiToolCallOutcome;
227
+ risk?: AiToolRisk;
228
+ summary?: AiBilingualText;
229
+ dataRead?: AiBilingualText[];
230
+ } | {
231
+ type: 'citation';
232
+ citation: AiCitation;
233
+ } | {
234
+ type: 'proposal';
235
+ proposal: AiProposal;
236
+ } | {
237
+ type: 'done';
238
+ answer: string;
239
+ stopReason: AiStopReason;
240
+ partial: boolean;
241
+ conversationId: string | null;
242
+ runId: string | null;
243
+ } | {
244
+ type: 'error';
245
+ error: AiErrorInfo;
246
+ };
247
+ export type AiToolCallOutcome = 'executed' | 'proposed' | 'refused_permission' | 'refused_policy' | 'refused_risk' | 'refused_limit' | 'error';
248
+ /** Turns a JSON assistant answer into the event sequence a streamed run would have produced. */
249
+ export declare function answerToEvents(answer: AiAssistantAnswer): AiRunEvent[];
250
+ /**
251
+ * What a screen needs to know about a failure, from core's envelopes:
252
+ *
253
+ * disabled 503 `ai_disabled` — AI is off here (not an outage; never retried)
254
+ * budget_exhausted 402 `ai_credits_exhausted`, or a budget / unpriced-model refusal
255
+ * rate_limited 429 (`retry_after_seconds` when given)
256
+ * forbidden 403 — permission or authority missing (re-checked at confirm)
257
+ * acknowledgement_required 422 — a destructive proposal sent without the acknowledgement
258
+ * expired 410 — the proposal's time ran out
259
+ * conflict 409 — already decided, or the tool is no longer available
260
+ * not_found 404
261
+ * refused another 4xx refusal (validation, the action itself refused)
262
+ * network no answer at all
263
+ * aborted the person pressed stop
264
+ * unknown anything else (5xx)
265
+ */
266
+ export type AiErrorKind = 'disabled' | 'budget_exhausted' | 'rate_limited' | 'forbidden' | 'acknowledgement_required' | 'expired' | 'conflict' | 'not_found' | 'refused' | 'network' | 'aborted' | 'unknown';
267
+ export interface AiErrorInfo {
268
+ kind: AiErrorKind;
269
+ /** The server's own words when it sent any (already in the reader's language). */
270
+ message: string | null;
271
+ /** The machine-readable code (`reason` or `code`). */
272
+ code: string | null;
273
+ status: number | null;
274
+ retryAfterSeconds: number | null;
275
+ }
276
+ export declare function describeAiError(error: unknown): AiErrorInfo;
277
+ export interface AiCallOptions {
278
+ signal?: AbortSignal;
279
+ /** Retries for reads only (writes are never retried without an idempotency key). */
280
+ retry?: RetryOptions | false;
281
+ }
282
+ export interface AiDecisionOptions {
283
+ signal?: AbortSignal;
284
+ /** Reuse the same key when retrying the same decision. */
285
+ idempotencyKey?: string;
286
+ }
287
+ export interface AiStreamOptions {
288
+ signal?: AbortSignal;
289
+ headers?: Record<string, string>;
290
+ }
291
+ export interface AiNamespace {
292
+ settings: {
293
+ features(options?: AiCallOptions): Promise<{
294
+ data: AiFeatureSettings;
295
+ }>;
296
+ /** `key` is a feature key, or `availability` for the organisation-wide switch. Null inherits. */
297
+ setFeature(key: string, value: AiSwitchValue | null, options?: AiDecisionOptions): Promise<{
298
+ data: AiFeatureSettings;
299
+ }>;
300
+ budget(options?: AiCallOptions): Promise<{
301
+ data: AiBudget;
302
+ }>;
303
+ setBudget(change: AiBudgetChange, options?: AiDecisionOptions): Promise<{
304
+ data: AiBudget;
305
+ }>;
306
+ clearBudget(options?: AiDecisionOptions): Promise<{
307
+ data: AiBudget;
308
+ }>;
309
+ };
310
+ usage(query?: AiUsageQuery, options?: AiCallOptions): Promise<{
311
+ data: AiUsageReport;
312
+ } | AiUsageReport>;
313
+ person: {
314
+ settings(options?: AiCallOptions): Promise<{
315
+ data: PersonAiSettings;
316
+ }>;
317
+ updateSettings(change: PersonAiSettingsChange, options?: AiDecisionOptions): Promise<{
318
+ data: PersonAiSettings;
319
+ }>;
320
+ /**
321
+ * One turn of the person's own assistant, streamed (`POST /api/person/ai/assistant/stream`).
322
+ * Proposals it prepares are decided with `proposals.*(id, …, 'person')`. A delegate passes
323
+ * `X-On-Behalf-Of` in `options.headers`. Never throws: a failure (including the feature
324
+ * being off, `disabled`) is an `error` event; aborting stops the run on the server.
325
+ */
326
+ askAsEvents(request: AiPersonAskRequest, options?: AiStreamOptions): AsyncGenerator<AiRunEvent>;
327
+ };
328
+ assistant: {
329
+ /** One staff assistant turn as JSON (photos go here). Abortable; never retried (a turn may prepare proposals). */
330
+ ask(request: AiAssistantAskRequest, options?: AiStreamOptions): Promise<AiAssistantAnswer>;
331
+ /**
332
+ * The same turn streamed (`/api/ai/assistant/ask/stream`), falling back to `ask` only when
333
+ * the server has no stream route. Never throws: a failure is an `error` event; aborting
334
+ * stops the run on the server too.
335
+ */
336
+ askAsEvents(request: AiAssistantAskRequest, options?: AiStreamOptions): AsyncGenerator<AiRunEvent>;
337
+ };
338
+ proposals: {
339
+ get(id: string, store?: AiProposalStore, options?: AiCallOptions): Promise<{
340
+ proposal: AiProposal;
341
+ }>;
342
+ confirm(id: string, decision?: {
343
+ acknowledgeDestructive?: boolean;
344
+ }, store?: AiProposalStore, options?: AiDecisionOptions): Promise<AiProposalDecision>;
345
+ reject(id: string, store?: AiProposalStore, options?: AiDecisionOptions): Promise<AiProposalDecision>;
346
+ };
347
+ /**
348
+ * Reads a streamed agent run (`text/event-stream`) and yields `AiRunEvent`s. Frames: `token`
349
+ * `{text}`, `tool_started` `{call_id, tool, summary?}`, `tool_finished` `{call_id, tool, outcome,
350
+ * summary?, data_read?}`, `citation` `{…AiCitation}`, `proposal` `{…AiProposal}`, `done`
351
+ * `{answer, stop_reason, conversation_id, run_id}`, `error` `{code, message}`; a plain `message`
352
+ * frame of `{text}` counts as a token. The path is the feature's own stream endpoint. Never
353
+ * throws: an abort ends it quietly, a failure is an `error` event.
354
+ */
355
+ streamRun(path: string, body: unknown, options?: AiStreamOptions): AsyncGenerator<AiRunEvent>;
356
+ }
357
+ /** Maps one stream frame to an event; unknown frames are skipped (forward compatible). */
358
+ export declare function frameToRunEvent(event: string, data: string): AiRunEvent | null;
359
+ export declare function createAiNamespace(http: Http, config: NuwahClientConfig): AiNamespace;
package/dist/ai.js ADDED
@@ -0,0 +1,229 @@
1
+
2
+
3
+ import { NuwahApiError, refusalReason } from './http.js';
4
+ import { isAbortError, openEventStream, retryAfterSeconds, withRetry } from './event-stream.js';
5
+
6
+ export function answerToEvents(answer) {
7
+ const conversationId = answer.conversation_id ?? null;
8
+ const runId = answer.run_id ?? null;
9
+ const events = [{ type: 'run_started', runId, conversationId }];
10
+ answer.tools_used.forEach((tool, index) => events.push({ type: 'tool_finished', callId: `${index}:${tool}`, tool, outcome: 'executed' }));
11
+ if (answer.answer)
12
+ events.push({ type: 'token', text: answer.answer });
13
+ for (const citation of answer.citations ?? [])
14
+ events.push({ type: 'citation', citation });
15
+ for (const proposal of answer.proposals)
16
+ events.push({ type: 'proposal', proposal });
17
+ const stopReason = answer.stop_reason ?? 'completed';
18
+ events.push({ type: 'done', answer: answer.answer, stopReason, partial: answer.partial ?? stopReason !== 'completed', conversationId, runId });
19
+ return events;
20
+ }
21
+ const BUDGET_CODES = ['ai_credits_exhausted', 'budget_exceeded', 'ai_budget_exceeded'];
22
+ export function describeAiError(error) {
23
+ if (isAbortError(error))
24
+ return { kind: 'aborted', message: null, code: null, status: null, retryAfterSeconds: null };
25
+ if (!(error instanceof NuwahApiError)) {
26
+ return { kind: error instanceof TypeError ? 'network' : 'unknown', message: null, code: null, status: null, retryAfterSeconds: null };
27
+ }
28
+ const code = refusalReason(error) ?? errorField(error.body);
29
+ const body = error.body;
30
+ const message = body && typeof body === 'object' && typeof body.message === 'string' && body.message !== '' ? body.message : null;
31
+ const base = { message, code, status: error.status, retryAfterSeconds: retryAfterSeconds(error) };
32
+ const kind = (() => {
33
+ if (code === 'ai_disabled')
34
+ return 'disabled';
35
+ if (error.status === 402 || (code !== null && (BUDGET_CODES.includes(code) || code.startsWith('model_unpriced'))))
36
+ return 'budget_exhausted';
37
+ if (code === 'acknowledgement_required')
38
+ return 'acknowledgement_required';
39
+ switch (error.status) {
40
+ case 429: return 'rate_limited';
41
+ case 403: return 'forbidden';
42
+ case 401: return 'forbidden';
43
+ case 404: return 'not_found';
44
+ case 409: return 'conflict';
45
+ case 410: return 'expired';
46
+ case 503: return 'disabled';
47
+ default: return error.status >= 400 && error.status < 500 ? 'refused' : 'unknown';
48
+ }
49
+ })();
50
+ return { kind, ...base };
51
+ }
52
+ function errorField(body) {
53
+ if (!body || typeof body !== 'object')
54
+ return null;
55
+ const value = body.error;
56
+ return typeof value === 'string' && value !== '' ? value : null;
57
+ }
58
+
59
+ const STREAM_CODE_STATUS = {
60
+ ai_disabled: 503,
61
+ ai_credits_exhausted: 402,
62
+ rate_limited: 429,
63
+ forbidden: 403,
64
+ };
65
+ function readOptions(options = {}, write = false) {
66
+ const headers = {};
67
+ if (write)
68
+ headers['Idempotency-Key'] = options.idempotencyKey ?? newKey();
69
+ return { headers, ...(options.signal ? { signal: options.signal } : {}) };
70
+ }
71
+ function newKey() {
72
+ const crypto = globalThis.crypto;
73
+ if (crypto?.randomUUID)
74
+ return crypto.randomUUID();
75
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;
76
+ }
77
+ function proposalBase(store) {
78
+ if (store === 'person')
79
+ return '/api/person/ai/proposals';
80
+ return store === 'onboarding' ? '/api/ai/onboarding/proposals' : '/api/ai/assistant/proposals';
81
+ }
82
+ function bilingualOrUndefined(value) {
83
+ if (value && typeof value === 'object' && typeof value.en === 'string' && typeof value.ar === 'string') {
84
+ return value;
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ export function frameToRunEvent(event, data) {
90
+ let payload = {};
91
+ try {
92
+ const parsed = data ? JSON.parse(data) : {};
93
+ payload = parsed && typeof parsed === 'object' ? parsed : { text: String(parsed) };
94
+ }
95
+ catch {
96
+ payload = { text: data };
97
+ }
98
+ const text = (key) => (typeof payload[key] === 'string' ? payload[key] : null);
99
+ switch (event) {
100
+ case 'message':
101
+ case 'token':
102
+ case 'delta': {
103
+ const delta = text('text') ?? text('delta') ?? text('chunk');
104
+ return delta !== null && delta !== '' ? { type: 'token', text: delta } : null;
105
+ }
106
+ case 'run_started':
107
+ return { type: 'run_started', runId: text('run_id'), conversationId: text('conversation_id') };
108
+ case 'tool_started':
109
+ return {
110
+ type: 'tool_started',
111
+ callId: text('call_id') ?? text('tool') ?? 'step',
112
+ tool: text('tool') ?? '',
113
+ risk: (text('risk') ?? undefined),
114
+ summary: bilingualOrUndefined(payload.summary),
115
+ };
116
+ case 'tool_finished':
117
+ return {
118
+ type: 'tool_finished',
119
+ callId: text('call_id') ?? text('tool') ?? 'step',
120
+ tool: text('tool') ?? '',
121
+ outcome: (text('outcome') ?? 'executed'),
122
+ risk: (text('risk') ?? undefined),
123
+ summary: bilingualOrUndefined(payload.summary),
124
+ dataRead: Array.isArray(payload.data_read) ? payload.data_read.map(bilingualOrUndefined).filter((value) => value !== undefined) : undefined,
125
+ };
126
+ case 'citation':
127
+ return { type: 'citation', citation: payload };
128
+ case 'proposal':
129
+ return { type: 'proposal', proposal: payload };
130
+ case 'done': {
131
+ const stopReason = (text('stop_reason') ?? 'completed');
132
+ return {
133
+ type: 'done',
134
+ answer: text('answer') ?? '',
135
+ stopReason,
136
+ partial: typeof payload.partial === 'boolean' ? payload.partial : stopReason !== 'completed',
137
+ conversationId: text('conversation_id'),
138
+ runId: text('run_id'),
139
+ };
140
+ }
141
+ case 'error': {
142
+ const code = text('code');
143
+ const status = (code !== null ? STREAM_CODE_STATUS[code] : undefined) ?? 500;
144
+ return { type: 'error', error: describeAiError(new NuwahApiError(status, payload)) };
145
+ }
146
+ default:
147
+ return null;
148
+ }
149
+ }
150
+ export function createAiNamespace(http, config) {
151
+ const read = (operation, options = {}) => options.retry === false ? operation() : withRetry(operation, { ...(options.retry ?? {}), signal: options.signal });
152
+ const ask = (request, options = {}) => http.post('/api/ai/assistant/ask', request, { ...(options.signal ? { signal: options.signal } : {}), ...(options.headers ? { headers: options.headers } : {}) });
153
+
154
+ async function* events(path, body, options) {
155
+ for await (const frame of openEventStream(config, path, { body, signal: options.signal, headers: options.headers })) {
156
+ const event = frameToRunEvent(frame.event, frame.data);
157
+ if (event)
158
+ yield event;
159
+ }
160
+ }
161
+
162
+ async function* safeEvents(path, body, options) {
163
+ try {
164
+ yield* events(path, body, options);
165
+ }
166
+ catch (error) {
167
+ if (isAbortError(error) || options.signal?.aborted)
168
+ return;
169
+ yield { type: 'error', error: describeAiError(error) };
170
+ }
171
+ }
172
+
173
+ let staffStreamMissing = false;
174
+ return {
175
+ settings: {
176
+ features: (options) => read(() => http.get('/api/ai/settings/features', readOptions(options)), options),
177
+ setFeature: (key, value, options) => http.put(`/api/ai/settings/features/${encodeURIComponent(key)}`, { value }, readOptions(options, true)),
178
+ budget: (options) => read(() => http.get('/api/ai/settings/budget', readOptions(options)), options),
179
+ setBudget: (change, options) => http.put('/api/ai/settings/budget', change, readOptions(options, true)),
180
+ clearBudget: (options) => http.delete('/api/ai/settings/budget', readOptions(options, true)),
181
+ },
182
+ usage: (query = {}, options) => read(() => http.get('/api/ai/usage', { ...readOptions(options), params: { from: query.from, to: query.to } }), options),
183
+ person: {
184
+ settings: (options) => read(() => http.get('/api/person/ai/settings', readOptions(options)), options),
185
+ updateSettings: (change, options) => http.put('/api/person/ai/settings', change, readOptions(options, true)),
186
+ askAsEvents: (request, options = {}) => safeEvents('/api/person/ai/assistant/stream', request, options),
187
+ },
188
+ assistant: {
189
+ ask,
190
+ askAsEvents: async function* (request, options = {}) {
191
+ if (!staffStreamMissing) {
192
+ let received = false;
193
+ try {
194
+ for await (const event of events('/api/ai/assistant/ask/stream', request, options)) {
195
+ received = true;
196
+ yield event;
197
+ }
198
+ return;
199
+ }
200
+ catch (error) {
201
+ if (isAbortError(error) || options.signal?.aborted)
202
+ return;
203
+ const noRoute = !received && error instanceof NuwahApiError && (error.status === 404 || error.status === 405);
204
+ if (!noRoute) {
205
+ yield { type: 'error', error: describeAiError(error) };
206
+ return;
207
+ }
208
+ staffStreamMissing = true;
209
+ }
210
+ }
211
+ try {
212
+ const answer = await ask(request, options);
213
+ yield* answerToEvents(answer);
214
+ }
215
+ catch (error) {
216
+ if (isAbortError(error) || options.signal?.aborted)
217
+ return;
218
+ yield { type: 'error', error: describeAiError(error) };
219
+ }
220
+ },
221
+ },
222
+ proposals: {
223
+ get: (id, store = 'organisation', options) => read(() => http.get(`${proposalBase(store)}/${encodeURIComponent(id)}`, readOptions(options)), options),
224
+ confirm: (id, decision = {}, store = 'organisation', options) => http.post(`${proposalBase(store)}/${encodeURIComponent(id)}/confirm`, decision.acknowledgeDestructive ? { acknowledge_destructive: true } : {}, readOptions(options, true)),
225
+ reject: (id, store = 'organisation', options) => http.post(`${proposalBase(store)}/${encodeURIComponent(id)}/reject`, {}, readOptions(options, true)),
226
+ },
227
+ streamRun: (path, body, options = {}) => safeEvents(path, body, options),
228
+ };
229
+ }
@@ -0,0 +1,37 @@
1
+ import type { Http } from './http.js';
2
+ import type { Paginated } from './types.js';
3
+ /** One projected daily aggregate fact from the read-model. */
4
+ export interface AnalyticsFact {
5
+ /** The aggregation day, ISO `YYYY-MM-DD`. */
6
+ day: string;
7
+ /** The metric key — e.g. `revenue`, `sessions_completed`, `no_shows`. */
8
+ metric: string;
9
+ /** The slice this row is grouped by (e.g. practitioner id), or `null` for the ungrouped total. */
10
+ dimension: string | null;
11
+ /** The additive value SUM as a bcmath decimal STRING (money is summed here). */
12
+ value: string;
13
+ /** The additive event COUNT for the grain. */
14
+ count: number;
15
+ /** When this projected row was last written, ISO-8601, or `null`. */
16
+ updated_at: string | null;
17
+ }
18
+ export interface AnalyticsFactsQuery {
19
+ /** The metric to read — the dashboard always asks for one. */
20
+ metric?: string;
21
+ /** Inclusive day-range lower bound, ISO `YYYY-MM-DD`. */
22
+ from?: string;
23
+ /** Inclusive day-range upper bound, ISO `YYYY-MM-DD`. */
24
+ to?: string;
25
+ /** Exact dimension slice to filter to. */
26
+ dimension?: string;
27
+ page?: number;
28
+ per_page?: number;
29
+ [param: string]: string | number | boolean | null | undefined | Array<string | number>;
30
+ }
31
+ export declare function createAnalyticsNamespace(http: Http): {
32
+ facts: {
33
+ /** GET /api/analytics/facts — projected daily facts, day-ascending, paginated `{ data, meta }`. */
34
+ list: (query?: AnalyticsFactsQuery) => Promise<Paginated<AnalyticsFact>>;
35
+ };
36
+ };
37
+ export type AnalyticsNamespace = ReturnType<typeof createAnalyticsNamespace>;
@@ -0,0 +1,8 @@
1
+ export function createAnalyticsNamespace(http) {
2
+ return {
3
+ facts: {
4
+
5
+ list: (query) => http.get('/api/analytics/facts', { params: query }),
6
+ },
7
+ };
8
+ }