@animastor/assistant 0.1.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 ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Initial publishable release of `@animastor/assistant`.
6
+ - Chat engine: persona/system prompt assembly, book context (full + compact),
7
+ mode/topic prompts, `edit_book` tool, response parsing and the validated
8
+ JSON-patch pipeline with scene-participants normalization.
9
+ - HTTP contour: `/api/v1/ai/*` session CRUD, non-streaming chat and SSE
10
+ streaming (`meta` / `delta` / `done` / `error`).
11
+ - Contracts: `AssistantPorts` + chat-session repository interfaces with
12
+ fail-fast assertions.
13
+ - Host-agnostic: zero runtime dependencies, no filesystem, no ambient env
14
+ reads; persona content arrives as injected `aiProfile`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Animastor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # @animastor/assistant
2
+
3
+ The AI assistant contour of the Animastor backend, packaged as a standalone,
4
+ host-agnostic module.
5
+
6
+ ## What this is
7
+
8
+ `@animastor/assistant` owns the assistant logic and its HTTP contract:
9
+
10
+ - **Chat engine** — persona/system prompt assembly, book-context builders
11
+ (full + compact), mode/topic prompts, the `edit_book` tool definition,
12
+ AI response parsing and the JSON-patch pipeline with bundle-contract
13
+ validation and a deterministic scene-participants normalizer.
14
+ - **HTTP contour** — the `/api/v1/ai/*` surface: session CRUD, the
15
+ non-streaming chat route and the SSE stream route
16
+ (`meta` / `delta` / `done` / `error` frames), tool-call orchestration,
17
+ connector shared-inference and cloud-provider transports.
18
+ - **Contracts** — the `AssistantPorts` seam and the chat-session repository
19
+ interface the host must implement.
20
+
21
+ The package is **pure logic + contracts**. It has **zero runtime
22
+ dependencies**, does **not** touch the filesystem, does **not** read
23
+ `process.env`, and imports nothing from the host. Every host capability
24
+ arrives through an injected dependency or port.
25
+
26
+ ## Requirements
27
+
28
+ - Node.js >= 18
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ npm install @animastor/assistant
34
+ ```
35
+
36
+ ## Public API
37
+
38
+ The package exposes a single root entrypoint — deep imports are blocked by
39
+ the `exports` map:
40
+
41
+ ```js
42
+ const {
43
+ createChatEngine,
44
+ createAssistantRoutes,
45
+ assertAssistantPorts,
46
+ assertSessionRepo,
47
+ } = require('@animastor/assistant');
48
+ ```
49
+
50
+ ## Basic usage
51
+
52
+ ```js
53
+ const {
54
+ createChatEngine,
55
+ createAssistantRoutes,
56
+ assertAssistantPorts,
57
+ } = require('@animastor/assistant');
58
+ const express = require('express');
59
+
60
+ // 1. Build the engine with injected host dependencies.
61
+ const chatEngine = createChatEngine(config, {
62
+ // REQUIRED — host bundle-contract validator (object form).
63
+ validateBundleObject: (bundle) => ({ valid: true, errors: [] }),
64
+
65
+ // OPTIONAL — persona CONTENT (the host reads its own file and passes
66
+ // the resulting string; the package never sees the path or filesystem).
67
+ aiProfile: personaMarkdown,
68
+
69
+ // OPTIONAL — chat fallback provider base URL (operator config).
70
+ aiApiBaseUrl: process.env.AI_API_BASE_URL,
71
+ });
72
+
73
+ // 2. Build the host port adapter and validate it fail-fast.
74
+ const assistantPorts = assertAssistantPorts({
75
+ loadBook, // (bookId) => book bundle | null
76
+ persistBook, // (bookId, bundle) => void
77
+ validateBundle, // (bundle) => { valid, errors }
78
+ validateBundleFile, // (name, data) => { valid, errors }
79
+ resolveChatAI, // (bookId) => provider snapshot
80
+ sessionRepo, // chat-session repository (see contract below)
81
+ purgeForBook, // (bookId) => Promise<void>
82
+ chatTransport: {
83
+ safeFetch, // SSRF-guarded fetch
84
+ runSharedInference, // connector / shared inference
85
+ describeSharedError,// (code) => string
86
+ chatAiSourceToken, // (ai) => 'cloud' | 'system' | 'shared' | ...
87
+ },
88
+ log, // host logger
89
+ });
90
+
91
+ // 3. Register the HTTP contour.
92
+ const app = express();
93
+ app.use(express.json());
94
+ createAssistantRoutes(app, redis, {
95
+ chatEngine,
96
+ assistantPorts,
97
+ utils: { log },
98
+ });
99
+ ```
100
+
101
+ ## Required injected ports
102
+
103
+ | Port | Purpose |
104
+ |---|---|
105
+ | `loadBook(bookId)` | Canonical-or-draft book read |
106
+ | `persistBook(bookId, bundle)` | Book save (single semantics) |
107
+ | `validateBundle(bundle)` | Bundle-contract validation |
108
+ | `validateBundleFile(name, data)` | Per-file validation |
109
+ | `resolveChatAI(bookId)` | Chat provider resolution |
110
+ | `sessionRepo` | Chat-session persistence (see below) |
111
+ | `purgeForBook(bookId)` | Assistant-data purge on book deletion |
112
+ | `chatTransport.safeFetch` | SSRF-guarded outbound fetch |
113
+ | `chatTransport.runSharedInference` | Connector/shared inference |
114
+ | `chatTransport.describeSharedError` | Sanitized error text |
115
+ | `chatTransport.chatAiSourceToken` | Safe consumer source token |
116
+ | `log` | Host logger |
117
+
118
+ `sessionRepo` must implement:
119
+ `listSessionsForBook`, `getSession`, `getMessages`, `createSession`,
120
+ `setMessages`, `renameSession`, `deleteSession`, `getBookIdForSession`,
121
+ `purgeSessionsForBook` (validated by `assertSessionRepo`).
122
+
123
+ ## Architecture / dependency model
124
+
125
+ ```
126
+ Host
127
+ ├── provider adapter ─┐
128
+ ├── book adapter │
129
+ ├── session repository ├── injected ports (AssistantPorts)
130
+ ├── transport adapter │
131
+ └── AI profile loader ─┘
132
+ ↓
133
+ @animastor/assistant
134
+ ↓
135
+ public API
136
+ ```
137
+
138
+ Dependency direction is **host → package**. The package never imports host
139
+ code; the host supplies concrete implementations at composition time. This
140
+ keeps storage, filesystem, provider and transport concerns on the host side.
141
+
142
+ ## Versioning / release
143
+
144
+ - Current version: `0.1.0` (first publishable release; `npm pack` verified).
145
+ - SemVer: the four public factories, the root-only export map, the
146
+ `AssistantPorts` shape and the `/api/v1/ai/*` HTTP/SSE contract are the
147
+ public contract — breaking any of them requires a major bump.
148
+ - Publication is a manual, explicit step and is **not** automated in CI.
149
+
150
+ ## License
151
+
152
+ MIT
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@animastor/assistant",
3
+ "version": "0.1.0",
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
+ "keywords": [
6
+ "animastor",
7
+ "ai-assistant",
8
+ "chat",
9
+ "sse",
10
+ "llm"
11
+ ],
12
+ "main": "src/index.cjs",
13
+ "exports": {
14
+ ".": "./src/index.cjs"
15
+ },
16
+ "files": [
17
+ "src/",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE"
21
+ ],
22
+ "scripts": {
23
+ "test": "mocha --exit test/*.test.js"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "license": "MIT",
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/Animastor/animastor.git",
35
+ "directory": "packages/animastor-assistant"
36
+ },
37
+ "homepage": "https://github.com/Animastor/animastor/tree/main/packages/animastor-assistant#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/Animastor/animastor/issues"
40
+ },
41
+ "devDependencies": {
42
+ "chai": "^6.2.2",
43
+ "mocha": "^11.7.5"
44
+ }
45
+ }
@@ -0,0 +1,60 @@
1
+ // ======================================================
2
+ // ASSISTANT PORTS — CONTRACT (Assistant-owned)
3
+ // ======================================================
4
+ // The interface half of the AssistantPorts seam: the narrow host contract
5
+ // the Assistant contour consumes. The IMPLEMENTATION half (the host
6
+ // adapter that knows Book Model, saveBookBundle, lazyBook.getBookDir, the
7
+ // bundle validator, the Provider Gateway and the filesystem) stays
8
+ // HOST-side in backend/src/services/assistant-ports.cjs and is injected
9
+ // here by the composition root.
10
+ //
11
+ // Contract (every member is required — see assertAssistantPorts):
12
+ // loadBook(bookId) → canonical||draft book read (lazy mode)
13
+ // persistBook(bookId, bundle) → ONE save semantics: full bundle save
14
+ // when chapters are intact; targeted
15
+ // per-file save (chapters skipped) on a
16
+ // corrupted zero-chapter load
17
+ // validateBundle(bundle) → bundle-contract validation (object)
18
+ // validateBundleFile(name, data) → per-file validation (targeted save)
19
+ // resolveChatAI(bookId) → chat provider resolution
20
+ // sessionRepo → chat-session repository port
21
+ // (session-repo-contract.cjs surface)
22
+ // purgeForBook(bookId) → Assistant-data purge (book deletion /
23
+ // cache teardown reverse edge)
24
+ // chatTransport → inference transport legs:
25
+ // safeFetch(url, opts) → SSRF-guarded fetch (cloud providers)
26
+ // runSharedInference(...) → connector shared inference
27
+ // describeSharedError(code) → sanitized shared-inference message
28
+ // chatAiSourceToken(ai) → safe consumer-facing source token
29
+ // log → host logger
30
+ //
31
+ // (docs/architecture/ai-assistant-extraction.md)
32
+
33
+ 'use strict';
34
+
35
+ const { assertSessionRepo } = require('./session-repo-contract.cjs');
36
+
37
+ /**
38
+ * Runtime contract check for an AssistantPorts adapter. Throws a named
39
+ * error when a required port is missing — the composition root fails
40
+ * fast instead of the first request. Returns the ports unchanged.
41
+ */
42
+ function assertAssistantPorts(ports) {
43
+ const must = (cond, msg) => { if (!cond) throw new Error(`assistantPorts: ${msg}`); };
44
+ must(typeof ports?.loadBook === 'function', 'loadBook is required');
45
+ must(typeof ports?.persistBook === 'function', 'persistBook is required');
46
+ must(typeof ports?.validateBundle === 'function', 'validateBundle is required');
47
+ must(typeof ports?.validateBundleFile === 'function', 'validateBundleFile is required');
48
+ must(typeof ports?.resolveChatAI === 'function', 'resolveChatAI is required');
49
+ must(typeof ports?.purgeForBook === 'function', 'purgeForBook is required');
50
+ must(typeof ports?.log === 'function', 'log is required');
51
+ assertSessionRepo(ports?.sessionRepo, 'assistantPorts.sessionRepo');
52
+ const t = ports?.chatTransport;
53
+ must(typeof t?.safeFetch === 'function', 'chatTransport.safeFetch is required');
54
+ must(typeof t?.runSharedInference === 'function', 'chatTransport.runSharedInference is required');
55
+ must(typeof t?.describeSharedError === 'function', 'chatTransport.describeSharedError is required');
56
+ must(typeof t?.chatAiSourceToken === 'function', 'chatTransport.chatAiSourceToken is required');
57
+ return ports;
58
+ }
59
+
60
+ module.exports = { assertAssistantPorts };