@siduri-x/api 1.0.0 → 1.0.2

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/dist/index.js DELETED
@@ -1,167 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.app = exports.createApp = void 0;
21
- const promises_1 = require("node:fs/promises");
22
- const node_path_1 = __importDefault(require("node:path"));
23
- const app_1 = require("./app");
24
- Object.defineProperty(exports, "createApp", { enumerable: true, get: function () { return app_1.createApp; } });
25
- const runtime_1 = require("./runtime");
26
- const brain_1 = require("@siduri-x/brain");
27
- const memory_1 = require("@siduri-x/memory");
28
- const voice_1 = require("@siduri-x/voice");
29
- const knowledge_1 = require("@siduri-x/knowledge");
30
- const vision_1 = require("@siduri-x/vision");
31
- const behavior_1 = require("@siduri-x/behavior");
32
- const body_1 = require("@siduri-x/body");
33
- const observation_1 = require("@siduri-x/observation");
34
- __exportStar(require("./context-mapper"), exports);
35
- const runtimes = new Map();
36
- const instance = (0, app_1.createApp)(runtimes);
37
- exports.app = instance.app;
38
- exports.default = exports.app;
39
- function createBrain(config) {
40
- const provider = config.provider || 'openrouter';
41
- const defaultKeyEnv = provider === 'openai-compatible' ? 'OPENAI_COMPATIBLE_API_KEY' : 'OPENROUTER_API_KEY';
42
- const apiKey = config.apiKey || process.env[config.apiKeyEnv || defaultKeyEnv] || '';
43
- if (provider === 'openai-compatible') {
44
- return new brain_1.OpenAICompatibleBrain({
45
- apiKey,
46
- model: config.model || 'local-model',
47
- baseUrl: config.baseUrl || 'http://127.0.0.1:1234/v1',
48
- });
49
- }
50
- return new brain_1.OpenRouterBrain({ apiKey, model: config.model || 'gpt-4o-mini' });
51
- }
52
- function isDisabled(config) {
53
- return !config || config.provider === 'none';
54
- }
55
- function createVoice(config) {
56
- return isDisabled(config)
57
- ? undefined
58
- : new voice_1.VoicevoxAdapter({ baseUrl: process.env.VOICEVOX_URL || 'http://localhost:50021', speakerId: config.speakerId || 1 });
59
- }
60
- function createKnowledge(config) {
61
- if (isDisabled(config))
62
- return undefined;
63
- if (!config?.packPath && !config?.registryUrl && !config?.baseUrl && !config?.hubUrl) {
64
- return undefined;
65
- }
66
- return new knowledge_1.EKnowledgeAdapter(config);
67
- }
68
- function createVision(config) {
69
- return isDisabled(config)
70
- ? undefined
71
- : new vision_1.OpenRouterVisionAdapter({ apiKey: process.env.OPENROUTER_API_KEY || '', model: config.model || 'gpt-4-vision' });
72
- }
73
- function createBehavior(config) {
74
- return isDisabled(config) ? undefined : new behavior_1.ActiveSelfCompiler();
75
- }
76
- function createBody(config) {
77
- return isDisabled(config)
78
- ? undefined
79
- : new body_1.Live2DAdapter(config);
80
- }
81
- const PORT = process.env.PORT || 3001;
82
- const defaultCompanionConfig = {
83
- id: 'default',
84
- name: 'Siduri',
85
- brain: { provider: 'openrouter', model: 'gpt-4o-mini' },
86
- voice: { provider: 'voicevox', speakerId: 1 },
87
- memory: { provider: 'postgres' },
88
- knowledge: {
89
- provider: process.env.SIDURI_KNOWLEDGE_PROVIDER || 'e-knowledge',
90
- packPath: process.env.SIDURI_KNOWLEDGE_PACK || '',
91
- registryUrl: process.env.SIDURI_KNOWLEDGE_REGISTRY_URL || '',
92
- packId: process.env.SIDURI_KNOWLEDGE_PACK_ID || '',
93
- timeoutMs: Number(process.env.SIDURI_KNOWLEDGE_TIMEOUT_MS || 5000),
94
- preferredMode: process.env.SIDURI_KNOWLEDGE_MODE || 'lexical',
95
- },
96
- behavior: { provider: 'active_self' },
97
- body: {
98
- provider: 'live2d',
99
- },
100
- vision: { provider: 'openrouter', model: 'gpt-4-vision' }
101
- };
102
- async function loadCompanionConfig() {
103
- const configPath = process.env.SIDURI_CONFIG || node_path_1.default.resolve(process.cwd(), 'siduri.config.json');
104
- let fileConfig = {};
105
- try {
106
- fileConfig = JSON.parse(await (0, promises_1.readFile)(configPath, 'utf8'));
107
- console.log(`Loaded companion configuration from ${configPath}`);
108
- }
109
- catch (error) {
110
- if (error?.code !== 'ENOENT')
111
- throw new Error(`Unable to read ${configPath}: ${error.message}`);
112
- console.log(`No ${configPath} found; using environment/default configuration.`);
113
- }
114
- const config = {
115
- ...defaultCompanionConfig,
116
- ...fileConfig,
117
- id: fileConfig.id || defaultCompanionConfig.id,
118
- brain: { ...defaultCompanionConfig.brain, ...fileConfig.brain },
119
- voice: { ...defaultCompanionConfig.voice, ...fileConfig.voice },
120
- memory: { ...defaultCompanionConfig.memory, ...fileConfig.memory },
121
- knowledge: { ...defaultCompanionConfig.knowledge, ...fileConfig.knowledge },
122
- behavior: { ...defaultCompanionConfig.behavior, ...fileConfig.behavior },
123
- body: { ...defaultCompanionConfig.body, ...fileConfig.body },
124
- vision: { ...defaultCompanionConfig.vision, ...fileConfig.vision },
125
- };
126
- if (process.env.SIDURI_KNOWLEDGE_PROVIDER)
127
- config.knowledge.provider = process.env.SIDURI_KNOWLEDGE_PROVIDER;
128
- if (process.env.SIDURI_KNOWLEDGE_PACK)
129
- config.knowledge.packPath = process.env.SIDURI_KNOWLEDGE_PACK;
130
- if (process.env.SIDURI_KNOWLEDGE_REGISTRY_URL)
131
- config.knowledge.registryUrl = process.env.SIDURI_KNOWLEDGE_REGISTRY_URL;
132
- if (process.env.SIDURI_KNOWLEDGE_PACK_ID)
133
- config.knowledge.packId = process.env.SIDURI_KNOWLEDGE_PACK_ID;
134
- if (process.env.SIDURI_KNOWLEDGE_MODE)
135
- config.knowledge.preferredMode = process.env.SIDURI_KNOWLEDGE_MODE;
136
- return config;
137
- }
138
- async function bootDefaultCompanion() {
139
- if (runtimes.has('default'))
140
- return;
141
- console.log("Booting default companion...");
142
- const config = await loadCompanionConfig();
143
- const brain = createBrain(config.brain);
144
- const memory = new memory_1.PostgresMemoryOrgan({ connectionString: process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/siduri' });
145
- const voice = createVoice(config.voice);
146
- const knowledge = createKnowledge(config.knowledge);
147
- const vision = createVision(config.vision);
148
- const observation = new observation_1.FixtureObservationOrgan(vision ?? { analyze: async () => JSON.stringify({ readings: [] }) });
149
- instance.setObservationOrgan(observation);
150
- const behavior = createBehavior(config.behavior);
151
- const body = createBody(config.body);
152
- await memory.runMigrations().catch(e => console.warn("Migrations warning:", e.message));
153
- const runtime = new runtime_1.SiduriRuntime('default', config, { brain, memory, voice, knowledge, vision, behavior, body });
154
- await runtime.initialize();
155
- runtimes.set('default', runtime);
156
- console.log("Default companion booted successfully.");
157
- }
158
- if (process.env.NODE_ENV !== 'test') {
159
- bootDefaultCompanion().then(() => {
160
- exports.app.listen(PORT, () => {
161
- console.log(`Siduri-Y API running on port ${PORT}`);
162
- });
163
- }).catch(e => {
164
- console.error("Failed to boot default companion:", e);
165
- process.exit(1);
166
- });
167
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,115 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const supertest_1 = __importDefault(require("supertest"));
7
- const app_1 = require("./app");
8
- describe('API Boundary Context Validation (P2 Route Integration)', () => {
9
- const fakeRuntime = {
10
- handleUserMessage: jest.fn().mockResolvedValue({
11
- response: { subtitle_en: 'Hello there' },
12
- metadata: {},
13
- }),
14
- };
15
- let app;
16
- let runtimes;
17
- beforeEach(() => {
18
- runtimes = new Map([['companion-a', fakeRuntime]]);
19
- const created = (0, app_1.createApp)(runtimes);
20
- app = created.app;
21
- fakeRuntime.handleUserMessage.mockClear();
22
- });
23
- test('accepts valid anonymous chat request and maps through API boundary', async () => {
24
- const res = await (0, supertest_1.default)(app)
25
- .post('/chat')
26
- .send({
27
- id: 'companion-a',
28
- message: 'Hello neutral world',
29
- history: [],
30
- });
31
- expect(res.status).toBe(200);
32
- expect(fakeRuntime.handleUserMessage).toHaveBeenCalledWith('Hello neutral world', 'VIEWER', []);
33
- });
34
- test('accepts neutral context chat envelope at /chat route', async () => {
35
- const res = await (0, supertest_1.default)(app)
36
- .post('/chat')
37
- .send({
38
- companionId: 'companion-a',
39
- context: {
40
- actor: {
41
- actorId: 'actor-a',
42
- sessionId: 'session-a',
43
- authorizationRole: 'viewer',
44
- capabilities: ['chat:public'],
45
- authenticated: false,
46
- },
47
- conversation: {
48
- channel: 'public',
49
- audienceId: 'audience-public',
50
- correlationId: 'corr-route-1',
51
- },
52
- },
53
- message: 'Hello structured context',
54
- history: [],
55
- });
56
- expect(res.status).toBe(200);
57
- expect(fakeRuntime.handleUserMessage).toHaveBeenCalledWith('Hello structured context', 'VIEWER', []);
58
- });
59
- test('rejects MASTER_PRIVATE in public request with 400 and structured error', async () => {
60
- const res = await (0, supertest_1.default)(app)
61
- .post('/chat')
62
- .send({
63
- companionId: 'companion-a',
64
- context: {
65
- actor: {
66
- actorId: 'actor-a',
67
- sessionId: 'session-a',
68
- authorizationRole: 'viewer',
69
- capabilities: ['chat:public'],
70
- authenticated: false,
71
- },
72
- conversation: {
73
- channel: 'public',
74
- audienceId: 'MASTER_PRIVATE',
75
- correlationId: 'corr-err-1',
76
- },
77
- },
78
- message: 'Forbidden audience test',
79
- });
80
- expect(res.status).toBe(400);
81
- expect(res.body.accepted).toBe(false);
82
- expect(res.body.error.code).toBe('LEGACY_PERSONAL_AUDIENCE');
83
- expect(fakeRuntime.handleUserMessage).not.toHaveBeenCalled();
84
- });
85
- test('rejects global primary_user subject with 400 and structured error', async () => {
86
- const res = await (0, supertest_1.default)(app)
87
- .post('/chat')
88
- .send({
89
- companionId: 'companion-a',
90
- context: {
91
- actor: {
92
- actorId: 'actor-a',
93
- sessionId: 'session-a',
94
- authorizationRole: 'viewer',
95
- capabilities: ['chat:public'],
96
- authenticated: true,
97
- },
98
- conversation: {
99
- channel: 'public',
100
- audienceId: 'audience-public',
101
- correlationId: 'corr-err-2',
102
- },
103
- subject: {
104
- subjectId: 'primary_user',
105
- kind: 'actor',
106
- },
107
- },
108
- message: 'Forbidden primary user test',
109
- });
110
- expect(res.status).toBe(400);
111
- expect(res.body.accepted).toBe(false);
112
- expect(res.body.error.code).toBe('FORBIDDEN_CONTEXT');
113
- expect(fakeRuntime.handleUserMessage).not.toHaveBeenCalled();
114
- });
115
- });
package/dist/runtime.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from '@siduri-x/core';
package/dist/runtime.js DELETED
@@ -1,17 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("@siduri-x/core"), exports);
@@ -1 +0,0 @@
1
- export {};
@@ -1,240 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const runtime_1 = require("./runtime");
4
- const hands_1 = require("@siduri-x/hands");
5
- const ear_1 = require("@siduri-x/ear");
6
- const core_1 = require("@siduri-x/core");
7
- describe('Siduri Runtime Orchestration', () => {
8
- test('handles concurrent context retrieval and graceful degradation', async () => {
9
- let knowledgeSearchCalled = false;
10
- let brainGenerateCalled = false;
11
- let proposedClaims = [];
12
- let noKnowledgeContext = false;
13
- const mockBrain = {
14
- generatePlan: async (args) => {
15
- brainGenerateCalled = true;
16
- if (!args.contextPrompt.includes("KNOWLEDGE:")) {
17
- noKnowledgeContext = true;
18
- }
19
- return {
20
- speech: "Hello",
21
- language: "en",
22
- memoryProposals: [
23
- { subject: "Test", predicate: "is", value: "working" }
24
- ]
25
- };
26
- }
27
- };
28
- const mockMemory = {
29
- initialize: async () => { },
30
- searchClaims: async () => {
31
- await new Promise(r => setTimeout(r, 10));
32
- return [];
33
- },
34
- getDirectives: async () => [],
35
- proposeClaim: async (claim) => {
36
- proposedClaims.push(claim);
37
- return { id: "claim-1", ...claim };
38
- },
39
- proposeDirective: async () => ({})
40
- };
41
- const mockKnowledge = {
42
- search: async () => {
43
- knowledgeSearchCalled = true;
44
- throw new Error("E-Teyvat is down");
45
- }
46
- };
47
- const mockVoice = {
48
- enqueueSpeech: () => "speech-1",
49
- onLifecycleEvent: () => { },
50
- getQueueStatus: () => ({ pending: 0 }),
51
- };
52
- const mockVision = { analyze: async () => "" };
53
- const mockBehavior = { compile: async () => "Compiled behavior" };
54
- const mockBody = { speak: () => { } };
55
- const runtime = new runtime_1.SiduriRuntime('default', { name: "Test Companion" }, {
56
- brain: mockBrain,
57
- memory: mockMemory,
58
- voice: mockVoice,
59
- knowledge: mockKnowledge,
60
- vision: mockVision,
61
- behavior: mockBehavior,
62
- body: mockBody
63
- });
64
- const response = await runtime.handleUserMessage("Remember this", "OWNER");
65
- expect(response.response.subtitle_en).toBe("Hello");
66
- expect(knowledgeSearchCalled).toBe(true);
67
- expect(brainGenerateCalled).toBe(true);
68
- expect(noKnowledgeContext).toBe(true);
69
- expect(proposedClaims.length).toBe(1);
70
- expect(proposedClaims[0].subject).toBe("Test");
71
- expect(proposedClaims[0].scope).toBe("OWNER");
72
- expect(response.metadata.memory_proposals[0].proposal_id).toBe("claim-1");
73
- });
74
- test('Primary Invariant: Brain proposes an action, ActionPolicyEngine authorizes, Hands executes', async () => {
75
- let toolExecuted = false;
76
- const hands = new hands_1.DefaultHandsOrgan();
77
- hands.registerTool({
78
- definition: {
79
- name: 'search_web',
80
- providerId: 'builtin',
81
- description: 'Web search',
82
- inputSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
83
- riskLevel: 'LOW',
84
- requiredCapabilities: ['chat:public'],
85
- },
86
- execute: async (params) => {
87
- toolExecuted = true;
88
- return { hits: [`Result for ${params.query}`] };
89
- },
90
- });
91
- const mockBrain = {
92
- generatePlan: async () => ({
93
- speech: "I found this for you.",
94
- language: "en",
95
- actionIntents: [
96
- {
97
- actionId: 'act-plan-1',
98
- toolName: 'builtin/search_web',
99
- parameters: { query: 'Teyvat history' },
100
- }
101
- ]
102
- })
103
- };
104
- const mockMemory = {
105
- initialize: async () => { },
106
- searchClaims: async () => [],
107
- getDirectives: async () => [],
108
- proposeClaim: async (c) => c,
109
- };
110
- const actionPolicy = new core_1.ActionPolicyEngine();
111
- const runtime = new runtime_1.SiduriRuntime('companion-secure', { name: "SecureCompanion" }, {
112
- brain: mockBrain,
113
- memory: mockMemory,
114
- hands,
115
- actionPolicy,
116
- });
117
- await runtime.initialize();
118
- const context = {
119
- companionId: 'companion-secure',
120
- actor: {
121
- actorId: 'user-alice',
122
- sessionId: 'sess-alice',
123
- authorizationRole: 'operator',
124
- capabilities: ['chat:public'],
125
- authenticated: true,
126
- },
127
- conversation: {
128
- channel: 'direct',
129
- audienceId: 'audience-direct',
130
- correlationId: 'corr-alice-123',
131
- },
132
- };
133
- const res = await runtime.handleUserMessage("Find history", context);
134
- expect(res.status).toBe('APPROVED');
135
- expect(toolExecuted).toBe(true);
136
- expect(res.metadata.action_results).toHaveLength(1);
137
- expect(res.metadata.action_results[0].success).toBe(true);
138
- expect(res.metadata.action_results[0].lifecycle).toBe('COMPLETED');
139
- expect(res.metadata.action_results[0].decision.allowed).toBe(true);
140
- // Verify audit log has recorded the action execution
141
- const auditLogs = await actionPolicy.getAuditLog();
142
- expect(auditLogs.length).toBeGreaterThan(0);
143
- const audit = auditLogs.find(a => a.actionId === 'act-plan-1');
144
- expect(audit).toBeDefined();
145
- expect(audit?.actorId).toBe('user-alice');
146
- expect(audit?.correlationId).toBe('corr-alice-123');
147
- });
148
- test('Policy rejects unauthorized action proposed by Brain and Hands never executes it', async () => {
149
- let dangerousExecuted = false;
150
- const hands = new hands_1.DefaultHandsOrgan();
151
- hands.registerTool({
152
- definition: {
153
- name: 'delete_system',
154
- providerId: 'admin',
155
- description: 'Delete system',
156
- inputSchema: { type: 'object' },
157
- riskLevel: 'CRITICAL',
158
- requiredCapabilities: ['system:admin'],
159
- allowedRoles: ['administrator'],
160
- },
161
- execute: async () => {
162
- dangerousExecuted = true;
163
- return { deleted: true };
164
- },
165
- });
166
- const mockBrain = {
167
- generatePlan: async () => ({
168
- speech: "Attempting to delete system.",
169
- language: "en",
170
- actionIntents: [
171
- {
172
- actionId: 'act-danger-1',
173
- toolName: 'admin/delete_system',
174
- parameters: {},
175
- }
176
- ]
177
- })
178
- };
179
- const mockMemory = {
180
- initialize: async () => { },
181
- searchClaims: async () => [],
182
- getDirectives: async () => [],
183
- };
184
- const actionPolicy = new core_1.ActionPolicyEngine();
185
- const runtime = new runtime_1.SiduriRuntime('companion-secure-2', { name: "SecureCompanion2" }, {
186
- brain: mockBrain,
187
- memory: mockMemory,
188
- hands,
189
- actionPolicy,
190
- });
191
- await runtime.initialize();
192
- // Viewer context without administrator role or system:admin capability
193
- const viewerContext = {
194
- companionId: 'companion-secure-2',
195
- actor: {
196
- actorId: 'viewer-bob',
197
- sessionId: 'sess-bob',
198
- authorizationRole: 'viewer',
199
- capabilities: ['chat:public'],
200
- authenticated: false,
201
- },
202
- conversation: {
203
- channel: 'public',
204
- audienceId: 'audience-public',
205
- correlationId: 'corr-bob-999',
206
- },
207
- };
208
- const res = await runtime.handleUserMessage("Delete system", viewerContext);
209
- expect(dangerousExecuted).toBe(false);
210
- expect(res.metadata.action_results).toHaveLength(1);
211
- expect(res.metadata.action_results[0].success).toBe(false);
212
- expect(res.metadata.action_results[0].lifecycle).toBe('REJECTED');
213
- expect(res.metadata.action_results[0].error).toContain('Action authorization rejected by policy');
214
- });
215
- test('Universal Perception: User input passes through EarOrgan and validates resource limits', async () => {
216
- const ear = new ear_1.DefaultEarOrgan({
217
- maxTextLength: 50,
218
- });
219
- const mockBrain = {
220
- generatePlan: async (ctx) => ({
221
- speech: "Response",
222
- language: "en",
223
- })
224
- };
225
- const mockMemory = {
226
- initialize: async () => { },
227
- searchClaims: async () => [],
228
- getDirectives: async () => [],
229
- };
230
- const runtime = new runtime_1.SiduriRuntime('companion-ear-test', { name: "EarCompanion" }, {
231
- brain: mockBrain,
232
- memory: mockMemory,
233
- ear,
234
- });
235
- await runtime.initialize();
236
- // Oversized message should be rejected at Ear boundary
237
- const oversizedMsg = 'X'.repeat(100);
238
- await expect(runtime.handleUserMessage(oversizedMsg, 'OWNER')).rejects.toThrow(/Ear text input exceeds maximum allowed length/);
239
- });
240
- });
File without changes
@@ -1,6 +0,0 @@
1
- "use strict";
2
- describe('Legacy Smoke Test Migration', () => {
3
- test('placeholder smoke test for Jest runner compatibility', () => {
4
- expect(true).toBe(true);
5
- });
6
- });
@@ -1 +0,0 @@
1
- export {};