ucode-agent 1.62.7 → 1.63.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/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -368,6 +368,7 @@ Everything after the frontmatter is the instruction.
368
368
  | `/undo` | put back every file the last turn changed |
369
369
  | `/look [url]` | open the running app and report what is on the page |
370
370
  | `/deploy [folder]` | put the app online and get its link |
371
+ | `/mic` | say what you want instead of typing it — same as `ctrl+t` |
371
372
  | `/stats` | time, steps and tokens this session |
372
373
  | `/doctor` | check that everything ucode needs is working |
373
374
  | `/skills` | what it knows how to do, and what is loaded |
@@ -380,6 +381,18 @@ Everything after the frontmatter is the instruction.
380
381
  `↑ ↓` scroll the conversation, or walk history once you are typing ·
381
382
  `tab` completes a command
382
383
 
384
+ ### Speak instead of typing
385
+
386
+ Press `ctrl+t` (or click `mic`, or type `/mic`) and say what you want —
387
+ "make me a quiz app about planets". The chip turns red while it listens.
388
+ `enter` stops and sends it; `ctrl+t` stops and puts the words in the box to
389
+ check first; `esc` throws it away. It stops by itself after two minutes.
390
+
391
+ Gemini writes down what you said, so nothing extra is needed beyond your key.
392
+ Recording uses what the computer already has: Windows' built-in recorder, `sox`
393
+ or `ffmpeg` on macOS (`brew install sox`), `arecord` or `sox` on Linux. If a
394
+ quiet mic is taken for silence, set `UCODE_MIC_QUIET` lower than 800.
395
+
383
396
  ## Options
384
397
 
385
398
  ```
@@ -456,7 +469,12 @@ The tests need no network and no framework — `node test/run.js` runs them all.
456
469
 
457
470
  ## Licence
458
471
 
459
- MIT — see [LICENSE](LICENSE). Made with ❤️ by om dixit.
472
+ Dual-licensed under either of, at your option:
473
+
474
+ - MIT — see [LICENSE](LICENSE)
475
+ - Apache License 2.0 — see [LICENSE-APACHE](LICENSE-APACHE)
476
+
477
+ Made with ❤️ by om dixit.
460
478
 
461
479
  The edit matchers, the summary template, the context-overflow and transient-error
462
480
  patterns and tool-name repair are adapted from
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ucode-agent",
3
- "version": "1.62.7",
3
+ "version": "1.63.0",
4
4
  "description": "ucode - a terminal coding agent that reads, edits and runs your code, on Google Gemini models.",
5
5
  "type": "module",
6
6
  "main": "ucode.js",
@@ -12,7 +12,8 @@
12
12
  "src/",
13
13
  "skills/",
14
14
  "templates/",
15
- "THIRD_PARTY_NOTICES.md"
15
+ "THIRD_PARTY_NOTICES.md",
16
+ "LICENSE-APACHE"
16
17
  ],
17
18
  "scripts": {
18
19
  "start": "node ucode.js",
@@ -42,7 +43,7 @@
42
43
  "ai"
43
44
  ],
44
45
  "author": "om dixit",
45
- "license": "MIT",
46
+ "license": "(MIT OR Apache-2.0)",
46
47
  "dependencies": {
47
48
  "@babel/parser": "^7.29.9",
48
49
  "chalk": "^6.0.0",
package/src/core/loop.js CHANGED
@@ -28,7 +28,7 @@ import { spawn } from 'node:child_process';
28
28
 
29
29
  import {
30
30
  ask, model, setModel, modelName, modelList, contextLimit, rateLimits,
31
- estimateConversation, MODELS, DEFAULT_MODEL, PROVIDER, fallbackFor, backupFor,
31
+ estimateConversation, MODELS, DEFAULT_MODEL, PROVIDER, fallbackFor, backupFor, transcribe,
32
32
  } from './provider.js';
33
33
  import {
34
34
  tools, runTool, describe, setRoot, setConfirm, setRequest,
@@ -54,6 +54,7 @@ import { MAX_FILE_OUTPUT } from '../tools/shared.js';
54
54
  import { openInBrowser } from './opener.js';
55
55
  import { withScope, isNoise } from './scope.js';
56
56
  import { chooseFile, projectFiles, loadAttachments } from './attach.js';
57
+ import { startRecording, isSilent, cleanTranscript, MAX_RECORD_MS } from './voice.js';
57
58
  import { runDoctor } from './doctor.js';
58
59
  import { JS_LOGIC } from './jslogic.js';
59
60
  import { deploy } from '../tools/deploy.js';
@@ -1028,6 +1029,7 @@ export class Agent {
1028
1029
  };
1029
1030
  this.ui.onModeChange = () => this.showHeader({ clear: false });
1030
1031
  this.ui.onAttach = () => { this.attachFile().catch(() => {}); };
1032
+ this.ui.onMic = (action) => { this.mic(action).catch((err) => this.ui.error(err, { debug: this.debug })); };
1031
1033
  }
1032
1034
 
1033
1035
  for (const problem of this.skills.problems ?? []) {
@@ -1827,6 +1829,59 @@ export class Agent {
1827
1829
  }
1828
1830
  }
1829
1831
 
1832
+ /**
1833
+ * The mic button (ctrl+t, a click, or /mic). 'toggle' starts listening, or
1834
+ * stops and puts the words in the box; 'send' stops and sends them; 'cancel'
1835
+ * throws the recording away.
1836
+ */
1837
+ async mic(action = 'toggle') {
1838
+ const state = this.ui.listening;
1839
+ if (state === 'starting' || state === 'writing') return;
1840
+
1841
+ if (state !== 'listening') {
1842
+ if (action !== 'toggle') return;
1843
+ this.ui.setListening('starting');
1844
+ try {
1845
+ this.recording = await startRecording();
1846
+ } catch (err) {
1847
+ this.ui.setListening(null);
1848
+ this.ui.note(`mic: ${err.message}`);
1849
+ return;
1850
+ }
1851
+ this.ui.setListening('listening');
1852
+ this.micTimer = setTimeout(() => this.ui.onMic?.('toggle'), MAX_RECORD_MS);
1853
+ return;
1854
+ }
1855
+
1856
+ clearTimeout(this.micTimer);
1857
+ // Taken and the state moved on before any await, so a second press
1858
+ // while this one finishes finds nothing to stop.
1859
+ const recording = this.recording;
1860
+ this.recording = null;
1861
+ if (!recording) return;
1862
+ if (action === 'cancel') {
1863
+ this.ui.setListening(null);
1864
+ this.ui.flash('stopped listening');
1865
+ await recording.cancel();
1866
+ return;
1867
+ }
1868
+
1869
+ this.ui.setListening('writing');
1870
+ let text = '';
1871
+ try {
1872
+ const wav = await recording.stop();
1873
+ if (!wav || isSilent(wav)) {
1874
+ this.ui.note('mic: heard nothing — check the microphone is on, then speak a little louder');
1875
+ return;
1876
+ }
1877
+ text = cleanTranscript(await transcribe(wav));
1878
+ if (!text) this.ui.note('mic: could not make out any words — try again, closer to the microphone');
1879
+ } finally {
1880
+ this.ui.setListening(null);
1881
+ }
1882
+ if (text) this.ui.insertText(text, { send: action === 'send' });
1883
+ }
1884
+
1830
1885
  /** Show a URL or a page in the project in the desktop browser (see opener.js). UCODE_OPEN=0 turns it off. */
1831
1886
  openInBrowser(target) {
1832
1887
  if (!this.full || process.env.UCODE_OPEN === '0') return false;
@@ -2961,6 +3016,9 @@ export class Agent {
2961
3016
  case '/doctor': return this.cmdDoctor();
2962
3017
  case '/look': return this.cmdLook(arg);
2963
3018
  case '/deploy': return this.cmdDeploy(arg);
3019
+ case '/mic':
3020
+ if (this.ui.onMic) return this.mic('toggle');
3021
+ return this.ui.note('the mic works in the full-screen view — start ucode in a terminal window');
2964
3022
  case '/exit':
2965
3023
  case '/quit': return 'exit';
2966
3024
 
@@ -3031,6 +3089,7 @@ ${out.content}` });
3031
3089
  ['/doctor', 'check that everything ucode needs is working'],
3032
3090
  ['/look [url]', 'open the running app and report what is on the page'],
3033
3091
  ['/deploy [folder]', 'put the app online and get its link'],
3092
+ ['/mic', 'say what you want instead of typing it (or ctrl+t)'],
3034
3093
  ['/model', 'show the models and switch between them'],
3035
3094
  ['/resume', 'pick up an earlier conversation'],
3036
3095
  ['/new', 'save this one and start fresh'],
@@ -3049,6 +3108,7 @@ ${out.content}` });
3049
3108
  this.ui.blank();
3050
3109
  this.ui.write(dim(' /models, /session and /sessions do the same as /model and /resume.'));
3051
3110
  this.ui.write(dim(' ctrl+b swaps plan and build · + file (or ctrl+o) adds a picture or file · esc stops a running turn · ctrl+d quits'));
3111
+ this.ui.write(dim(' ctrl+t (or the mic button) listens: speak, then enter to send, ctrl+t to check it first, esc to cancel'));
3052
3112
  this.ui.blank();
3053
3113
  }
3054
3114
 
@@ -276,6 +276,37 @@ export function resetConnection() {
276
276
  client = null;
277
277
  }
278
278
 
279
+ const TRANSCRIBE_PROMPT =
280
+ 'Transcribe the speech in this recording word for word, in the language spoken. ' +
281
+ 'Reply with only the words spoken - no quotes, no notes. If nothing is said, reply with nothing.';
282
+
283
+ /**
284
+ * Write down what was said in a WAV recording (the mic button). Uses the
285
+ * session's model, and the backup model when that one is overloaded.
286
+ */
287
+ export async function transcribe(wav, { timeout = 45_000 } = {}) {
288
+ const request = (id) => connection().chat.completions.create({
289
+ model: id,
290
+ messages: [{
291
+ role: 'user',
292
+ content: [
293
+ { type: 'text', text: TRANSCRIBE_PROMPT },
294
+ { type: 'input_audio', input_audio: { data: wav.toString('base64'), format: 'wav' } },
295
+ ],
296
+ }],
297
+ }, { timeout });
298
+
299
+ let res;
300
+ try {
301
+ res = await request(current);
302
+ } catch (err) {
303
+ const backup = backupFor(current);
304
+ if (!backup) throw explain(err, current);
305
+ res = await request(backup).catch((again) => { throw explain(again, backup); });
306
+ }
307
+ return res.choices?.[0]?.message?.content ?? '';
308
+ }
309
+
279
310
  // ---------------------------------------------------------------------------
280
311
  // Live quota, taken from whatever rate-limit headers come back
281
312
  // ---------------------------------------------------------------------------
@@ -0,0 +1,172 @@
1
+ /**
2
+ * voice.js — the mic button: say what you want instead of typing it.
3
+ *
4
+ * Recording uses what the computer already has, so there is nothing to
5
+ * install on Windows: its own sound recorder API (winmm, driven through
6
+ * PowerShell). macOS uses sox or ffmpeg, Linux arecord or sox, whichever is
7
+ * there. The recording is sent to the same Gemini model as everything else,
8
+ * which writes down what was said (see transcribe in provider.js).
9
+ */
10
+
11
+ import { spawn } from 'node:child_process';
12
+ import { promises as fs } from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+
16
+ /** Longest a recording runs before it stops by itself. */
17
+ export const MAX_RECORD_MS = 2 * 60_000;
18
+
19
+ /**
20
+ * Loudest sample (of 32767) below which a recording counts as silence. A quiet
21
+ * room measured ~400 on a laptop mic, speech ~3,000 and up. UCODE_MIC_QUIET
22
+ * tunes it for a mic that reads differently.
23
+ */
24
+ export const quietBelow = () => Number(process.env.UCODE_MIC_QUIET) || 800;
25
+
26
+ // winmm's MCI strings refuse long paths (error 304), so the file sits directly
27
+ // in the temp folder with a short name. The script says "ready" once it is
28
+ // recording, and saves when a line arrives on stdin.
29
+ const WINDOWS_SCRIPT = [
30
+ '$sig = \'[DllImport("winmm.dll", CharSet = CharSet.Unicode)] public static extern int mciSendString(string c, System.Text.StringBuilder r, int l, System.IntPtr h);\'',
31
+ '$w = Add-Type -MemberDefinition $sig -Name Mci -Namespace UcodeMic -PassThru',
32
+ 'function mci($c) { $r = $w::mciSendString($c, $null, 0, [IntPtr]::Zero); if ($r -ne 0) { [Console]::Out.WriteLine("mci-error $r"); exit 1 } }',
33
+ 'mci "open new type waveaudio alias ucodemic"',
34
+ 'mci "set ucodemic bitspersample 16 channels 1 samplespersec 16000 bytespersec 32000 alignment 2"',
35
+ 'mci "record ucodemic"',
36
+ '[Console]::Out.WriteLine("ready")',
37
+ '[void][Console]::In.ReadLine()',
38
+ 'mci "stop ucodemic"',
39
+ 'mci (\'save ucodemic "\' + $env:UCODE_MIC_FILE + \'"\')',
40
+ 'mci "close ucodemic"',
41
+ ].join('\n');
42
+
43
+ /**
44
+ * The recorders to try on this platform, in order. `stop` is how each is told
45
+ * to finish and write its file: a line on stdin, "q" on stdin, or SIGINT.
46
+ */
47
+ export function recordersFor(platform, file) {
48
+ if (platform === 'win32') {
49
+ const encoded = Buffer.from(WINDOWS_SCRIPT, 'utf16le').toString('base64');
50
+ return [{
51
+ cmd: 'powershell.exe',
52
+ args: ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
53
+ stop: 'line',
54
+ saysReady: true,
55
+ }];
56
+ }
57
+ const sox = { cmd: 'rec', args: ['-q', '-c', '1', '-r', '16000', '-b', '16', file], stop: 'SIGINT' };
58
+ if (platform === 'darwin') {
59
+ return [sox, {
60
+ cmd: 'ffmpeg',
61
+ args: ['-loglevel', 'error', '-f', 'avfoundation', '-i', ':0', '-ac', '1', '-ar', '16000', '-y', file],
62
+ stop: 'q',
63
+ }];
64
+ }
65
+ return [{ cmd: 'arecord', args: ['-q', '-f', 'S16_LE', '-r', '16000', '-c', '1', file], stop: 'SIGINT' }, sox];
66
+ }
67
+
68
+ const NO_RECORDER = {
69
+ darwin: 'No recorder found. Install one with: brew install sox',
70
+ linux: 'No recorder found. Install one with: sudo apt install alsa-utils',
71
+ };
72
+
73
+ /** Start one recorder; resolves once it is listening, rejects with the reason it could not. */
74
+ function launch(rec, file, run) {
75
+ return new Promise((resolve, reject) => {
76
+ const child = run(rec.cmd, rec.args, {
77
+ env: { ...process.env, UCODE_MIC_FILE: file },
78
+ windowsHide: true,
79
+ stdio: ['pipe', 'pipe', 'pipe'],
80
+ });
81
+ let out = '';
82
+ let settled = false;
83
+ const done = (fn, value) => { if (!settled) { settled = true; fn(value); } };
84
+
85
+ child.on('error', (err) => done(reject, err));
86
+ child.stdout?.on('data', (d) => {
87
+ out += d;
88
+ if (rec.saysReady && out.includes('ready')) done(resolve, child);
89
+ const code = /mci-error (\d+)/.exec(out)?.[1];
90
+ if (code) done(reject, new Error(`Windows could not use the microphone (error ${code}). Check one is plugged in and allowed in Settings › Privacy › Microphone.`));
91
+ });
92
+ child.on('exit', (code) => done(reject, new Error(`The recorder stopped before listening (exit ${code}). Check a microphone is connected.`)));
93
+ if (!rec.saysReady) child.on('spawn', () => done(resolve, child));
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Start recording from the default microphone.
99
+ * Resolves to { stop() → Promise<Buffer|null>, cancel() → Promise<void> } once listening.
100
+ */
101
+ export async function startRecording({ platform = process.platform, run = spawn, dir = os.tmpdir() } = {}) {
102
+ // A private folder of its own, so no other user can guess or pre-place the file.
103
+ const folder = await fs.mkdtemp(path.join(dir, 'ucm-'));
104
+ const file = path.join(folder, 'mic.wav');
105
+ const remove = () => fs.rm(folder, { recursive: true, force: true }).catch(() => {});
106
+
107
+ let child = null;
108
+ let rec = null;
109
+ try {
110
+ for (const candidate of recordersFor(platform, file)) {
111
+ try {
112
+ child = await launch(candidate, file, run);
113
+ rec = candidate;
114
+ break;
115
+ } catch (err) {
116
+ if (err.code !== 'ENOENT') throw err;
117
+ }
118
+ }
119
+ } catch (err) {
120
+ await remove();
121
+ throw err;
122
+ }
123
+ if (!child) {
124
+ await remove();
125
+ throw new Error(NO_RECORDER[platform] ?? 'No sound recorder found on this computer.');
126
+ }
127
+
128
+ const closed = new Promise((resolve) => child.on('close', resolve));
129
+ // A recorder that will not finish is killed rather than waited on forever.
130
+ const finished = async () => {
131
+ const timer = setTimeout(() => child.kill('SIGKILL'), 10_000);
132
+ await closed;
133
+ clearTimeout(timer);
134
+ };
135
+
136
+ return {
137
+ async stop() {
138
+ if (rec.stop === 'line') child.stdin.write('\n');
139
+ else if (rec.stop === 'q') child.stdin.write('q');
140
+ else child.kill('SIGINT');
141
+ await finished();
142
+ const wav = await fs.readFile(file).catch(() => null);
143
+ await remove();
144
+ return wav;
145
+ },
146
+ async cancel() {
147
+ child.kill();
148
+ await finished();
149
+ await remove();
150
+ },
151
+ };
152
+ }
153
+
154
+ /** True when a 16-bit PCM WAV holds nothing louder than room noise, or under a third of a second. */
155
+ export function isSilent(wav, threshold = quietBelow()) {
156
+ const at = wav.indexOf('data');
157
+ const start = at >= 0 ? at + 8 : 44;
158
+ if (wav.length - start < 16000 * 2 / 3) return true;
159
+ for (let i = start; i + 1 < wav.length; i += 2) {
160
+ if (Math.abs(wav.readInt16LE(i)) >= threshold) return false;
161
+ }
162
+ return true;
163
+ }
164
+
165
+ /** What the model heard, as one line for the input box: no quotes, no line breaks. */
166
+ export function cleanTranscript(text) {
167
+ return String(text ?? '')
168
+ .replace(/\s+/g, ' ')
169
+ .trim()
170
+ .replace(/^["'“”]+|["'“”]+$/g, '')
171
+ .trim();
172
+ }
package/src/ui/screen.js CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  theme, blue, sky, deep, dim, edge, ADDED, REMOVED, BANNER, BANNER_WIDTH, SPINNER,
41
41
  boxTop, boxBottom, boxRow, visLen, padVis, clip, wrapAnsi,
42
42
  shortenPath, asLabel, ensureColour, planLine, bare, narration, narrationMark, groupKind, groupLabel, groupTarget, runLine, planRows, tidyReply, trimAnswer,
43
- bannerPaint, RAIL, modeChip, ADD_CHIP, asNarrationLine } from './theme.js';
43
+ bannerPaint, RAIL, modeChip, ADD_CHIP, micChip, asNarrationLine } from './theme.js';
44
44
  import { FRAME_MS, spinnerGlyph, formatDuration, doneLine, workingLine, bannerSweep, SWEEP_MS } from './activity.js';
45
45
  import { gitBranch } from '../core/git.js';
46
46
  import { renderer, render } from './markdown.js';
@@ -60,7 +60,7 @@ export function isLabel(text) {
60
60
  export const COMMANDS = [
61
61
  '/help', '/model', '/models', '/session', '/sessions', '/resume',
62
62
  '/new', '/remember', '/skills', '/clear', '/search', '/copy', '/exit',
63
- '/stats', '/doctor', '/deploy', '/look', '/undo',
63
+ '/stats', '/doctor', '/deploy', '/look', '/undo', '/mic',
64
64
  ];
65
65
 
66
66
  // ANSI ----------------------------------------------------------------------
@@ -215,6 +215,12 @@ export class Screen {
215
215
  this.plusTo = 0;
216
216
  this.attachments = [];
217
217
  this.onAttach = null;
218
+ // The mic button: null when idle, else 'starting' | 'listening' | 'writing'.
219
+ // Ctrl+T starts and stops it; while it listens, enter stops and sends.
220
+ this.micFrom = 0;
221
+ this.micTo = 0;
222
+ this.listening = null;
223
+ this.onMic = null;
218
224
  this.onInterrupt = null;
219
225
  this.onModeChange = null;
220
226
  this.spinTimer = null;
@@ -808,7 +814,7 @@ export class Screen {
808
814
  ['dir', value(shortenPath(this.facts.cwd ?? this.cwd, room - 10))],
809
815
  branch && ['branch', value(branch)],
810
816
  VERSION && ['version', value(this.facts.update ? `${VERSION} → ${this.facts.update} next start` : VERSION)],
811
- ['keys', value('/help · esc interrupts · ctrl+b plan · ctrl+o file')],
817
+ ['keys', value('/help · ctrl+t mic · ctrl+o file · ctrl+b plan · esc stops')],
812
818
  ].filter(Boolean).slice(0, BANNER.length - 1);
813
819
 
814
820
  while (facts.length < BANNER.length - 1) facts.push(['', '']);
@@ -986,7 +992,8 @@ export class Screen {
986
992
  statusRow(width = this.width()) {
987
993
  const inner = width - 2; // the space between the two borders
988
994
  const chip = this.modeChip();
989
- const left = ` ${chip} ${ADD_CHIP} ${chalk.white(this.model || '—')}`;
995
+ const mic = micChip(this.listening);
996
+ const buttons = ` ${chip} ${ADD_CHIP} ${mic}`;
990
997
 
991
998
  // How long the turn has taken, back in the box beside the other two facts
992
999
  // about the session. It is not on the live line: that line says what is
@@ -996,16 +1003,24 @@ export class Screen {
996
1003
  const since = this.activity?.start ?? this.status.since ?? 0;
997
1004
  const running = this.busy() && since && now - since >= 1000;
998
1005
  const right = `${running ? `${dim(formatDuration(now - since))} ` : ''}${this.percentChip()} `;
1006
+ // On a narrow terminal the model name goes before any button does.
1007
+ const withModel = `${buttons} ${chalk.white(this.model || '—')}`;
1008
+ const left = visLen(withModel) + visLen(right) < inner ? withModel : buttons;
999
1009
 
1000
1010
  // Where a click on the bottom row still counts as hitting the mode chip.
1001
1011
  this.chipTo = 2 + visLen(chip);
1002
1012
  this.plusFrom = this.chipTo + 3; // after the two spaces
1003
1013
  this.plusTo = this.plusFrom + visLen(ADD_CHIP) - 1;
1014
+ this.micFrom = this.plusTo + 3;
1015
+ this.micTo = this.micFrom + visLen(mic) - 1;
1004
1016
 
1005
1017
  const between = Math.max(1, inner - visLen(left) - visLen(right));
1006
1018
  const files = this.attachments.map((f) => path.basename(f)).join(', ');
1007
- const middle = this.flashText ? dim(clip(this.flashText, between - 2))
1008
- : files ? sky(clip(`+ ${files}`, between - 2)) : '';
1019
+ // Room for the three spaces after it and at least one before.
1020
+ const room = between - 4;
1021
+ const middle = this.listening === 'listening' ? sky(clip('speak now · enter sends · ctrl+t stops · esc cancels', room))
1022
+ : this.flashText ? dim(clip(this.flashText, room))
1023
+ : files ? sky(clip(`+ ${files}`, room)) : '';
1009
1024
 
1010
1025
  const tail = middle ? `${middle} ` : '';
1011
1026
  const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
@@ -1430,12 +1445,30 @@ export class Screen {
1430
1445
  if (row !== statusRow) return;
1431
1446
  if (col > g.left + 1 && col <= g.left + this.chipTo) this.toggleMode();
1432
1447
  else if (col >= g.left + this.plusFrom && col <= g.left + this.plusTo) this.onAttach?.();
1448
+ else if (col >= g.left + this.micFrom && col <= g.left + this.micTo) this.onMic?.('toggle');
1433
1449
  return;
1434
1450
  }
1435
- // The mode chip and the "+ file" button, at the left of the bottom row.
1451
+ // The mode chip, "+ file" and mic buttons, at the left of the bottom row.
1436
1452
  if (row !== this.rows - 1) return;
1437
1453
  if (col >= 2 && col <= this.chipTo) this.toggleMode();
1438
1454
  else if (col >= this.plusFrom && col <= this.plusTo) this.onAttach?.();
1455
+ else if (col >= this.micFrom && col <= this.micTo) this.onMic?.('toggle');
1456
+ }
1457
+
1458
+ /** The mic's state, for the chip: null, 'starting', 'listening' or 'writing'. */
1459
+ setListening(state) {
1460
+ this.listening = state;
1461
+ this.render();
1462
+ }
1463
+
1464
+ /** Words from the mic, into the box at the cursor; `send` presses enter for them. */
1465
+ insertText(text, { send = false } = {}) {
1466
+ const before = this.buffer.slice(0, this.cursor);
1467
+ const joined = before && !before.endsWith(' ') ? `${before} ${text}` : before + text;
1468
+ this.buffer = joined + this.buffer.slice(this.cursor);
1469
+ this.cursor = joined.length;
1470
+ if (send) this.onKey('\r');
1471
+ else this.render();
1439
1472
  }
1440
1473
 
1441
1474
  /** A file chosen with "+ file", to go with the next message. */
@@ -1470,6 +1503,12 @@ export class Screen {
1470
1503
  return;
1471
1504
  }
1472
1505
 
1506
+ // While the mic listens, enter means "done, send it" and esc means "never mind".
1507
+ if (this.listening === 'listening') {
1508
+ if (key === '\r' || key === '\n') { this.onMic?.('send'); return; }
1509
+ if (key === ESC || key === '\x03') { this.onMic?.('cancel'); return; }
1510
+ }
1511
+
1473
1512
  switch (key) {
1474
1513
  case '\r':
1475
1514
  case '\n': {
@@ -1516,6 +1555,10 @@ export class Screen {
1516
1555
  this.onAttach?.();
1517
1556
  return;
1518
1557
 
1558
+ case '\x14': // ctrl+t — the mic button: start listening, or stop and put the words in the box
1559
+ this.onMic?.('toggle');
1560
+ return;
1561
+
1519
1562
  case '\x15': // ctrl+u — clear the line; on an empty line, the attached files
1520
1563
  if (!this.buffer) this.attachments = [];
1521
1564
  this.buffer = this.buffer.slice(this.cursor);
package/src/ui/theme.js CHANGED
@@ -130,6 +130,13 @@ export const modeChip = (mode) =>
130
130
  /** The "+ file" button beside the mode chip, in the quieter of the two chip styles. */
131
131
  export const ADD_CHIP = PLAN_CHIP(' + file ');
132
132
 
133
+ /** The mic button beside it: quiet when idle, red while it is listening. */
134
+ const LISTEN_CHIP = chalk.bgHex('#e5484d').hex('#ffffff').bold;
135
+ export const micChip = (state) =>
136
+ state === 'listening' ? LISTEN_CHIP(' ● listening ')
137
+ : state ? PLAN_CHIP(` ${state === 'starting' ? 'starting' : 'writing'}… `)
138
+ : PLAN_CHIP(' mic ');
139
+
133
140
  /** The spinner. Braille dots, because they animate in place without jitter. */
134
141
  export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
135
142