@ramme-io/create-app 3.3.1 → 3.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ramme-io/create-app",
3
- "version": "3.3.1",
3
+ "version": "3.4.0",
4
4
  "description": "The official CLI to create Ramme applications.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,5 +1,21 @@
1
1
  # ramme-starter
2
2
 
3
+ ## 2.0.27
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [3e265ac]
8
+ - @ramme-io/shared@4.1.0
9
+ - @ramme-io/kernel@8.1.1
10
+ - @ramme-io/ui@5.0.1
11
+
12
+ ## 2.0.26
13
+
14
+ ### Patch Changes
15
+
16
+ - Updated dependencies [e982562]
17
+ - @ramme-io/kernel@8.1.0
18
+
3
19
  ## 2.0.25
4
20
 
5
21
  ### Patch Changes
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ramme-starter",
3
3
  "private": true,
4
- "version": "2.0.25",
4
+ "version": "2.0.27",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "vite",
@@ -1,5 +1,12 @@
1
1
  # ramme-home
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [3e265ac]
8
+ - @ramme-io/shared@4.1.0
9
+
3
10
  ## 0.1.1
4
11
 
5
12
  ### Patch Changes
@@ -28,6 +28,21 @@ Firmware updates still come only from ramme.io, whatever server a board talks to
28
28
  claude mcp add ramme --env RAMME_API_URL=http://localhost:3000 --env RAMME_TOKEN=rmh_… -- npx -y @ramme-io/devkit mcp
29
29
  ```
30
30
 
31
+ ## Voice
32
+
33
+ A board with a talk button sends a short clip while the button is held (never otherwise), and this server turns it into text. It does that **on this machine**, so your voice stays in the house. Without a speech-to-text program it tells the board voice is off.
34
+
35
+ Any program that takes a WAV file and prints the words will do. [whisper.cpp](https://github.com/ggml-org/whisper.cpp) is free, runs offline, and is quick on an Apple Silicon Mac:
36
+
37
+ 1. Install it (`brew install whisper-cpp` on a Mac) and download a model, such as `ggml-base.en.bin` from its models page.
38
+ 2. Start this server with the command in `RAMME_TRANSCRIBE`. `{clip}` is replaced with the clip's path. The command is split on spaces, so keep the model in a path without any:
39
+
40
+ ```bash
41
+ RAMME_TRANSCRIBE="whisper-cli -m /path/to/ggml-base.en.bin -nt -np -f {clip}" pnpm start
42
+ ```
43
+
44
+ `pnpm start` says whether voice is on. What a board last heard shows in its vitals (`/api/device/vitals?id=…`, `heard`), so a coding agent can act on it. As local models improve, swap the model or the program; nothing on the board changes.
45
+
31
46
  ## What is here
32
47
 
33
48
  | file | what it is |
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ramme-home",
3
3
  "private": true,
4
- "version": "0.1.1",
4
+ "version": "0.1.2",
5
5
  "type": "module",
6
6
  "description": "Your own Ramme server: boards on your network talk to this instead of ramme.io.",
7
7
  "scripts": {
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * Two kinds of caller:
9
9
  *
10
- * boards the four calls in DEVICE_PROTOCOL (@ramme-io/shared) — the same
10
+ * boards the five calls in DEVICE_PROTOCOL (@ramme-io/shared) — the same
11
11
  * calls, answered the same way, as ramme.io. server.test.mjs holds
12
12
  * this file to them.
13
13
  * you the page at / (your boards, and a box to send an app), and the
@@ -19,22 +19,31 @@
19
19
  * There are no accounts. Firmware updates are not here on purpose: a board
20
20
  * takes firmware only from ramme.io, whatever server it talks to.
21
21
  *
22
+ * Voice: a board holding its talk button sends a short clip, and this server
23
+ * turns it into text on this machine — the clip never leaves your network. It
24
+ * needs a speech-to-text program you choose, named in RAMME_TRANSCRIBE (see
25
+ * README.md, "Voice"); without one, a board is told voice is off here.
26
+ *
22
27
  * Everything is kept in one JSON file (data.json by default), readable and
23
28
  * editable by hand while the server is stopped.
24
29
  */
25
30
  import { createServer } from 'node:http';
26
31
  import { randomBytes } from 'node:crypto';
27
- import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
28
- import { networkInterfaces } from 'node:os';
32
+ import { execFile } from 'node:child_process';
33
+ import { promisify } from 'node:util';
34
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, renameSync } from 'node:fs';
35
+ import { networkInterfaces, tmpdir } from 'node:os';
29
36
  import { dirname, join } from 'node:path';
30
37
  import { fileURLToPath } from 'node:url';
31
38
  import {
32
39
  AppDocumentSchema,
33
40
  DEVICE_PROTOCOL,
41
+ DEVICE_VOICE_CLIP,
34
42
  DeviceIdSchema,
35
43
  DevicePollReplySchema,
36
44
  DeviceRegistrationSchema,
37
45
  DeviceReportSchema,
46
+ DeviceVoiceReplySchema,
38
47
  } from '@ramme-io/shared';
39
48
 
40
49
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -73,13 +82,46 @@ const openStore = file => {
73
82
  return { data, save, board: id => (data.boards[id] ??= { deviceId: id }) };
74
83
  };
75
84
 
85
+ /**
86
+ * A transcriber from a command line, for RAMME_TRANSCRIBE: the clip is written
87
+ * to a temporary file whose path replaces `{clip}` (or goes last), and what the
88
+ * program prints is the text. Run directly, never through a shell, so nothing
89
+ * in a clip's path can become a command.
90
+ */
91
+ export const commandTranscriber = command => {
92
+ if (!command?.trim()) return undefined;
93
+ const [bin, ...args] = command.trim().split(/\s+/);
94
+ const run = promisify(execFile);
95
+ return async wav => {
96
+ const dir = mkdtempSync(join(tmpdir(), 'ramme-voice-'));
97
+ const clip = join(dir, 'clip.wav');
98
+ writeFileSync(clip, wav);
99
+ try {
100
+ const argv = args.includes('{clip}') ? args.map(a => (a === '{clip}' ? clip : a)) : [...args, clip];
101
+ const { stdout } = await run(bin, argv, { timeout: 60_000, maxBuffer: 1 << 20 });
102
+ return stdout.replace(/\s+/g, ' ').trim();
103
+ } finally {
104
+ rmSync(dir, { recursive: true, force: true });
105
+ }
106
+ };
107
+ };
108
+
109
+ /** RIFF…WAVE: the only shape `voice` takes, checked before anything runs on it. */
110
+ const isWav = bytes =>
111
+ Buffer.isBuffer(bytes) && bytes.length > 44 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WAVE';
112
+
76
113
  const json = (status, body) => ({ status, body: body === undefined ? undefined : JSON.stringify(body), type: 'application/json' });
77
114
 
78
115
  /**
79
116
  * The server's logic, as a function from a request to an answer, so a test can
80
117
  * call it without opening a port. `now` is injectable for the same reason.
81
118
  */
82
- export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HERE, 'photos'), now = () => Date.now() } = {}) => {
119
+ export const createHandler = ({
120
+ file = join(HERE, 'data.json'),
121
+ photos = join(HERE, 'photos'),
122
+ now = () => Date.now(),
123
+ transcribe = commandTranscriber(process.env.RAMME_TRANSCRIBE),
124
+ } = {}) => {
83
125
  const store = openStore(file);
84
126
  const page = () => readFileSync(join(HERE, 'page.html'), 'utf8');
85
127
 
@@ -145,6 +187,28 @@ export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HE
145
187
  return { status: 200, bytes: readFileSync(path), type: 'application/octet-stream' };
146
188
  },
147
189
 
190
+ [`POST ${DEVICE_PROTOCOL.voice.path}`]: async ({ query, raw }) => {
191
+ const id = DeviceIdSchema.safeParse(query.get('id'));
192
+ if (!id.success) return json(400, { error: 'BAD_DEVICE_ID' });
193
+ // Said before the clip is looked at: a board with nowhere to send its
194
+ // voice should learn that from its first press, not its tenth.
195
+ if (!transcribe) return json(501, { error: 'NO_TRANSCRIBER', message: 'Voice is off on this server: set RAMME_TRANSCRIBE.' });
196
+ const board = store.data.boards[id.data];
197
+ if (!board) return json(403, { error: 'NOT_ALLOWED', message: 'Register first.' });
198
+ if (raw && raw.length > DEVICE_VOICE_CLIP.maxBytes) return json(413, { error: 'CLIP_TOO_LONG' });
199
+ if (!isWav(raw)) return json(400, { error: 'BAD_CLIP', message: `Send ${DEVICE_VOICE_CLIP.contentType}.` });
200
+ let text;
201
+ try {
202
+ text = (await transcribe(raw)).slice(0, 2000);
203
+ } catch (e) {
204
+ return json(502, { error: 'TRANSCRIBE_FAILED', message: e instanceof Error ? e.message.slice(0, 200) : 'failed' });
205
+ }
206
+ // Kept, so the page and a coding agent (vitals) can see what was said.
207
+ board.heard = { text, at: now() };
208
+ store.save();
209
+ return json(200, DeviceVoiceReplySchema.parse({ text }));
210
+ },
211
+
148
212
  // ── what you call: the page and the devkit ───────────────────────────────
149
213
  'GET /': () => ({ status: 200, body: page(), type: 'text/html; charset=utf-8' }),
150
214
 
@@ -163,7 +227,7 @@ export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HE
163
227
  'GET /api/device/vitals': ({ query }) => {
164
228
  const board = store.data.boards[query.get('id') ?? ''];
165
229
  if (!board) return json(404, { error: 'NOT_FOUND' });
166
- return json(200, { vitals: board.vitals ?? {}, readings: board.readings ?? [] });
230
+ return json(200, { vitals: board.vitals ?? {}, readings: board.readings ?? [], ...(board.heard ? { heard: board.heard } : {}) });
167
231
  },
168
232
 
169
233
  'POST /api/device/send': ({ headers, body }) => {
@@ -183,8 +247,12 @@ export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HE
183
247
  },
184
248
  };
185
249
 
186
- /** One request in, one answer out. `body` is already parsed JSON. */
187
- return ({ method, url, headers = {}, body = {} }) => {
250
+ /**
251
+ * One request in, one answer out. `body` is already parsed JSON; `raw` is
252
+ * the bytes, for the one call whose body is not JSON (voice). Every answer is
253
+ * immediate except voice's, which is a promise.
254
+ */
255
+ return ({ method, url, headers = {}, body = {}, raw }) => {
188
256
  const u = new URL(url, 'http://localhost');
189
257
  // The example apps, so the page can start you off with one.
190
258
  const example = method === 'GET' && /^\/apps\/([a-z0-9-]+)\.json$/.exec(u.pathname);
@@ -194,7 +262,7 @@ export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HE
194
262
  }
195
263
  const route = routes[`${method} ${u.pathname}`];
196
264
  if (!route) return json(404, { error: 'NOT_FOUND' });
197
- return route({ query: u.searchParams, headers, body: body && typeof body === 'object' ? body : {} });
265
+ return route({ query: u.searchParams, headers, body: body && typeof body === 'object' ? body : {}, raw });
198
266
  };
199
267
  };
200
268
 
@@ -202,21 +270,28 @@ export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HE
202
270
  export const startServer = ({ port = Number(process.env.PORT ?? 3000), ...options } = {}) => {
203
271
  const handle = createHandler(options);
204
272
  const server = createServer((req, res) => {
273
+ const voice = new URL(req.url, 'http://localhost').pathname === DEVICE_PROTOCOL.voice.path;
274
+ const limit = voice ? DEVICE_VOICE_CLIP.maxBytes : MAX_BODY;
205
275
  const chunks = [];
206
276
  let size = 0;
207
277
  req.on('data', c => {
208
278
  size += c.length;
209
- if (size > MAX_BODY) req.destroy();
210
- else chunks.push(c);
279
+ if (size <= limit) return void chunks.push(c);
280
+ if (voice && !res.headersSent) {
281
+ res.writeHead(413, { 'content-type': 'application/json' });
282
+ res.end(JSON.stringify({ error: 'CLIP_TOO_LONG' }));
283
+ }
284
+ req.destroy();
211
285
  });
212
- req.on('end', () => {
286
+ req.on('end', async () => {
287
+ const raw = Buffer.concat(chunks);
213
288
  let body = {};
214
289
  try {
215
- body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
290
+ body = chunks.length && !voice ? JSON.parse(raw.toString('utf8')) : {};
216
291
  } catch {
217
292
  // Left empty: each route answers a missing body with its own 400.
218
293
  }
219
- const out = handle({ method: req.method, url: req.url, headers: req.headers, body });
294
+ const out = await handle({ method: req.method, url: req.url, headers: req.headers, body, ...(voice ? { raw } : {}) });
220
295
  res.writeHead(out.status, out.type && out.status !== 204 && out.status !== 304 ? { 'content-type': out.type } : {});
221
296
  res.end(out.bytes ?? out.body);
222
297
  });
@@ -238,5 +313,10 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
238
313
  console.log(`\nRamme is running on port ${port}.\n`);
239
314
  for (const ip of lanAddresses()) console.log(` On a board's setup page, set Server to: http://${ip}:${port}`);
240
315
  console.log(` Your boards, in a browser: http://localhost:${port}`);
316
+ console.log(
317
+ process.env.RAMME_TRANSCRIBE?.trim()
318
+ ? ` Voice: on, transcribed on this machine by ${process.env.RAMME_TRANSCRIBE.trim().split(/\s+/)[0]}`
319
+ : ' Voice: off (set RAMME_TRANSCRIBE to turn it on; see README.md)',
320
+ );
241
321
  console.log(`\n For the devkit: RAMME_API_URL=http://localhost:${port} RAMME_TOKEN=${token}\n`);
242
322
  }
@@ -11,8 +11,8 @@ import { describe, it, expect, beforeEach } from 'vitest';
11
11
  import { mkdtempSync, readFileSync, readdirSync } from 'node:fs';
12
12
  import { tmpdir } from 'node:os';
13
13
  import { join } from 'node:path';
14
- import { AppDocumentSchema, DEVICE_PROTOCOL, DevicePollReplySchema } from '@ramme-io/shared';
15
- import { createHandler } from './server.mjs';
14
+ import { AppDocumentSchema, DEVICE_PROTOCOL, DEVICE_VOICE_CLIP, DevicePollReplySchema, DeviceVoiceReplySchema } from '@ramme-io/shared';
15
+ import { commandTranscriber, createHandler } from './server.mjs';
16
16
 
17
17
  const ID = 'A7K2M9QP';
18
18
  const CODE = '4821';
@@ -97,6 +97,74 @@ describe('sending', () => {
97
97
  });
98
98
  });
99
99
 
100
+ /** A WAV of `seconds` of silence, in the shape DEVICE_VOICE_CLIP names. */
101
+ const wav = seconds => {
102
+ const data = DEVICE_VOICE_CLIP.sampleRate * 2 * seconds;
103
+ const b = Buffer.alloc(44 + data);
104
+ b.write('RIFF', 0, 'ascii');
105
+ b.writeUInt32LE(36 + data, 4);
106
+ b.write('WAVEfmt ', 8, 'ascii');
107
+ b.writeUInt32LE(16, 16);
108
+ b.writeUInt16LE(1, 20);
109
+ b.writeUInt16LE(1, 22);
110
+ b.writeUInt32LE(DEVICE_VOICE_CLIP.sampleRate, 24);
111
+ b.writeUInt32LE(DEVICE_VOICE_CLIP.sampleRate * 2, 28);
112
+ b.writeUInt16LE(2, 32);
113
+ b.writeUInt16LE(16, 34);
114
+ b.write('data', 36, 'ascii');
115
+ b.writeUInt32LE(data, 40);
116
+ return b;
117
+ };
118
+
119
+ describe('voice', () => {
120
+ const speak = async (raw, id = ID) => {
121
+ const out = await handle({ method: 'POST', url: `${DEVICE_PROTOCOL.voice.path}?id=${id}`, raw });
122
+ return { ...out, json: out.body ? JSON.parse(out.body) : undefined };
123
+ };
124
+ const listening = heard => {
125
+ handle = createHandler({ file, now: () => clock, transcribe: async () => heard });
126
+ };
127
+
128
+ it('is off, and says so, until a transcriber is set', async () => {
129
+ handle = createHandler({ file, now: () => clock, transcribe: null });
130
+ register();
131
+ expect(await speak(wav(1))).toMatchObject({ status: 501, json: { error: 'NO_TRANSCRIBER' } });
132
+ });
133
+
134
+ it('turns a clip into text, and keeps what it heard for the devkit', async () => {
135
+ listening('show the soil moisture as a gauge');
136
+ register();
137
+ const r = await speak(wav(2));
138
+ expect(r.status).toBe(200);
139
+ expect(DeviceVoiceReplySchema.parse(r.json)).toEqual({ text: 'show the soil moisture as a gauge' });
140
+ expect(call('GET', `/api/device/vitals?id=${ID}`).json.heard).toEqual({ text: 'show the soil moisture as a gauge', at: clock });
141
+ });
142
+
143
+ it('refuses what is not a clip from a board it knows', async () => {
144
+ listening('hello');
145
+ expect((await speak(wav(1), 'nope')).status).toBe(400);
146
+ expect((await speak(wav(1))).status).toBe(403); // never registered
147
+ register();
148
+ expect(await speak(Buffer.from('not a wav at all, just some bytes that are long enough to pass'))).toMatchObject({ status: 400, json: { error: 'BAD_CLIP' } });
149
+ expect((await speak(wav(DEVICE_VOICE_CLIP.maxSeconds + 1))).status).toBe(413);
150
+ expect((await speak(wav(DEVICE_VOICE_CLIP.maxSeconds))).status).toBe(200);
151
+ });
152
+
153
+ it('says so when the transcriber fails', async () => {
154
+ handle = createHandler({ file, now: () => clock, transcribe: async () => { throw new Error('model missing'); } });
155
+ register();
156
+ expect(await speak(wav(1))).toMatchObject({ status: 502, json: { error: 'TRANSCRIBE_FAILED' } });
157
+ });
158
+
159
+ it('runs a command line with the clip in place of {clip}, and reads what it prints', async () => {
160
+ // `node -e` stands in for whisper-cli: it prints the clip's size.
161
+ const run = commandTranscriber(`${process.execPath} -e process.stdout.write(String(require('fs').statSync(process.argv[1]).size)) {clip}`);
162
+ expect(await run(wav(1))).toBe(String(44 + DEVICE_VOICE_CLIP.sampleRate * 2));
163
+ expect(commandTranscriber('')).toBeUndefined();
164
+ expect(commandTranscriber(undefined)).toBeUndefined();
165
+ });
166
+ });
167
+
100
168
  describe('the devkit', () => {
101
169
  it('lists boards without their codes', () => {
102
170
  register();