@startsimpli/integrations 0.2.53 → 0.2.55

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.
@@ -24,24 +24,23 @@
24
24
  import type { CorpusHttp } from './client';
25
25
  import type { TenantEntity, TenantRelationship } from './entities';
26
26
  import type { CorpusScope } from './types';
27
+ import { ABOUT_FOCUS, fileDocument, listFocusChoices } from './filing';
28
+ import type { FocusChoice } from './filing';
27
29
 
28
- /**
29
- * A document is ABOUT a focus — its own edge, not `in_focus`. `in_focus` is
30
- * declared commitment -> focus only (a relationship definition has one source
31
- * type), and the Planning counts walk it expecting items. Reusing it for
32
- * documents would have been rejected by the tenant (400 "source must be a
33
- * 'commitment'"); widening it would let documents leak into item counts.
34
- */
35
- export const ABOUT_FOCUS = 'about_focus';
30
+ export { ABOUT_FOCUS };
31
+ export type { FocusChoice };
36
32
 
37
33
  export const VOICE_SOURCE = 'voice';
38
34
  export const VOICE_SOURCE_LABEL = 'Voice note';
39
35
  export type VoiceStatus = 'processing' | 'ready' | 'failed';
40
36
 
41
- export interface FocusChoice {
42
- id: string;
43
- title: string;
44
- detail?: string;
37
+ /** What the model call cost, summed over every call the analysis made (a repair is a second call). */
38
+ export interface AnalysisUsage {
39
+ provider: string;
40
+ model: string;
41
+ tokensIn: number;
42
+ tokensOut: number;
43
+ calls: number;
45
44
  }
46
45
 
47
46
  export interface VoiceAnalysis {
@@ -49,6 +48,31 @@ export interface VoiceAnalysis {
49
48
  summary: string;
50
49
  /** One of the offered focus ids, or null when none fit. */
51
50
  focusId: string | null;
51
+ usage?: AnalysisUsage;
52
+ }
53
+
54
+ /** A transcript plus what produced it, so the speech cost can be recorded. */
55
+ export interface TranscriptOutcome {
56
+ text: string;
57
+ provider?: string;
58
+ model?: string;
59
+ audioSeconds?: number;
60
+ }
61
+
62
+ /**
63
+ * Cost inputs recorded on a ready note: enough to derive cost per note and per
64
+ * month from the vendors' price lists without re-running anything. Stored as
65
+ * `voice_usage` (snake_case) on the row.
66
+ */
67
+ export interface VoiceUsage {
68
+ sttProvider?: string;
69
+ sttModel?: string;
70
+ audioSeconds?: number;
71
+ llmProvider?: string;
72
+ llmModel?: string;
73
+ tokensIn?: number;
74
+ tokensOut?: number;
75
+ llmCalls?: number;
52
76
  }
53
77
 
54
78
  export interface VoiceAnalyzer {
@@ -56,7 +80,8 @@ export interface VoiceAnalyzer {
56
80
  }
57
81
 
58
82
  export interface VoiceTranscriber {
59
- transcribe(input: { audio: Uint8Array; mimeType: string; focusTitles: string[] }): Promise<string>;
83
+ /** A bare string is accepted (no usage known); an outcome carries provider/model/audio seconds. */
84
+ transcribe(input: { audio: Uint8Array; mimeType: string; focusTitles: string[] }): Promise<string | TranscriptOutcome>;
60
85
  }
61
86
 
62
87
  export interface VoiceAudioStore {
@@ -92,6 +117,7 @@ export function voiceToEntity(input: {
92
117
  audioMime?: string;
93
118
  durationMs?: number;
94
119
  error?: string;
120
+ usage?: VoiceUsage;
95
121
  }): { entity_type: string; external_id: string; name: string; data: Record<string, unknown> } {
96
122
  return {
97
123
  entity_type: 'source_document',
@@ -110,10 +136,35 @@ export function voiceToEntity(input: {
110
136
  ...(input.audioMime ? { audio_mime: input.audioMime } : {}),
111
137
  ...(input.durationMs !== undefined ? { duration_ms: input.durationMs } : {}),
112
138
  ...(input.error !== undefined ? { voice_error: input.error } : {}),
139
+ ...(input.usage ? { voice_usage: usageToRow(input.usage) } : {}),
113
140
  },
114
141
  };
115
142
  }
116
143
 
144
+ const USAGE_KEYS: Array<[keyof VoiceUsage, string]> = [
145
+ ['sttProvider', 'stt_provider'], ['sttModel', 'stt_model'], ['audioSeconds', 'audio_seconds'],
146
+ ['llmProvider', 'llm_provider'], ['llmModel', 'llm_model'],
147
+ ['tokensIn', 'tokens_in'], ['tokensOut', 'tokens_out'], ['llmCalls', 'llm_calls'],
148
+ ];
149
+
150
+ function usageToRow(usage: VoiceUsage): Record<string, unknown> {
151
+ const row: Record<string, unknown> = {};
152
+ for (const [camel, snake] of USAGE_KEYS) if (usage[camel] !== undefined) row[snake] = usage[camel];
153
+ return row;
154
+ }
155
+
156
+ /** Reads `voice_usage` under either spelling (the API client camel-cases keys inside `data`). */
157
+ function usageFromRow(value: unknown): VoiceUsage | undefined {
158
+ if (!value || typeof value !== 'object') return undefined;
159
+ const row = value as Record<string, unknown>;
160
+ const out: Record<string, unknown> = {};
161
+ for (const [camel, snake] of USAGE_KEYS) {
162
+ const v = row[snake] ?? row[camel];
163
+ if (v !== undefined && v !== null && v !== '') out[camel] = v;
164
+ }
165
+ return Object.keys(out).length ? (out as VoiceUsage) : undefined;
166
+ }
167
+
117
168
  // ---------------------------------------------------------------------------
118
169
  // the pipeline
119
170
  // ---------------------------------------------------------------------------
@@ -167,6 +218,16 @@ export async function startVoiceNote(
167
218
  return { id: String(row.id), noteId: submission.noteId, audioRef };
168
219
  }
169
220
 
221
+ function noteUsage(heard: TranscriptOutcome, llm: AnalysisUsage | undefined, durationMs?: number): VoiceUsage {
222
+ const audioSeconds = heard.audioSeconds ?? (durationMs !== undefined ? durationMs / 1000 : undefined);
223
+ return {
224
+ ...(heard.provider ? { sttProvider: heard.provider } : {}),
225
+ ...(heard.model ? { sttModel: heard.model } : {}),
226
+ ...(audioSeconds !== undefined ? { audioSeconds } : {}),
227
+ ...(llm ? { llmProvider: llm.provider, llmModel: llm.model, tokensIn: llm.tokensIn, tokensOut: llm.tokensOut, llmCalls: llm.calls } : {}),
228
+ };
229
+ }
230
+
170
231
  export interface FinishedVoiceNote {
171
232
  id: string;
172
233
  focusId: string | null;
@@ -203,11 +264,13 @@ export async function finishVoiceNote(
203
264
 
204
265
  try {
205
266
  const focuses = await deps.listFocuses().catch(() => [] as FocusChoice[]);
206
- const transcript = (await deps.transcriber.transcribe({
267
+ const heard = await deps.transcriber.transcribe({
207
268
  audio: submission.audio,
208
269
  mimeType: submission.mimeType,
209
270
  focusTitles: focuses.map((f) => f.title),
210
- })).trim();
271
+ });
272
+ const outcome: TranscriptOutcome = typeof heard === 'string' ? { text: heard } : heard;
273
+ const transcript = outcome.text.trim();
211
274
  if (!transcript) throw new Error('No speech was detected in the recording.');
212
275
 
213
276
  const analysis = await deps.analyzer.analyze({ transcript, focuses });
@@ -216,6 +279,7 @@ export async function finishVoiceNote(
216
279
  await deps.http.post('api/v1/entities/upsert', voiceToEntity({
217
280
  noteId: started.noteId, title, status: 'ready', occurredAt: at.toISOString(),
218
281
  body: transcript, summary: analysis.summary,
282
+ usage: noteUsage(outcome, analysis.usage, submission.durationMs),
219
283
  }));
220
284
  // Filing is best-effort AFTER the note is already `ready`: a refused edge
221
285
  // must leave a readable, unfiled note — not overwrite it as `failed` and
@@ -253,6 +317,8 @@ export interface VoiceNote {
253
317
  durationMs?: number;
254
318
  focusId: string | null;
255
319
  audioRef?: string;
320
+ /** Provider, model, audio seconds and tokens behind this note — cost is derivable from it. */
321
+ usage?: VoiceUsage;
256
322
  }
257
323
 
258
324
  export interface VoiceFocus { id: string; title: string }
@@ -264,6 +330,12 @@ export interface VoiceNotesApi {
264
330
  listFocuses(): Promise<VoiceFocus[]>;
265
331
  /** Move a note to another project, or `null` to unfile it. */
266
332
  file(noteId: string, focusId: string | null): Promise<void>;
333
+ /** Re-run a failed note from its stored audio (bd startsim-ikxdz). Absent = no Retry button. */
334
+ retry?(noteId: string): Promise<void>;
335
+ /** Delete a note, its project edge and its recording. Absent = no Delete button. */
336
+ remove?(noteId: string): Promise<void>;
337
+ /** A playable URL for the recording, fetched with the caller's credentials. Absent = no player. */
338
+ audioUrl?(noteId: string): Promise<string>;
267
339
  }
268
340
 
269
341
  function text(value: unknown): string {
@@ -279,6 +351,7 @@ export function toVoiceNote(entity: TenantEntity, focusId: string | null): Voice
279
351
  const error = text(pick('voice_error', 'voiceError'));
280
352
  const durationMs = pick('duration_ms', 'durationMs');
281
353
  const audioRef = text(pick('audio_ref', 'audioRef'));
354
+ const usage = usageFromRow(pick('voice_usage', 'voiceUsage'));
282
355
  return {
283
356
  id: String(entity.id),
284
357
  title: text(data.title) || entity.name || 'Voice note',
@@ -290,14 +363,17 @@ export function toVoiceNote(entity: TenantEntity, focusId: string | null): Voice
290
363
  ...(typeof durationMs === 'number' ? { durationMs } : {}),
291
364
  focusId,
292
365
  ...(audioRef ? { audioRef } : {}),
366
+ ...(usage ? { usage } : {}),
293
367
  };
294
368
  }
295
369
 
296
370
  export interface CreateVoiceApiOptions {
297
371
  http: CorpusHttp;
298
372
  scope: CorpusScope;
299
- /** Sends the recording to the server route. */
300
- upload: (audio: Blob, meta: { durationMs: number }) => Promise<{ id: string }>;
373
+ /** Sends the recording to the server route. Optional when `server` is given. */
374
+ upload?: (audio: Blob, meta: { durationMs: number }) => Promise<{ id: string }>;
375
+ /** The /corpus/voice client (`createVoiceServerClient`): upload + retry + delete + audio. */
376
+ server?: Pick<VoiceNotesApi, 'retry' | 'remove' | 'audioUrl'> & { upload: VoiceNotesApi['submit'] };
301
377
  limit?: number;
302
378
  }
303
379
 
@@ -305,8 +381,13 @@ type Page<T> = { results?: T[] };
305
381
 
306
382
  export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
307
383
  const { http } = options;
384
+ const submit = options.server?.upload ?? options.upload;
385
+ if (!submit) throw new Error('createVoiceApi needs an upload function or a server client.');
308
386
  return {
309
- submit: options.upload,
387
+ submit,
388
+ ...(options.server?.retry ? { retry: options.server.retry } : {}),
389
+ ...(options.server?.remove ? { remove: options.server.remove } : {}),
390
+ ...(options.server?.audioUrl ? { audioUrl: options.server.audioUrl } : {}),
310
391
 
311
392
  async list() {
312
393
  const page = await http.get<Page<TenantEntity>>('api/v1/entities', {
@@ -326,29 +407,9 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
326
407
  .map((r) => toVoiceNote(r, focusOf.get(String(r.id)) ?? null));
327
408
  },
328
409
 
329
- async listFocuses() {
330
- const page = await http.get<Page<TenantEntity>>('api/v1/entities', {
331
- params: { type: 'focus', order: 'attr.title', page_size: 200 },
332
- });
333
- return (page.results ?? []).map((r) => ({
334
- id: String(r.id),
335
- title: text(((r.data ?? {}) as Record<string, unknown>).title) || r.name || 'Untitled',
336
- }));
337
- },
410
+ listFocuses: () => listFocusChoices(http),
338
411
 
339
- async file(noteId, focusId) {
340
- if (!http.post) throw new Error('This client is read-only.');
341
- // Replace, never add: a note lives in one project.
342
- const existing = await http.get<Page<TenantRelationship>>('api/v1/relationships', {
343
- params: { rel_type: ABOUT_FOCUS, source: noteId },
344
- });
345
- if (existing.results?.length) {
346
- if (!http.delete) throw new Error('This client cannot move a note — no delete method was supplied.');
347
- for (const edge of existing.results) await http.delete(`api/v1/relationships/${edge.id}`);
348
- }
349
- if (focusId) {
350
- await http.post('api/v1/relationships', { rel_type: ABOUT_FOCUS, source: noteId, target: focusId });
351
- }
352
- },
412
+ // Replace, never add: a note lives in one project (see ./filing).
413
+ file: (noteId, focusId) => fileDocument(http, noteId, focusId),
353
414
  };
354
415
  }