@animastor/assistant 0.1.0 → 0.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ - Fix: `enable_thinking` is sent only to providers that accept it
6
+ (`supportsEnableThinking`: qwen* models, not on NVIDIA endpoints). Strict
7
+ OpenAI-compatible gateways (integrate.api.nvidia.com) rejected every chat
8
+ turn with 400 "Unsupported parameter(s): enable_thinking".
9
+ - A 400 "Unsupported parameter" on a body carrying non-standard fields is
10
+ retried once without them (streaming and non-streaming routes).
11
+ - Upstream errors reach the user as `AI API error <status>: <provider message>`
12
+ (key-looking strings masked) instead of the bare status.
13
+ - New export `buildChatRequestExtras` so the host provider connection test
14
+ sends the same body extras as the chat.
15
+
3
16
  ## 0.1.0
4
17
 
5
18
  - Initial publishable release of `@animastor/assistant`.
package/README.md CHANGED
@@ -44,6 +44,7 @@ const {
44
44
  createAssistantRoutes,
45
45
  assertAssistantPorts,
46
46
  assertSessionRepo,
47
+ buildChatRequestExtras, // chat body extras (max_tokens + provider-gated enable_thinking)
47
48
  } = require('@animastor/assistant');
48
49
  ```
49
50
 
@@ -141,8 +142,8 @@ keeps storage, filesystem, provider and transport concerns on the host side.
141
142
 
142
143
  ## Versioning / release
143
144
 
144
- - Current version: `0.1.0` (first publishable release; `npm pack` verified).
145
- - SemVer: the four public factories, the root-only export map, the
145
+ - Current version: `0.1.1` (see CHANGELOG.md).
146
+ - SemVer: the four public factories + `buildChatRequestExtras`, the root-only export map, the
146
147
  `AssistantPorts` shape and the `/api/v1/ai/*` HTTP/SSE contract are the
147
148
  public contract — breaking any of them requires a major bump.
148
149
  - Publication is a manual, explicit step and is **not** automated in CI.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/assistant",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Animastor Assistant — the AI assistant contour of the Animastor backend, physically extracted from the host: chat engine (persona/system prompts, book context, mode tools, JSON patch pipeline with bundle-contract validation), the /api/v1/ai/* HTTP contour (sessions CRUD, non-streaming chat, SSE streaming with meta/delta/done/error frames, tool-call orchestration) and the chat-session repository contract. The package reaches the host (book read/write, bundle validation, provider resolution, session persistence, shared-inference transport, logging) ONLY through the injected AssistantPorts seam — no PG, no Book internals, no filesystem, no provider gateway inside.",
5
5
  "keywords": [
6
6
  "animastor",
@@ -31,12 +31,12 @@
31
31
  },
32
32
  "repository": {
33
33
  "type": "git",
34
- "url": "git+https://github.com/Animastor/animastor.git",
34
+ "url": "git+https://github.com/Animastor/animastor-backend.git",
35
35
  "directory": "packages/animastor-assistant"
36
36
  },
37
- "homepage": "https://github.com/Animastor/animastor/tree/main/packages/animastor-assistant#readme",
37
+ "homepage": "https://github.com/Animastor/animastor-backend/tree/main/packages/animastor-assistant#readme",
38
38
  "bugs": {
39
- "url": "https://github.com/Animastor/animastor/issues"
39
+ "url": "https://github.com/Animastor/animastor-backend/issues"
40
40
  },
41
41
  "devDependencies": {
42
42
  "chai": "^6.2.2",
@@ -20,6 +20,13 @@ module.exports = function(app, redis, deps) {
20
20
  utils,
21
21
  } = deps;
22
22
  const { log } = utils;
23
+ // Token budget, provider-gated enable_thinking, the one-shot
24
+ // "Unsupported parameter" retry and upstream error text — package
25
+ // logic (request-extras.cjs) carried by the engine.
26
+ const {
27
+ MAX_TOKENS_WITH_TOOLS, MAX_TOKENS_PLAIN,
28
+ buildChatRequestExtras, describeUpstreamError, fetchChatCompletion,
29
+ } = chatEngine.requestExtras;
23
30
  // The ports seam is the single host contract of the Assistant contour.
24
31
  const {
25
32
  loadBook, persistBook, resolveChatAI,
@@ -51,22 +58,11 @@ module.exports = function(app, redis, deps) {
51
58
 
52
59
  const AI_FETCH_TIMEOUT_MS = 180_000; // 3 minutes — AI providers need time for large book contexts
53
60
 
54
- // ── Token budget & thinking policy ─────────────────
55
- // Tool-carrying requests use a HIGH max_tokens: reasoning models
56
- // (deepseek-v4-flash, qwen3) count reasoning tokens against max_tokens,
57
- // so a 4096 cap can be fully consumed by reasoning before any
58
- // content/tool_call is produced (observed: finish_reason=length,
59
- // reasoning_tokens=4096, empty content → "Tool executed" ghost reply).
60
- // Tool-less conversation gets a small budget and no thinking — faster,
61
- // cheaper replies.
62
- const MAX_TOKENS_WITH_TOOLS = 16384;
63
-
64
61
  // History entries with empty content (e.g. a UI-side "no result" turn
65
62
  // pushed as {assistant, ''}) fail the connector's strict non-empty
66
63
  // content validation — and would poison every later turn of the session.
67
64
  // Dropped at the seam by both chat routes via this filter.
68
65
  const hasNonEmptyContent = (m) => m && typeof m.content === 'string' && m.content.length > 0;
69
- const MAX_TOKENS_PLAIN = 4096;
70
66
 
71
67
  // Local AI Connector per-message cap is 32 KB (lib/chat.cjs
72
68
  // maxMessageChars, mirrored by transport). The base system prompt plus
@@ -74,14 +70,6 @@ module.exports = function(app, redis, deps) {
74
70
  // below it; anything larger rides as the compact structural summary.
75
71
  const CONNECTOR_BOOK_CONTEXT_BUDGET = 24 * 1024;
76
72
 
77
- function aiRequestBodyExtras(tools) {
78
- const hasTools = Array.isArray(tools) && tools.length > 0;
79
- return {
80
- max_tokens: hasTools ? MAX_TOKENS_WITH_TOOLS : MAX_TOKENS_PLAIN,
81
- enable_thinking: hasTools, // reasoning only for tool/edit work
82
- };
83
- }
84
-
85
73
  // ── Hermesian tool call parser ──────────────────────
86
74
  // Qwen3-32B (reasoning model) sometimes outputs tool_call as text in content
87
75
  // instead of using the structured tool_calls field. This parser extracts those.
@@ -494,25 +482,24 @@ module.exports = function(app, redis, deps) {
494
482
  } else {
495
483
  const controller = new AbortController();
496
484
  const timeout = setTimeout(() => controller.abort(), AI_FETCH_TIMEOUT_MS);
497
- const response = await safeFetch(`${ai.baseUrl}/chat/completions`, {
485
+ const { response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
498
486
  method: 'POST',
499
487
  headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
500
- body: JSON.stringify({
501
- model: ai.model,
502
- messages: apiMessages,
503
- tools: tools.length > 0 ? tools : undefined,
504
- tool_choice: tools.length > 0 ? 'auto' : undefined,
505
- ...aiRequestBodyExtras(tools),
506
- }),
507
488
  signal: controller.signal,
508
489
  validatePublic: ai.validatePublic,
490
+ }, {
491
+ model: ai.model,
492
+ messages: apiMessages,
493
+ tools: tools.length > 0 ? tools : undefined,
494
+ tool_choice: tools.length > 0 ? 'auto' : undefined,
495
+ ...buildChatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }),
509
496
  });
510
497
  clearTimeout(timeout);
511
498
 
512
499
  if (!response.ok) {
513
- const errText = await response.text();
514
- console.error('[AI] API error:', response.status, errText);
515
- return res.status(502).json({ error: `AI API error: ${response.status}` });
500
+ const upstreamError = describeUpstreamError(response.status, errText); // key-masked
501
+ console.error('[AI]', upstreamError);
502
+ return res.status(502).json({ error: upstreamError, code: 'upstream_error' });
516
503
  }
517
504
 
518
505
  aiResponse = await response.json();
@@ -1031,30 +1018,28 @@ module.exports = function(app, redis, deps) {
1031
1018
  const onOuterAbort = () => controller.abort();
1032
1019
  abort.signal.addEventListener('abort', onOuterAbort, { once: true });
1033
1020
  const timeout = setTimeout(() => controller.abort(), clampStreamTimeoutMs(req.body?.timeout_ms));
1034
- let response;
1021
+ let response, errText;
1035
1022
  try {
1036
- response = await safeFetch(`${ai.baseUrl}/chat/completions`, {
1023
+ ({ response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
1037
1024
  method: 'POST',
1038
1025
  headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
1039
- body: JSON.stringify({
1040
- model: ai.model,
1041
- messages: apiMessages,
1042
- tools: tools.length > 0 ? tools : undefined,
1043
- tool_choice: tools.length > 0 ? 'auto' : undefined,
1044
- ...aiRequestBodyExtras(tools),
1045
- }),
1046
1026
  signal: controller.signal,
1047
1027
  validatePublic: ai.validatePublic,
1048
- });
1028
+ }, {
1029
+ model: ai.model,
1030
+ messages: apiMessages,
1031
+ tools: tools.length > 0 ? tools : undefined,
1032
+ tool_choice: tools.length > 0 ? 'auto' : undefined,
1033
+ ...buildChatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }),
1034
+ }));
1049
1035
  } finally {
1050
1036
  clearTimeout(timeout);
1051
1037
  abort.signal.removeEventListener('abort', onOuterAbort);
1052
1038
  }
1053
1039
 
1054
1040
  if (!response.ok) {
1055
- const errText = await response.text().catch(() => '');
1056
- console.error('[AI STREAM] API error:', response.status, errText.substring(0, 200));
1057
- const errorData = { error: `AI API error: ${response.status}`, code: 'upstream_error' };
1041
+ const errorData = { error: describeUpstreamError(response.status, errText), code: 'upstream_error' }; // key-masked
1042
+ console.error('[AI STREAM]', errorData.error);
1058
1043
  if (!clientGone) sendTerminal('error', errorData);
1059
1044
  await persistFailedTurn(`⚠️ ${errorData.error}`);
1060
1045
  return;
@@ -18,6 +18,8 @@
18
18
  // The package holds no host imports, no fs and no ambient env reads —
19
19
  // pure Assistant logic only.
20
20
 
21
+ const requestExtras = require('./request-extras.cjs');
22
+
21
23
  module.exports = function(config, deps = {}) {
22
24
  const { validateBundleObject } = deps;
23
25
  if (typeof validateBundleObject !== 'function') {
@@ -561,5 +563,9 @@ module.exports = function(config, deps = {}) {
561
563
  toolDefinitions: {
562
564
  EDIT_BOOK_TOOL,
563
565
  },
566
+ // Chat body extras + compatibility retry (request-extras.cjs) —
567
+ // handed to the routes through the engine (the route file holds no
568
+ // require() calls).
569
+ requestExtras,
564
570
  };
565
571
  };
package/src/index.cjs CHANGED
@@ -57,10 +57,14 @@ const createChatEngine = require('./chat-engine.cjs');
57
57
  const createAssistantRoutes = require('./assistant-routes.cjs');
58
58
  const { assertAssistantPorts } = require('./assistant-ports-contract.cjs');
59
59
  const { assertSessionRepo } = require('./session-repo-contract.cjs');
60
+ const { buildChatRequestExtras } = require('./request-extras.cjs');
60
61
 
61
62
  module.exports = {
62
63
  createChatEngine,
63
64
  createAssistantRoutes,
64
65
  assertAssistantPorts,
65
66
  assertSessionRepo,
67
+ // Chat body extras (token budget + provider-gated enable_thinking) —
68
+ // exported so the host provider connection test sends the chat's body.
69
+ buildChatRequestExtras,
66
70
  };
@@ -0,0 +1,126 @@
1
+ // ======================================================
2
+ // @animastor/assistant — CHAT REQUEST EXTRAS (provider compatibility)
3
+ // ======================================================
4
+ // The non-message part of a /chat/completions body (token budget +
5
+ // thinking switch) and the one-shot compatibility retry around it.
6
+ //
7
+ // `enable_thinking` is a Qwen-specific (DashScope / vLLM-qwen) extension,
8
+ // NOT part of the OpenAI chat/completions schema. Strict OpenAI-compatible
9
+ // gateways reject it — NVIDIA (integrate.api.nvidia.com) answers
10
+ // 400 "Unsupported parameter(s): enable_thinking". It is therefore sent
11
+ // ONLY where it is known to work (supportsEnableThinking), and a 400
12
+ // "Unsupported parameter" on a body that carried it is retried once
13
+ // without the non-standard fields (fetchChatCompletion).
14
+ //
15
+ // The host's provider connection test builds its body through the SAME
16
+ // buildChatRequestExtras, so a test that passes means the chat body passes.
17
+
18
+ // Tool-carrying requests use a HIGH max_tokens: reasoning models
19
+ // (deepseek-v4-flash, qwen3) count reasoning tokens against max_tokens,
20
+ // so a 4096 cap can be fully consumed by reasoning before any
21
+ // content/tool_call is produced (observed: finish_reason=length,
22
+ // reasoning_tokens=4096, empty content → "Tool executed" ghost reply).
23
+ // Tool-less conversation gets a small budget and no thinking — faster,
24
+ // cheaper replies.
25
+ const MAX_TOKENS_WITH_TOOLS = 16384;
26
+ const MAX_TOKENS_PLAIN = 4096;
27
+
28
+ // Body fields outside the OpenAI chat/completions schema. Dropped on the
29
+ // compatibility retry.
30
+ const NON_STANDARD_FIELDS = ['enable_thinking'];
31
+
32
+ // Gateways that host qwen models but reject `enable_thinking`.
33
+ const NO_ENABLE_THINKING_HOSTS = [/(^|\.)nvidia\.com$/i];
34
+
35
+ function hostOf(baseUrl) {
36
+ try { return new URL(String(baseUrl)).hostname; } catch (_) { return ''; }
37
+ }
38
+
39
+ /**
40
+ * Does this provider/model accept the `enable_thinking` body field?
41
+ * Currently: qwen* models (incl. vendor-prefixed "qwen/qwen3-32b"), except
42
+ * on endpoints known to reject the field.
43
+ * @param {{model?:string, baseUrl?:string}} target
44
+ */
45
+ function supportsEnableThinking({ model, baseUrl } = {}) {
46
+ const m = String(model || '').toLowerCase();
47
+ const name = m.slice(m.lastIndexOf('/') + 1);
48
+ if (!name.startsWith('qwen')) return false;
49
+ const host = hostOf(baseUrl);
50
+ return !NO_ENABLE_THINKING_HOSTS.some((re) => re.test(host));
51
+ }
52
+
53
+ /**
54
+ * Token budget + (where supported) thinking switch for a chat body.
55
+ * @param {{model?:string, baseUrl?:string, tools?:Array}} input
56
+ */
57
+ function buildChatRequestExtras({ model, baseUrl, tools } = {}) {
58
+ const hasTools = Array.isArray(tools) && tools.length > 0;
59
+ const extras = { max_tokens: hasTools ? MAX_TOKENS_WITH_TOOLS : MAX_TOKENS_PLAIN };
60
+ if (supportsEnableThinking({ model, baseUrl })) {
61
+ extras.enable_thinking = hasTools; // reasoning only for tool/edit work
62
+ }
63
+ return extras;
64
+ }
65
+
66
+ function isUnsupportedParamError(status, text) {
67
+ return status === 400 && /unsupported parameter/i.test(String(text || ''));
68
+ }
69
+
70
+ /**
71
+ * Short, key-free description of an upstream error body: the provider's
72
+ * own message (OpenAI `{error:{message}}`, `{message}`, `{detail}`) or a
73
+ * plain-text excerpt. Bearer tokens / key-looking strings are masked.
74
+ */
75
+ function describeUpstreamError(status, text) {
76
+ let msg = '';
77
+ const raw = String(text || '');
78
+ try {
79
+ const j = JSON.parse(raw);
80
+ const e = j && j.error;
81
+ msg = (e && typeof e === 'object' ? e.message : e) || j.message || j.detail || '';
82
+ if (typeof msg !== 'string') msg = JSON.stringify(msg);
83
+ } catch (_) {
84
+ msg = raw;
85
+ }
86
+ msg = msg
87
+ .replace(/Bearer\s+\S+/gi, 'Bearer ***')
88
+ .replace(/\b(sk|nvapi|key)[-_][A-Za-z0-9_-]{8,}/gi, '***')
89
+ .replace(/\s+/g, ' ')
90
+ .trim();
91
+ if (msg.length > 200) msg = `${msg.slice(0, 200)}…`;
92
+ return msg ? `AI API error ${status}: ${msg}` : `AI API error: ${status}`;
93
+ }
94
+
95
+ /**
96
+ * POST a chat/completions body; on 400 "Unsupported parameter" for a body
97
+ * that carried non-standard fields, retry ONCE without them.
98
+ * @returns {Promise<{response, errText?:string}>} errText is set (body
99
+ * already consumed) when the final response is not ok.
100
+ */
101
+ async function fetchChatCompletion(safeFetch, url, init, body) {
102
+ let response = await safeFetch(url, { ...init, body: JSON.stringify(body) });
103
+ if (response.ok) return { response };
104
+ let errText = await response.text().catch(() => '');
105
+ const carried = NON_STANDARD_FIELDS.filter((f) => f in body);
106
+ if (carried.length > 0 && isUnsupportedParamError(response.status, errText)) {
107
+ console.warn(`[AI] upstream rejected ${carried.join(',')} (400) — retrying without non-standard fields`);
108
+ const stripped = { ...body };
109
+ for (const f of carried) delete stripped[f];
110
+ response = await safeFetch(url, { ...init, body: JSON.stringify(stripped) });
111
+ if (response.ok) return { response };
112
+ errText = await response.text().catch(() => '');
113
+ }
114
+ return { response, errText };
115
+ }
116
+
117
+ module.exports = {
118
+ MAX_TOKENS_WITH_TOOLS,
119
+ MAX_TOKENS_PLAIN,
120
+ NON_STANDARD_FIELDS,
121
+ supportsEnableThinking,
122
+ buildChatRequestExtras,
123
+ isUnsupportedParamError,
124
+ describeUpstreamError,
125
+ fetchChatCompletion,
126
+ };