adula 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -0,0 +1,487 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { subject } from '@casl/ability';
3
+ import { buildAbility } from '../auth/ability.js';
4
+ import { AdulaError } from '../admin/errors.js';
5
+ import { logActivity } from '../core/activity.js';
6
+ import { parseResourceToolArgs, resourceToolError, runResourceTool, } from '../admin/resource_tools.js';
7
+ import { AssistantError } from './client.js';
8
+ import { ASSISTANT_NOTICE_KEY, } from './settings.js';
9
+ import { ASSISTANT_PREAMBLE, PROPOSE_TOOL, READ_TOOL, TOOL_ARGUMENT_LIMIT, resourceCatalogue, toolDefinitions, wrapToolResult, } from './prompt.js';
10
+ import { remainingTokens, reserveTokens, settleTokens, usageDay } from './usage.js';
11
+ const RESOURCE = 'core.ai';
12
+ export const ASSISTANT_SUBJECT = 'core.ai';
13
+ export const MESSAGE_LIMIT = 4000;
14
+ export const HISTORY_ENTRIES = 20;
15
+ export const HISTORY_CHARACTERS = 24_000;
16
+ export const LIST_ROW_LIMIT = 20;
17
+ export const PROPOSAL_TTL_MINUTES = 10;
18
+ const TURN_DEADLINE_MS = 90_000;
19
+ const TOOL_CALLS_PER_STEP = 5;
20
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
21
+ const disabled = () => new AdulaError(404, 'E_AI_DISABLED', 'المساعد غير مفعّل');
22
+ const forbidden = () => new AdulaError(403, 'E_FORBIDDEN', 'لا تملك صلاحية استخدام المساعد');
23
+ const invalidInput = (message = 'الرسالة غير صالحة') => new AdulaError(422, 'E_AI_INPUT', message);
24
+ /** Validates a turn body: only the new message and prior user/assistant text. */
25
+ export function parseTurnInput(value) {
26
+ if (!value || typeof value !== 'object' || Array.isArray(value))
27
+ throw invalidInput();
28
+ const body = value;
29
+ if (Object.keys(body).some((key) => key !== 'message' && key !== 'history'))
30
+ throw invalidInput();
31
+ const message = typeof body.message === 'string' ? body.message.trim() : '';
32
+ if (!message || message.length > MESSAGE_LIMIT)
33
+ throw invalidInput(`اكتب سؤالاً لا يتجاوز ${MESSAGE_LIMIT} حرف`);
34
+ const raw = body.history === undefined ? [] : body.history;
35
+ if (!Array.isArray(raw) || raw.length > HISTORY_ENTRIES)
36
+ throw invalidInput('سجل المحادثة غير صالح');
37
+ let characters = message.length;
38
+ const history = raw.map((item) => {
39
+ if (!item || typeof item !== 'object' || Array.isArray(item))
40
+ throw invalidInput('سجل المحادثة غير صالح');
41
+ const entry = item;
42
+ const keys = Object.keys(entry);
43
+ if (keys.length !== 2 ||
44
+ !keys.includes('role') ||
45
+ !keys.includes('content') ||
46
+ (entry.role !== 'user' && entry.role !== 'assistant') ||
47
+ typeof entry.content !== 'string' ||
48
+ entry.content.length > MESSAGE_LIMIT)
49
+ throw invalidInput('سجل المحادثة غير صالح');
50
+ characters += entry.content.length;
51
+ return { role: entry.role, content: entry.content };
52
+ });
53
+ if (characters > HISTORY_CHARACTERS)
54
+ throw invalidInput('المحادثة طويلة؛ ابدأ محادثة جديدة');
55
+ return { message, history };
56
+ }
57
+ function estimateTokens(messages, maxOutput) {
58
+ // Arabic text averages fewer characters per token than English; two is conservative.
59
+ return Math.ceil(JSON.stringify(messages).length / 2) + maxOutput;
60
+ }
61
+ /**
62
+ * The built-in assistant (ADR 052). Every tool call runs through the shared resource tool
63
+ * runner as the signed-in actor; the model can only propose writes, which run when the
64
+ * user confirms them in a separate request.
65
+ */
66
+ export class Assistant {
67
+ db;
68
+ registry;
69
+ resources;
70
+ settings;
71
+ client;
72
+ options;
73
+ constructor(db, registry, resources, settings, client, options = {}) {
74
+ this.db = db;
75
+ this.registry = registry;
76
+ this.resources = resources;
77
+ this.settings = settings;
78
+ this.client = client;
79
+ this.options = options;
80
+ }
81
+ now() {
82
+ return this.options.now?.() ?? new Date();
83
+ }
84
+ /** Whether the role rules grant `use` on `core.ai` (administrators always pass). */
85
+ canUse(actor) {
86
+ return buildAbility(actor.rules).can('use', subject(ASSISTANT_SUBJECT, {}));
87
+ }
88
+ async status(actor) {
89
+ if (!this.canUse(actor))
90
+ return { available: false, noticeAccepted: false };
91
+ const config = await this.settings.read();
92
+ const available = config.enabled && config.hasKey && config.model !== '';
93
+ return { available, noticeAccepted: available && (await this.noticeAccepted(actor.id)) };
94
+ }
95
+ async noticeAccepted(userId) {
96
+ const row = await this.db('settings')
97
+ .where({ key: ASSISTANT_NOTICE_KEY, scope: 'user', scope_id: String(userId) })
98
+ .first('id');
99
+ return Boolean(row);
100
+ }
101
+ /** Permission, configuration and key; the provider key is returned for this call only. */
102
+ async usable(actor) {
103
+ if (!this.canUse(actor))
104
+ throw forbidden();
105
+ const { config, key } = await this.settings.runtime();
106
+ if (!config.enabled || !key || !config.model)
107
+ throw disabled();
108
+ return { config, key };
109
+ }
110
+ /** Records that the user read the provider notice; an impersonator cannot accept it. */
111
+ async acceptNotice(actor) {
112
+ await this.usable(actor);
113
+ if (actor.impersonatorId)
114
+ throw new AdulaError(403, 'E_AI_IMPERSONATION', 'لا يمكن قبول تنبيه المساعد نيابة عن مستخدم آخر');
115
+ await this.db('settings')
116
+ .insert({
117
+ key: ASSISTANT_NOTICE_KEY,
118
+ scope: 'user',
119
+ scope_id: String(actor.id),
120
+ value: JSON.stringify({ acceptedAt: this.now().toISOString() }),
121
+ })
122
+ .onConflict(['key', 'scope', 'scope_id'])
123
+ .ignore();
124
+ }
125
+ async startConversation(actor) {
126
+ await this.usable(actor);
127
+ const [row] = await this.db('ai_conversations')
128
+ .insert({ user_id: actor.id, impersonator_id: actor.impersonatorId ?? null })
129
+ .returning('id');
130
+ return { id: Number(row.id) };
131
+ }
132
+ async turn(actor, conversationId, body) {
133
+ const { message, history } = parseTurnInput(body);
134
+ const { config, key } = await this.usable(actor);
135
+ if (!(await this.noticeAccepted(actor.id)))
136
+ throw new AdulaError(409, 'E_AI_NOTICE', 'اقرأ تنبيه المساعد ووافق عليه أولاً');
137
+ await this.conversation(actor, conversationId);
138
+ const persona = config.systemPrompt.trim();
139
+ const messages = [
140
+ {
141
+ role: 'system',
142
+ content: [
143
+ ASSISTANT_PREAMBLE,
144
+ `Today (UTC): ${usageDay(this.now())}.`,
145
+ `Resources this user may read: ${JSON.stringify(resourceCatalogue(this.registry, actor))}`,
146
+ ].join('\n'),
147
+ },
148
+ ...(persona ? [{ role: 'system', content: persona }] : []),
149
+ ...history,
150
+ { role: 'user', content: message },
151
+ ];
152
+ const state = { conversationId, proposals: [] };
153
+ const deadline = AbortSignal.timeout(TURN_DEADLINE_MS);
154
+ const day = usageDay(this.now());
155
+ let reply = '';
156
+ let spent = 0;
157
+ for (let step = 0; step <= config.maxToolIterations; step++) {
158
+ // The last step offers no tools, so the model has to answer in text.
159
+ const offerTools = step < config.maxToolIterations;
160
+ const estimate = estimateTokens(messages, config.maxOutputTokens);
161
+ if (!(await reserveTokens(this.db, actor.id, day, estimate, config.dailyTokenBudget))) {
162
+ if (step === 0)
163
+ throw new AdulaError(429, 'E_AI_BUDGET', 'استنفدت حصتك اليومية من المساعد. حاول غداً.');
164
+ reply = 'توقف المساعد لأن حصتك اليومية لا تكفي لمتابعة هذا السؤال.';
165
+ break;
166
+ }
167
+ let completion;
168
+ try {
169
+ completion = await this.client({
170
+ baseUrl: config.baseUrl,
171
+ key,
172
+ signal: AbortSignal.any([AbortSignal.timeout(config.timeoutSeconds * 1000), deadline]),
173
+ body: {
174
+ model: config.model,
175
+ messages,
176
+ max_tokens: config.maxOutputTokens,
177
+ temperature: 0.2,
178
+ ...(offerTools
179
+ ? { tools: toolDefinitions(config.allowWriteProposals), tool_choice: 'auto' }
180
+ : {}),
181
+ },
182
+ });
183
+ }
184
+ catch (error) {
185
+ await settleTokens(this.db, actor.id, day, estimate, { prompt: 0, completion: 0 });
186
+ throw error instanceof AdulaError ? error : new AssistantError('connect');
187
+ }
188
+ const used = completion.usage ?? {
189
+ prompt: estimate - config.maxOutputTokens,
190
+ completion: config.maxOutputTokens,
191
+ };
192
+ await settleTokens(this.db, actor.id, day, estimate, used);
193
+ spent += used.prompt + used.completion;
194
+ if (!offerTools || !completion.toolCalls.length) {
195
+ reply = completion.content ?? '';
196
+ break;
197
+ }
198
+ messages.push({
199
+ role: 'assistant',
200
+ content: completion.content,
201
+ tool_calls: completion.toolCalls,
202
+ });
203
+ for (const [index, call] of completion.toolCalls.entries()) {
204
+ const content = index < TOOL_CALLS_PER_STEP
205
+ ? await this.runTool(actor, config, state, call.function.name, call.function.arguments)
206
+ : wrapToolResult({
207
+ ok: false,
208
+ error: { code: 'E_AI_TOOL', message: 'Too many tool calls' },
209
+ });
210
+ messages.push({ role: 'tool', tool_call_id: call.id, content });
211
+ }
212
+ }
213
+ await this.db('ai_conversations')
214
+ .where({ id: conversationId, user_id: actor.id })
215
+ .update({
216
+ turns: this.db.raw('turns + 1'),
217
+ tokens: this.db.raw('tokens + ?', [spent]),
218
+ last_turn_at: this.now(),
219
+ });
220
+ return {
221
+ reply: reply.trim() || 'لم يصل رد من المساعد.',
222
+ proposals: state.proposals,
223
+ usage: {
224
+ remainingToday: await remainingTokens(this.db, actor.id, day, config.dailyTokenBudget),
225
+ },
226
+ };
227
+ }
228
+ async conversation(actor, id) {
229
+ if (!Number.isSafeInteger(id) || id < 1)
230
+ throw new AdulaError(404, 'E_NOT_FOUND', 'المحادثة غير موجودة');
231
+ const row = await this.db('ai_conversations').where({ id, user_id: actor.id }).first('id');
232
+ if (!row)
233
+ throw new AdulaError(404, 'E_NOT_FOUND', 'المحادثة غير موجودة');
234
+ }
235
+ runtime(actor) {
236
+ return { registry: this.registry, resources: this.resources, actor };
237
+ }
238
+ async audit(actor, conversationId, action, changes) {
239
+ await logActivity(this.db, {
240
+ resource: RESOURCE,
241
+ recordId: conversationId,
242
+ actorId: actor.id,
243
+ impersonatorId: actor.impersonatorId,
244
+ action,
245
+ changes: changes,
246
+ });
247
+ }
248
+ /**
249
+ * Runs one model tool call. Names, argument whitelist and the actor are fixed here;
250
+ * nothing in the arguments or in earlier tool output can widen them.
251
+ */
252
+ async runTool(actor, config, state, name, rawArguments) {
253
+ const write = name === PROPOSE_TOOL;
254
+ if (name !== READ_TOOL && !(write && config.allowWriteProposals)) {
255
+ await this.audit(actor, state.conversationId, 'tool.denied', {
256
+ tool: name.slice(0, 60),
257
+ outcome: { status: 404, code: 'E_AI_TOOL' },
258
+ });
259
+ return wrapToolResult({ ok: false, error: { code: 'E_AI_TOOL', message: 'Unknown tool' } });
260
+ }
261
+ let call = null;
262
+ try {
263
+ if (rawArguments.length > TOOL_ARGUMENT_LIMIT)
264
+ throw invalidInput('Tool arguments too large');
265
+ let args;
266
+ try {
267
+ args = JSON.parse(rawArguments || '{}');
268
+ }
269
+ catch {
270
+ throw invalidInput('Tool arguments are not JSON');
271
+ }
272
+ call = parseResourceToolArgs(this.runtime(actor), args, write);
273
+ if (write)
274
+ return await this.propose(actor, state, call);
275
+ if (call.action === 'list')
276
+ call.options = {
277
+ ...call.options,
278
+ limit: Math.min(Number(call.options?.limit ?? LIST_ROW_LIMIT), LIST_ROW_LIMIT),
279
+ };
280
+ const result = (await runResourceTool(this.runtime(actor), call));
281
+ await this.audit(actor, state.conversationId, 'tool.read', {
282
+ tool: name,
283
+ resource: call.resource,
284
+ action: call.action,
285
+ ids: call.action === 'list'
286
+ ? (Array.isArray(result?.data) ? result.data : [])
287
+ .map((row) => Number(row?.id))
288
+ .filter(Number.isSafeInteger)
289
+ .slice(0, LIST_ROW_LIMIT)
290
+ : call.id
291
+ ? [call.id]
292
+ : [],
293
+ outcome: { status: 200 },
294
+ });
295
+ return wrapToolResult({ ok: true, result });
296
+ }
297
+ catch (error) {
298
+ const failure = resourceToolError(error);
299
+ await this.audit(actor, state.conversationId, [401, 403, 404].includes(failure.status)
300
+ ? 'tool.denied'
301
+ : write
302
+ ? 'tool.propose'
303
+ : 'tool.read', {
304
+ tool: name,
305
+ resource: call?.resource ?? null,
306
+ action: call?.action ?? null,
307
+ ids: call?.id ? [call.id] : [],
308
+ outcome: { status: failure.status, code: failure.code },
309
+ });
310
+ return wrapToolResult({ ok: false, error: failure });
311
+ }
312
+ }
313
+ /** Stores a proposal for the user to confirm. No ResourceService write happens here. */
314
+ async propose(actor, state, call) {
315
+ if (state.proposals.length >= 1)
316
+ throw new AdulaError(422, 'E_AI_ONE_PROPOSAL', 'Only one proposal per answer');
317
+ const resource = this.registry.get(call.resource);
318
+ let before = null;
319
+ let recordTitle = null;
320
+ if (call.action === 'create' || call.action === 'update') {
321
+ // The editor applies the update (or create) permission and lists the writable fields.
322
+ const editor = await this.resources.editor(call.resource, actor, call.id);
323
+ const writable = new Set(editor.fields.map((field) => field.key));
324
+ writable.add('version');
325
+ if (resource.scoped)
326
+ writable.add('orgUnitId');
327
+ const keys = Object.keys(call.input ?? {});
328
+ if (!keys.length || keys.some((key) => !writable.has(key)))
329
+ throw new AdulaError(422, 'E_AI_FIELDS', 'Input contains fields the user cannot write');
330
+ }
331
+ if (call.id) {
332
+ const shown = (await this.resources.show(call.resource, call.id, actor));
333
+ recordTitle = typeof shown.data?._title === 'string' ? shown.data._title : `#${call.id}`;
334
+ if (call.action === 'update')
335
+ before = Object.fromEntries(Object.keys(call.input ?? {})
336
+ .filter((key) => key !== 'version')
337
+ .map((key) => [key, shown.data?.[key] ?? null]));
338
+ }
339
+ const id = randomUUID();
340
+ const expiresAt = new Date(this.now().getTime() + PROPOSAL_TTL_MINUTES * 60_000);
341
+ const version = Number.isSafeInteger(call.version)
342
+ ? Number(call.version)
343
+ : Number.isSafeInteger(call.input?.version)
344
+ ? Number(call.input?.version)
345
+ : null;
346
+ await this.db('ai_pending_actions').insert({
347
+ id,
348
+ conversation_id: state.conversationId,
349
+ user_id: actor.id,
350
+ impersonator_id: actor.impersonatorId ?? null,
351
+ resource: call.resource,
352
+ action: call.action,
353
+ record_id: call.id ?? null,
354
+ input: call.input ? JSON.stringify(call.input) : null,
355
+ version: Number.isSafeInteger(call.version) ? call.version : null,
356
+ expires_at: expiresAt,
357
+ });
358
+ await this.audit(actor, state.conversationId, 'tool.propose', {
359
+ tool: PROPOSE_TOOL,
360
+ resource: call.resource,
361
+ action: call.action,
362
+ ids: call.id ? [call.id] : [],
363
+ proposal: id,
364
+ outcome: { status: 202 },
365
+ });
366
+ state.proposals.push({
367
+ id,
368
+ resource: call.resource,
369
+ resourceLabel: resource.label.ar,
370
+ action: call.action,
371
+ recordId: call.id ?? null,
372
+ recordTitle,
373
+ input: call.input ?? null,
374
+ before,
375
+ version,
376
+ expiresAt: expiresAt.toISOString(),
377
+ });
378
+ return wrapToolResult({ ok: true, proposalId: id, status: 'awaiting_user_confirmation' });
379
+ }
380
+ /** Atomically takes the user's own unexpired proposal; null when there is none. */
381
+ async take(actor, conversationId, id, outcome) {
382
+ if (!UUID.test(id) || !Number.isSafeInteger(conversationId))
383
+ return null;
384
+ const result = await this.db.raw(`UPDATE ai_pending_actions SET consumed_at = now(), outcome = ?
385
+ WHERE id = ? AND user_id = ? AND conversation_id = ?
386
+ AND impersonator_id IS NOT DISTINCT FROM ?
387
+ AND consumed_at IS NULL AND expires_at > ?
388
+ RETURNING *`, [outcome, id, actor.id, conversationId, actor.impersonatorId ?? null, this.now()]);
389
+ return result.rows[0] ?? null;
390
+ }
391
+ /** Runs a proposal the user confirmed, through ResourceService as the user. */
392
+ async confirm(actor, conversationId, id) {
393
+ const { config } = await this.usable(actor);
394
+ if (!config.allowWriteProposals)
395
+ throw new AdulaError(409, 'E_AI_WRITES_OFF', 'اقتراح التعديلات غير مفعّل');
396
+ const row = await this.take(actor, conversationId, id, 'confirmed');
397
+ if (!row)
398
+ throw new AdulaError(404, 'E_AI_PROPOSAL', 'المقترح غير موجود أو انتهت صلاحيته');
399
+ await this.db('ai_pending_actions').where('id', id).update({ input: null });
400
+ const args = { resource: row.resource, action: row.action };
401
+ if (row.record_id !== null)
402
+ args.id = Number(row.record_id);
403
+ if (row.input)
404
+ args.input = row.input;
405
+ if (row.version !== null && !['create', 'update'].includes(row.action))
406
+ args.version = Number(row.version);
407
+ try {
408
+ const runtime = this.runtime(actor);
409
+ const result = await runResourceTool(runtime, parseResourceToolArgs(runtime, args, true));
410
+ await this.audit(actor, conversationId, 'tool.confirm', {
411
+ tool: PROPOSE_TOOL,
412
+ resource: row.resource,
413
+ action: row.action,
414
+ ids: row.record_id !== null ? [Number(row.record_id)] : [],
415
+ proposal: id,
416
+ outcome: { status: 200 },
417
+ });
418
+ return result;
419
+ }
420
+ catch (error) {
421
+ const failure = resourceToolError(error);
422
+ await this.db('ai_pending_actions').where('id', id).update({ outcome: 'failed' });
423
+ await this.audit(actor, conversationId, 'tool.confirm', {
424
+ tool: PROPOSE_TOOL,
425
+ resource: row.resource,
426
+ action: row.action,
427
+ ids: row.record_id !== null ? [Number(row.record_id)] : [],
428
+ proposal: id,
429
+ outcome: { status: failure.status, code: failure.code },
430
+ });
431
+ throw error;
432
+ }
433
+ }
434
+ async reject(actor, conversationId, id) {
435
+ if (!this.canUse(actor))
436
+ throw forbidden();
437
+ const row = await this.take(actor, conversationId, id, 'rejected');
438
+ if (!row)
439
+ throw new AdulaError(404, 'E_AI_PROPOSAL', 'المقترح غير موجود أو انتهت صلاحيته');
440
+ await this.db('ai_pending_actions').where('id', id).update({ input: null });
441
+ await this.audit(actor, conversationId, 'tool.reject', {
442
+ tool: PROPOSE_TOOL,
443
+ resource: row.resource,
444
+ action: row.action,
445
+ ids: row.record_id !== null ? [Number(row.record_id)] : [],
446
+ proposal: id,
447
+ outcome: { status: 200 },
448
+ });
449
+ }
450
+ /** Sends one minimal request with the stored key; returns only a failure category. */
451
+ async testConnection() {
452
+ const { config, key } = await this.settings.runtime();
453
+ if (!key || !config.model)
454
+ throw new AdulaError(409, 'E_AI_NOT_CONFIGURED', 'أدخل المفتاح والنموذج أولاً');
455
+ try {
456
+ await this.client({
457
+ baseUrl: config.baseUrl,
458
+ key,
459
+ signal: AbortSignal.timeout(config.timeoutSeconds * 1000),
460
+ body: { model: config.model, messages: [{ role: 'user', content: 'ping' }], max_tokens: 1 },
461
+ });
462
+ return { ok: true, category: null };
463
+ }
464
+ catch (error) {
465
+ return { ok: false, category: error instanceof AssistantError ? error.category : 'connect' };
466
+ }
467
+ }
468
+ /** Retention: conversation metadata after 30 days, used proposals after a day, usage after 90. */
469
+ async prune(now = this.now()) {
470
+ const day = 24 * 60 * 60 * 1000;
471
+ const conversations = await this.db('ai_conversations')
472
+ .where('created_at', '<', new Date(now.getTime() - 30 * day))
473
+ .delete();
474
+ const proposals = await this.db('ai_pending_actions')
475
+ .where('expires_at', '<', new Date(now.getTime() - day))
476
+ .delete();
477
+ const usage = await this.db('ai_usage')
478
+ .where('day', '<', usageDay(new Date(now.getTime() - 90 * day)))
479
+ .delete();
480
+ // Expired, never-used proposals lose their input right away.
481
+ await this.db('ai_pending_actions')
482
+ .where('expires_at', '<', now)
483
+ .whereNotNull('input')
484
+ .update({ input: null });
485
+ return { conversations, proposals, usage };
486
+ }
487
+ }
@@ -0,0 +1,49 @@
1
+ import { type OutboundOptions } from '../integrations/outbound.js';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ export type AssistantToolCall = {
4
+ id: string;
5
+ type: 'function';
6
+ function: {
7
+ name: string;
8
+ arguments: string;
9
+ };
10
+ };
11
+ export type AssistantMessage = {
12
+ role: 'system' | 'user';
13
+ content: string;
14
+ } | {
15
+ role: 'assistant';
16
+ content: string | null;
17
+ tool_calls?: AssistantToolCall[];
18
+ } | {
19
+ role: 'tool';
20
+ tool_call_id: string;
21
+ content: string;
22
+ };
23
+ export type ChatRequest = {
24
+ baseUrl: string;
25
+ key: string;
26
+ body: Record<string, unknown>;
27
+ signal: AbortSignal;
28
+ };
29
+ export type ChatCompletion = {
30
+ content: string | null;
31
+ toolCalls: AssistantToolCall[];
32
+ usage: {
33
+ prompt: number;
34
+ completion: number;
35
+ } | null;
36
+ };
37
+ export type ChatClient = (request: ChatRequest) => Promise<ChatCompletion>;
38
+ /** A provider failure; only its category is kept, never the provider's message or body. */
39
+ export declare class AssistantError extends AdulaError {
40
+ category: string;
41
+ constructor(category: string);
42
+ }
43
+ export declare const ASSISTANT_RESPONSE_LIMIT: number;
44
+ /**
45
+ * An OpenAI-compatible chat-completions client (OpenRouter by default) over the guarded
46
+ * outbound requester: pinned DNS, no redirects, public targets only unless allowed, and a
47
+ * capped response body.
48
+ */
49
+ export declare function createChatClient(options?: OutboundOptions): ChatClient;
@@ -0,0 +1,85 @@
1
+ import { OutboundResponseTooLargeError, OutboundTargetError, createOutboundRequester, outboundErrorCategory, } from '../integrations/outbound.js';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ /** A provider failure; only its category is kept, never the provider's message or body. */
4
+ export class AssistantError extends AdulaError {
5
+ category;
6
+ constructor(category) {
7
+ super(502, 'E_AI_PROVIDER', 'تعذر الحصول على رد من مزوّد المساعد. حاول لاحقاً.');
8
+ this.category = category;
9
+ }
10
+ }
11
+ export const ASSISTANT_RESPONSE_LIMIT = 1024 * 1024;
12
+ function toolCalls(value) {
13
+ if (value === undefined || value === null)
14
+ return [];
15
+ if (!Array.isArray(value))
16
+ throw new AssistantError('invalid-response');
17
+ return value.slice(0, 8).map((call) => {
18
+ const c = call;
19
+ if (!c ||
20
+ typeof c.id !== 'string' ||
21
+ typeof c.function?.name !== 'string' ||
22
+ typeof c.function?.arguments !== 'string')
23
+ throw new AssistantError('invalid-response');
24
+ return {
25
+ id: c.id.slice(0, 100),
26
+ type: 'function',
27
+ function: { name: c.function.name.slice(0, 100), arguments: c.function.arguments },
28
+ };
29
+ });
30
+ }
31
+ /**
32
+ * An OpenAI-compatible chat-completions client (OpenRouter by default) over the guarded
33
+ * outbound requester: pinned DNS, no redirects, public targets only unless allowed, and a
34
+ * capped response body.
35
+ */
36
+ export function createChatClient(options = {}) {
37
+ const request = createOutboundRequester(options);
38
+ return async ({ baseUrl, key, body, signal }) => {
39
+ let response;
40
+ try {
41
+ response = await request(`${baseUrl}/chat/completions`, {
42
+ headers: {
43
+ 'Content-Type': 'application/json',
44
+ 'Accept': 'application/json',
45
+ 'Authorization': `Bearer ${key}`,
46
+ },
47
+ body: JSON.stringify(body),
48
+ signal,
49
+ maxResponseBytes: ASSISTANT_RESPONSE_LIMIT,
50
+ });
51
+ }
52
+ catch (error) {
53
+ if (error instanceof OutboundResponseTooLargeError)
54
+ throw new AssistantError('too-large');
55
+ if (error instanceof OutboundTargetError)
56
+ throw new AssistantError(error.category);
57
+ throw new AssistantError(outboundErrorCategory(error));
58
+ }
59
+ if (response.status !== 200)
60
+ throw new AssistantError(`provider-status:${response.status}`);
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(response.body.toString('utf8'));
64
+ }
65
+ catch {
66
+ throw new AssistantError('invalid-response');
67
+ }
68
+ const message = parsed?.choices?.[0]?.message;
69
+ if (!message || typeof message !== 'object')
70
+ throw new AssistantError('invalid-response');
71
+ const content = typeof message.content === 'string' ? message.content : null;
72
+ const usage = parsed.usage;
73
+ return {
74
+ content,
75
+ toolCalls: toolCalls(message.tool_calls),
76
+ usage: usage &&
77
+ Number.isSafeInteger(usage.prompt_tokens) &&
78
+ Number.isSafeInteger(usage.completion_tokens) &&
79
+ usage.prompt_tokens >= 0 &&
80
+ usage.completion_tokens >= 0
81
+ ? { prompt: usage.prompt_tokens, completion: usage.completion_tokens }
82
+ : null,
83
+ };
84
+ };
85
+ }
@@ -0,0 +1,23 @@
1
+ import type { Actor } from '../auth/ability.js';
2
+ import type { ResourceRegistry } from '../resource/registry.js';
3
+ export declare const READ_TOOL = "adula_resource_read";
4
+ export declare const PROPOSE_TOOL = "adula_propose_write";
5
+ export declare const TOOL_RESULT_LIMIT: number;
6
+ export declare const TOOL_ARGUMENT_LIMIT: number;
7
+ export declare const STRING_LIMIT = 2000;
8
+ /**
9
+ * The fixed framework preamble. It comes before the administrator's persona and cannot be
10
+ * edited: tool output is data, and writes are proposals the user reviews.
11
+ */
12
+ export declare const ASSISTANT_PREAMBLE: string;
13
+ /** Resource names, Arabic labels and the actions this actor may use: metadata only. */
14
+ export declare function resourceCatalogue(registry: ResourceRegistry, actor: Actor): {
15
+ name: string;
16
+ label: string;
17
+ actions: import("../resource/types.ts").Action[];
18
+ }[];
19
+ export declare function toolDefinitions(proposals: boolean): Record<string, unknown>[];
20
+ /** Serializes a tool result within `limit` bytes, dropping trailing list rows first. */
21
+ export declare function capJson(value: unknown, limit?: number): string;
22
+ /** Marks a tool result as untrusted data before it reaches the model. */
23
+ export declare function wrapToolResult(value: unknown): string;