lambda-erp 1.4.24__tar.gz → 1.4.26__tar.gz

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 (140) hide show
  1. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/PKG-INFO +4 -4
  2. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/README.md +3 -3
  3. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/chat.py +191 -28
  4. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/providers.py +18 -3
  5. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/masters.py +35 -0
  6. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/mcp.py +2 -1
  7. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/tool_permissions.py +1 -1
  8. lambda_erp-1.4.26/api/tool_results.py +110 -0
  9. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/pyproject.toml +1 -1
  10. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/.gitignore +0 -0
  11. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/LICENSE +0 -0
  12. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/__init__.py +0 -0
  13. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/attachments.py +0 -0
  14. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/auth.py +0 -0
  15. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/bootstrap.py +0 -0
  16. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/chat_links.py +0 -0
  17. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/demo_limits.py +0 -0
  18. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/deps.py +0 -0
  19. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/erp_context.py +0 -0
  20. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/errors.py +0 -0
  21. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/list_values.py +0 -0
  22. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/llm_provider.py +0 -0
  23. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/main.py +0 -0
  24. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/mcp_oauth.py +0 -0
  25. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/mentions.py +0 -0
  26. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/menu_layout.py +0 -0
  27. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/oauth.py +0 -0
  28. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf.py +0 -0
  29. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf_contract.py +0 -0
  30. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf_exports.py +0 -0
  31. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf_fonts.py +0 -0
  32. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf_pages.py +0 -0
  33. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf_profiles.py +0 -0
  34. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pdf_templates.py +0 -0
  35. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/pricing_actions.py +0 -0
  36. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/record_attachments.py +0 -0
  37. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/record_notes.py +0 -0
  38. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/remarks_md.py +0 -0
  39. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/__init__.py +0 -0
  40. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/accounting.py +0 -0
  41. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/actions.py +0 -0
  42. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/admin.py +0 -0
  43. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/analytics.py +0 -0
  44. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/availability.py +0 -0
  45. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/bank_reconciliation.py +0 -0
  46. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/bank_statements.py +0 -0
  47. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/chat_api.py +0 -0
  48. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/documents.py +0 -0
  49. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/pdf_templates.py +0 -0
  50. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/proposals.py +0 -0
  51. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/reports.py +0 -0
  52. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/routers/setup.py +0 -0
  53. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/services.py +0 -0
  54. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/stock_actions.py +0 -0
  55. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/_proposal_totals.html +0 -0
  56. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/_record_base.html +0 -0
  57. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/delivery_note.html +0 -0
  58. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/document.html +0 -0
  59. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/proposal.html +0 -0
  60. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/record.html +0 -0
  61. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/templates/reservation.html +0 -0
  62. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/time_filters.py +0 -0
  63. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/api/write_context.py +0 -0
  64. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/docs/agents/README.md +0 -0
  65. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/frontend/LICENSE +0 -0
  66. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/frontend/README.md +0 -0
  67. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/frontend/src/api/client.ts +0 -0
  68. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/__init__.py +0 -0
  69. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/__init__.py +0 -0
  70. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/bank_account.py +0 -0
  71. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  72. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/bank_statement_import.py +0 -0
  73. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/bank_transaction.py +0 -0
  74. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/budget.py +0 -0
  75. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/camt.py +0 -0
  76. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  77. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/general_ledger.py +0 -0
  78. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/journal_entry.py +0 -0
  79. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/payment_entry.py +0 -0
  80. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/pos_invoice.py +0 -0
  81. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/purchase_invoice.py +0 -0
  82. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/revaluation.py +0 -0
  83. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/sales_invoice.py +0 -0
  84. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/settlement.py +0 -0
  85. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/__init__.py +0 -0
  86. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/engine.py +0 -0
  87. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/pack.py +0 -0
  88. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  89. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  90. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  91. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  92. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  93. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  94. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/profiles.py +0 -0
  95. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/setup/spine.py +0 -0
  96. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/accounting/subscription.py +0 -0
  97. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/addresses.py +0 -0
  98. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/assets/__init__.py +0 -0
  99. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/assets/asset.py +0 -0
  100. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/assets/lifecycle.py +0 -0
  101. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/assets/reservation.py +0 -0
  102. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/backlog.py +0 -0
  103. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/bundles.py +0 -0
  104. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/buying/__init__.py +0 -0
  105. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/buying/purchase_order.py +0 -0
  106. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/__init__.py +0 -0
  107. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/currency.py +0 -0
  108. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/defaults.py +0 -0
  109. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/item_price.py +0 -0
  110. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/item_prices.py +0 -0
  111. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/price_resolution.py +0 -0
  112. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/pricing_rule.py +0 -0
  113. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/tax_defaults.py +0 -0
  114. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  115. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/database.py +0 -0
  116. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/exceptions.py +0 -0
  117. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/hooks.py +0 -0
  118. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/master_integrity.py +0 -0
  119. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/model.py +0 -0
  120. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/permissions.py +0 -0
  121. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/selling/__init__.py +0 -0
  122. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/selling/proposal.py +0 -0
  123. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/selling/quotation.py +0 -0
  124. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/selling/sales_order.py +0 -0
  125. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/simulation.py +0 -0
  126. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/__init__.py +0 -0
  127. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/consignment.py +0 -0
  128. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/delivery_note.py +0 -0
  129. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/purchase_receipt.py +0 -0
  130. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/reservation.py +0 -0
  131. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/serial.py +0 -0
  132. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/stock_count.py +0 -0
  133. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/stock_entry.py +0 -0
  134. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/stock/stock_ledger.py +0 -0
  135. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/timestamps.py +0 -0
  136. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/units.py +0 -0
  137. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/utils.py +0 -0
  138. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/validation.py +0 -0
  139. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/lambda_erp/workflow.py +0 -0
  140. {lambda_erp-1.4.24 → lambda_erp-1.4.26}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.24
3
+ Version: 1.4.26
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -265,8 +265,8 @@ Open `http://localhost:5173`. Vite proxies `/api/*` to the backend.
265
265
 
266
266
  ```
267
267
  OPENAI_API_KEY=sk-...
268
- LAMBDA_ERP_CHAT_MODEL=gpt-6.1-sol # optional chat override; default shown
269
- LAMBDA_ERP_REPORT_MODEL=gpt-6.1-sol # optional specialist override; default shown
268
+ LAMBDA_ERP_CHAT_MODEL=gpt-6.2-sol # optional chat override; default shown
269
+ LAMBDA_ERP_REPORT_MODEL=gpt-6.2-sol # optional specialist override; default shown
270
270
  LAMBDA_ERP_TITLE_MODEL=gpt-6-luna # optional chat-title override; default shown
271
271
  LAMBDA_ERP_ADMIN_EMAIL=admin@example.com # optional, seeds the admin at boot
272
272
  LAMBDA_ERP_ADMIN_PASSWORD=... # optional, required with the line above
@@ -274,7 +274,7 @@ LAMBDA_ERP_ADMIN_NAME=Administrator # optional, display name for the seed
274
274
  ```
275
275
 
276
276
  Chat, chat titles and custom-report specification generation share
277
- `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.1 Sol,
277
+ `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.2 Sol,
278
278
  titles to GPT-6 Luna; see [docs/llm-pricing.md](docs/llm-pricing.md) for prices.
279
279
 
280
280
  **Seeded admin.** By default the first person to register becomes the admin. Set `LAMBDA_ERP_ADMIN_EMAIL` + `LAMBDA_ERP_ADMIN_PASSWORD` to instead provision that admin automatically at startup — useful when the database is recreated on every deploy, so a redeployed instance can't be claimed by whoever visits first. It's create-if-missing and idempotent (an existing account with that email is promoted to an enabled admin; its password is left untouched), and the password is only ever read from the environment.
@@ -235,8 +235,8 @@ Open `http://localhost:5173`. Vite proxies `/api/*` to the backend.
235
235
 
236
236
  ```
237
237
  OPENAI_API_KEY=sk-...
238
- LAMBDA_ERP_CHAT_MODEL=gpt-6.1-sol # optional chat override; default shown
239
- LAMBDA_ERP_REPORT_MODEL=gpt-6.1-sol # optional specialist override; default shown
238
+ LAMBDA_ERP_CHAT_MODEL=gpt-6.2-sol # optional chat override; default shown
239
+ LAMBDA_ERP_REPORT_MODEL=gpt-6.2-sol # optional specialist override; default shown
240
240
  LAMBDA_ERP_TITLE_MODEL=gpt-6-luna # optional chat-title override; default shown
241
241
  LAMBDA_ERP_ADMIN_EMAIL=admin@example.com # optional, seeds the admin at boot
242
242
  LAMBDA_ERP_ADMIN_PASSWORD=... # optional, required with the line above
@@ -244,7 +244,7 @@ LAMBDA_ERP_ADMIN_NAME=Administrator # optional, display name for the seed
244
244
  ```
245
245
 
246
246
  Chat, chat titles and custom-report specification generation share
247
- `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.1 Sol,
247
+ `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.2 Sol,
248
248
  titles to GPT-6 Luna; see [docs/llm-pricing.md](docs/llm-pricing.md) for prices.
249
249
 
250
250
  **Seeded admin.** By default the first person to register becomes the admin. Set `LAMBDA_ERP_ADMIN_EMAIL` + `LAMBDA_ERP_ADMIN_PASSWORD` to instead provision that admin automatically at startup — useful when the database is recreated on every deploy, so a redeployed instance can't be claimed by whoever visits first. It's create-if-missing and idempotent (an existing account with that email is promoted to an enabled admin; its password is left untouched), and the password is only ever read from the environment.
@@ -162,14 +162,16 @@ def get_session(session_id: str) -> dict | None:
162
162
 
163
163
 
164
164
  def can_access_session(session: dict | None, user: dict | None) -> bool:
165
+ """Whether `user` may open, write into, rename or delete a chat: only
166
+ its owner, admins included. A chat holds whatever its owner typed; until
167
+ 1.4.26 an admin could open and write into anyone's chat by its address."""
165
168
  if not session or not user:
166
169
  return False
167
170
  stamp = get_db().sql('SELECT access_stamp FROM "Chat Session" WHERE id = ?', [session.get("id")])
168
171
  if not stamp or not _session_readable(dict(stamp[0]), user.get("restrictions")):
169
172
  return False
170
- if user.get("role") == "admin":
171
- return True
172
- return session.get("user_id") == user.get("name")
173
+ owner = session.get("user_id")
174
+ return bool(owner) and owner == user.get("name")
173
175
 
174
176
 
175
177
  # A session runs one agent turn at a time. The claim lives on the session row,
@@ -641,12 +643,14 @@ TOOLS = [
641
643
  "type": "function",
642
644
  "function": {
643
645
  "name": "get_document",
644
- "description": "Load a specific document by its name/ID. Returns the full document with all fields and child tables.",
646
+ "description": "Load a specific document by its name/ID. Returns the document with all fields and its line tables. A table with more than `limit` lines (default 200) comes as a window of it; `_lines` then gives the total per table and has_more, and `offset` reads on.",
645
647
  "parameters": {
646
648
  "type": "object",
647
649
  "properties": {
648
650
  "doctype": {"type": "string", "enum": DOCUMENT_SLUGS},
649
651
  "name": {"type": "string", "description": "Document name/ID, e.g. 'QTN-0001'"},
652
+ "limit": {"type": "integer", "description": "Maximum lines per line table, default 200, range 1–2000."},
653
+ "offset": {"type": "integer", "description": "Skip this many lines of each line table.", "default": 0},
650
654
  },
651
655
  "required": ["doctype", "name"],
652
656
  },
@@ -786,7 +790,7 @@ TOOLS = [
786
790
  "type": "function",
787
791
  "function": {
788
792
  "name": "search_masters",
789
- "description": "Search and filter master data (customers, suppliers, items, warehouses, accounts, companies, cost centers). `query` is a case-insensitive free-text lookup with fuzzy fallback for simple misspellings. Use `filters` for deterministic field-aware queries and for combining different values across fields. With time_filter or include_meta=true returns a page object with rows, total, pagination and coverage (default limit 50, max 500; no fuzzy fallback). Legacy simple lookups return all matches as an array unless limit is supplied.",
793
+ "description": "Search and filter master data (customers, suppliers, items, warehouses, accounts, companies, cost centers). `query` is a case-insensitive free-text lookup with fuzzy fallback for simple misspellings. Use `filters` for deterministic field-aware queries and for combining different values across fields. With time_filter or include_meta=true returns a page object with rows, total, pagination and coverage (default limit 50, max 500; no fuzzy fallback). A simple lookup returns an array of full records when up to 50 match, or when you set `limit` yourself (at most 500). Without a limit, when more than 50 match it returns a page instead: {rows, total, returned, offset, has_more, note} with the first 50 records and only their identifying columns; then narrow the search (a more specific query, or filters such as {\"root_type\": \"Expense\"}, {\"account_type\": \"Bank\"}, {\"is_group\": 0} for accounts, {\"item_group\": ...} for items), page with offset, or name the columns you need in result_fields.",
790
794
  "parameters": {
791
795
  "type": "object",
792
796
  "properties": {
@@ -806,7 +810,7 @@ TOOLS = [
806
810
  },
807
811
  "order_by": {"type": "string", "description": "Optional real column or registered alias (item_code = name) to sort by. Defaults to the time_filter field when supplied, otherwise name."},
808
812
  "order": {"type": "string", "enum": ["asc", "desc"], "description": "Sort direction (default asc).", "default": "asc"},
809
- "limit": {"type": "integer", "description": "Maximum results. With time_filter/include_meta: default 50, range 1–500. Legacy simple lookups have no cap when omitted."},
813
+ "limit": {"type": "integer", "description": "Maximum results, range 1–500. Set it and a simple lookup returns a plain array of that many full records; leave it out to get the first 50 with the total and has_more when there are more."},
810
814
  "offset": {"type": "integer", "description": "Skip this many matching rows. Use with limit for pagination.", "default": 0},
811
815
  "result_fields": {
812
816
  "type": "array",
@@ -833,6 +837,36 @@ TOOLS = [
833
837
  },
834
838
  },
835
839
  },
840
+ {
841
+ "type": "function",
842
+ "function": {
843
+ "name": "batch_create_masters",
844
+ "description": (
845
+ "Create MANY master records of the SAME type in ONE call: a chart of accounts, a customer "
846
+ "list, an item list. Use this instead of one create_master per record whenever there are more "
847
+ "than a handful; a whole chart of accounts is one or two calls. `records` is an array of "
848
+ "`data` objects, each exactly as create_master takes it (see create_master and "
849
+ "get_master_fields for the fields). Max 200 per call. Records are created one by one in the "
850
+ "order given: list a parent (group account, parent warehouse) before its children. "
851
+ "Best-effort and per record: one that is refused (already exists, missing field, unknown "
852
+ "parent) does not undo the others. Returns {\"created\", \"failed\", \"results\": "
853
+ "[{\"index\", \"ok\", \"name\", \"error\"?}]}; report the failed ones with their reason and "
854
+ "do not blindly resend records that were created."
855
+ ),
856
+ "parameters": {
857
+ "type": "object",
858
+ "properties": {
859
+ "master_type": {"type": "string", "enum": MASTER_TYPES},
860
+ "records": {
861
+ "type": "array",
862
+ "description": "Up to 200 data objects, one per record to create (same shape as create_master's data).",
863
+ "items": {"type": "object"},
864
+ },
865
+ },
866
+ "required": ["master_type", "records"],
867
+ },
868
+ },
869
+ },
836
870
  {
837
871
  "type": "function",
838
872
  "function": {
@@ -908,10 +942,12 @@ TOOLS = [
908
942
  "type": "function",
909
943
  "function": {
910
944
  "name": "get_report",
911
- "description": "Run a financial or stock report.",
945
+ "description": "Run a financial or stock report. A report with a list of rows returns at most `limit` rows (default 200) plus total_rows and has_more; prefer the report's filters over paging through everything.",
912
946
  "parameters": {
913
947
  "type": "object",
914
948
  "properties": {
949
+ "limit": {"type": "integer", "description": "Maximum rows of a list report, default 200, range 1–2000. The general ledger uses filters.limit / filters.offset instead."},
950
+ "offset": {"type": "integer", "description": "Skip this many rows.", "default": 0},
915
951
  "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "batch-recipients", "batch-changes", "serial-trace", "sales-backlog", "purchase-backlog", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
916
952
  "filters": {"type": "object", "description": "Optional filters: company, account, from_date, to_date, item_code, warehouse; for batch-stock also batch_no, item_prefix, expiring_before, include_empty; for stock-detail also location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty; batch-movements requires batch_no. For trial-balance / profit-and-loss / balance-sheet you may also pass `presentation_currency` (e.g. \"EUR\") to view the report translated from the company's base currency at the period's closing rate — display only, the ledger stays in base currency.", "default": {}},
917
953
  },
@@ -1663,7 +1699,26 @@ def _handle_get_document_fields(args):
1663
1699
 
1664
1700
  @with_record_view_urls("doctype")
1665
1701
  def _handle_get_document(args):
1666
- return services.load_document(args["doctype"], args["name"])
1702
+ """One document. A line table longer than `limit` (default 200) is
1703
+ returned as a window of it, with `_lines` saying how many there are: a
1704
+ stock count or a bank statement can have thousands of lines."""
1705
+ from api import tool_results
1706
+ limit, offset, problem = tool_results.page_window(args)
1707
+ if problem:
1708
+ return {"error": problem}
1709
+ doc = services.load_document(args["doctype"], args["name"])
1710
+ if not isinstance(doc, dict):
1711
+ return doc
1712
+ windows = {}
1713
+ for key, value in list(doc.items()):
1714
+ if isinstance(value, list) and (len(value) > limit or (offset and value)):
1715
+ doc[key] = value[offset:offset + limit]
1716
+ windows[key] = {"total": len(value), "offset": offset, "returned": len(doc[key]),
1717
+ "has_more": offset + len(doc[key]) < len(value)}
1718
+ if windows:
1719
+ doc["_lines"] = {**windows, "note": "Not all lines are included. Read on with offset (and limit, up to "
1720
+ f"{tool_results.MAX_ROWS}); totals on the document cover all lines."}
1721
+ return doc
1667
1722
 
1668
1723
 
1669
1724
  @with_record_view_urls("doctype")
@@ -1786,6 +1841,44 @@ def _handle_get_master_fields(args):
1786
1841
  }
1787
1842
 
1788
1843
 
1844
+ def _compact_master_columns(db, doctype):
1845
+ """What identifies a master record in a list: its id, the columns a
1846
+ free-text search looks at, and a few that tell records apart."""
1847
+ columns = db._get_table_columns(doctype)
1848
+ wanted = ["name", *_master_search_columns(db, doctype),
1849
+ "root_type", "account_type", "is_group", "parent_account", "company",
1850
+ "item_group", "stock_uom", "city", "zip_code", "country", "customer", "disabled"]
1851
+ return [column for column in dict.fromkeys(wanted) if column in columns][:9]
1852
+
1853
+
1854
+ def _master_page(master_type, doctype, args, rows, limit, offset, result_fields, search_cols):
1855
+ """More records match than one answer holds: a page instead of the whole
1856
+ list, with compact rows unless the caller chose the columns."""
1857
+ db = get_db()
1858
+ counted = services.list_master_records(
1859
+ master_type, filters=args.get("filters") or {}, search=(args.get("query") or "").strip() or None,
1860
+ search_fields=search_cols, include_disabled=bool(args.get("include_disabled")), limit=1, offset=0,
1861
+ fields=["name"], with_total=True)
1862
+ total = counted.get("total", len(rows))
1863
+ if total <= len(rows) and not offset:
1864
+ return rows
1865
+ compact = not result_fields
1866
+ if compact:
1867
+ keep = _compact_master_columns(db, doctype)
1868
+ rows = [{column: row.get(column) for column in keep if column in row} for row in rows]
1869
+ more = offset + len(rows) < total
1870
+ return {
1871
+ "rows": rows, "total": total, "returned": len(rows), "offset": offset, "has_more": more,
1872
+ "note": (f"{total} {master_type} records match; {len(rows)} are shown"
1873
+ + (" with their identifying columns only" if compact else "") + ". "
1874
+ + ("Narrow the search with a more specific query or with filters "
1875
+ "(see get_master_fields for the columns), or read on with offset="
1876
+ f"{offset + len(rows)}. " if more else "")
1877
+ + ("For other columns pass result_fields, or read one record by its name."
1878
+ if compact else "")),
1879
+ }
1880
+
1881
+
1789
1882
  @with_record_view_urls("master_type", master=True)
1790
1883
  def _handle_search_masters(args):
1791
1884
  db = get_db()
@@ -1793,16 +1886,18 @@ def _handle_search_masters(args):
1793
1886
  master_type = args["master_type"]
1794
1887
  query = (args.get("query") or "").strip()
1795
1888
 
1796
- # Optional result cap the caller sets per call; omit for NO cap (return all —
1797
- # e.g. the whole chart of accounts). Coerced to int so the LIMIT clause below
1798
- # can't be injected.
1889
+ # A simple lookup returns at most DEFAULT_PAGE rows unless the caller sets
1890
+ # `limit` (up to MAX_PAGE). Until 1.4.25 it returned every match with every
1891
+ # column: 5000 customers were 2.9 million characters. Coerced to int so the
1892
+ # LIMIT clause below can't be injected.
1893
+ from api import tool_results
1799
1894
  _raw_limit = args.get("limit")
1800
- limit = None
1895
+ limit = tool_results.DEFAULT_PAGE
1801
1896
  if _raw_limit not in (None, "", 0):
1802
1897
  try:
1803
- limit = max(1, int(_raw_limit))
1898
+ limit = min(tool_results.MAX_PAGE, max(1, int(_raw_limit)))
1804
1899
  except (TypeError, ValueError):
1805
- limit = None
1900
+ limit = tool_results.DEFAULT_PAGE
1806
1901
  if meta:
1807
1902
  limit = args.get("limit", 50)
1808
1903
  offset = args.get("offset", 0)
@@ -1873,7 +1968,12 @@ def _handle_search_masters(args):
1873
1968
  if meta:
1874
1969
  return result
1875
1970
  if rows or not query:
1876
- return rows
1971
+ # A caller that set `limit` itself gets its array, as always (now at
1972
+ # most MAX_PAGE rows). So does a search that returned everything.
1973
+ if _raw_limit not in (None, "", 0) or (len(rows) < limit and not offset):
1974
+ return rows
1975
+ return _master_page(master_type, doctype, args, rows, limit, offset, result_fields,
1976
+ search_cols if query else None)
1877
1977
 
1878
1978
  # Preserve the established fuzzy fallback for a simple lookup. A
1879
1979
  # deterministic field-filter query must return exactly its literal result;
@@ -1902,6 +2002,15 @@ def _handle_create_master(args):
1902
2002
  return result
1903
2003
 
1904
2004
 
2005
+ @with_record_view_urls("master_type", master=True)
2006
+ def _handle_batch_create_masters(args):
2007
+ from api.routers.masters import batch_create_master_records
2008
+ try:
2009
+ return batch_create_master_records(args.get("master_type"), args.get("records"))
2010
+ except Exception as exc: # unknown type, empty or oversized batch
2011
+ return {"error": str(getattr(exc, "detail", None) or exc)}
2012
+
2013
+
1905
2014
  @with_record_view_urls("master_type", master=True)
1906
2015
  def _handle_update_master(args):
1907
2016
  master_type = args["master_type"]
@@ -2000,6 +2109,30 @@ def _handle_retrieve_chat_history(args, session_id=None):
2000
2109
 
2001
2110
 
2002
2111
  def _handle_get_report(args):
2112
+ """A report. Its list of rows is returned as a window (default 200 rows)
2113
+ with the total, so a stock report over thousands of items stays readable.
2114
+ Totals and summaries of a report always cover all rows. The general
2115
+ ledger pages itself through its own filters."""
2116
+ from api import tool_results
2117
+ result = _run_report(args)
2118
+ if args.get("report_type") == "general-ledger" or not isinstance(result, dict):
2119
+ return result
2120
+ rows = result.get("rows")
2121
+ if not isinstance(rows, list):
2122
+ return result
2123
+ limit, offset, problem = tool_results.page_window(args)
2124
+ if problem:
2125
+ return {"error": problem}
2126
+ if len(rows) <= limit and not offset:
2127
+ return result
2128
+ window = rows[offset:offset + limit]
2129
+ return {**result, "rows": window, "total_rows": len(rows), "offset": offset, "returned": len(window),
2130
+ "has_more": offset + len(window) < len(rows),
2131
+ "note": (f"{len(rows)} rows in all; {len(window)} are included. Narrow the report with its filters "
2132
+ f"(item_code, item_prefix, warehouse, customer, ...) or read on with offset={offset + len(window)}.")}
2133
+
2134
+
2135
+ def _run_report(args):
2003
2136
  report_type = args["report_type"]
2004
2137
  filters = args.get("filters", {})
2005
2138
  db = get_db()
@@ -2392,7 +2525,8 @@ def _handle_query_dataset(args):
2392
2525
  measures=measures,
2393
2526
  filters=args.get("filters"),
2394
2527
  order_by=args.get("order_by") or [],
2395
- limit=args.get("limit"),
2528
+ # An assistant reads groups, not a table export: 200 unless it asks.
2529
+ limit=args.get("limit") or 200,
2396
2530
  )
2397
2531
  except HTTPException as e:
2398
2532
  return {"error": str(e.detail)}
@@ -2539,6 +2673,7 @@ TOOL_HANDLERS = {
2539
2673
  "get_master_fields": _handle_get_master_fields,
2540
2674
  "search_masters": _handle_search_masters,
2541
2675
  "create_master": _handle_create_master,
2676
+ "batch_create_masters": _handle_batch_create_masters,
2542
2677
  "update_master": _handle_update_master,
2543
2678
  "get_report": _handle_get_report,
2544
2679
  "revalue_currencies": _handle_revalue_currencies,
@@ -3060,6 +3195,10 @@ For a complete sales return (financial + stock): create and submit both a Credit
3060
3195
  - On quotations, sales orders, delivery notes and sales / POS invoices, put the bundle's item_code and qty on a line and save: the line is replaced by one line per item of the bundle, which are then ordinary lines. Do not give a bundle line a rate, discount or batch; do not expand a bundle by hand.
3061
3196
  - When the user names a set, look for it with list_documents doctype="item-bundle" (or the item) before listing single items yourself.
3062
3197
 
3198
+ ### Entering many records
3199
+ - To enter a list of master records (a chart of accounts, customers, items from a file or a pasted table) use batch_create_masters with up to 200 records per call, not one create_master each. Give parents before their children. Afterwards report how many were created and name each one that was refused with its reason; never resend a list blindly, because the records that were created would be refused as duplicates.
3200
+ - A search that says more records match than it shows (`has_more`) has not shown you everything: narrow it with filters or read on with offset before concluding that something does not exist.
3201
+
3063
3202
  ### Units of measure (ordering in a pack, stocking in pieces)
3064
3203
  - An item is stocked in its `stock_uom`. An **Item Unit** (doctype `item-unit`: item_code, uom, conversion_factor = stock units per unit, e.g. Karton = 100) gives it a further unit. List an item's units with list_documents doctype="item-unit" filtered by item_code.
3065
3204
  - To enter a line in such a unit, send `qty` and `rate` in that unit and name it in `uom` (qty 2, uom "Karton", rate 290). On save the line is stored per stock unit (qty 200, rate 2.90) and keeps `order_uom`, `conversion_factor` and `order_qty` (2). Amounts are unchanged: 2 x 290 = 200 x 2.90.
@@ -3254,14 +3393,14 @@ Users can attach PDFs and images (receipts, bills, contracts, screenshots) to th
3254
3393
  # ---------------------------------------------------------------------------
3255
3394
  # OpenAI report-spec specialist
3256
3395
  #
3257
- # GPT-6.1 Sol acts as the planner/orchestrator. When it decides a report needs
3396
+ # GPT-6.2 Sol acts as the planner/orchestrator. When it decides a report needs
3258
3397
  # a custom analytics view it calls the create/update custom analytics tools.
3259
- # Those handlers make a separate, narrowly prompted GPT-6.1 Sol call for the bounded
3398
+ # Those handlers make a separate, narrowly prompted GPT-6.2 Sol call for the bounded
3260
3399
  # declarative report spec. Both roles use the same provider and key (api/llm_provider.py).
3261
3400
  # ---------------------------------------------------------------------------
3262
3401
 
3263
3402
 
3264
- REPORT_SPECIALIST_MODEL = "gpt-6.1-sol"
3403
+ REPORT_SPECIALIST_MODEL = "gpt-6.2-sol"
3265
3404
 
3266
3405
 
3267
3406
  def _report_specialist_model() -> str:
@@ -3688,11 +3827,12 @@ async def generate_title(
3688
3827
  # Reasoning loop
3689
3828
  # ---------------------------------------------------------------------------
3690
3829
 
3691
- # GPT-6.1 Sol requires Responses for function tools and does not support
3830
+ # GPT-6.2 Sol (default since core 1.4.26; GPT-6.1 Sol before) requires
3831
+ # Responses for function tools and does not support
3692
3832
  # reasoning effort "none", including tool-free wrap-ups after the step limit.
3693
3833
  # LAMBDA_ERP_CHAT_MODEL overrides it per deployment (e.g. to trial a cheaper
3694
3834
  # model on dev); see docs/llm-pricing.md.
3695
- ORCHESTRATOR_MODEL = "gpt-6.1-sol"
3835
+ ORCHESTRATOR_MODEL = "gpt-6.2-sol"
3696
3836
 
3697
3837
 
3698
3838
  def _chat_model() -> str:
@@ -3713,9 +3853,9 @@ def _chat_model() -> str:
3713
3853
  # ---------------------------------------------------------------------------
3714
3854
 
3715
3855
  def _use_responses_api() -> bool:
3716
- # A legacy deployment flag must not route a GPT-6.1 model into an
3856
+ # A legacy deployment flag must not route a GPT-6.1 / 6.2 model into an
3717
3857
  # unsupported API.
3718
- if _chat_model().startswith("gpt-6.1-"):
3858
+ if _chat_model().startswith(("gpt-6.1-", "gpt-6.2-")):
3719
3859
  return True
3720
3860
  # Default: the Responses API (needed for Office attachments + native
3721
3861
  # reasoning). Set ERP_CHAT_API=chat to fall back to Chat Completions.
@@ -3879,7 +4019,7 @@ def _shim_usage_from_responses(usage):
3879
4019
 
3880
4020
  def _orchestrator_turn(client, messages, tools, max_tokens, *, tool_choice="auto"):
3881
4021
  """One orchestrator LLM turn. Returns (message, usage) shaped like Chat
3882
- Completions. GPT-6.1 models always use Responses; others honor ERP_CHAT_API.
4022
+ Completions. GPT-6.1 and 6.2 models always use Responses; others honor ERP_CHAT_API.
3883
4023
  Blocking — call via asyncio.to_thread."""
3884
4024
  if _use_responses_api():
3885
4025
  instructions, input_items = _responses_request_from_chat(messages)
@@ -3906,21 +4046,37 @@ def _orchestrator_turn(client, messages, tools, max_tokens, *, tool_choice="auto
3906
4046
  return resp.choices[0].message, getattr(resp, "usage", None)
3907
4047
 
3908
4048
 
4049
+ DEMO_MAX_STEPS = 12
4050
+
4051
+
4052
+ def chat_max_steps() -> int:
4053
+ """How many steps (a model call with the tool calls it asks for) one
4054
+ message may take before the assistant must stop and report. 30 since
4055
+ 1.4.25 (12 before): entering a chart of accounts or working through a
4056
+ list ran out of steps mid-task. LAMBDA_ERP_CHAT_MAX_STEPS sets it (1-100).
4057
+ Demo visitors keep 12, whatever is configured."""
4058
+ try:
4059
+ steps = int(os.environ.get("LAMBDA_ERP_CHAT_MAX_STEPS") or 30)
4060
+ except ValueError:
4061
+ steps = 30
4062
+ return max(1, min(100, steps))
4063
+
4064
+
3909
4065
  async def run_thinking_loop(
3910
4066
  messages: list[dict],
3911
4067
  on_event,
3912
4068
  session_id: str = None,
3913
- max_iterations: int = 12,
4069
+ max_iterations: int | None = None,
3914
4070
  user_info: dict | None = None,
3915
4071
  client_ip: str | None = None,
3916
4072
  ):
3917
4073
  """Run the agentic reasoning loop.
3918
4074
 
3919
- The orchestrator and the report specialist use GPT-6.1 Sol.
4075
+ The orchestrator and the report specialist use GPT-6.2 Sol.
3920
4076
  When GPT decides to call
3921
4077
  `create_custom_analytics_report` or `update_custom_analytics_report`
3922
4078
  with an intent/feedback hint, the tool handler itself delegates the
3923
- declarative-spec step to a separate narrowly prompted GPT-6.1 Sol call. We emit an
4079
+ declarative-spec step to a separate narrowly prompted GPT-6.2 Sol call. We emit an
3924
4080
  `llm_provider` event around that delegation so the UI can surface it.
3925
4081
  """
3926
4082
  if not llm_configured():
@@ -3953,9 +4109,13 @@ async def run_thinking_loop(
3953
4109
  # cost per turn; logged-in managers/admins keep the original cap.
3954
4110
  max_completion = demo_max_completion_tokens() if demo_mode else 4096
3955
4111
 
4112
+ if max_iterations is None:
4113
+ max_iterations = DEMO_MAX_STEPS if demo_mode else chat_max_steps()
4114
+
3956
4115
  if demo_mode:
3957
4116
  denied = lambda _args: {"error": "Demo mode cannot create, update, or delete master data."}
3958
4117
  tool_handlers["create_master"] = denied
4118
+ tool_handlers["batch_create_masters"] = denied
3959
4119
  tool_handlers["update_master"] = denied
3960
4120
  tool_handlers["delete_master"] = denied
3961
4121
 
@@ -4131,7 +4291,7 @@ async def run_thinking_loop(
4131
4291
  principal_ref[0] = refresh_auth_principal(principal_ref[0])
4132
4292
  live_role = principal_ref[0].get("role") if principal_ref[0] else None
4133
4293
 
4134
- # If the orchestrator is delegating report-spec generation to GPT-6.1 Sol,
4294
+ # If the orchestrator is delegating report-spec generation to GPT-6.2 Sol,
4135
4295
  # surface the handoff in the UI.
4136
4296
  will_delegate_to_report_specialist = (
4137
4297
  tool_allowed(fn_name, live_role)
@@ -4176,6 +4336,9 @@ async def run_thinking_loop(
4176
4336
  multimodal_block = result.pop("_multimodal_content", None)
4177
4337
  page_images = result.pop("_images", None)
4178
4338
 
4339
+ # No tool result reaches the model larger than a model can read.
4340
+ from api.tool_results import bound_tool_result
4341
+ result = bound_tool_result(fn_name, result)
4179
4342
  result_str = json.dumps(result, default=str)
4180
4343
  summary = result_str[:500] + "..." if len(result_str) > 500 else result_str
4181
4344
 
@@ -19,7 +19,22 @@ from typing import Any, Optional
19
19
  # ---------------------------------------------------------------------------
20
20
 
21
21
  OPENAI_PRICING: dict[str, dict[str, Any]] = {
22
- # The models available to us, Standard tier, verified 2026-10-30. Above
22
+ "gpt-6.2-astra": {
23
+ "tiered": True,
24
+ "tiers": [
25
+ {"max_input_tokens": 272_000, "input": 8.00, "cached_input": 0.40, "cache_write": 10.00, "cache_write_12h": 20.00, "output": 40.00},
26
+ {"max_input_tokens": None, "input": 16.00, "cached_input": 0.80, "cache_write": 20.00, "cache_write_12h": 40.00, "output": 60.00},
27
+ ],
28
+ },
29
+ "gpt-6.2-sol": {
30
+ "tiered": True,
31
+ "tiers": [
32
+ {"max_input_tokens": 272_000, "input": 2.00, "cached_input": 0.10, "cache_write": 2.50, "cache_write_12h": 5.00, "output": 10.00},
33
+ {"max_input_tokens": None, "input": 4.00, "cached_input": 0.20, "cache_write": 5.00, "cache_write_12h": 10.00, "output": 15.00},
34
+ ],
35
+ },
36
+ # The models available to us, Standard tier, verified 2026-10-30 (the
37
+ # GPT-6.2 models 2026-11-18, developers.openai.com/api/docs/pricing). Above
23
38
  # 272K input tokens the higher rates apply to the entire request
24
39
  # (including cache hits). cache_write is the 30-minute retention rate,
25
40
  # cache_write_12h the 12-hour one.
@@ -62,14 +77,14 @@ TRANSCRIBE_PRICING: dict[str, dict[str, float]] = {
62
77
 
63
78
 
64
79
  # ---------------------------------------------------------------------------
65
- # Rate lookup — unknown model IDs are estimated at the gpt-6.1-sol rates.
80
+ # Rate lookup — unknown model IDs are estimated at the gpt-6.2-sol rates.
66
81
  # Register a model explicitly before using it; this fallback is not a price cap.
67
82
  # ---------------------------------------------------------------------------
68
83
 
69
84
  def get_openai_rates(model: str, input_tokens: int = 0) -> dict[str, float]:
70
85
  entry = OPENAI_PRICING.get(model)
71
86
  if entry is None:
72
- entry = OPENAI_PRICING["gpt-6.1-sol"]
87
+ entry = OPENAI_PRICING["gpt-6.2-sol"]
73
88
  if entry.get("tiered"):
74
89
  for tier in entry["tiers"]:
75
90
  cap = tier.get("max_input_tokens")
@@ -429,6 +429,41 @@ def create_master_record(master_type: str, data: dict) -> dict:
429
429
  return _create_master_record(master_type, data)
430
430
 
431
431
 
432
+ BATCH_CREATE_MAX = 200
433
+
434
+
435
+ def batch_create_master_records(master_type: str, records: list) -> dict:
436
+ """Create many master records of ONE type in a single call: a chart of
437
+ accounts, a customer list, an item list.
438
+
439
+ Each record is created on its own, in the order given, exactly as
440
+ create_master_record would (same checks, same hooks), so a record that
441
+ is refused does not undo the others, and a parent listed before its
442
+ children exists when they are created. Returns ``{"created", "failed",
443
+ "results": [{"index", "ok", "name"?, "error"?}]}``.
444
+ """
445
+ if _get_table(master_type)[0] is None: # before anything is written
446
+ raise ValueError(f"Unknown master type: {master_type}")
447
+ if not isinstance(records, list) or not records:
448
+ raise ValueError("records must be a non-empty array of data objects")
449
+ if len(records) > BATCH_CREATE_MAX:
450
+ raise ValueError(f"Too many records ({len(records)}); max {BATCH_CREATE_MAX} per call")
451
+ results, created = [], 0
452
+ for index, data in enumerate(records):
453
+ if not isinstance(data, dict) or not data:
454
+ results.append({"index": index, "ok": False, "error": "not a data object"})
455
+ continue
456
+ try:
457
+ record = dict(create_master_record(master_type, data))
458
+ results.append({"index": index, "ok": True, "name": record.get("name")})
459
+ created += 1
460
+ except Exception as exc: # noqa: BLE001 — per record; report, don't abort
461
+ detail = getattr(exc, "detail", None)
462
+ results.append({"index": index, "ok": False, "name": data.get("name"),
463
+ "error": str(detail or exc)})
464
+ return {"created": created, "failed": len(results) - created, "results": results}
465
+
466
+
432
467
  def _create_master_record(master_type: str, data: dict) -> dict:
433
468
  doctype, _ = _get_table(master_type)
434
469
  if not doctype:
@@ -186,7 +186,8 @@ def _handle(msg: dict, user: dict):
186
186
  params = msg.get("params") or {}
187
187
  name = params.get("name")
188
188
  try:
189
- out = _call(name, params.get("arguments") or {}, user)
189
+ from api.tool_results import bound_tool_result
190
+ out = bound_tool_result(name, _call(name, params.get("arguments") or {}, user))
190
191
  except KeyError:
191
192
  return _rpc_error(mid, -32602, f"Unknown tool: {name}")
192
193
  except Exception as e: # noqa: BLE001 — surface as an MCP tool error, not a 500
@@ -29,7 +29,7 @@ TOOL_ROLES = {
29
29
  "submit_document", "cancel_document", "discard_document", "convert_document",
30
30
  ), _DOCUMENT_WRITERS),
31
31
  **dict.fromkeys((
32
- "create_master", "update_master", "revalue_currencies",
32
+ "create_master", "batch_create_masters", "update_master", "revalue_currencies",
33
33
  "import_bank_statement_attachments", "list_bank_reconciliation_queue",
34
34
  "suggest_bank_reconciliation", "reconcile_bank_transaction",
35
35
  "undo_bank_reconciliation",