@siduri-x/api 1.0.2 → 1.0.5

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 (43) hide show
  1. package/dist/app.d.ts +43 -0
  2. package/dist/app.js +637 -0
  3. package/dist/auth.d.ts +34 -0
  4. package/dist/auth.js +84 -0
  5. package/dist/auth.test.d.ts +1 -0
  6. package/dist/auth.test.js +74 -0
  7. package/dist/b0-b6.test.d.ts +1 -0
  8. package/dist/b0-b6.test.js +121 -0
  9. package/dist/context-mapper.d.ts +18 -0
  10. package/dist/context-mapper.js +160 -0
  11. package/dist/context-mapper.test.d.ts +1 -0
  12. package/dist/context-mapper.test.js +136 -0
  13. package/dist/cors.d.ts +3 -0
  14. package/dist/cors.js +42 -0
  15. package/dist/index.d.ts +6 -0
  16. package/dist/index.js +191 -0
  17. package/dist/index.test.d.ts +1 -0
  18. package/dist/index.test.js +137 -0
  19. package/dist/runtime.d.ts +1 -0
  20. package/dist/runtime.js +17 -0
  21. package/dist/runtime.test.d.ts +1 -0
  22. package/dist/runtime.test.js +282 -0
  23. package/dist/smoke.test.d.ts +0 -0
  24. package/dist/smoke.test.js +6 -0
  25. package/dist/t4-gating.test.d.ts +1 -0
  26. package/dist/t4-gating.test.js +193 -0
  27. package/dist/t5-experience.test.d.ts +1 -0
  28. package/dist/t5-experience.test.js +155 -0
  29. package/dist/t6-security.test.d.ts +1 -0
  30. package/dist/t6-security.test.js +423 -0
  31. package/dist/t7-release.test.d.ts +1 -0
  32. package/dist/t7-release.test.js +119 -0
  33. package/package.json +14 -11
  34. package/src/app.ts +36 -64
  35. package/src/auth.test.ts +56 -23
  36. package/src/auth.ts +74 -22
  37. package/src/context-mapper.test.ts +42 -147
  38. package/src/context-mapper.ts +44 -179
  39. package/src/index.test.ts +8 -32
  40. package/src/index.ts +19 -3
  41. package/src/runtime.test.ts +3 -5
  42. package/src/t5-experience.test.ts +0 -1
  43. package/src/t6-security.test.ts +0 -1
package/dist/app.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { Express } from 'express';
2
+ import { SiduriRuntime } from './runtime';
3
+ import { VoiceConfig } from '@siduri-x/voice';
4
+ import { EKnowledgeConfig } from '@siduri-x/knowledge';
5
+ import { OpenRouterVisionConfig } from '@siduri-x/vision';
6
+ import { Live2DAdapterConfig } from '@siduri-x/body';
7
+ import { FixtureObservationOrgan } from '@siduri-x/observation';
8
+ import { DefaultHandsOrganConfig } from '@siduri-x/hands';
9
+ import { EarOrganConfig } from '@siduri-x/ear';
10
+ import { DefaultMouthOrganConfig } from '@siduri-x/mouth';
11
+ export interface AppBrainConfig {
12
+ provider?: 'openrouter' | 'openai-compatible' | string;
13
+ model?: string;
14
+ apiKey?: string;
15
+ apiKeyEnv?: string;
16
+ baseUrl?: string;
17
+ timeoutMs?: number;
18
+ [key: string]: unknown;
19
+ }
20
+ export interface AppBehaviorConfig {
21
+ provider?: 'active_self' | 'none' | string;
22
+ preset?: string;
23
+ [key: string]: unknown;
24
+ }
25
+ export interface AppBootCompanionConfig {
26
+ name: string;
27
+ brain?: AppBrainConfig;
28
+ voice?: VoiceConfig;
29
+ knowledge?: EKnowledgeConfig;
30
+ vision?: OpenRouterVisionConfig;
31
+ behavior?: AppBehaviorConfig;
32
+ body?: Live2DAdapterConfig;
33
+ hands?: DefaultHandsOrganConfig;
34
+ ear?: EarOrganConfig;
35
+ mouth?: DefaultMouthOrganConfig;
36
+ [key: string]: unknown;
37
+ }
38
+ export interface AppInstance {
39
+ app: Express;
40
+ runtimes: Map<string, SiduriRuntime>;
41
+ setObservationOrgan: (org: FixtureObservationOrgan) => void;
42
+ }
43
+ export declare function createApp(runtimes?: Map<string, SiduriRuntime>): AppInstance;
package/dist/app.js ADDED
@@ -0,0 +1,637 @@
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
+ exports.createApp = createApp;
7
+ const express_1 = __importDefault(require("express"));
8
+ const cors_1 = __importDefault(require("cors"));
9
+ const cors_2 = require("./cors");
10
+ const runtime_1 = require("./runtime");
11
+ const brain_1 = require("@siduri-x/brain");
12
+ const memory_1 = require("@siduri-x/memory");
13
+ const voice_1 = require("@siduri-x/voice");
14
+ const knowledge_1 = require("@siduri-x/knowledge");
15
+ const vision_1 = require("@siduri-x/vision");
16
+ const behavior_1 = require("@siduri-x/behavior");
17
+ const body_1 = require("@siduri-x/body");
18
+ const hands_1 = require("@siduri-x/hands");
19
+ const ear_1 = require("@siduri-x/ear");
20
+ const mouth_1 = require("@siduri-x/mouth");
21
+ const auth_1 = require("./auth");
22
+ const context_mapper_1 = require("./context-mapper");
23
+ function createApp(runtimes = new Map()) {
24
+ const app = (0, express_1.default)();
25
+ app.use((0, cors_1.default)((0, cors_2.createCorsOptions)()));
26
+ app.use(express_1.default.json());
27
+ let observationOrgan;
28
+ function createBrain(config) {
29
+ const provider = config?.provider || 'openrouter';
30
+ const defaultKeyEnv = provider === 'openai-compatible' ? 'OPENAI_COMPATIBLE_API_KEY' : 'OPENROUTER_API_KEY';
31
+ const apiKey = config?.apiKey || process.env[config?.apiKeyEnv || defaultKeyEnv] || '';
32
+ if (provider === 'openai-compatible') {
33
+ return new brain_1.OpenAICompatibleBrain({
34
+ apiKey,
35
+ model: config?.model || 'local-model',
36
+ baseUrl: config?.baseUrl || 'http://127.0.0.1:1234/v1',
37
+ });
38
+ }
39
+ return new brain_1.OpenRouterBrain({ apiKey, model: config?.model || 'gpt-4o-mini' });
40
+ }
41
+ function isDisabled(config) {
42
+ return !config || config.provider === 'none';
43
+ }
44
+ function createVoice(config) {
45
+ return isDisabled(config)
46
+ ? undefined
47
+ : new voice_1.VoiceAdapter({
48
+ provider: config?.provider || 'voicevox',
49
+ baseUrl: config?.baseUrl || process.env.VOICEVOX_URL || 'http://localhost:50021',
50
+ speakerId: config?.speakerId || 1,
51
+ ...config,
52
+ });
53
+ }
54
+ function createKnowledge(config) {
55
+ return isDisabled(config) ? undefined : new knowledge_1.EKnowledgeAdapter(config || {});
56
+ }
57
+ function createVision(config) {
58
+ return isDisabled(config)
59
+ ? undefined
60
+ : new vision_1.OpenRouterVisionAdapter({
61
+ apiKey: config?.apiKey || process.env.OPENROUTER_API_KEY || '',
62
+ model: config?.model || 'gpt-4-vision',
63
+ ...config,
64
+ });
65
+ }
66
+ function createBehavior(config) {
67
+ return isDisabled(config) ? undefined : new behavior_1.ActiveSelfCompiler();
68
+ }
69
+ function createBody(config) {
70
+ return isDisabled(config)
71
+ ? undefined
72
+ : new body_1.Live2DAdapter(config);
73
+ }
74
+ function createHands(config) {
75
+ return isDisabled(config)
76
+ ? new hands_1.DefaultHandsOrgan()
77
+ : new hands_1.DefaultHandsOrgan(config);
78
+ }
79
+ function createEar(config) {
80
+ return isDisabled(config)
81
+ ? new ear_1.DefaultEarOrgan()
82
+ : new ear_1.DefaultEarOrgan(config);
83
+ }
84
+ function createMouth(config, voice) {
85
+ return isDisabled(config)
86
+ ? new mouth_1.DefaultMouthOrgan({ voice })
87
+ : new mouth_1.DefaultMouthOrgan({ ...config, voice });
88
+ }
89
+ app.post('/boot', auth_1.requireAuth, async (req, res) => {
90
+ try {
91
+ const { id, config } = req.body;
92
+ if (runtimes.has(id)) {
93
+ return res.status(400).json({ error: "Already booted" });
94
+ }
95
+ const brain = createBrain(config.brain);
96
+ const memory = new memory_1.PostgresMemoryOrgan({ connectionString: process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/siduri' });
97
+ const voice = createVoice(config.voice);
98
+ const knowledge = createKnowledge(config.knowledge);
99
+ const vision = createVision(config.vision);
100
+ const behavior = createBehavior(config.behavior);
101
+ const body = createBody(config.body);
102
+ const hands = createHands(config.hands);
103
+ const ear = createEar(config.ear);
104
+ const mouth = createMouth(config.mouth, voice);
105
+ const runtime = new runtime_1.SiduriRuntime(id, config, {
106
+ brain,
107
+ memory,
108
+ voice,
109
+ knowledge,
110
+ vision,
111
+ behavior,
112
+ body,
113
+ hands,
114
+ ear,
115
+ mouth,
116
+ observation: observationOrgan,
117
+ });
118
+ await runtime.initialize();
119
+ runtimes.set(id, runtime);
120
+ res.json({ success: true, id });
121
+ }
122
+ catch (e) {
123
+ res.status(500).json({ error: e.message });
124
+ }
125
+ });
126
+ // STATUS / HEALTH ENDPOINTS
127
+ app.get('/health', (req, res) => res.json({ status: "ok" }));
128
+ app.get('/version', (req, res) => res.json({ name: "siduri-x-api", version: "0.2.0-x" }));
129
+ app.get('/ready', (req, res) => {
130
+ const isReady = runtimes.size > 0;
131
+ res.status(isReady ? 200 : 503).json({
132
+ status: isReady ? "ready" : "not_ready",
133
+ companionCount: runtimes.size,
134
+ });
135
+ });
136
+ app.get('/voice/health', (req, res) => {
137
+ const hasVoice = Array.from(runtimes.values()).some((r) => Boolean(r.voice));
138
+ res.json({ provider: "siduri-voice", configured: hasVoice });
139
+ });
140
+ app.get('/obs/health', (req, res) => {
141
+ const connected = Boolean(observationOrgan) || Array.from(runtimes.values()).some((r) => Boolean(r.observation));
142
+ res.json({ connected });
143
+ });
144
+ app.get('/mouth/health', (req, res) => {
145
+ const hasMouth = Array.from(runtimes.values()).some((r) => Boolean(r.mouth));
146
+ res.json({ provider: "siduri-mouth", configured: hasMouth });
147
+ });
148
+ app.get('/mouth/channels', (req, res) => {
149
+ const id = req.query.id || Array.from(runtimes.keys())[0];
150
+ const runtime = runtimes.get(id);
151
+ if (!runtime || !runtime.mouth || typeof runtime.mouth.getRegisteredChannels !== 'function') {
152
+ return res.json({ channels: [] });
153
+ }
154
+ res.json({ channels: runtime.mouth.getRegisteredChannels() });
155
+ });
156
+ app.get('/me', auth_1.attachIdentity, (req, res) => {
157
+ const identity = req.identity;
158
+ res.json({
159
+ actorId: identity.actorId || (identity.authenticated ? 'owner-user' : 'anonymous-session'),
160
+ role: identity.role || (identity.authenticated ? 'OWNER' : 'VIEWER'),
161
+ authenticated: Boolean(identity.authenticated),
162
+ });
163
+ });
164
+ app.put('/me', auth_1.requireAuth, (req, res) => res.json({ success: true }));
165
+ // CHAT (API context boundary validation)
166
+ app.post('/chat', auth_1.attachIdentity, async (req, res) => {
167
+ const { id, message, history } = req.body;
168
+ const identity = req.identity;
169
+ // Single-owner companion model: map request context directly
170
+ const mappingResult = (0, context_mapper_1.mapRequestContext)({
171
+ ...req.body,
172
+ id: id || req.body.companionId,
173
+ authenticated: identity?.authenticated ?? true,
174
+ source: identity?.source ?? 'local',
175
+ generateCorrelationId: true,
176
+ });
177
+ if (!mappingResult.accepted) {
178
+ return res.status(400).json({
179
+ accepted: false,
180
+ error: mappingResult.error,
181
+ });
182
+ }
183
+ const companionId = mappingResult.context.companionId;
184
+ const runtime = runtimes.get(companionId);
185
+ if (!runtime)
186
+ return res.status(404).json({ error: "Companion not found" });
187
+ try {
188
+ const response = await (0, runtime_1.dispatchCompanionChat)(runtime, {
189
+ id: companionId,
190
+ companionId,
191
+ message,
192
+ context: mappingResult.context,
193
+ history,
194
+ ...(req.body?.medium ? { medium: req.body.medium } : {}),
195
+ });
196
+ res.json(response);
197
+ }
198
+ catch (e) {
199
+ res.status(500).json({ error: e.message });
200
+ }
201
+ });
202
+ // REAL-TIME SSE STREAMING (Mouth transport)
203
+ app.post('/chat/stream', auth_1.attachIdentity, async (req, res) => {
204
+ const { id, message, history } = req.body;
205
+ const identity = req.identity;
206
+ const mappingResult = (0, context_mapper_1.mapRequestContext)({
207
+ ...req.body,
208
+ id: id || req.body.companionId,
209
+ authenticated: identity?.authenticated ?? true,
210
+ source: identity?.source ?? 'local',
211
+ generateCorrelationId: true,
212
+ });
213
+ if (!mappingResult.accepted) {
214
+ return res.status(400).json({
215
+ accepted: false,
216
+ error: mappingResult.error,
217
+ });
218
+ }
219
+ const companionId = mappingResult.context.companionId;
220
+ const runtime = runtimes.get(companionId);
221
+ if (!runtime)
222
+ return res.status(404).json({ error: "Companion not found" });
223
+ res.setHeader('Content-Type', 'text/event-stream');
224
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
225
+ res.setHeader('Connection', 'keep-alive');
226
+ res.flushHeaders?.();
227
+ const abortController = new AbortController();
228
+ const onClose = () => {
229
+ abortController.abort('client_disconnect');
230
+ if (typeof runtime.interruptMouth === 'function') {
231
+ runtime.interruptMouth('client_disconnect');
232
+ }
233
+ };
234
+ req.on('close', onClose);
235
+ try {
236
+ const response = await (0, runtime_1.dispatchCompanionChat)(runtime, {
237
+ id: companionId,
238
+ companionId,
239
+ message,
240
+ context: mappingResult.context,
241
+ history,
242
+ medium: 'web',
243
+ signal: abortController.signal,
244
+ });
245
+ res.write(`event: staged\ndata: ${JSON.stringify({ response_id: response.response_id, correlation_id: response.correlation_id, status: response.status })}\n\n`);
246
+ const avatarEvent = response.metadata?.events?.find((e) => (e.kind === 'avatar' || e.kind === 'body') && (e.approval === 'APPROVED' || !e.approval));
247
+ if (avatarEvent) {
248
+ res.write(`event: avatar\ndata: ${JSON.stringify(avatarEvent)}\n\n`);
249
+ }
250
+ const speechText = response.delivery?.text || response.response?.subtitle_en || response.response?.spoken_ja || '';
251
+ const utterance = {
252
+ utteranceId: response.response_id || 'utt-stream',
253
+ companionId,
254
+ responseId: response.response_id,
255
+ correlationId: response.correlation_id,
256
+ text: speechText,
257
+ medium: 'web',
258
+ expression: avatarEvent?.expression,
259
+ action: avatarEvent?.action,
260
+ signal: abortController.signal,
261
+ };
262
+ if (runtime.mouth && typeof runtime.mouth.stream === 'function') {
263
+ for await (const chunk of runtime.mouth.stream(utterance)) {
264
+ if (abortController.signal.aborted) {
265
+ res.write(`event: chunk\ndata: ${JSON.stringify({ ...chunk, interrupted: true })}\n\n`);
266
+ break;
267
+ }
268
+ res.write(`event: chunk\ndata: ${JSON.stringify(chunk)}\n\n`);
269
+ }
270
+ }
271
+ else {
272
+ res.write(`event: chunk\ndata: ${JSON.stringify({ utteranceId: utterance.utteranceId, index: 1, deltaText: speechText, isComplete: true, medium: 'web' })}\n\n`);
273
+ }
274
+ res.write(`event: done\ndata: ${JSON.stringify(response)}\n\n`);
275
+ res.end();
276
+ }
277
+ catch (e) {
278
+ if (abortController.signal.aborted) {
279
+ res.write(`event: interrupted\ndata: ${JSON.stringify({ reason: abortController.signal.reason })}\n\n`);
280
+ }
281
+ else {
282
+ res.write(`event: error\ndata: ${JSON.stringify({ error: e.message })}\n\n`);
283
+ }
284
+ res.end();
285
+ }
286
+ finally {
287
+ req.removeListener('close', onClose);
288
+ }
289
+ });
290
+ // INTERRUPTION / BARGE-IN
291
+ app.post('/chat/interrupt', auth_1.attachIdentity, (req, res) => {
292
+ const companionId = req.body?.companionId || req.body?.id || Array.from(runtimes.keys())[0];
293
+ const runtime = companionId ? runtimes.get(companionId) : undefined;
294
+ const reason = req.body?.reason || 'user_barge_in';
295
+ if (runtime) {
296
+ runtime.interruptMouth(reason);
297
+ return res.json({ success: true, interrupted: true, companionId, reason });
298
+ }
299
+ for (const r of runtimes.values()) {
300
+ r.interruptMouth(reason);
301
+ }
302
+ return res.json({ success: true, interrupted: true, reason });
303
+ });
304
+ app.post('/mouth/interrupt', auth_1.attachIdentity, (req, res) => {
305
+ const companionId = req.body?.companionId || req.body?.id || Array.from(runtimes.keys())[0];
306
+ const runtime = companionId ? runtimes.get(companionId) : undefined;
307
+ const reason = req.body?.reason || 'user_barge_in';
308
+ if (runtime) {
309
+ runtime.interruptMouth(reason);
310
+ return res.json({ success: true, interrupted: true, companionId, reason });
311
+ }
312
+ for (const r of runtimes.values()) {
313
+ r.interruptMouth(reason);
314
+ }
315
+ return res.json({ success: true, interrupted: true, reason });
316
+ });
317
+ // MEMORY GETTERS
318
+ app.get('/memory/proposals', auth_1.requireAuth, async (req, res) => {
319
+ const id = req.query.id || Array.from(runtimes.keys())[0];
320
+ const runtime = runtimes.get(id);
321
+ if (!runtime)
322
+ return res.status(404).json({ error: "Companion not found" });
323
+ if (!runtime.memory)
324
+ return res.json({ proposals: [] });
325
+ try {
326
+ const proposals = await runtime.getPendingClaims();
327
+ res.json({ proposals });
328
+ }
329
+ catch (e) {
330
+ res.status(500).json({ error: e.message });
331
+ }
332
+ });
333
+ app.get('/memory', auth_1.requireAuth, async (req, res) => {
334
+ const id = req.query.id || Array.from(runtimes.keys())[0];
335
+ const runtime = runtimes.get(id);
336
+ if (!runtime)
337
+ return res.status(404).json({ error: "Companion not found" });
338
+ if (!runtime.memory)
339
+ return res.json({ items: [] });
340
+ try {
341
+ const items = await runtime.getClaims();
342
+ res.json({ items });
343
+ }
344
+ catch (e) {
345
+ res.status(500).json({ error: e.message });
346
+ }
347
+ });
348
+ app.get('/memory/claims', auth_1.requireAuth, async (req, res) => {
349
+ const id = req.query.id || Array.from(runtimes.keys())[0];
350
+ const runtime = runtimes.get(id);
351
+ if (!runtime)
352
+ return res.status(404).json({ error: "Companion not found" });
353
+ if (!runtime.memory)
354
+ return res.json({ claims: [] });
355
+ try {
356
+ const claims = await runtime.getClaims();
357
+ res.json({ claims });
358
+ }
359
+ catch (e) {
360
+ res.status(500).json({ error: e.message });
361
+ }
362
+ });
363
+ app.get('/memory/behavioral', auth_1.requireAuth, async (req, res) => {
364
+ const id = req.query.id || Array.from(runtimes.keys())[0];
365
+ const runtime = runtimes.get(id);
366
+ if (!runtime)
367
+ return res.status(404).json({ error: "Companion not found" });
368
+ if (!runtime.memory)
369
+ return res.json({ directives: [] });
370
+ try {
371
+ const directives = await runtime.getDirectives();
372
+ res.json({ directives });
373
+ }
374
+ catch (e) {
375
+ res.status(500).json({ error: e.message });
376
+ }
377
+ });
378
+ // MEMORY MUTATIONS - PROPOSALS
379
+ app.post('/memory/proposals/update', auth_1.requireAuth, async (req, res) => {
380
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
381
+ const runtime = runtimes.get(id);
382
+ if (!runtime)
383
+ return res.status(404).json({ error: "Companion not found" });
384
+ if (!runtime.memory || typeof runtime.memory.updateClaim !== 'function') {
385
+ return res.status(400).json({ error: "Memory organ does not support updating claims" });
386
+ }
387
+ try {
388
+ const claimId = req.body.id || req.body.claimId;
389
+ if (!claimId) {
390
+ return res.status(400).json({ error: "Missing required claim id" });
391
+ }
392
+ const updated = await runtime.updateClaim(claimId, req.body.updates || req.body);
393
+ res.json({ success: true, claim: updated });
394
+ }
395
+ catch (e) {
396
+ res.status(500).json({ error: e.message });
397
+ }
398
+ });
399
+ app.post('/memory/proposals/approve', auth_1.requireAuth, async (req, res) => {
400
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
401
+ const runtime = runtimes.get(id);
402
+ if (!runtime)
403
+ return res.status(404).json({ error: "Companion not found" });
404
+ if (!runtime.memory)
405
+ return res.status(400).json({ error: "Memory organ not configured" });
406
+ try {
407
+ await runtime.approveClaim(req.body.id);
408
+ res.json({ approved: true });
409
+ }
410
+ catch (e) {
411
+ res.status(500).json({ error: e.message });
412
+ }
413
+ });
414
+ app.post('/memory/proposals/reject', auth_1.requireAuth, async (req, res) => {
415
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
416
+ const runtime = runtimes.get(id);
417
+ if (!runtime)
418
+ return res.status(404).json({ error: "Companion not found" });
419
+ if (!runtime.memory)
420
+ return res.status(400).json({ error: "Memory organ not configured" });
421
+ try {
422
+ await runtime.rejectClaim(req.body.id);
423
+ res.json({ rejected: true });
424
+ }
425
+ catch (e) {
426
+ res.status(500).json({ error: e.message });
427
+ }
428
+ });
429
+ // MEMORY MUTATIONS - BEHAVIORAL
430
+ app.post('/memory/behavioral/approve', auth_1.requireAuth, async (req, res) => {
431
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
432
+ const runtime = runtimes.get(id);
433
+ if (!runtime)
434
+ return res.status(404).json({ error: "Companion not found" });
435
+ if (!runtime.memory)
436
+ return res.status(400).json({ error: "Memory organ not configured" });
437
+ try {
438
+ await runtime.approveDirective(req.body.id);
439
+ res.json({ approved: true });
440
+ }
441
+ catch (e) {
442
+ res.status(500).json({ error: e.message });
443
+ }
444
+ });
445
+ app.post('/memory/behavioral/reject', auth_1.requireAuth, async (req, res) => {
446
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
447
+ const runtime = runtimes.get(id);
448
+ if (!runtime)
449
+ return res.status(404).json({ error: "Companion not found" });
450
+ if (!runtime.memory)
451
+ return res.status(400).json({ error: "Memory organ not configured" });
452
+ try {
453
+ await runtime.rejectDirective(req.body.id);
454
+ res.json({ rejected: true });
455
+ }
456
+ catch (e) {
457
+ res.status(500).json({ error: e.message });
458
+ }
459
+ });
460
+ app.post('/memory/behavioral/revoke', auth_1.requireAuth, async (req, res) => {
461
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
462
+ const runtime = runtimes.get(id);
463
+ if (!runtime)
464
+ return res.status(404).json({ error: "Companion not found" });
465
+ if (!runtime.memory)
466
+ return res.status(400).json({ error: "Memory organ not configured" });
467
+ try {
468
+ await runtime.revokeDirective(req.body.id);
469
+ res.json({ revoked: true });
470
+ }
471
+ catch (e) {
472
+ res.status(500).json({ error: e.message });
473
+ }
474
+ });
475
+ app.post('/memory/behavioral/disable', auth_1.requireAuth, async (req, res) => {
476
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
477
+ const runtime = runtimes.get(id);
478
+ if (!runtime)
479
+ return res.status(404).json({ error: "Companion not found" });
480
+ if (!runtime.memory)
481
+ return res.status(400).json({ error: "Memory organ not configured" });
482
+ try {
483
+ await runtime.disableDirective(req.body.id);
484
+ res.json({ disabled: true });
485
+ }
486
+ catch (e) {
487
+ res.status(500).json({ error: e.message });
488
+ }
489
+ });
490
+ const isDevMode = process.env.NODE_ENV !== 'production' || process.env.SIDURI_DEV_MODE === 'true';
491
+ if (isDevMode) {
492
+ app.post('/dev/memory/reset', auth_1.requireAuth, async (req, res) => {
493
+ const id = req.body.companionId || Array.from(runtimes.keys())[0];
494
+ const runtime = runtimes.get(id);
495
+ if (!runtime)
496
+ return res.status(404).json({ error: "Companion not found" });
497
+ if (!runtime.memory || typeof runtime.memory.resetMemory !== 'function') {
498
+ return res.status(400).json({ error: "Memory organ does not support reset" });
499
+ }
500
+ try {
501
+ await runtime.resetMemory();
502
+ res.json({ reset: true });
503
+ }
504
+ catch (e) {
505
+ res.status(500).json({ error: e.message });
506
+ }
507
+ });
508
+ app.post('/dev/mock-response', async (req, res) => {
509
+ const companionId = req.body?.companionId || Array.from(runtimes.keys())[0] || 'default';
510
+ const runtime = runtimes.get(companionId);
511
+ if (!runtime)
512
+ return res.status(404).json({ accepted: false, error: 'Companion not found' });
513
+ const staged = runtime.stageResponse({
514
+ requestContext: {
515
+ companionId,
516
+ actor: {
517
+ actorId: 'local-user',
518
+ sessionId: 'sess-local',
519
+ capabilities: ['chat', 'memory:approve'],
520
+ authenticated: true,
521
+ },
522
+ conversation: {
523
+ correlationId: req.body?.correlation_id || `corr-${Date.now()}`,
524
+ },
525
+ },
526
+ candidateSpeech: req.body?.speech || 'Mocked staged response for review',
527
+ candidateLanguage: req.body?.language || 'en',
528
+ requiresApproval: req.body?.requiresApproval ?? true,
529
+ });
530
+ res.json({
531
+ accepted: true,
532
+ staged: true,
533
+ status: staged.status,
534
+ response_id: staged.responseId,
535
+ correlation_id: staged.correlationId,
536
+ speech: staged.speech,
537
+ });
538
+ });
539
+ app.post('/dev/approve-response', async (req, res) => {
540
+ const companionId = req.body?.companionId || Array.from(runtimes.keys())[0] || 'default';
541
+ const runtime = runtimes.get(companionId);
542
+ if (!runtime)
543
+ return res.status(404).json({ approved: false, error: 'Companion not found' });
544
+ let responseId = req.body?.responseId;
545
+ let correlationId = req.body?.correlation_id;
546
+ if (!responseId && correlationId) {
547
+ const found = runtime.findStagedPlanByCorrelation(companionId, correlationId);
548
+ if (found) {
549
+ responseId = found.responseId;
550
+ }
551
+ }
552
+ else if (responseId && !correlationId) {
553
+ const found = runtime.getStagedPlan(responseId);
554
+ if (found) {
555
+ correlationId = found.correlationId;
556
+ }
557
+ }
558
+ if (!responseId) {
559
+ return res.status(400).json({ approved: false, error: 'UNKNOWN_APPROVAL_ID' });
560
+ }
561
+ const result = runtime.approveResponse({
562
+ responseId,
563
+ companionId,
564
+ correlationId: correlationId || '',
565
+ });
566
+ if (!result.success) {
567
+ return res.status(400).json({ approved: false, error: result.reason });
568
+ }
569
+ // Now evaluated as approved
570
+ const evaluation = runtime.evaluateGate(result.plan);
571
+ res.json({
572
+ approved: true,
573
+ status: evaluation.disposition,
574
+ response_id: result.plan.responseId,
575
+ speech: result.plan.speech,
576
+ language: result.plan.language,
577
+ });
578
+ });
579
+ app.post('/dev/reject-response', async (req, res) => {
580
+ const companionId = req.body?.companionId || Array.from(runtimes.keys())[0] || 'default';
581
+ const runtime = runtimes.get(companionId);
582
+ if (!runtime)
583
+ return res.status(404).json({ rejected: false, error: 'Companion not found' });
584
+ let responseId = req.body?.responseId;
585
+ let correlationId = req.body?.correlation_id;
586
+ if (!responseId && correlationId) {
587
+ const found = runtime.findStagedPlanByCorrelation(companionId, correlationId);
588
+ if (found) {
589
+ responseId = found.responseId;
590
+ }
591
+ }
592
+ else if (responseId && !correlationId) {
593
+ const found = runtime.getStagedPlan(responseId);
594
+ if (found) {
595
+ correlationId = found.correlationId;
596
+ }
597
+ }
598
+ if (!responseId) {
599
+ return res.status(400).json({ rejected: false, error: 'UNKNOWN_APPROVAL_ID' });
600
+ }
601
+ const result = runtime.rejectResponse({
602
+ responseId,
603
+ companionId,
604
+ correlationId: correlationId || '',
605
+ reason: req.body?.reason,
606
+ });
607
+ if (!result.success) {
608
+ return res.status(400).json({ rejected: false, error: result.reason });
609
+ }
610
+ res.json({
611
+ rejected: true,
612
+ status: result.plan.status,
613
+ response_id: result.plan.responseId,
614
+ });
615
+ });
616
+ app.post('/dev/mock-observation', async (req, res) => {
617
+ const activeRuntime = Array.from(runtimes.values())[0];
618
+ const targetObs = activeRuntime?.observation || observationOrgan;
619
+ if (!targetObs)
620
+ return res.status(503).json({ accepted: false, reason: 'observation_unavailable' });
621
+ const result = await targetObs.ingest(new Uint8Array([115, 121, 110, 116, 104, 101, 116, 105, 99]), 'fixture-observation', 'configured-vision');
622
+ if (!result.observation)
623
+ return res.status(result.duplicate ? 200 : 409).json({ accepted: false, ...result });
624
+ res.status(202).json({ accepted: true, observation: result.observation });
625
+ });
626
+ }
627
+ return {
628
+ app,
629
+ runtimes,
630
+ setObservationOrgan: (org) => {
631
+ observationOrgan = org;
632
+ for (const r of runtimes.values()) {
633
+ r.observation = org;
634
+ }
635
+ },
636
+ };
637
+ }