@wirecat/cli-core 0.663.0 → 0.665.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.
Files changed (109) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/index.d.ts +1 -1
  4. package/dist/calendar/index.js +1 -1
  5. package/dist/calendar/prepare.d.ts +2 -2
  6. package/dist/calendar/reads.d.ts +5 -5
  7. package/dist/calendar/writes.d.ts +4 -4
  8. package/dist/cli/chat-sending-command.d.ts +14 -0
  9. package/dist/cli/chat-sending-command.js +64 -0
  10. package/dist/cli/context.d.ts +7 -0
  11. package/dist/cli/context.js +12 -4
  12. package/dist/cli/index.d.ts +2 -0
  13. package/dist/cli/index.js +2 -0
  14. package/dist/cli/meeting-meaning-command.d.ts +47 -0
  15. package/dist/cli/meeting-meaning-command.js +136 -0
  16. package/dist/cli/meeting-preparation-answer.d.ts +6 -0
  17. package/dist/cli/meeting-preparation-projects.d.ts +6 -0
  18. package/dist/cli/meeting-preparation-read.d.ts +6 -0
  19. package/dist/cli/meeting-tags-command.d.ts +18 -0
  20. package/dist/cli/meeting-tags-command.js +74 -0
  21. package/dist/cli/messenger/conversation-answers.d.ts +1 -1
  22. package/dist/cli/messenger/conversation-answers.js +1 -0
  23. package/dist/cli/messenger/conversations-command.js +38 -12
  24. package/dist/cli/messenger/models-command.js +7 -0
  25. package/dist/cli/messenger/records-command.d.ts +4 -1
  26. package/dist/cli/messenger/records-command.js +6 -1
  27. package/dist/cli/model-catalogue-command.js +2 -0
  28. package/dist/cli/profile-token.d.ts +15 -1
  29. package/dist/cli/profile-token.js +103 -7
  30. package/dist/cli/program.js +2 -2
  31. package/dist/domain/links.d.ts +11 -0
  32. package/dist/domain/links.js +4 -0
  33. package/dist/entities/chat-sending.d.ts +10 -0
  34. package/dist/entities/chat-sending.js +11 -0
  35. package/dist/entities/index.d.ts +43 -1
  36. package/dist/entities/index.js +6 -2
  37. package/dist/entities/listings.d.ts +60 -0
  38. package/dist/entities/listings.js +15 -0
  39. package/dist/entities/meeting-preparation.d.ts +6 -0
  40. package/dist/entities/meeting.d.ts +1 -1
  41. package/dist/entities/meeting.js +1 -1
  42. package/dist/errors/reasons.js +25 -1
  43. package/dist/mcp/meeting-preparation.d.ts +6 -0
  44. package/dist/meetings/answers.d.ts +7 -0
  45. package/dist/meetings/answers.js +4 -0
  46. package/dist/meetings/event-store.d.ts +2 -1
  47. package/dist/meetings/event-store.js +6 -0
  48. package/dist/meetings/index.d.ts +2 -1
  49. package/dist/meetings/index.js +2 -1
  50. package/dist/meetings/mcp/search.d.ts +6 -0
  51. package/dist/meetings/project-evidence-answer.d.ts +6 -0
  52. package/dist/meetings/tag-answers.d.ts +43 -0
  53. package/dist/meetings/tag-answers.js +41 -0
  54. package/dist/models/chat-sending.d.ts +24 -0
  55. package/dist/models/chat-sending.js +40 -0
  56. package/dist/runs/events.d.ts +1 -1
  57. package/dist/search/question-plan.d.ts +5 -0
  58. package/dist/search/question-plan.js +5 -0
  59. package/dist/search/task-similarity.d.ts +1 -0
  60. package/dist/search/task-similarity.js +1 -1
  61. package/dist/services/embeddings-search.js +19 -5
  62. package/dist/services/embeddings.d.ts +4 -0
  63. package/dist/services/index.d.ts +2 -0
  64. package/dist/services/index.js +2 -0
  65. package/dist/services/listings.js +17 -2
  66. package/dist/services/meeting-meaning.d.ts +47 -0
  67. package/dist/services/meeting-meaning.js +158 -0
  68. package/dist/services/meeting-tags.d.ts +27 -0
  69. package/dist/services/meeting-tags.js +81 -0
  70. package/dist/services/messages-discovery.js +2 -2
  71. package/dist/sftp/index.d.ts +1 -1
  72. package/dist/sftp/index.js +1 -1
  73. package/dist/sftp/session.d.ts +30 -4
  74. package/dist/sftp/session.js +195 -11
  75. package/dist/sftp/ssh2.d.ts +19 -4
  76. package/dist/sftp/ssh2.js +144 -17
  77. package/dist/speech/cloud.d.ts +47 -0
  78. package/dist/speech/cloud.js +73 -0
  79. package/dist/speech/decode.d.ts +36 -9
  80. package/dist/speech/decode.js +208 -61
  81. package/dist/speech/index.d.ts +2 -1
  82. package/dist/speech/index.js +2 -1
  83. package/dist/speech/openai.d.ts +4 -0
  84. package/dist/speech/openai.js +13 -12
  85. package/dist/sql/index.d.ts +1 -0
  86. package/dist/sql/index.js +1 -0
  87. package/dist/sql/reader.d.ts +95 -0
  88. package/dist/sql/reader.js +214 -0
  89. package/dist/store/sqlite/drizzle/bun.js +4 -4
  90. package/dist/store/sqlite/drizzle/bun.js.map +1 -1
  91. package/dist/store/sqlite/drizzle/core.js +5 -5
  92. package/dist/store/sqlite/drizzle/core.js.map +1 -1
  93. package/dist/store/sqlite/drizzle/node.js +4 -4
  94. package/dist/store/sqlite/drizzle/node.js.map +1 -1
  95. package/dist/store/sqlite/drizzle/{shared-55XJMTPA.js → shared-5XR7K42U.js} +58 -58
  96. package/dist/store/sqlite/drizzle/{shared-55XJMTPA.js.map → shared-5XR7K42U.js.map} +1 -1
  97. package/dist/store/sqlite/knowledge.d.ts +1 -1
  98. package/dist/store/sqlite/knowledge.js +8 -4
  99. package/dist/store/sqlite/labelled.d.ts +5 -0
  100. package/dist/store/sqlite/labelled.js +6 -0
  101. package/dist/store/sqlite/link-row.d.ts +1 -0
  102. package/dist/store/sqlite/link-row.js +2 -0
  103. package/dist/store/sqlite/meeting-listing.d.ts +12 -0
  104. package/dist/store/sqlite/meeting-listing.js +20 -5
  105. package/dist/store/sqlite/notes.d.ts +1 -1
  106. package/dist/store/sqlite/notes.js +1 -1
  107. package/package.json +18 -3
  108. package/parity.json +20 -1
  109. package/skills/link-conversations/SKILL.md +1 -1
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { createRequire } from "node:module";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
@@ -76,65 +76,167 @@ const decodeMp3 = async (bytes) => {
76
76
  decoder.free();
77
77
  }
78
78
  };
79
+ const tooLongError = () => new CliError("validation_error", `the audio is longer than ${LONGEST_AUDIO_SECONDS / 60} minutes`);
80
+ const FLOAT = 3;
81
+ const LONGEST_HEADER = 64 * 1024;
82
+ const EXTENSIBLE = 0xfffe;
79
83
  /**
80
- * The owner's own ffmpeg, for what no bundled decoder reads — AAC above all, which every small decoder does under
81
- * the GPL. From a file rather than a pipe: an MP4 whose index sits at the end cannot be read from a pipe.
84
+ * The 32-bit float WAV ffmpeg writes to a pipe, read as it arrives: each channel's samples go to their own array at
85
+ * once, so the interleaved bytes are never held whole. ffmpeg cannot seek back on a pipe, so the sizes in the header
86
+ * are placeholders and the samples run to the end of the stream. `push` answers false once a channel passes `most`
87
+ * samples.
82
88
  */
89
+ export const wavStream = (most) => {
90
+ let head = Buffer.alloc(0);
91
+ let channels = 0;
92
+ let rate = 0;
93
+ let rest = Buffer.alloc(0);
94
+ let length = 0;
95
+ let parts = [];
96
+ const header = () => {
97
+ if (head.length < 12)
98
+ return false;
99
+ if (head.toString("latin1", 0, 4) !== "RIFF" || head.toString("latin1", 8, 12) !== "WAVE")
100
+ throw new CliError("validation_error", "ffmpeg did not answer with WAV audio");
101
+ for (let at = 12; at + 8 <= head.length;) {
102
+ const id = head.toString("latin1", at, at + 4);
103
+ const size = head.readUInt32LE(at + 4);
104
+ if (id === "data") {
105
+ rest = head.subarray(at + 8);
106
+ head = Buffer.alloc(0);
107
+ return true;
108
+ }
109
+ if (at + 8 + size > head.length)
110
+ return false;
111
+ if (id === "fmt ") {
112
+ const tag = head.readUInt16LE(at + 8);
113
+ channels = head.readUInt16LE(at + 10);
114
+ rate = head.readUInt32LE(at + 12);
115
+ if ((tag !== FLOAT && tag !== EXTENSIBLE) || head.readUInt16LE(at + 22) !== 32 || channels < 1)
116
+ throw new CliError("validation_error", "ffmpeg did not answer with 32-bit float samples");
117
+ parts = Array.from({ length: channels }, () => []);
118
+ }
119
+ at += 8 + size + (size % 2);
120
+ }
121
+ return false;
122
+ };
123
+ return {
124
+ push: (chunk) => {
125
+ if (channels === 0 || head.length > 0) {
126
+ head = Buffer.concat([head, chunk]);
127
+ if (head.length > LONGEST_HEADER)
128
+ throw new CliError("validation_error", "ffmpeg's WAV header never ended");
129
+ if (!header())
130
+ return true;
131
+ chunk = Buffer.alloc(0);
132
+ }
133
+ const bytes = rest.length ? Buffer.concat([rest, chunk]) : chunk;
134
+ const frame = channels * 4;
135
+ const frames = Math.floor(bytes.length / frame);
136
+ rest = Buffer.from(bytes.subarray(frames * frame));
137
+ if (frames === 0)
138
+ return length <= most;
139
+ const view = new DataView(bytes.buffer, bytes.byteOffset, frames * frame);
140
+ for (let channel = 0; channel < channels; channel++) {
141
+ const samples = new Float32Array(frames);
142
+ for (let index = 0; index < frames; index++)
143
+ samples[index] = view.getFloat32(index * frame + channel * 4, true);
144
+ parts[channel]?.push(samples);
145
+ }
146
+ length += frames;
147
+ return length <= most;
148
+ },
149
+ end: () => {
150
+ if (channels === 0)
151
+ throw new CliError("validation_error", "no audio in that file");
152
+ return parts.map((pieces, channel) => {
153
+ const samples = new Float32Array(length);
154
+ let at = 0;
155
+ for (const piece of pieces) {
156
+ samples.set(piece, at);
157
+ at += piece.length;
158
+ }
159
+ // Each channel's pieces are let go once joined, so the peak stays near one copy of the samples, not two.
160
+ parts[channel] = [];
161
+ return { samples, rate };
162
+ });
163
+ },
164
+ };
165
+ };
166
+ /**
167
+ * The owner's own ffmpeg on a file, for what no bundled decoder reads — AAC above all, which every small decoder does
168
+ * under the GPL; Asterisk's WAV and GSM too. A mono file stays one channel and a stereo call two, one speaker each; a
169
+ * file of more channels is mixed down to two. From a file rather than a pipe: an MP4 whose index sits at the end
170
+ * cannot be read from a pipe. Stops past an hour of audio, so a channel holds at most an hour of 16 kHz samples.
171
+ */
172
+ export const runFfmpegFile = (path) => new Promise((resolve, reject) => {
173
+ const child = spawn("ffmpeg", [
174
+ "-nostdin",
175
+ "-hide_banner",
176
+ "-loglevel",
177
+ "error",
178
+ "-protocol_whitelist",
179
+ "file",
180
+ "-format_whitelist",
181
+ FFMPEG_FORMATS,
182
+ "-i",
183
+ path,
184
+ "-vn",
185
+ "-af",
186
+ "aformat=channel_layouts=mono|stereo",
187
+ "-ar",
188
+ String(SAMPLE_RATE),
189
+ "-c:a",
190
+ "pcm_f32le",
191
+ "-bitexact",
192
+ "-f",
193
+ "wav",
194
+ "pipe:1",
195
+ ], { stdio: ["ignore", "pipe", "pipe"], timeout: FFMPEG_TIMEOUT_MS });
196
+ const wav = wavStream(LONGEST_AUDIO_SECONDS * SAMPLE_RATE);
197
+ let long = false;
198
+ let broken;
199
+ let errors = "";
200
+ child.stdout.on("data", (chunk) => {
201
+ if (long || broken)
202
+ return;
203
+ try {
204
+ long = !wav.push(chunk);
205
+ }
206
+ catch (error) {
207
+ broken = error;
208
+ }
209
+ if (long || broken)
210
+ child.kill();
211
+ });
212
+ child.stderr.on("data", (chunk) => {
213
+ errors = (errors + chunk.toString()).slice(-500);
214
+ });
215
+ child.on("error", (error) => reject(error.code === "ENOENT"
216
+ ? new CliError("validation_error", "only ffmpeg reads this audio format, and ffmpeg is not installed")
217
+ : error));
218
+ child.on("close", (code) => {
219
+ if (long)
220
+ return reject(tooLongError());
221
+ if (broken)
222
+ return reject(broken);
223
+ if (code !== 0)
224
+ return reject(new CliError("validation_error", `ffmpeg could not read the audio: ${errors.trim() || code}`));
225
+ try {
226
+ resolve(wav.end());
227
+ }
228
+ catch (error) {
229
+ reject(error);
230
+ }
231
+ });
232
+ });
233
+ /** `runFfmpegFile` on bytes already in memory, through a private temporary file. */
83
234
  export const runFfmpeg = async (bytes) => {
84
235
  const directory = await mkdtemp(join(tmpdir(), "wirecat-audio-"));
85
236
  try {
86
237
  const input = join(directory, "audio");
87
238
  await writeFile(input, bytes, { mode: 0o600 });
88
- const largest = LONGEST_AUDIO_SECONDS * SAMPLE_RATE * 4;
89
- const output = await new Promise((resolve, reject) => {
90
- const child = spawn("ffmpeg", [
91
- "-nostdin",
92
- "-hide_banner",
93
- "-loglevel",
94
- "error",
95
- "-protocol_whitelist",
96
- "file",
97
- "-format_whitelist",
98
- FFMPEG_FORMATS,
99
- "-i",
100
- input,
101
- "-vn",
102
- "-ac",
103
- "1",
104
- "-ar",
105
- String(SAMPLE_RATE),
106
- "-f",
107
- "f32le",
108
- "pipe:1",
109
- ], { stdio: ["ignore", "pipe", "pipe"], timeout: FFMPEG_TIMEOUT_MS });
110
- const chunks = [];
111
- let size = 0;
112
- let errors = "";
113
- child.stdout.on("data", (chunk) => {
114
- size += chunk.length;
115
- if (size > largest)
116
- child.kill();
117
- else
118
- chunks.push(chunk);
119
- });
120
- child.stderr.on("data", (chunk) => {
121
- errors = (errors + chunk.toString()).slice(-500);
122
- });
123
- child.on("error", (error) => reject(error.code === "ENOENT"
124
- ? new CliError("validation_error", "only ffmpeg reads this audio format, and ffmpeg is not installed")
125
- : error));
126
- child.on("close", (code) => {
127
- if (size > largest)
128
- reject(new CliError("validation_error", `the audio is longer than ${LONGEST_AUDIO_SECONDS / 60} minutes`));
129
- else if (code === 0)
130
- resolve(Buffer.concat(chunks));
131
- else
132
- reject(new CliError("validation_error", `ffmpeg could not read the audio: ${errors.trim() || code}`));
133
- });
134
- });
135
- const samples = new Float32Array(Math.floor(output.length / 4));
136
- Buffer.from(samples.buffer).set(output.subarray(0, samples.length * 4));
137
- return { samples, rate: SAMPLE_RATE };
239
+ return await runFfmpegFile(input);
138
240
  }
139
241
  finally {
140
242
  await rm(directory, { recursive: true, force: true });
@@ -147,23 +249,68 @@ const BUNDLED = {
147
249
  mp3: decodeMp3,
148
250
  };
149
251
  const tooLong = (pcm) => pcm.samples.length / pcm.rate > LONGEST_AUDIO_SECONDS;
252
+ const fromFfmpeg = (answer) => Array.isArray(answer) ? { channels: answer, mixed: false } : { channels: [answer], mixed: true };
150
253
  /**
151
- * Every channel the file has, one `Pcm` each: a phone call recorded in stereo keeps one speaker per channel.
152
- * Only the bundled decoders keep channels apart; what ffmpeg reads arrives mixed down to one, and says so.
254
+ * Every channel the file has, one `Pcm` each: a phone call recorded in stereo keeps one speaker per channel. Opus,
255
+ * Vorbis, FLAC and MP3 by the bundled decoders; anything else, or what one of them could not read, by ffmpeg when the
256
+ * machine has it. The bundled decoder's error wins: it names the file's own problem.
153
257
  */
154
258
  export const decodeChannels = async (bytes, ffmpeg = runFfmpeg) => {
155
259
  const format = formatOf(bytes);
156
260
  const decoded = format === "other"
157
- ? { channels: [await ffmpeg(bytes)], mixed: true }
158
- : await BUNDLED[format](bytes).then((channels) => ({ channels, mixed: false }), (error) => ffmpeg(bytes).then((pcm) => ({ channels: [pcm], mixed: true }), () => {
261
+ ? fromFfmpeg(await ffmpeg(bytes))
262
+ : await BUNDLED[format](bytes).then((channels) => ({ channels, mixed: false }), (error) => ffmpeg(bytes).then(fromFfmpeg, () => {
159
263
  throw error;
160
264
  }));
265
+ if (decoded.channels.length === 0)
266
+ throw new CliError("validation_error", "no audio in that file");
161
267
  if (decoded.channels.some(tooLong))
162
- throw new CliError("validation_error", `the audio is longer than ${LONGEST_AUDIO_SECONDS / 60} minutes`);
268
+ throw tooLongError();
163
269
  return decoded;
164
270
  };
165
271
  /**
166
- * Opus, Vorbis, FLAC and MP3 by the bundled decoders; anything else, or what one of them could not read, by ffmpeg
167
- * when the machine has it. The bundled decoder's error wins: it names the file's own problem. The first channel only.
272
+ * The channels of a file on disk, for a recording too large to read into memory first: what ffmpeg reads (WAV, GSM,
273
+ * AAC…) goes to it by path, and only the samples are held. A format a bundled decoder reads is read whole, at most
274
+ * `maxBytes` (64 MB when not given): those decoders take bytes, and a compressed file decodes to many times its size.
168
275
  */
169
- export const decodeAudio = async (bytes, ffmpeg = runFfmpeg) => (await decodeChannels(bytes, ffmpeg)).channels[0];
276
+ export const decodeChannelsFile = async (path, { maxBytes = 64 * 1024 * 1024, ffmpegFile = runFfmpegFile, } = {}) => {
277
+ const file = await open(path, "r");
278
+ let start;
279
+ let size;
280
+ try {
281
+ size = (await file.stat()).size;
282
+ const head = Buffer.alloc(Math.min(size, 128));
283
+ await file.read(head, 0, head.length, 0);
284
+ start = head;
285
+ }
286
+ finally {
287
+ await file.close();
288
+ }
289
+ if (formatOf(start) === "other") {
290
+ const channels = await ffmpegFile(path);
291
+ if (channels.some(tooLong))
292
+ throw tooLongError();
293
+ return { channels, mixed: false };
294
+ }
295
+ if (size > maxBytes)
296
+ throw new CliError("validation_error", `the audio file is larger than ${Math.round(maxBytes / 1024 / 1024)} MB`, {
297
+ reason: "file.too-large",
298
+ });
299
+ return decodeChannels(new Uint8Array(await readFile(path)), () => ffmpegFile(path));
300
+ };
301
+ /** Every channel averaged into one, so a caller that wants one text keeps both sides of a stereo recording. */
302
+ export const mixDown = (channels) => {
303
+ const [first] = channels;
304
+ if (!first)
305
+ throw new CliError("validation_error", "no audio in that file");
306
+ if (channels.length === 1)
307
+ return first;
308
+ const length = channels.reduce((longest, { samples }) => Math.max(longest, samples.length), 0);
309
+ const samples = new Float32Array(length);
310
+ for (const channel of channels)
311
+ for (let index = 0; index < channel.samples.length; index++)
312
+ samples[index] = (samples[index] ?? 0) + (channel.samples[index] ?? 0) / channels.length;
313
+ return { samples, rate: first.rate };
314
+ };
315
+ /** One voice for a caller that wants the text and not the turns, a voice message: the channels mixed into one. */
316
+ export const decodeAudio = async (bytes, ffmpeg = runFfmpeg) => mixDown((await decodeChannels(bytes, ffmpeg)).channels);
@@ -1,4 +1,5 @@
1
- export { decodeAudio, decodeChannels, type Ffmpeg, type Pcm, runFfmpeg, } from "./decode.js";
1
+ export { type CloudSpeech, type CloudSpeechDeps, cloudSpeech } from "./cloud.js";
2
+ export { type DecodedChannels, decodeAudio, decodeChannels, decodeChannelsFile, type Ffmpeg, mixDown, type Pcm, runFfmpeg, runFfmpegFile, } from "./decode.js";
2
3
  export { type Fetch, install, installedBytes, isInstalled, megabytes, modelPath, modelsDirectory, sharedModelsDirectory, vadPath, } from "./install.js";
3
4
  export { type LocalSpeechBackend, type LocalSpeechRecognitionModel, type LocalSpeechRecognizer, type LocalSpeechRecognizerOptions, localSpeechRecognitionModel, openLocalSpeechRecognizer, recognizeLocalPieces, } from "./local.js";
4
5
  export { DEFAULT_ORDER, findModel, MODELS, type ModelFile, OPENAI_TRANSCRIBE_MODEL, orderedModels, type SpeechModel, speechModel, VAD, } from "./models.js";
@@ -1,4 +1,5 @@
1
- export { decodeAudio, decodeChannels, runFfmpeg, } from "./decode.js";
1
+ export { cloudSpeech } from "./cloud.js";
2
+ export { decodeAudio, decodeChannels, decodeChannelsFile, mixDown, runFfmpeg, runFfmpegFile, } from "./decode.js";
2
3
  export { install, installedBytes, isInstalled, megabytes, modelPath, modelsDirectory, sharedModelsDirectory, vadPath, } from "./install.js";
3
4
  export { localSpeechRecognitionModel, openLocalSpeechRecognizer, recognizeLocalPieces, } from "./local.js";
4
5
  export { DEFAULT_ORDER, findModel, MODELS, OPENAI_TRANSCRIBE_MODEL, orderedModels, speechModel, VAD, } from "./models.js";
@@ -17,6 +17,10 @@ export interface OpenAITranscription {
17
17
  /** Literal terms expected in the speech; OpenAI refuses the whole request if one holds `<`, `>` or a line break. */
18
18
  keywords?: readonly string[];
19
19
  baseUrl?: string;
20
+ /** Who the errors name: `OpenAI` when not given, a compatible service's host otherwise. */
21
+ label?: string;
22
+ /** The command that sets the key, named when the service refuses it; `models keys set openai` when not given. */
23
+ keyHint?: string;
20
24
  signal?: AbortSignal;
21
25
  fetch?: Fetch;
22
26
  /**
@@ -2,7 +2,7 @@ import { setTimeout as wait } from "node:timers/promises";
2
2
  import { backoffMs, CliError, DEFAULT_RETRY } from "@wirecat/cli-base";
3
3
  import { providerWaitMs } from "@wirecat/cli-base/http";
4
4
  import { OPENAI_URL } from "../embeddings/remote.js";
5
- import { endpointFetch } from "../models/endpoint.js";
5
+ import { endpointFetch, onThisComputer } from "../models/endpoint.js";
6
6
  import { refuseModelAddress } from "../models/local-only.js";
7
7
  import { filesPresent, modelsDirectory, vadPath } from "./install.js";
8
8
  import { OPENAI_TRANSCRIBE_MODEL, VAD } from "./models.js";
@@ -77,13 +77,14 @@ const send = async (wav, options) => {
77
77
  const retry = options.retry ?? RETRY;
78
78
  const sleep = options.sleep ?? sleeping;
79
79
  const random = options.random ?? Math.random;
80
+ const who = options.label ?? "OpenAI";
80
81
  for (let attempt = 1;; attempt++) {
81
82
  interrupted(options.signal);
82
83
  let response;
83
84
  try {
84
85
  response = await post(url, {
85
86
  method: "POST",
86
- headers: { authorization: `Bearer ${options.apiKey}` },
87
+ headers: options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {},
87
88
  body: formOf(wav, options),
88
89
  ...(options.signal ? { signal: options.signal } : {}),
89
90
  });
@@ -91,14 +92,14 @@ const send = async (wav, options) => {
91
92
  catch {
92
93
  interrupted(options.signal);
93
94
  if (attempt > retry.retries)
94
- throw new CliError("network_error", "OpenAI could not be reached", { reason: "network.failed" });
95
+ throw new CliError("network_error", `${who} could not be reached`, { reason: "network.failed" });
95
96
  await sleep(backoffMs(attempt, retry, random), options.signal);
96
97
  continue;
97
98
  }
98
99
  if (response.ok) {
99
100
  const body = (await response.json().catch(() => interrupted(options.signal)));
100
101
  if (typeof body?.text !== "string")
101
- throw new CliError("invalid_response", "OpenAI answered without a transcript", {
102
+ throw new CliError("invalid_response", `${who} answered without a transcript`, {
102
103
  reason: "provider.invalid-response",
103
104
  });
104
105
  return body.text.trim();
@@ -107,15 +108,15 @@ const send = async (wav, options) => {
107
108
  const status = response.status;
108
109
  const said = `HTTP ${status}${code ? `, ${code}` : type ? `, ${type}` : ""}`;
109
110
  if (status === 401)
110
- throw new CliError("authentication_error", `OpenAI refused the key (${said}) — set it again with \`models keys set openai\``, { reason: "auth.failed" });
111
+ throw new CliError("authentication_error", `${who} refused the key (${said}) — set it again with \`${options.keyHint ?? "models keys set openai"}\``, { reason: "auth.failed" });
111
112
  if (status === 403)
112
- throw new CliError("permission_error", `OpenAI refused the request (${said}) — it answers this when the country or region is not supported, or the key's project may not use the model`, { reason: "access.denied" });
113
+ throw new CliError("permission_error", `${who} refused the request (${said}) — OpenAI answers this when the country or region is not supported, or the key's project may not use the model`, { reason: "access.denied" });
113
114
  if (status === 413)
114
- throw new CliError("validation_error", `OpenAI refused the audio as too large (${said})`, {
115
+ throw new CliError("validation_error", `${who} refused the audio as too large (${said})`, {
115
116
  reason: "transcription.too-large",
116
117
  });
117
118
  if (EXHAUSTED.has(code ?? "") || EXHAUSTED.has(type ?? ""))
118
- throw new CliError("permission_error", `OpenAI refused: the account's credit, spend limit or usage limit is used up (${said}) — see the billing page`, { reason: "transcription.quota-exhausted" });
119
+ throw new CliError("permission_error", `${who} refused: the account's credit, spend limit or usage limit is used up (${said}) — see the billing page`, { reason: "transcription.quota-exhausted" });
119
120
  const again = status === 408 || status === 429 || status >= 500;
120
121
  const asked = providerWaitMs(response.headers, () => new Date());
121
122
  if (again && attempt <= retry.retries && (asked === undefined || asked <= retry.maxRetryAfterMs)) {
@@ -123,13 +124,13 @@ const send = async (wav, options) => {
123
124
  continue;
124
125
  }
125
126
  if (status === 429)
126
- throw new CliError("rate_limited", `OpenAI answered ${said}`, {
127
+ throw new CliError("rate_limited", `${who} answered ${said}`, {
127
128
  reason: "provider.rate-limited",
128
129
  ...(asked === undefined ? {} : { retry_after_ms: asked }),
129
130
  });
130
131
  if (status >= 500)
131
- throw new CliError([502, 503, 504].includes(status) ? "provider_unavailable" : "provider_error", `OpenAI answered ${said}`, { reason: [502, 503, 504].includes(status) ? "provider.unavailable" : "provider.refused" });
132
- throw new CliError("provider_error", `OpenAI answered ${said}`, { reason: "provider.refused" });
132
+ throw new CliError([502, 503, 504].includes(status) ? "provider_unavailable" : "provider_error", `${who} answered ${said}`, { reason: [502, 503, 504].includes(status) ? "provider.unavailable" : "provider.refused" });
133
+ throw new CliError("provider_error", `${who} answered ${said}`, { reason: "provider.refused" });
133
134
  }
134
135
  };
135
136
  /**
@@ -166,7 +167,7 @@ const checkKeywords = (keywords = []) => {
166
167
  */
167
168
  export const transcribeOpenAI = async (audio, options) => {
168
169
  refuseModelAddress(options.env ?? process.env, options.baseUrl ?? OPENAI_URL, "audio");
169
- if (!options.apiKey)
170
+ if (!options.apiKey && !onThisComputer(options.baseUrl ?? OPENAI_URL))
170
171
  throw new CliError("authentication_error", "no OpenAI key — `models keys set openai`, or OPENAI_API_KEY", {
171
172
  reason: "transcription.no-key",
172
173
  });
@@ -0,0 +1 @@
1
+ export { openSqlReader, quoteSql, SQL_CONNECT_TIMEOUT_MS, SQL_QUERY_TIMEOUT_MS, type SqlColumn, type SqlCondition, type SqlDriver, type SqlKind, type SqlOptions, type SqlPages, type SqlReader, type SqlRow, sqlFailure, } from "./reader.js";
@@ -0,0 +1 @@
1
+ export { openSqlReader, quoteSql, SQL_CONNECT_TIMEOUT_MS, SQL_QUERY_TIMEOUT_MS, sqlFailure, } from "./reader.js";
@@ -0,0 +1,95 @@
1
+ import type { Duplex } from "node:stream";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import type { RequestEvent } from "../runs/events.js";
4
+ export type SqlKind = "mysql" | "postgres";
5
+ /** A row as the driver gives it: a time without a zone stays the wall-time text it is, never this computer's zone. */
6
+ export type SqlRow = Record<string, unknown>;
7
+ export interface SqlColumn {
8
+ name: string;
9
+ /** True for PostgreSQL's `timestamp with time zone`; MySQL keeps no zone with a time. */
10
+ zoned: boolean;
11
+ }
12
+ export interface SqlOptions {
13
+ kind: SqlKind;
14
+ /** The server's name; through a tunnel, still the name its TLS certificate carries. */
15
+ host: string;
16
+ /** 3306 for MySQL and MariaDB, 5432 for PostgreSQL, when not given. */
17
+ port?: number | null | undefined;
18
+ database: string;
19
+ user: string;
20
+ password: string;
21
+ /** TLS with the certificate checked against the computer's trust store; never without the check (WC-SECR-14). */
22
+ tls?: boolean;
23
+ /**
24
+ * A stream already connected to the server, opened once for the connection: an SSH tunnel's
25
+ * `connect(host, port)` for a database that listens only on its own server.
26
+ */
27
+ socket?: () => Promise<Duplex>;
28
+ connectTimeoutMs?: number;
29
+ /** How long one query may run. */
30
+ queryTimeoutMs?: number;
31
+ /** The run's events (WC-LIFE-17); the current command's run when not given. */
32
+ events?: (event: RequestEvent) => void;
33
+ /** The run's signal: aborting it closes the connection and stops the next page. */
34
+ signal?: AbortSignal | undefined;
35
+ /** A seam for tests: the driver in place of mysql2 or pg. */
36
+ driver?: (options: SqlOptions, socket: Duplex | undefined) => Promise<SqlDriver>;
37
+ }
38
+ /** One condition of a paged read: a column compared to a value, sent as a parameter. */
39
+ export interface SqlCondition {
40
+ column: string;
41
+ op: "=" | "<" | "<=" | ">" | ">=";
42
+ value: unknown;
43
+ }
44
+ export interface SqlPages {
45
+ /** A table, or `schema.table`, checked as an identifier. */
46
+ table: string;
47
+ /** All of them true. */
48
+ where?: readonly SqlCondition[];
49
+ /** The order of the read, oldest first for a log. */
50
+ orderBy: readonly string[];
51
+ /**
52
+ * True when `orderBy` names each row once: pages then go by the last row's key, so a row written during the read
53
+ * never shifts a page. Otherwise by offset.
54
+ */
55
+ unique?: boolean;
56
+ /** 5,000 when not given: a first import of years of rows never holds one answer of millions. */
57
+ pageSize?: number;
58
+ }
59
+ export interface SqlReader {
60
+ readonly kind: SqlKind;
61
+ /** The table's columns, from an empty read of it. */
62
+ columns(table: string): Promise<SqlColumn[]>;
63
+ /** The rows in pages, in order; each page is a request in the run. */
64
+ pages(read: SqlPages): AsyncIterable<SqlRow[]>;
65
+ /**
66
+ * A statement of the host's own, run in the read-only session: values only as parameters, written `?` for MySQL
67
+ * and `$1`, `$2`… for PostgreSQL (`placeholder` gives the right one).
68
+ */
69
+ query(sql: string, params?: readonly unknown[]): Promise<SqlRow[]>;
70
+ /** An identifier quoted for this server, after the same check as `pages`'s. */
71
+ quote(identifier: string): string;
72
+ placeholder(index: number): string;
73
+ close(): Promise<void>;
74
+ }
75
+ /** What a driver does for the reader; mysql2 and pg are the two, a test brings its own. */
76
+ export interface SqlDriver {
77
+ columns(sql: string): Promise<SqlColumn[]>;
78
+ query(sql: string, params: readonly unknown[]): Promise<SqlRow[]>;
79
+ close(): Promise<void>;
80
+ }
81
+ export declare const SQL_CONNECT_TIMEOUT_MS = 15000;
82
+ export declare const SQL_QUERY_TIMEOUT_MS = 120000;
83
+ export declare const quoteSql: (kind: SqlKind, identifier: string) => string;
84
+ /**
85
+ * The driver's refusal, without its text: it can quote the host, the user or the statement (WC-SECR-6). The reasons
86
+ * are the host's to word again (`db.no-table` → "set db_table").
87
+ */
88
+ export declare const sqlFailure: (kind: SqlKind, error: unknown) => CliError;
89
+ /**
90
+ * A MySQL, MariaDB or PostgreSQL database, read only: the session is opened read-only, and a paged read is one SELECT
91
+ * whose names were checked as identifiers and whose values are parameters. The host brings its own schema: which
92
+ * table, which columns, which order. Every connect and page is a request in the run's events, with no statement,
93
+ * value or name in it.
94
+ */
95
+ export declare const openSqlReader: (options: SqlOptions) => Promise<SqlReader>;