@animastor/assistant 0.1.0 → 0.2.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-11-10, unpublished)
4
+
5
+ - Edit-mode prompt and `edit_book` tool describe behavior.json schema v2:
6
+ entries at `/behaviors/characters/{character_id}`.
7
+ - Deterministic guard inside `applyPatches` (exported as
8
+ `normalizeBehaviorPatches`): on a v2 book, legacy `/behaviors/<id>…` paths
9
+ are rewritten to `/behaviors/characters/<id>…`, and a flat map written to
10
+ `/behaviors` becomes `characters` while `rules`/`schema_version` survive.
11
+ - Character-delete cascade in `applyPatches`: a character removed by the
12
+ patches loses its `behaviors.characters` entry and its `scope:"character"`
13
+ rules (same contract as the editor).
14
+
15
+ ## 0.1.1
16
+
17
+ - Fix: `enable_thinking` is sent only to providers that accept it
18
+ (`supportsEnableThinking`: qwen* models, not on NVIDIA endpoints). Strict
19
+ OpenAI-compatible gateways (integrate.api.nvidia.com) rejected every chat
20
+ turn with 400 "Unsupported parameter(s): enable_thinking".
21
+ - A 400 "Unsupported parameter" on a body carrying non-standard fields is
22
+ retried once without them (streaming and non-streaming routes).
23
+ - Upstream errors reach the user as `AI API error <status>: <provider message>`
24
+ (key-looking strings masked) instead of the bare status.
25
+ - New export `buildChatRequestExtras` so the host provider connection test
26
+ sends the same body extras as the chat.
27
+
3
28
  ## 0.1.0
4
29
 
5
30
  - 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.2.0` (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.2.0",
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') {
@@ -45,21 +47,24 @@ module.exports = function(config, deps = {}) {
45
47
  'When the user asks to fix participants across the whole book, apply the change to EVERY scene in EVERY chapter — do not stop after one scene. List one patch per affected scene.',
46
48
  '',
47
49
  '## Character Behavior',
48
- 'Each character can have a Behavior entry in the book data under `behaviors` (keyed by character_id).',
50
+ 'Each character can have a Behavior entry in the book data under `behaviors.characters` (keyed by character_id).',
51
+ '`behaviors` is schema v2: `{"schema_version": 2, "rules": [...], "characters": {...}}`. Edit ONLY `behaviors.characters.<character_id>`; never change `schema_version` or `rules` unless the user explicitly asks about behaviour rules.',
49
52
  'Behavior describes HOW a character acts — their mannerisms, habits, and reactions.',
50
53
  '',
51
54
  'Behavior schema:',
52
55
  '```json',
53
56
  '{',
54
- ' "<character_id>": {',
55
- ' "baseline": "How the character normally behaves — characteristic manner of movement, expressions, gestures, posture, speech patterns.",',
56
- ' "quirks": ["Repeated characteristic habit or mannerism."],',
57
- ' "reactions": [',
58
- ' {',
59
- ' "trigger": "A situation or emotional state.",',
60
- ' "reaction": "The observable behavioral response."',
61
- ' }',
62
- ' ]',
57
+ ' "characters": {',
58
+ ' "<character_id>": {',
59
+ ' "baseline": "How the character normally behaves — characteristic manner of movement, expressions, gestures, posture, speech patterns.",',
60
+ ' "quirks": ["Repeated characteristic habit or mannerism."],',
61
+ ' "reactions": [',
62
+ ' {',
63
+ ' "trigger": "A situation or emotional state.",',
64
+ ' "reaction": "The observable behavioral response."',
65
+ ' }',
66
+ ' ]',
67
+ ' }',
63
68
  ' }',
64
69
  '}',
65
70
  '```',
@@ -73,7 +78,7 @@ module.exports = function(config, deps = {}) {
73
78
  '1. Find the character by character_id from `characters` in the book data.',
74
79
  '2. Study the character passport (appearance, clothes, description) to understand their personality.',
75
80
  '3. Create behavior that matches the character personality — distinct, specific, believable.',
76
- '4. Use `edit_book` to write to `/behaviors/{character_id}` with the full behavior object.',
81
+ '4. Use `edit_book` to write to `/behaviors/characters/{character_id}` with the full behavior object.',
77
82
  '5. Do NOT create a new character. Do NOT modify passport or voice unless asked.',
78
83
  '',
79
84
  'Example user request: "Придумай поведение для Юры и Светланы."',
@@ -287,7 +292,7 @@ module.exports = function(config, deps = {}) {
287
292
  type: 'function',
288
293
  function: {
289
294
  name: 'edit_book',
290
- description: 'Apply changes to the current book. Call this when the user asks to edit the book content (title, author, characters, scenes, text, behavior, etc.). Supports writing to /behaviors/{character_id} for character behavior. Do NOT call if the book is locked.',
295
+ description: 'Apply changes to the current book. Call this when the user asks to edit the book content (title, author, characters, scenes, text, behavior, etc.). Supports writing to /behaviors/characters/{character_id} for character behavior. Do NOT call if the book is locked.',
291
296
  parameters: {
292
297
  type: 'object',
293
298
  properties: {
@@ -298,7 +303,7 @@ module.exports = function(config, deps = {}) {
298
303
  type: 'object',
299
304
  properties: {
300
305
  op: { type: 'string', enum: ['replace', 'add', 'remove'], description: 'Operation type' },
301
- path: { type: 'string', description: 'JSON path like /book/title, /chapters/0/scenes/1/units/0/text, /behaviors/character_id/baseline' },
306
+ path: { type: 'string', description: 'JSON path like /book/title, /chapters/0/scenes/1/units/0/text, /behaviors/characters/character_id/baseline' },
302
307
  value: { description: 'New value (for replace/add)' },
303
308
  },
304
309
  required: ['op', 'path'],
@@ -393,7 +398,7 @@ module.exports = function(config, deps = {}) {
393
398
  const result = JSON.parse(JSON.stringify(obj));
394
399
  const errors = [];
395
400
 
396
- for (const patch of patches) {
401
+ for (const patch of normalizeBehaviorPatches(obj, patches || [])) {
397
402
  const { op, path: pathStr, value } = patch;
398
403
  const { parent, key, value: oldValue } = resolvePath(result, pathStr);
399
404
 
@@ -456,9 +461,35 @@ module.exports = function(config, deps = {}) {
456
461
  }
457
462
  }
458
463
 
464
+ cascadeDeletedCharacterBehaviors(obj, result);
459
465
  return { result, errors };
460
466
  }
461
467
 
468
+ // ── Character-removal cascade for behavior.json v2 ──
469
+ // A character removed by the patches (present in obj.characters, gone in
470
+ // result.characters) loses its behaviors.characters entry and every rule
471
+ // with scope:"character" bound to it — same contract as the editor's
472
+ // character removal route. Global rules stay. Legacy (no schema_version)
473
+ // in-memory maps only lose the entry.
474
+ function cascadeDeletedCharacterBehaviors(before, after) {
475
+ if (!after || !after.behaviors || typeof after.behaviors !== 'object') return;
476
+ const ids = (list) => new Set((Array.isArray(list) ? list : []).map(c => c && c.id).filter(Boolean));
477
+ const was = ids(before && before.characters);
478
+ if (was.size === 0) return;
479
+ const now = ids(after.characters);
480
+ const gone = [...was].filter(id => !now.has(id));
481
+ if (gone.length === 0) return;
482
+ const bh = after.behaviors;
483
+ const isV2 = bh.schema_version != null;
484
+ const chars = isV2 ? bh.characters : bh;
485
+ for (const id of gone) {
486
+ if (chars && typeof chars === 'object') delete chars[id];
487
+ if (isV2 && Array.isArray(bh.rules)) {
488
+ bh.rules = bh.rules.filter(r => !(r && r.scope === 'character' && r.character_id === id));
489
+ }
490
+ }
491
+ }
492
+
462
493
  // ── Deterministic scene-participants guard ─────────
463
494
  // Models frequently produce `scene.participants` in the wrong shape when
464
495
  // editing (e.g. {"item": [...]} — a JSON-Schema `items` hallucination, or
@@ -523,6 +554,44 @@ module.exports = function(config, deps = {}) {
523
554
  // state. On violation the result is withheld (null) so no caller can
524
555
  // persist broken JSON; errors name the failing file/resource so the
525
556
  // assistant (or the user) can issue a corrective patch in the next turn.
557
+ // ── Deterministic behavior.json v2 guard ───────────
558
+ // In memory `behaviors` is schema v2 ({schema_version, rules, characters}).
559
+ // Models (and older prompts) still write the v2.1 paths, so before the
560
+ // patches run:
561
+ // /behaviors/<character_id>[/...] → /behaviors/characters/<character_id>[/...]
562
+ // add|replace /behaviors with a flat map (schema_version !== 2)
563
+ // → the map becomes `characters`,
564
+ // stored rules/schema_version survive.
565
+ // Runs inside applyPatches, so every caller gets it. Reserved top-level
566
+ // keys are never treated as character ids. A legacy
567
+ // in-memory book (no schema_version) is left alone — it is migrated on save.
568
+ const BEHAVIOR_RESERVED_KEYS = ['schema_version', 'rules', 'characters', 'defaults'];
569
+ function normalizeBehaviorPatches(obj, patches) {
570
+ const stored = obj && obj.behaviors;
571
+ const isV2 = stored && typeof stored === 'object' && !Array.isArray(stored) && stored.schema_version != null;
572
+ if (!isV2 || !Array.isArray(patches)) return patches;
573
+ return patches.map((patch) => {
574
+ if (!patch || typeof patch.path !== 'string') return patch;
575
+ const p = patch.path;
576
+ if (p === '/behaviors' && (patch.op === 'add' || patch.op === 'replace')) {
577
+ const v = patch.value;
578
+ if (v && typeof v === 'object' && !Array.isArray(v) && v.schema_version !== 2) {
579
+ const characters = {};
580
+ for (const [k, entry] of Object.entries(v)) {
581
+ if (!BEHAVIOR_RESERVED_KEYS.includes(k)) characters[k] = entry;
582
+ }
583
+ return { ...patch, value: { ...stored, characters } };
584
+ }
585
+ return patch;
586
+ }
587
+ const m = /^\/behaviors\/([^/]+)(\/.*)?$/.exec(p);
588
+ if (!m) return patch;
589
+ const seg = m[1];
590
+ if (BEHAVIOR_RESERVED_KEYS.includes(seg)) return patch;
591
+ return { ...patch, path: `/behaviors/characters/${seg}${m[2] || ''}` };
592
+ });
593
+ }
594
+
526
595
  function applyPatchesValidated(obj, patches) {
527
596
  const { result, errors } = applyPatches(obj, patches);
528
597
  if (errors.length > 0) {
@@ -556,10 +625,15 @@ module.exports = function(config, deps = {}) {
556
625
  resolvePath,
557
626
  applyPatches,
558
627
  applyPatchesValidated,
628
+ normalizeBehaviorPatches,
559
629
  normalizeBookParticipants,
560
630
  validateBundleObject,
561
631
  toolDefinitions: {
562
632
  EDIT_BOOK_TOOL,
563
633
  },
634
+ // Chat body extras + compatibility retry (request-extras.cjs) —
635
+ // handed to the routes through the engine (the route file holds no
636
+ // require() calls).
637
+ requestExtras,
564
638
  };
565
639
  };
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
+ };