@redaksjon/protokoll-engine 0.1.12 → 0.1.13-dev.20260303161030.b4a6c26

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index28.js","sources":["../src/agentic/types.ts"],"sourcesContent":["/**\n * Agentic Transcription Types\n *\n * Types for tool-based transcription enhancement.\n * Includes Zod schemas for validation and documentation.\n */\n\nimport { z } from 'zod';\nimport * as Context from '@redaksjon/context';\nimport * as Routing from '../routing';\nimport type { WeightModelProvider } from '../weighting/provider';\n\n// ============================================================================\n// Zod Schemas for Structured Outputs\n// ============================================================================\n\n/**\n * Schema for a corrected entity (spelling/name correction)\n */\nexport const CorrectedEntitySchema = z.object({\n original: z.string().describe('Original text from transcript'),\n corrected: z.string().describe('Corrected spelling/name'),\n type: z.enum(['person', 'project', 'term', 'company']).describe('Entity type'),\n confidence: z.number().min(0).max(1).describe('Confidence in correction'),\n});\n\nexport type CorrectedEntity = z.infer<typeof CorrectedEntitySchema>;\n\n/**\n * Schema for routing decision\n * Note: Uses the existing ClassificationSignal types from routing/types.ts\n */\nexport const RoutingDecisionSchema = z.object({\n projectId: z.string().optional().describe('Matched project ID'),\n destination: z.object({\n path: z.string().describe('File destination path'),\n structure: z.enum(['none', 'year', 'month', 'day']).default('month'),\n }),\n confidence: z.number().min(0).max(1).describe('Confidence in routing'),\n signals: z.array(z.object({\n type: z.enum(['explicit_phrase', 'associated_person', 'associated_company', 'topic', 'context_type']),\n value: z.string(),\n weight: z.number(),\n })).optional(),\n reasoning: z.string().optional().describe('Why this destination was chosen'),\n});\n\nexport type RoutingDecision = z.infer<typeof RoutingDecisionSchema>;\n\n/**\n * Schema for referenced entities\n */\nexport const ReferencedEntitiesSchema = z.object({\n people: z.array(z.string()).describe('IDs of people mentioned'),\n projects: z.array(z.string()).describe('IDs of projects mentioned'),\n terms: z.array(z.string()).describe('IDs of terms mentioned'),\n companies: z.array(z.string()).describe('IDs of companies mentioned'),\n});\n\nexport type ReferencedEntitiesOutput = z.infer<typeof ReferencedEntitiesSchema>;\n\n/**\n * Schema for tool result data\n */\nexport const ToolResultSchema = z.object({\n success: z.boolean(),\n data: z.any().optional(),\n error: z.string().optional(),\n needsUserInput: z.boolean().optional(),\n userPrompt: z.string().optional(),\n});\n\n// ============================================================================\n// TypeScript Interfaces (existing, preserved for compatibility)\n// ============================================================================\n\nexport interface TranscriptionTool {\n name: string;\n description: string;\n \n parameters: Record<string, any>; // JSON Schema\n \n execute: (args: any) => Promise<ToolResult>;\n}\n\n/**\n * Record of a single tool call made during enhancement\n */\nexport interface ToolCallLogEntry {\n tool: string;\n input: Record<string, unknown>;\n output: unknown;\n durationMs: number;\n success: boolean;\n timestamp: Date;\n}\n\nexport interface ToolContext {\n transcriptText: string;\n audioDate: Date;\n sourceFile: string;\n contextInstance: Context.ContextInstance;\n routingInstance: Routing.RoutingInstance;\n interactiveMode: boolean;\n // interactiveInstance?: Interactive.InteractiveInstance; // Interactive moved to protokoll-cli\n resolvedEntities?: Map<string, string>; // Entities resolved during this session\n /** Optional: entity affinity graph predictions for LLM prepositioning */\n weightModelProvider?: WeightModelProvider;\n /** Optional: called just before a tool executes — enables incremental status writes */\n onToolCallStart?: (tool: string, input: Record<string, unknown>) => void;\n /** Optional: called after a tool completes — enables incremental log writes */\n onToolCallComplete?: (entry: ToolCallLogEntry) => void;\n /**\n * Entities pre-identified by the simple-replace phase before LLM enhancement.\n * These are seeded into referencedEntities so they show up in the transcript\n * metadata even if the LLM doesn't redundantly look them up again.\n */\n preIdentifiedEntities?: {\n people: Set<string>;\n projects: Set<string>;\n terms: Set<string>;\n companies: Set<string>;\n };\n}\n\nexport interface ToolResult {\n success: boolean;\n \n data?: any;\n error?: string;\n needsUserInput?: boolean;\n userPrompt?: string;\n}\n\nexport interface ReferencedEntity {\n id: string;\n name: string;\n type: 'person' | 'project' | 'term' | 'company';\n}\n\nexport interface TranscriptionState {\n originalText: string;\n correctedText: string;\n unknownEntities: string[];\n resolvedEntities: Map<string, string>; // name mapping (old -> new)\n \n routeDecision?: RoutingDecision;\n confidence: number;\n \n // Track all entities referenced during processing\n referencedEntities: {\n people: Set<string>; // IDs of people mentioned\n projects: Set<string>; // IDs of projects mentioned\n terms: Set<string>; // IDs of terms mentioned\n companies: Set<string>; // IDs of companies mentioned\n };\n}\n\n"],"names":[],"mappings":";;AAmBO,MAAM,qBAAA,GAAwB,EAAE,MAAA,CAAO;AAAA,EAC1C,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,+BAA+B,CAAA;AAAA,EAC7D,SAAA,EAAW,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,yBAAyB,CAAA;AAAA,EACxD,IAAA,EAAM,CAAA,CAAE,IAAA,CAAK,CAAC,QAAA,EAAU,SAAA,EAAW,MAAA,EAAQ,SAAS,CAAC,CAAA,CAAE,QAAA,CAAS,aAAa,CAAA;AAAA,EAC7E,UAAA,EAAY,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,QAAA,CAAS,0BAA0B;AAC5E,CAAC;AAQM,MAAM,qBAAA,GAAwB,EAAE,MAAA,CAAO;AAAA,EAC1C,WAAW,CAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CAAE,SAAS,oBAAoB,CAAA;AAAA,EAC9D,WAAA,EAAa,EAAE,MAAA,CAAO;AAAA,IAClB,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,uBAAuB,CAAA;AAAA,IACjD,SAAA,EAAW,CAAA,CAAE,IAAA,CAAK,CAAC,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,KAAK,CAAC,CAAA,CAAE,OAAA,CAAQ,OAAO;AAAA,GACtE,CAAA;AAAA,EACD,UAAA,EAAY,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,CAAC,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"}
1
+ {"version":3,"file":"index28.js","sources":["../src/agentic/types.ts"],"sourcesContent":["/**\n * Agentic Transcription Types\n *\n * Types for tool-based transcription enhancement.\n * Includes Zod schemas for validation and documentation.\n */\n\nimport { z } from 'zod';\nimport * as Context from '@redaksjon/context';\nimport type { ToolCall, ToolDefinition } from '../reasoning/types';\nimport * as Routing from '../routing';\nimport type { WeightModelProvider } from '../weighting/provider';\n\n// ============================================================================\n// Zod Schemas for Structured Outputs\n// ============================================================================\n\n/**\n * Schema for a corrected entity (spelling/name correction)\n */\nexport const CorrectedEntitySchema = z.object({\n original: z.string().describe('Original text from transcript'),\n corrected: z.string().describe('Corrected spelling/name'),\n type: z.enum(['person', 'project', 'term', 'company']).describe('Entity type'),\n confidence: z.number().min(0).max(1).describe('Confidence in correction'),\n});\n\nexport type CorrectedEntity = z.infer<typeof CorrectedEntitySchema>;\n\n/**\n * Schema for routing decision\n * Note: Uses the existing ClassificationSignal types from routing/types.ts\n */\nexport const RoutingDecisionSchema = z.object({\n projectId: z.string().optional().describe('Matched project ID'),\n destination: z.object({\n path: z.string().describe('File destination path'),\n structure: z.enum(['none', 'year', 'month', 'day']).default('month'),\n }),\n confidence: z.number().min(0).max(1).describe('Confidence in routing'),\n signals: z.array(z.object({\n type: z.enum(['explicit_phrase', 'associated_person', 'associated_company', 'topic', 'context_type']),\n value: z.string(),\n weight: z.number(),\n })).optional(),\n reasoning: z.string().optional().describe('Why this destination was chosen'),\n});\n\nexport type RoutingDecision = z.infer<typeof RoutingDecisionSchema>;\n\n/**\n * Schema for referenced entities\n */\nexport const ReferencedEntitiesSchema = z.object({\n people: z.array(z.string()).describe('IDs of people mentioned'),\n projects: z.array(z.string()).describe('IDs of projects mentioned'),\n terms: z.array(z.string()).describe('IDs of terms mentioned'),\n companies: z.array(z.string()).describe('IDs of companies mentioned'),\n});\n\nexport type ReferencedEntitiesOutput = z.infer<typeof ReferencedEntitiesSchema>;\n\n/**\n * Schema for tool result data\n */\nexport const ToolResultSchema = z.object({\n success: z.boolean(),\n data: z.any().optional(),\n error: z.string().optional(),\n needsUserInput: z.boolean().optional(),\n userPrompt: z.string().optional(),\n});\n\n// ============================================================================\n// TypeScript Interfaces (existing, preserved for compatibility)\n// ============================================================================\n\nexport interface TranscriptionTool {\n name: string;\n description: string;\n \n parameters: Record<string, any>; // JSON Schema\n \n execute: (args: any) => Promise<ToolResult>;\n}\n\n/**\n * Record of a single tool call made during enhancement\n */\nexport interface ToolCallLogEntry {\n tool: string;\n input: Record<string, unknown>;\n output: unknown;\n durationMs: number;\n success: boolean;\n timestamp: Date;\n}\n\n/**\n * Record of a single model call made during enhancement\n */\nexport interface ModelCallStartLogEntry {\n callIndex: number;\n phase: 'initial' | 'continuation' | 'final';\n request: {\n model?: string;\n reasoningLevel?: string;\n prompt: string;\n systemPrompt?: string;\n maxIterations?: number;\n tools?: ToolDefinition[];\n };\n timestamp: Date;\n}\n\nexport interface ModelCallCompleteLogEntry {\n callIndex: number;\n phase: 'initial' | 'continuation' | 'final';\n durationMs: number;\n response: {\n model?: string;\n finishReason?: string;\n usage?: {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n };\n toolCalls?: ToolCall[];\n contentLength: number;\n };\n timestamp: Date;\n}\n\nexport interface ToolContext {\n transcriptText: string;\n audioDate: Date;\n sourceFile: string;\n contextInstance: Context.ContextInstance;\n routingInstance: Routing.RoutingInstance;\n interactiveMode: boolean;\n // interactiveInstance?: Interactive.InteractiveInstance; // Interactive moved to protokoll-cli\n resolvedEntities?: Map<string, string>; // Entities resolved during this session\n /** Optional: entity affinity graph predictions for LLM prepositioning */\n weightModelProvider?: WeightModelProvider;\n /** Optional: called just before a tool executes — enables incremental status writes */\n onToolCallStart?: (tool: string, input: Record<string, unknown>) => void;\n /** Optional: called after a tool completes — enables incremental log writes */\n onToolCallComplete?: (entry: ToolCallLogEntry) => void;\n /** Optional: called just before each model call to capture request payload details */\n onModelCallStart?: (entry: ModelCallStartLogEntry) => void;\n /** Optional: called after each model call to capture usage/details */\n onModelCallComplete?: (entry: ModelCallCompleteLogEntry) => void;\n /** Optional: model metadata for observability in enhancement logs */\n modelConfiguration?: {\n model: string;\n reasoningLevel?: string;\n };\n /**\n * Entities pre-identified by the simple-replace phase before LLM enhancement.\n * These are seeded into referencedEntities so they show up in the transcript\n * metadata even if the LLM doesn't redundantly look them up again.\n */\n preIdentifiedEntities?: {\n people: Set<string>;\n projects: Set<string>;\n terms: Set<string>;\n companies: Set<string>;\n };\n}\n\nexport interface ToolResult {\n success: boolean;\n \n data?: any;\n error?: string;\n needsUserInput?: boolean;\n userPrompt?: string;\n}\n\nexport interface ReferencedEntity {\n id: string;\n name: string;\n type: 'person' | 'project' | 'term' | 'company';\n}\n\nexport interface TranscriptionState {\n originalText: string;\n correctedText: string;\n unknownEntities: string[];\n resolvedEntities: Map<string, string>; // name mapping (old -> new)\n \n routeDecision?: RoutingDecision;\n confidence: number;\n \n // Track all entities referenced during processing\n referencedEntities: {\n people: Set<string>; // IDs of people mentioned\n projects: Set<string>; // IDs of projects mentioned\n terms: Set<string>; // IDs of terms mentioned\n companies: Set<string>; // IDs of companies mentioned\n };\n}\n\n"],"names":[],"mappings":";;AAoBO,MAAM,qBAAA,GAAwB,EAAE,MAAA,CAAO;AAAA,EAC1C,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,+BAA+B,CAAA;AAAA,EAC7D,SAAA,EAAW,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,yBAAyB,CAAA;AAAA,EACxD,IAAA,EAAM,CAAA,CAAE,IAAA,CAAK,CAAC,QAAA,EAAU,SAAA,EAAW,MAAA,EAAQ,SAAS,CAAC,CAAA,CAAE,QAAA,CAAS,aAAa,CAAA;AAAA,EAC7E,UAAA,EAAY,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,QAAA,CAAS,0BAA0B;AAC5E,CAAC;AAQM,MAAM,qBAA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wBAAwB,CAAA;AAAA,EAC5D,SAAA,EAAW,EAAE,KAAA,CAAM,CAAA,CAAE,QAAQ,CAAA,CAAE,SAAS,4BAA4B;AACxE,CAAC;AAOM,MAAM,gBAAA,GAAmB,EAAE,MAAA,CAAO;AAAA,EACrC,OAAA,EAAS,EAAE,OAAA,EAAQ;AAAA,EACnB,IAAA,EAAM,CAAA,CAAE,GAAA,EAAI,CAAE,QAAA,EAAS;AAAA,EACvB,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,cAAA,EAAgB,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAA,EAAS;AAAA,EACrC,UAAA,EAAY,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AAC3B,CAAC;;;;"}
package/dist/index33.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as Context from '@redaksjon/context';
2
2
  import { create as create$1 } from './index6.js';
3
- import { create as create$2 } from './index59.js';
3
+ import { create as create$2 } from './index53.js';
4
4
  import { create as create$3 } from './index11.js';
5
5
  import { create as create$4 } from './index3.js';
6
6
  import { create as create$5 } from './index2.js';
@@ -273,7 +273,13 @@ ${textSample}`
273
273
  // interactiveInstance: interactive,
274
274
  weightModelProvider: config.weightModelProvider,
275
275
  onToolCallStart: input.onToolCallStart,
276
- onToolCallComplete: input.onToolCallComplete
276
+ onToolCallComplete: input.onToolCallComplete,
277
+ onModelCallStart: input.onModelCallStart,
278
+ onModelCallComplete: input.onModelCallComplete,
279
+ modelConfiguration: {
280
+ model: config.model,
281
+ reasoningLevel: config.reasoningLevel
282
+ }
277
283
  };
278
284
  const executor = create$8(reasoning, toolContext);
279
285
  const agenticResult = await executor.process(simpleReplaceResult.text);
@@ -1 +1 @@
1
- {"version":3,"file":"index33.js","sources":["../src/pipeline/orchestrator.ts"],"sourcesContent":["/**\n * Pipeline Orchestrator\n *\n * Orchestrates the intelligent transcription pipeline, coordinating\n * all the modules: context, routing, transcription, reasoning,\n * agentic tools, interactive mode, output management, and reflection.\n * \n * THIS IS THE MAIN PROCESSING FLOW - NOT DEAD CODE!\n */\n\nimport { PipelineConfig, PipelineInput, PipelineResult, PipelineState } from './types';\nimport * as Context from '@redaksjon/context';\nimport * as Routing from '../routing';\nimport * as Output from '../out';\nimport * as Reflection from '../reflection';\nimport * as Transcription from '../transcription';\nimport * as Reasoning from '../reasoning';\nimport * as Agentic from '../agentic';\nimport * as CompletePhase from '../phases/complete';\nimport * as SimpleReplace from '../phases/simple-replace';\nimport * as Logging from '../logging';\nimport { randomUUID } from 'node:crypto';\nimport * as path from 'node:path';\nimport * as Metadata from '../util/metadata';\n\nexport interface OrchestratorInstance {\n process(input: PipelineInput): Promise<PipelineResult>;\n}\n\nexport interface OrchestratorConfig extends PipelineConfig {\n outputDirectory: string;\n outputStructure: string;\n outputFilenameOptions: string[];\n maxAudioSize: number;\n tempDirectory: string;\n}\n\nexport const create = async (config: OrchestratorConfig): Promise<OrchestratorInstance> => {\n const logger = Logging.getLogger();\n const currentWorkingDir = globalThis.process.cwd();\n \n logger.debug('Initializing intelligent transcription pipeline...');\n \n // Initialize context system (async)\n // Prefer a pre-loaded context instance (required for GCS-backed storage);\n // otherwise create one from contextDirectory/contextDirectories.\n const context = config.contextInstance ?? await Context.create({\n startingDir: config.contextDirectory || currentWorkingDir,\n contextDirectories: config.contextDirectories,\n });\n logger.debug('Context system initialized - ready to query entities via tools');\n \n // Default routing configuration (used as fallback for projects without custom destination)\n const defaultPath = config.outputDirectory || '~/notes';\n const defaultStructure = (config.outputStructure || 'month') as Routing.FilesystemStructure;\n const defaultFilenameOptions = (config.outputFilenameOptions || ['date', 'time', 'subject']) as Routing.FilenameOption[];\n\n // Convert context projects to routing format\n // Projects without a destination inherit from the global default\n const contextProjects = context.getAllProjects();\n const routingProjects: Routing.ProjectRoute[] = contextProjects\n .filter(project => project.active !== false)\n .map(project => ({\n projectId: project.id,\n destination: {\n path: project.routing?.destination || defaultPath,\n structure: project.routing?.structure || defaultStructure,\n filename_options: project.routing?.filename_options || defaultFilenameOptions,\n createDirectories: true,\n },\n classification: project.classification,\n active: project.active,\n auto_tags: project.routing?.auto_tags,\n }));\n \n logger.debug('Loaded %d projects from context for routing', routingProjects.length);\n \n // Initialize routing with config-based defaults\n const routingConfig: Routing.RoutingConfig = {\n default: {\n path: defaultPath,\n structure: defaultStructure,\n filename_options: defaultFilenameOptions,\n createDirectories: true,\n },\n projects: routingProjects,\n conflict_resolution: 'primary',\n };\n \n const routing = Routing.create(routingConfig, context, config.weightModelProvider);\n logger.debug('Routing system initialized');\n \n // Interactive moved to protokoll-cli\n // const interactive = Interactive.create(\n // { enabled: config.interactive, defaultToSuggestion: true, silent: config.silent },\n // context\n // );\n \n const output = Output.create({\n intermediateDir: config.intermediateDir || './output/protokoll',\n keepIntermediates: config.keepIntermediates ?? true,\n timestampFormat: 'YYMMDD-HHmm',\n });\n logger.debug('Output manager initialized');\n \n const reflection = config.selfReflection \n ? Reflection.create({\n enabled: true,\n format: 'markdown',\n includeConversation: false,\n includeOutput: true,\n })\n : null;\n if (reflection) {\n logger.debug('Self-reflection system enabled');\n }\n \n // Initialize transcription service\n const transcription = Transcription.create({\n defaultModel: config.transcriptionModel as Transcription.TranscriptionModel,\n });\n logger.debug('Transcription service initialized with model: %s', config.transcriptionModel);\n \n // Initialize reasoning for agentic processing\n const reasoning = Reasoning.create({ \n model: config.model,\n reasoningLevel: config.reasoningLevel,\n });\n logger.debug('Reasoning system initialized with model: %s, reasoning level: %s', config.model, config.reasoningLevel || 'medium');\n\n // Initialize simple-replace phase for pre-LLM entity correction via sounds_like\n const simpleReplace = SimpleReplace.create({ debug: config.debug }, context);\n logger.debug('Simple-replace phase initialized with context instance');\n\n // Initialize complete phase for moving files to processed directory\n // Pass outputStructure so processed files use the same directory structure as output\n const complete = config.processedDirectory \n ? CompletePhase.create({\n processedDirectory: config.processedDirectory,\n outputStructure: config.outputStructure as CompletePhase.FilesystemStructure,\n dryRun: config.dryRun,\n })\n : null;\n if (complete) {\n logger.debug('Complete phase initialized with processed directory: %s', config.processedDirectory);\n }\n \n // Helper to extract a human-readable title from the output path\n const extractTitleFromPath = (outputPath: string): string | undefined => {\n const filename = outputPath.split('/').pop()?.replace(/\\.(md|pkl)$/, '');\n if (!filename) return undefined;\n \n // Remove date prefix (e.g., \"27-0716-\" from \"27-0716-meeting-notes\")\n const withoutDate = filename.replace(/^\\d{2}-\\d{4}-/, '');\n if (!withoutDate) return undefined;\n \n // Convert kebab-case to Title Case\n return withoutDate\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n };\n \n // Helper to check if a title is meaningful (not just numbers/timestamps)\n const isMeaningfulTitle = (title: string | undefined): boolean => {\n if (!title) return false;\n // Reject UUID-like strings (hex characters separated by dashes, e.g. filenames from recordings)\n const uuidPattern = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;\n if (uuidPattern.test(title.trim())) return false;\n // Also reject if the title starts with a UUID segment pattern (Title Case converted UUID)\n const uuidSegmentPattern = /^[0-9a-f]{8}\\s[0-9a-f]{4}\\s/i;\n if (uuidSegmentPattern.test(title.trim())) return false;\n // Check if title is mostly numbers (timestamp-like) or very short fragments\n const stripped = title.replace(/\\s+/g, '');\n const numberRatio = (stripped.match(/\\d/g) || []).length / stripped.length;\n // Reject if: mostly numbers, too short, or common bad patterns\n if (numberRatio > 0.5) return false;\n if (stripped.length < 3) return false;\n // Reject titles that are just common words without context\n const badPatterns = /^(i|i have|i am|the|a|an|um|uh|so|well|okay|oh|hey|hi)$/i;\n if (badPatterns.test(title.trim())) return false;\n return true;\n };\n \n // Generate a meaningful title from transcript content using LLM\n const generateTitleFromContent = async (transcriptText: string, fallbackTitle?: string): Promise<string> => {\n try {\n // Use first ~2000 chars for title generation (enough context, not too expensive)\n const textSample = transcriptText.slice(0, 2000);\n \n const response = await reasoning.complete({\n systemPrompt: `You are a title generator. Given a transcript, generate a concise, descriptive title (3-8 words) that captures the main topic or theme.\n\nRules:\n- Output ONLY the title, nothing else\n- No quotes around the title\n- Use Title Case\n- Be specific - avoid generic titles like \"Meeting Notes\" or \"Discussion\"\n- Focus on the main subject matter\n- If there are multiple topics, pick the most prominent one`,\n prompt: `Generate a title for this transcript:\\n\\n${textSample}`,\n });\n \n // Clean up the response - remove quotes, trim whitespace\n const title = response.content\n .trim()\n .replace(/^[\"']|[\"']$/g, '') // Remove surrounding quotes\n .replace(/^#\\s*/, '') // Remove markdown heading prefix\n .trim();\n \n // Validate the generated title\n if (title && title.length > 0 && title.length < 100) {\n logger.debug('Generated title from content: %s', title);\n return title;\n }\n \n logger.debug('Generated title was invalid, using fallback');\n return fallbackTitle || 'Untitled';\n } catch (error) {\n logger.warn('Title generation failed, using fallback', { error });\n return fallbackTitle || 'Untitled';\n }\n };\n\n const processInput = async (input: PipelineInput): Promise<PipelineResult> => {\n const startTime = Date.now();\n \n // Format progress prefix for log messages\n const progressPrefix = input.progress \n ? `[${input.progress.current}/${input.progress.total}]` \n : '';\n const log = (level: 'info' | 'debug', message: string, ...args: unknown[]) => {\n const prefixedMessage = progressPrefix ? `${progressPrefix} ${message}` : message;\n if (level === 'info') {\n logger.info(prefixedMessage, ...args);\n } else {\n logger.debug(prefixedMessage, ...args);\n }\n };\n \n log('info', 'Processing: %s (hash: %s)', input.audioFile, input.hash);\n \n // Initialize state\n const state: PipelineState = {\n input,\n startTime: new Date(),\n };\n \n // Start reflection collection if enabled\n if (reflection) {\n reflection.collector.start();\n }\n \n // Start interactive session if enabled\n // Interactive moved to protokoll-cli\n // if (config.interactive) {\n // interactive.startSession();\n // log('debug', 'Interactive session started');\n // }\n \n try {\n // Step 1: Check onboarding needs (moved to protokoll-cli)\n log('debug', 'Checking onboarding state...');\n // const onboardingState = interactive.checkNeedsOnboarding();\n const onboardingState = { needsOnboarding: false }; // Stub\n if (onboardingState.needsOnboarding) {\n log('debug', 'First-run detected - onboarding may be triggered');\n }\n \n // Step 2: Raw transcription using Transcription module\n log('info', 'Transcribing audio...');\n const whisperStart = Date.now();\n \n const transcriptionResult = await transcription.transcribe(input.audioFile, {\n model: config.transcriptionModel as Transcription.TranscriptionModel,\n });\n state.rawTranscript = transcriptionResult.text;\n \n const whisperDuration = Date.now() - whisperStart;\n log('info', 'Transcription: %d chars in %.1fs', \n state.rawTranscript.length, whisperDuration / 1000);\n \n if (reflection) {\n reflection.collector.recordWhisper(whisperDuration);\n }\n \n // Step 3: Route detection\n log('debug', 'Determining routing destination...');\n const routingContext: Routing.RoutingContext = {\n transcriptText: state.rawTranscript || '',\n audioDate: input.creation,\n sourceFile: input.audioFile,\n hash: input.hash,\n };\n \n const routeResult = routing.route(routingContext);\n \n log('debug', 'Routing decision: project=%s, confidence=%.2f', \n routeResult.projectId || 'default', routeResult.confidence);\n \n // Record routing decision in reflection\n if (reflection) {\n reflection.collector.recordRoutingDecision({\n projectId: routeResult.projectId,\n destination: routeResult.destination.path,\n confidence: routeResult.confidence,\n reasoning: routeResult.reasoning,\n signals: routeResult.signals.map(s => ({\n type: s.type,\n value: s.value,\n weight: s.weight,\n })),\n alternativesConsidered: routeResult.alternateMatches?.map(alt => ({\n projectId: alt.projectId,\n confidence: alt.confidence,\n whyNotChosen: `Lower confidence (${(alt.confidence * 100).toFixed(1)}%)`,\n })),\n });\n }\n \n // Build output path\n const outputPath = routing.buildOutputPath(routeResult, routingContext);\n log('debug', 'Output path: %s', outputPath);\n \n // Step 4: Create output paths using Output module\n log('debug', 'Setting up output directories...');\n const paths = output.createOutputPaths(\n input.audioFile,\n outputPath,\n input.hash,\n input.creation\n );\n \n await output.ensureDirectories(paths);\n \n // Write raw transcript to intermediate (for debugging)\n await output.writeIntermediate(paths, 'transcript', {\n text: state.rawTranscript,\n model: config.transcriptionModel,\n duration: whisperDuration,\n });\n\n // Step 4b: Simple-replace phase — sounds_like entity correction before LLM\n // Matches entity names (projects, people, terms) using sounds_like mappings,\n // corrects them in the transcript text, and tracks which entities were found.\n log('debug', 'Running simple-replace (sounds_like entity matching)...');\n // Derive the intermediate directory from an existing intermediate file path\n const intermediateDir = path.dirname(paths.intermediate.transcript);\n const simpleReplaceResult = await simpleReplace.replace(\n state.rawTranscript || '',\n {\n project: routeResult.projectId ?? undefined,\n confidence: routeResult.confidence,\n },\n intermediateDir,\n input.hash\n );\n\n if (simpleReplaceResult.replacementsMade) {\n log('info',\n 'Simple-replace: %d correction(s) applied (%d Tier-1, %d Tier-2)',\n simpleReplaceResult.stats.totalReplacements,\n simpleReplaceResult.stats.tier1Replacements,\n simpleReplaceResult.stats.tier2Replacements\n );\n // Write the corrected text to intermediate for inspection\n await output.writeIntermediate(paths, 'session', {\n simpleReplace: {\n replacementsMade: true,\n stats: simpleReplaceResult.stats,\n },\n });\n } else {\n log('debug', 'Simple-replace: no replacements made');\n }\n\n // Notify caller (e.g. worker) so it can write to the PKL enhancement log\n input.onSimpleReplaceComplete?.(simpleReplaceResult.stats);\n\n // Collect pre-identified entities from simple-replace applied mappings\n const preIdentifiedEntities: Agentic.ToolContext['preIdentifiedEntities'] = {\n people: new Set<string>(),\n projects: new Set<string>(),\n terms: new Set<string>(),\n companies: new Set<string>(),\n };\n for (const mapping of simpleReplaceResult.stats.appliedMappings) {\n if (!mapping.entityId || !mapping.entityType) continue;\n if (mapping.entityType === 'person') preIdentifiedEntities.people.add(mapping.entityId);\n else if (mapping.entityType === 'project') preIdentifiedEntities.projects.add(mapping.entityId);\n else if (mapping.entityType === 'term') preIdentifiedEntities.terms.add(mapping.entityId);\n else if (mapping.entityType === 'company') preIdentifiedEntities.companies.add(mapping.entityId);\n }\n \n // Step 5: Agentic enhancement using real executor\n // The LLM receives the already-corrected text (simple-replace output)\n // and is told which entities were pre-matched so it doesn't re-lookup them.\n log('info', 'Enhancing with %s...', config.model);\n \n const agenticStart = Date.now();\n const toolContext: Agentic.ToolContext = {\n transcriptText: simpleReplaceResult.text,\n audioDate: input.creation,\n sourceFile: input.audioFile,\n contextInstance: context,\n routingInstance: routing,\n preIdentifiedEntities,\n interactiveMode: config.interactive,\n // Interactive moved to protokoll-cli\n // interactiveInstance: interactive,\n weightModelProvider: config.weightModelProvider,\n onToolCallStart: input.onToolCallStart,\n onToolCallComplete: input.onToolCallComplete,\n };\n \n const executor = Agentic.create(reasoning, toolContext);\n const agenticResult = await executor.process(simpleReplaceResult.text);\n \n state.enhancedText = agenticResult.enhancedText;\n const toolsUsed = agenticResult.toolsUsed;\n const agenticDuration = Date.now() - agenticStart;\n \n // Record tool calls in reflection\n if (reflection) {\n for (const tool of toolsUsed) {\n reflection.collector.recordToolCall(tool, agenticDuration / toolsUsed.length, true);\n }\n reflection.collector.recordCorrection(state.rawTranscript || '', state.enhancedText);\n // Record token usage from agentic result\n if (agenticResult.totalTokens) {\n reflection.collector.recordModelResponse(config.model, agenticResult.totalTokens);\n }\n // Record context changes (new projects, entities created)\n if (agenticResult.contextChanges) {\n for (const change of agenticResult.contextChanges) {\n reflection.collector.recordContextChange(change);\n }\n }\n }\n \n // Write agentic session to intermediate\n await output.writeIntermediate(paths, 'session', {\n iterations: agenticResult.iterations,\n toolsUsed: agenticResult.toolsUsed,\n state: agenticResult.state,\n });\n \n // Step 5b: Check if agentic processing found a different route\n // (e.g., via lookup_project tool finding a project with custom destination)\n if (agenticResult.state.routeDecision?.destination?.path) {\n const agenticRoute = agenticResult.state.routeDecision;\n log('debug', 'Agentic processing found route: %s -> %s', \n agenticRoute.projectId || 'unknown', \n agenticRoute.destination.path\n );\n \n // Update routeResult with the agentic decision\n routeResult.projectId = agenticRoute.projectId || routeResult.projectId;\n routeResult.destination = {\n ...routeResult.destination,\n path: agenticRoute.destination.path,\n structure: agenticRoute.destination.structure || routeResult.destination.structure,\n };\n routeResult.confidence = agenticRoute.confidence || routeResult.confidence;\n routeResult.reasoning = agenticRoute.reasoning || routeResult.reasoning;\n if (agenticRoute.signals) {\n routeResult.signals = agenticRoute.signals;\n }\n \n // Rebuild output path with the new destination\n const newOutputPath = routing.buildOutputPath(routeResult, routingContext);\n log('debug', 'Updated output path: %s -> %s', outputPath, newOutputPath);\n \n // Recreate output paths with new destination\n const newPaths = output.createOutputPaths(\n input.audioFile,\n newOutputPath,\n input.hash,\n input.creation\n );\n await output.ensureDirectories(newPaths);\n \n // Update paths reference (reassign properties since paths is const)\n Object.assign(paths, newPaths);\n }\n\n // Step 5c: Write raw transcript to .transcript/ directory alongside final output\n // This is done AFTER the route is finalized so it goes to the correct location\n // Enables compare and reanalyze workflows\n log('debug', 'Writing raw transcript to .transcript/ directory...');\n await output.writeRawTranscript(paths, {\n text: state.rawTranscript,\n model: config.transcriptionModel,\n duration: whisperDuration,\n audioFile: input.audioFile,\n audioHash: input.hash,\n transcribedAt: new Date().toISOString(),\n });\n\n // Step 6: Write final output using Output module with metadata\n log('debug', 'Writing final transcript...');\n let finalTitle: string | undefined;\n let finalEntities: Metadata.TranscriptMetadata['entities'] | undefined;\n if (state.enhancedText) {\n // Build entity metadata from referenced entities\n const buildEntityReferences = (): Metadata.TranscriptMetadata['entities'] => {\n const refs = agenticResult.state.referencedEntities;\n if (!refs) return undefined;\n \n const entities: NonNullable<Metadata.TranscriptMetadata['entities']> = {\n people: [],\n projects: [],\n terms: [],\n companies: [],\n };\n \n for (const personId of refs.people) {\n if (!personId) continue;\n const person = context.getPerson(personId);\n if (person) {\n entities.people!.push({ id: person.id, name: person.name, type: 'person' });\n }\n }\n \n for (const projectId of refs.projects) {\n if (!projectId) continue;\n const project = context.getProject(projectId);\n if (project) {\n entities.projects!.push({ id: project.id, name: project.name, type: 'project' });\n }\n }\n \n for (const termId of refs.terms) {\n if (!termId) continue;\n const term = context.getTerm(termId);\n if (term) {\n entities.terms!.push({ id: term.id, name: term.name, type: 'term' });\n }\n }\n \n for (const companyId of refs.companies) {\n if (!companyId) continue;\n const company = context.getCompany(companyId);\n if (company) {\n entities.companies!.push({ id: company.id, name: company.name, type: 'company' });\n }\n }\n \n // Only return if we found any entities\n const hasEntities = \n entities.people!.length > 0 ||\n entities.projects!.length > 0 ||\n entities.terms!.length > 0 ||\n entities.companies!.length > 0;\n \n return hasEntities ? entities : undefined;\n };\n \n // Generate title - prefer path-derived title if meaningful, otherwise use LLM\n const pathTitle = extractTitleFromPath(paths.final);\n let title: string;\n if (isMeaningfulTitle(pathTitle)) {\n title = pathTitle!;\n } else {\n log('debug', 'Path-derived title not meaningful (%s), generating from content...', pathTitle || 'empty');\n title = await generateTitleFromContent(state.enhancedText, pathTitle);\n log('info', 'Generated title: %s', title);\n \n // Rebuild output path with the generated title as the subject\n // This ensures the filename matches the title\n const contextWithTitle: Routing.RoutingContext = {\n ...routingContext,\n subjectOverride: title,\n };\n const newOutputPath = routing.buildOutputPath(routeResult, contextWithTitle);\n \n if (newOutputPath !== paths.final) {\n log('debug', 'Updating output path with generated title: %s -> %s', paths.final, newOutputPath);\n \n // Recreate output paths with the new filename\n const newPaths = output.createOutputPaths(\n input.audioFile,\n newOutputPath,\n input.hash,\n input.creation\n );\n await output.ensureDirectories(newPaths);\n \n // Update paths reference\n Object.assign(paths, newPaths);\n }\n }\n \n // Generate UUID for this transcript\n const transcriptUuid = randomUUID();\n \n // Build metadata from routing decision and input\n const transcriptMetadata: Metadata.TranscriptMetadata = {\n id: transcriptUuid,\n title,\n projectId: routeResult.projectId || undefined,\n project: routeResult.projectId ? (context.getProject(routeResult.projectId)?.name || undefined) : undefined,\n date: input.creation,\n routing: Metadata.createRoutingMetadata(routeResult),\n tags: Metadata.extractTagsFromSignals(routeResult.signals),\n confidence: routeResult.confidence,\n entities: buildEntityReferences(),\n };\n \n await output.writeTranscript(paths, state.enhancedText, transcriptMetadata);\n finalTitle = title;\n finalEntities = transcriptMetadata.entities;\n \n // Notify weight model of entity updates (if callback provided)\n if (config.onTranscriptEntitiesUpdated && transcriptMetadata.entities) {\n const allEntityIds: string[] = [];\n if (transcriptMetadata.entities.people) {\n allEntityIds.push(...transcriptMetadata.entities.people.map(e => e.id));\n }\n if (transcriptMetadata.entities.projects) {\n allEntityIds.push(...transcriptMetadata.entities.projects.map(e => e.id));\n }\n if (transcriptMetadata.entities.terms) {\n allEntityIds.push(...transcriptMetadata.entities.terms.map(e => e.id));\n }\n if (transcriptMetadata.entities.companies) {\n allEntityIds.push(...transcriptMetadata.entities.companies.map(e => e.id));\n }\n \n config.onTranscriptEntitiesUpdated(\n transcriptUuid,\n allEntityIds,\n routeResult.projectId || undefined\n );\n }\n }\n \n // Step 7: Generate reflection report\n log('debug', 'Generating reflection report...');\n let reflectionReport: Reflection.ReflectionReport | undefined;\n if (reflection) {\n reflectionReport = reflection.generate(\n input.audioFile,\n paths.final,\n undefined,\n state.enhancedText\n );\n \n if (paths.intermediate.reflection) {\n await reflection.save(reflectionReport, paths.intermediate.reflection);\n }\n }\n \n // Step 8: End interactive session (moved to protokoll-cli)\n log('debug', 'Finalizing session...');\n // let session: Interactive.InteractiveSession | undefined;\n // if (config.interactive) {\n // session = interactive.endSession();\n // log('debug', 'Interactive session ended: %d clarifications', session.responses.length);\n // // Save session if path available\n // if (paths.intermediate.session) {\n // await output.writeIntermediate(paths, 'session', session);\n // }\n // }\n \n // Step 9: Cleanup if needed\n if (!config.keepIntermediates && !config.debug) {\n await output.cleanIntermediates(paths);\n }\n\n // Step 10: Move audio file to processed directory\n let processedAudioPath: string | undefined;\n if (complete) {\n // Extract subject from output path for naming\n const subject = paths.final.split('/').pop()?.replace('.md', '') || undefined;\n processedAudioPath = await complete.complete(\n input.audioFile, \n input.hash, \n input.creation,\n subject\n );\n }\n \n const processingTime = Date.now() - startTime;\n \n // Compact summary output\n log('info', 'Enhancement: %d iterations, %d tools, %.1fs', \n agenticResult.iterations, toolsUsed.length, agenticDuration / 1000);\n if (agenticResult.totalTokens) {\n log('info', 'Tokens: %d total', agenticResult.totalTokens);\n }\n log('info', 'Output: %s (%.1fs total)', paths.final, processingTime / 1000);\n \n return {\n outputPath: paths.final,\n enhancedText: state.enhancedText || '',\n rawTranscript: state.rawTranscript || '',\n title: finalTitle || '',\n routedProject: routeResult.projectId,\n routedProjectName: routeResult.projectId ? (context.getProject(routeResult.projectId)?.name || null) : null,\n routingConfidence: routeResult.confidence,\n entities: finalEntities,\n processingTime,\n toolsUsed,\n correctionsApplied: agenticResult.state.resolvedEntities.size,\n processedAudioPath,\n reflection: reflectionReport,\n // session, // Interactive moved to protokoll-cli\n intermediatePaths: paths,\n };\n \n } catch (error) {\n logger.error('Pipeline error', { error });\n throw error;\n }\n };\n \n return { process: processInput };\n};\n"],"names":["Logging.getLogger","Routing.create","Output.create","Reflection.create","Transcription.create","Reasoning.create","SimpleReplace.create","CompletePhase.create","Agentic.create","Metadata.createRoutingMetadata","Metadata.extractTagsFromSignals"],"mappings":";;;;;;;;;;;;;;AAqCO,MAAM,MAAA,GAAS,OAAO,MAAA,KAA8D;AACvF,EAAA,MAAM,MAAA,GAASA,SAAQ,EAAU;AACjC,EAAA,MAAM,iBAAA,GAAoB,UAAA,CAAW,OAAA,CAAQ,GAAA,EAAI;AAEjD,EAAA,MAAA,CAAO,MAAM,oDAAoD,CAAA;AAKjE,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,eAAA,IAAmB,MAAM,QAAQ,MAAA,CAAO;AAAA,IAC3D,WAAA,EAAa,OAAO,gBAAA,IAAoB,iBAAA;AAAA,IACxC,oBAAoB,MAAA,CAAO;AAAA,GAC9B,CAAA;AACD,EAAA,MAAA,CAAO,MAAM,gEAAgE,CAAA;AAG7E,EAAA,MAAM,WAAA,GAAc,OAAO,eAAA,IAAmB,SAAA;AAC9C,EAAA,MAAM,gBAAA,GAAoB,OAAO,eAAA,IAAmB,OAAA;AACpD,EAAA,MAAM,yBAA0B,MAAA,CAAO,qBAAA,IAAyB,CAAC,MAAA,EAAQ,QAAQ,SAAS,CAAA;AAI1F,EAAA,MAAM,eAAA,GAAkB,QAAQ,cAAA,EAAe;AAC/C,EAAA,MAAM,eAAA,GAA0C,gBAC3C,MAAA,CAAO,CAAA,OAAA,KAAW,QAAQ,MAAA,KAAW,KAAK,CAAA,CAC1C,GAAA,CAAI,CAAA,OAAA,MAA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AAAA,QACA,SAAA;AAAA,QACA,kBAAA,EAAoB,aAAA,CAAc,KAAA,CAAM,gBAAA,CAAiB,IAAA;AAAA,QACzD,kBAAA;AAAA,QACA,UAAA,EAAY,gBAAA;AAAA;AAAA,QAEZ,iBAAA,EAAmB;AAAA,OACvB;AAAA,IAEJ,SAAS,KAAA,EAAO;AACZ,MAAA,MAAA,CAAO,KAAA,CAAM,gBAAA,EAAkB,EAAE,KAAA,EAAO,CAAA;AACxC,MAAA,MAAM,KAAA;AAAA,IACV;AAAA,EACJ,CAAA;AAEA,EAAA,OAAO,EAAE,SAAS,YAAA,EAAa;AACnC;;;;"}
1
+ {"version":3,"file":"index33.js","sources":["../src/pipeline/orchestrator.ts"],"sourcesContent":["/**\n * Pipeline Orchestrator\n *\n * Orchestrates the intelligent transcription pipeline, coordinating\n * all the modules: context, routing, transcription, reasoning,\n * agentic tools, interactive mode, output management, and reflection.\n * \n * THIS IS THE MAIN PROCESSING FLOW - NOT DEAD CODE!\n */\n\nimport { PipelineConfig, PipelineInput, PipelineResult, PipelineState } from './types';\nimport * as Context from '@redaksjon/context';\nimport * as Routing from '../routing';\nimport * as Output from '../out';\nimport * as Reflection from '../reflection';\nimport * as Transcription from '../transcription';\nimport * as Reasoning from '../reasoning';\nimport * as Agentic from '../agentic';\nimport * as CompletePhase from '../phases/complete';\nimport * as SimpleReplace from '../phases/simple-replace';\nimport * as Logging from '../logging';\nimport { randomUUID } from 'node:crypto';\nimport * as path from 'node:path';\nimport * as Metadata from '../util/metadata';\n\nexport interface OrchestratorInstance {\n process(input: PipelineInput): Promise<PipelineResult>;\n}\n\nexport interface OrchestratorConfig extends PipelineConfig {\n outputDirectory: string;\n outputStructure: string;\n outputFilenameOptions: string[];\n maxAudioSize: number;\n tempDirectory: string;\n}\n\nexport const create = async (config: OrchestratorConfig): Promise<OrchestratorInstance> => {\n const logger = Logging.getLogger();\n const currentWorkingDir = globalThis.process.cwd();\n \n logger.debug('Initializing intelligent transcription pipeline...');\n \n // Initialize context system (async)\n // Prefer a pre-loaded context instance (required for GCS-backed storage);\n // otherwise create one from contextDirectory/contextDirectories.\n const context = config.contextInstance ?? await Context.create({\n startingDir: config.contextDirectory || currentWorkingDir,\n contextDirectories: config.contextDirectories,\n });\n logger.debug('Context system initialized - ready to query entities via tools');\n \n // Default routing configuration (used as fallback for projects without custom destination)\n const defaultPath = config.outputDirectory || '~/notes';\n const defaultStructure = (config.outputStructure || 'month') as Routing.FilesystemStructure;\n const defaultFilenameOptions = (config.outputFilenameOptions || ['date', 'time', 'subject']) as Routing.FilenameOption[];\n\n // Convert context projects to routing format\n // Projects without a destination inherit from the global default\n const contextProjects = context.getAllProjects();\n const routingProjects: Routing.ProjectRoute[] = contextProjects\n .filter(project => project.active !== false)\n .map(project => ({\n projectId: project.id,\n destination: {\n path: project.routing?.destination || defaultPath,\n structure: project.routing?.structure || defaultStructure,\n filename_options: project.routing?.filename_options || defaultFilenameOptions,\n createDirectories: true,\n },\n classification: project.classification,\n active: project.active,\n auto_tags: project.routing?.auto_tags,\n }));\n \n logger.debug('Loaded %d projects from context for routing', routingProjects.length);\n \n // Initialize routing with config-based defaults\n const routingConfig: Routing.RoutingConfig = {\n default: {\n path: defaultPath,\n structure: defaultStructure,\n filename_options: defaultFilenameOptions,\n createDirectories: true,\n },\n projects: routingProjects,\n conflict_resolution: 'primary',\n };\n \n const routing = Routing.create(routingConfig, context, config.weightModelProvider);\n logger.debug('Routing system initialized');\n \n // Interactive moved to protokoll-cli\n // const interactive = Interactive.create(\n // { enabled: config.interactive, defaultToSuggestion: true, silent: config.silent },\n // context\n // );\n \n const output = Output.create({\n intermediateDir: config.intermediateDir || './output/protokoll',\n keepIntermediates: config.keepIntermediates ?? true,\n timestampFormat: 'YYMMDD-HHmm',\n });\n logger.debug('Output manager initialized');\n \n const reflection = config.selfReflection \n ? Reflection.create({\n enabled: true,\n format: 'markdown',\n includeConversation: false,\n includeOutput: true,\n })\n : null;\n if (reflection) {\n logger.debug('Self-reflection system enabled');\n }\n \n // Initialize transcription service\n const transcription = Transcription.create({\n defaultModel: config.transcriptionModel as Transcription.TranscriptionModel,\n });\n logger.debug('Transcription service initialized with model: %s', config.transcriptionModel);\n \n // Initialize reasoning for agentic processing\n const reasoning = Reasoning.create({ \n model: config.model,\n reasoningLevel: config.reasoningLevel,\n });\n logger.debug('Reasoning system initialized with model: %s, reasoning level: %s', config.model, config.reasoningLevel || 'medium');\n\n // Initialize simple-replace phase for pre-LLM entity correction via sounds_like\n const simpleReplace = SimpleReplace.create({ debug: config.debug }, context);\n logger.debug('Simple-replace phase initialized with context instance');\n\n // Initialize complete phase for moving files to processed directory\n // Pass outputStructure so processed files use the same directory structure as output\n const complete = config.processedDirectory \n ? CompletePhase.create({\n processedDirectory: config.processedDirectory,\n outputStructure: config.outputStructure as CompletePhase.FilesystemStructure,\n dryRun: config.dryRun,\n })\n : null;\n if (complete) {\n logger.debug('Complete phase initialized with processed directory: %s', config.processedDirectory);\n }\n \n // Helper to extract a human-readable title from the output path\n const extractTitleFromPath = (outputPath: string): string | undefined => {\n const filename = outputPath.split('/').pop()?.replace(/\\.(md|pkl)$/, '');\n if (!filename) return undefined;\n \n // Remove date prefix (e.g., \"27-0716-\" from \"27-0716-meeting-notes\")\n const withoutDate = filename.replace(/^\\d{2}-\\d{4}-/, '');\n if (!withoutDate) return undefined;\n \n // Convert kebab-case to Title Case\n return withoutDate\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n };\n \n // Helper to check if a title is meaningful (not just numbers/timestamps)\n const isMeaningfulTitle = (title: string | undefined): boolean => {\n if (!title) return false;\n // Reject UUID-like strings (hex characters separated by dashes, e.g. filenames from recordings)\n const uuidPattern = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;\n if (uuidPattern.test(title.trim())) return false;\n // Also reject if the title starts with a UUID segment pattern (Title Case converted UUID)\n const uuidSegmentPattern = /^[0-9a-f]{8}\\s[0-9a-f]{4}\\s/i;\n if (uuidSegmentPattern.test(title.trim())) return false;\n // Check if title is mostly numbers (timestamp-like) or very short fragments\n const stripped = title.replace(/\\s+/g, '');\n const numberRatio = (stripped.match(/\\d/g) || []).length / stripped.length;\n // Reject if: mostly numbers, too short, or common bad patterns\n if (numberRatio > 0.5) return false;\n if (stripped.length < 3) return false;\n // Reject titles that are just common words without context\n const badPatterns = /^(i|i have|i am|the|a|an|um|uh|so|well|okay|oh|hey|hi)$/i;\n if (badPatterns.test(title.trim())) return false;\n return true;\n };\n \n // Generate a meaningful title from transcript content using LLM\n const generateTitleFromContent = async (transcriptText: string, fallbackTitle?: string): Promise<string> => {\n try {\n // Use first ~2000 chars for title generation (enough context, not too expensive)\n const textSample = transcriptText.slice(0, 2000);\n \n const response = await reasoning.complete({\n systemPrompt: `You are a title generator. Given a transcript, generate a concise, descriptive title (3-8 words) that captures the main topic or theme.\n\nRules:\n- Output ONLY the title, nothing else\n- No quotes around the title\n- Use Title Case\n- Be specific - avoid generic titles like \"Meeting Notes\" or \"Discussion\"\n- Focus on the main subject matter\n- If there are multiple topics, pick the most prominent one`,\n prompt: `Generate a title for this transcript:\\n\\n${textSample}`,\n });\n \n // Clean up the response - remove quotes, trim whitespace\n const title = response.content\n .trim()\n .replace(/^[\"']|[\"']$/g, '') // Remove surrounding quotes\n .replace(/^#\\s*/, '') // Remove markdown heading prefix\n .trim();\n \n // Validate the generated title\n if (title && title.length > 0 && title.length < 100) {\n logger.debug('Generated title from content: %s', title);\n return title;\n }\n \n logger.debug('Generated title was invalid, using fallback');\n return fallbackTitle || 'Untitled';\n } catch (error) {\n logger.warn('Title generation failed, using fallback', { error });\n return fallbackTitle || 'Untitled';\n }\n };\n\n const processInput = async (input: PipelineInput): Promise<PipelineResult> => {\n const startTime = Date.now();\n \n // Format progress prefix for log messages\n const progressPrefix = input.progress \n ? `[${input.progress.current}/${input.progress.total}]` \n : '';\n const log = (level: 'info' | 'debug', message: string, ...args: unknown[]) => {\n const prefixedMessage = progressPrefix ? `${progressPrefix} ${message}` : message;\n if (level === 'info') {\n logger.info(prefixedMessage, ...args);\n } else {\n logger.debug(prefixedMessage, ...args);\n }\n };\n \n log('info', 'Processing: %s (hash: %s)', input.audioFile, input.hash);\n \n // Initialize state\n const state: PipelineState = {\n input,\n startTime: new Date(),\n };\n \n // Start reflection collection if enabled\n if (reflection) {\n reflection.collector.start();\n }\n \n // Start interactive session if enabled\n // Interactive moved to protokoll-cli\n // if (config.interactive) {\n // interactive.startSession();\n // log('debug', 'Interactive session started');\n // }\n \n try {\n // Step 1: Check onboarding needs (moved to protokoll-cli)\n log('debug', 'Checking onboarding state...');\n // const onboardingState = interactive.checkNeedsOnboarding();\n const onboardingState = { needsOnboarding: false }; // Stub\n if (onboardingState.needsOnboarding) {\n log('debug', 'First-run detected - onboarding may be triggered');\n }\n \n // Step 2: Raw transcription using Transcription module\n log('info', 'Transcribing audio...');\n const whisperStart = Date.now();\n \n const transcriptionResult = await transcription.transcribe(input.audioFile, {\n model: config.transcriptionModel as Transcription.TranscriptionModel,\n });\n state.rawTranscript = transcriptionResult.text;\n \n const whisperDuration = Date.now() - whisperStart;\n log('info', 'Transcription: %d chars in %.1fs', \n state.rawTranscript.length, whisperDuration / 1000);\n \n if (reflection) {\n reflection.collector.recordWhisper(whisperDuration);\n }\n \n // Step 3: Route detection\n log('debug', 'Determining routing destination...');\n const routingContext: Routing.RoutingContext = {\n transcriptText: state.rawTranscript || '',\n audioDate: input.creation,\n sourceFile: input.audioFile,\n hash: input.hash,\n };\n \n const routeResult = routing.route(routingContext);\n \n log('debug', 'Routing decision: project=%s, confidence=%.2f', \n routeResult.projectId || 'default', routeResult.confidence);\n \n // Record routing decision in reflection\n if (reflection) {\n reflection.collector.recordRoutingDecision({\n projectId: routeResult.projectId,\n destination: routeResult.destination.path,\n confidence: routeResult.confidence,\n reasoning: routeResult.reasoning,\n signals: routeResult.signals.map(s => ({\n type: s.type,\n value: s.value,\n weight: s.weight,\n })),\n alternativesConsidered: routeResult.alternateMatches?.map(alt => ({\n projectId: alt.projectId,\n confidence: alt.confidence,\n whyNotChosen: `Lower confidence (${(alt.confidence * 100).toFixed(1)}%)`,\n })),\n });\n }\n \n // Build output path\n const outputPath = routing.buildOutputPath(routeResult, routingContext);\n log('debug', 'Output path: %s', outputPath);\n \n // Step 4: Create output paths using Output module\n log('debug', 'Setting up output directories...');\n const paths = output.createOutputPaths(\n input.audioFile,\n outputPath,\n input.hash,\n input.creation\n );\n \n await output.ensureDirectories(paths);\n \n // Write raw transcript to intermediate (for debugging)\n await output.writeIntermediate(paths, 'transcript', {\n text: state.rawTranscript,\n model: config.transcriptionModel,\n duration: whisperDuration,\n });\n\n // Step 4b: Simple-replace phase — sounds_like entity correction before LLM\n // Matches entity names (projects, people, terms) using sounds_like mappings,\n // corrects them in the transcript text, and tracks which entities were found.\n log('debug', 'Running simple-replace (sounds_like entity matching)...');\n // Derive the intermediate directory from an existing intermediate file path\n const intermediateDir = path.dirname(paths.intermediate.transcript);\n const simpleReplaceResult = await simpleReplace.replace(\n state.rawTranscript || '',\n {\n project: routeResult.projectId ?? undefined,\n confidence: routeResult.confidence,\n },\n intermediateDir,\n input.hash\n );\n\n if (simpleReplaceResult.replacementsMade) {\n log('info',\n 'Simple-replace: %d correction(s) applied (%d Tier-1, %d Tier-2)',\n simpleReplaceResult.stats.totalReplacements,\n simpleReplaceResult.stats.tier1Replacements,\n simpleReplaceResult.stats.tier2Replacements\n );\n // Write the corrected text to intermediate for inspection\n await output.writeIntermediate(paths, 'session', {\n simpleReplace: {\n replacementsMade: true,\n stats: simpleReplaceResult.stats,\n },\n });\n } else {\n log('debug', 'Simple-replace: no replacements made');\n }\n\n // Notify caller (e.g. worker) so it can write to the PKL enhancement log\n input.onSimpleReplaceComplete?.(simpleReplaceResult.stats);\n\n // Collect pre-identified entities from simple-replace applied mappings\n const preIdentifiedEntities: Agentic.ToolContext['preIdentifiedEntities'] = {\n people: new Set<string>(),\n projects: new Set<string>(),\n terms: new Set<string>(),\n companies: new Set<string>(),\n };\n for (const mapping of simpleReplaceResult.stats.appliedMappings) {\n if (!mapping.entityId || !mapping.entityType) continue;\n if (mapping.entityType === 'person') preIdentifiedEntities.people.add(mapping.entityId);\n else if (mapping.entityType === 'project') preIdentifiedEntities.projects.add(mapping.entityId);\n else if (mapping.entityType === 'term') preIdentifiedEntities.terms.add(mapping.entityId);\n else if (mapping.entityType === 'company') preIdentifiedEntities.companies.add(mapping.entityId);\n }\n \n // Step 5: Agentic enhancement using real executor\n // The LLM receives the already-corrected text (simple-replace output)\n // and is told which entities were pre-matched so it doesn't re-lookup them.\n log('info', 'Enhancing with %s...', config.model);\n \n const agenticStart = Date.now();\n const toolContext: Agentic.ToolContext = {\n transcriptText: simpleReplaceResult.text,\n audioDate: input.creation,\n sourceFile: input.audioFile,\n contextInstance: context,\n routingInstance: routing,\n preIdentifiedEntities,\n interactiveMode: config.interactive,\n // Interactive moved to protokoll-cli\n // interactiveInstance: interactive,\n weightModelProvider: config.weightModelProvider,\n onToolCallStart: input.onToolCallStart,\n onToolCallComplete: input.onToolCallComplete,\n onModelCallStart: input.onModelCallStart,\n onModelCallComplete: input.onModelCallComplete,\n modelConfiguration: {\n model: config.model,\n reasoningLevel: config.reasoningLevel,\n },\n };\n \n const executor = Agentic.create(reasoning, toolContext);\n const agenticResult = await executor.process(simpleReplaceResult.text);\n \n state.enhancedText = agenticResult.enhancedText;\n const toolsUsed = agenticResult.toolsUsed;\n const agenticDuration = Date.now() - agenticStart;\n \n // Record tool calls in reflection\n if (reflection) {\n for (const tool of toolsUsed) {\n reflection.collector.recordToolCall(tool, agenticDuration / toolsUsed.length, true);\n }\n reflection.collector.recordCorrection(state.rawTranscript || '', state.enhancedText);\n // Record token usage from agentic result\n if (agenticResult.totalTokens) {\n reflection.collector.recordModelResponse(config.model, agenticResult.totalTokens);\n }\n // Record context changes (new projects, entities created)\n if (agenticResult.contextChanges) {\n for (const change of agenticResult.contextChanges) {\n reflection.collector.recordContextChange(change);\n }\n }\n }\n \n // Write agentic session to intermediate\n await output.writeIntermediate(paths, 'session', {\n iterations: agenticResult.iterations,\n toolsUsed: agenticResult.toolsUsed,\n state: agenticResult.state,\n });\n \n // Step 5b: Check if agentic processing found a different route\n // (e.g., via lookup_project tool finding a project with custom destination)\n if (agenticResult.state.routeDecision?.destination?.path) {\n const agenticRoute = agenticResult.state.routeDecision;\n log('debug', 'Agentic processing found route: %s -> %s', \n agenticRoute.projectId || 'unknown', \n agenticRoute.destination.path\n );\n \n // Update routeResult with the agentic decision\n routeResult.projectId = agenticRoute.projectId || routeResult.projectId;\n routeResult.destination = {\n ...routeResult.destination,\n path: agenticRoute.destination.path,\n structure: agenticRoute.destination.structure || routeResult.destination.structure,\n };\n routeResult.confidence = agenticRoute.confidence || routeResult.confidence;\n routeResult.reasoning = agenticRoute.reasoning || routeResult.reasoning;\n if (agenticRoute.signals) {\n routeResult.signals = agenticRoute.signals;\n }\n \n // Rebuild output path with the new destination\n const newOutputPath = routing.buildOutputPath(routeResult, routingContext);\n log('debug', 'Updated output path: %s -> %s', outputPath, newOutputPath);\n \n // Recreate output paths with new destination\n const newPaths = output.createOutputPaths(\n input.audioFile,\n newOutputPath,\n input.hash,\n input.creation\n );\n await output.ensureDirectories(newPaths);\n \n // Update paths reference (reassign properties since paths is const)\n Object.assign(paths, newPaths);\n }\n\n // Step 5c: Write raw transcript to .transcript/ directory alongside final output\n // This is done AFTER the route is finalized so it goes to the correct location\n // Enables compare and reanalyze workflows\n log('debug', 'Writing raw transcript to .transcript/ directory...');\n await output.writeRawTranscript(paths, {\n text: state.rawTranscript,\n model: config.transcriptionModel,\n duration: whisperDuration,\n audioFile: input.audioFile,\n audioHash: input.hash,\n transcribedAt: new Date().toISOString(),\n });\n\n // Step 6: Write final output using Output module with metadata\n log('debug', 'Writing final transcript...');\n let finalTitle: string | undefined;\n let finalEntities: Metadata.TranscriptMetadata['entities'] | undefined;\n if (state.enhancedText) {\n // Build entity metadata from referenced entities\n const buildEntityReferences = (): Metadata.TranscriptMetadata['entities'] => {\n const refs = agenticResult.state.referencedEntities;\n if (!refs) return undefined;\n \n const entities: NonNullable<Metadata.TranscriptMetadata['entities']> = {\n people: [],\n projects: [],\n terms: [],\n companies: [],\n };\n \n for (const personId of refs.people) {\n if (!personId) continue;\n const person = context.getPerson(personId);\n if (person) {\n entities.people!.push({ id: person.id, name: person.name, type: 'person' });\n }\n }\n \n for (const projectId of refs.projects) {\n if (!projectId) continue;\n const project = context.getProject(projectId);\n if (project) {\n entities.projects!.push({ id: project.id, name: project.name, type: 'project' });\n }\n }\n \n for (const termId of refs.terms) {\n if (!termId) continue;\n const term = context.getTerm(termId);\n if (term) {\n entities.terms!.push({ id: term.id, name: term.name, type: 'term' });\n }\n }\n \n for (const companyId of refs.companies) {\n if (!companyId) continue;\n const company = context.getCompany(companyId);\n if (company) {\n entities.companies!.push({ id: company.id, name: company.name, type: 'company' });\n }\n }\n \n // Only return if we found any entities\n const hasEntities = \n entities.people!.length > 0 ||\n entities.projects!.length > 0 ||\n entities.terms!.length > 0 ||\n entities.companies!.length > 0;\n \n return hasEntities ? entities : undefined;\n };\n \n // Generate title - prefer path-derived title if meaningful, otherwise use LLM\n const pathTitle = extractTitleFromPath(paths.final);\n let title: string;\n if (isMeaningfulTitle(pathTitle)) {\n title = pathTitle!;\n } else {\n log('debug', 'Path-derived title not meaningful (%s), generating from content...', pathTitle || 'empty');\n title = await generateTitleFromContent(state.enhancedText, pathTitle);\n log('info', 'Generated title: %s', title);\n \n // Rebuild output path with the generated title as the subject\n // This ensures the filename matches the title\n const contextWithTitle: Routing.RoutingContext = {\n ...routingContext,\n subjectOverride: title,\n };\n const newOutputPath = routing.buildOutputPath(routeResult, contextWithTitle);\n \n if (newOutputPath !== paths.final) {\n log('debug', 'Updating output path with generated title: %s -> %s', paths.final, newOutputPath);\n \n // Recreate output paths with the new filename\n const newPaths = output.createOutputPaths(\n input.audioFile,\n newOutputPath,\n input.hash,\n input.creation\n );\n await output.ensureDirectories(newPaths);\n \n // Update paths reference\n Object.assign(paths, newPaths);\n }\n }\n \n // Generate UUID for this transcript\n const transcriptUuid = randomUUID();\n \n // Build metadata from routing decision and input\n const transcriptMetadata: Metadata.TranscriptMetadata = {\n id: transcriptUuid,\n title,\n projectId: routeResult.projectId || undefined,\n project: routeResult.projectId ? (context.getProject(routeResult.projectId)?.name || undefined) : undefined,\n date: input.creation,\n routing: Metadata.createRoutingMetadata(routeResult),\n tags: Metadata.extractTagsFromSignals(routeResult.signals),\n confidence: routeResult.confidence,\n entities: buildEntityReferences(),\n };\n \n await output.writeTranscript(paths, state.enhancedText, transcriptMetadata);\n finalTitle = title;\n finalEntities = transcriptMetadata.entities;\n \n // Notify weight model of entity updates (if callback provided)\n if (config.onTranscriptEntitiesUpdated && transcriptMetadata.entities) {\n const allEntityIds: string[] = [];\n if (transcriptMetadata.entities.people) {\n allEntityIds.push(...transcriptMetadata.entities.people.map(e => e.id));\n }\n if (transcriptMetadata.entities.projects) {\n allEntityIds.push(...transcriptMetadata.entities.projects.map(e => e.id));\n }\n if (transcriptMetadata.entities.terms) {\n allEntityIds.push(...transcriptMetadata.entities.terms.map(e => e.id));\n }\n if (transcriptMetadata.entities.companies) {\n allEntityIds.push(...transcriptMetadata.entities.companies.map(e => e.id));\n }\n \n config.onTranscriptEntitiesUpdated(\n transcriptUuid,\n allEntityIds,\n routeResult.projectId || undefined\n );\n }\n }\n \n // Step 7: Generate reflection report\n log('debug', 'Generating reflection report...');\n let reflectionReport: Reflection.ReflectionReport | undefined;\n if (reflection) {\n reflectionReport = reflection.generate(\n input.audioFile,\n paths.final,\n undefined,\n state.enhancedText\n );\n \n if (paths.intermediate.reflection) {\n await reflection.save(reflectionReport, paths.intermediate.reflection);\n }\n }\n \n // Step 8: End interactive session (moved to protokoll-cli)\n log('debug', 'Finalizing session...');\n // let session: Interactive.InteractiveSession | undefined;\n // if (config.interactive) {\n // session = interactive.endSession();\n // log('debug', 'Interactive session ended: %d clarifications', session.responses.length);\n // // Save session if path available\n // if (paths.intermediate.session) {\n // await output.writeIntermediate(paths, 'session', session);\n // }\n // }\n \n // Step 9: Cleanup if needed\n if (!config.keepIntermediates && !config.debug) {\n await output.cleanIntermediates(paths);\n }\n\n // Step 10: Move audio file to processed directory\n let processedAudioPath: string | undefined;\n if (complete) {\n // Extract subject from output path for naming\n const subject = paths.final.split('/').pop()?.replace('.md', '') || undefined;\n processedAudioPath = await complete.complete(\n input.audioFile, \n input.hash, \n input.creation,\n subject\n );\n }\n \n const processingTime = Date.now() - startTime;\n \n // Compact summary output\n log('info', 'Enhancement: %d iterations, %d tools, %.1fs', \n agenticResult.iterations, toolsUsed.length, agenticDuration / 1000);\n if (agenticResult.totalTokens) {\n log('info', 'Tokens: %d total', agenticResult.totalTokens);\n }\n log('info', 'Output: %s (%.1fs total)', paths.final, processingTime / 1000);\n \n return {\n outputPath: paths.final,\n enhancedText: state.enhancedText || '',\n rawTranscript: state.rawTranscript || '',\n title: finalTitle || '',\n routedProject: routeResult.projectId,\n routedProjectName: routeResult.projectId ? (context.getProject(routeResult.projectId)?.name || null) : null,\n routingConfidence: routeResult.confidence,\n entities: finalEntities,\n processingTime,\n toolsUsed,\n correctionsApplied: agenticResult.state.resolvedEntities.size,\n processedAudioPath,\n reflection: reflectionReport,\n // session, // Interactive moved to protokoll-cli\n intermediatePaths: paths,\n };\n \n } catch (error) {\n logger.error('Pipeline error', { error });\n throw error;\n }\n };\n \n return { process: processInput };\n};\n"],"names":["Logging.getLogger","Routing.create","Output.create","Reflection.create","Transcription.create","Reasoning.create","SimpleReplace.create","CompletePhase.create","Agentic.create","Metadata.createRoutingMetadata","Metadata.extractTagsFromSignals"],"mappings":";;;;;;;;;;;;;;AAqCO,MAAM,MAAA,GAAS,OAAO,MAAA,KAA8D;AACvF,EAAA,MAAM,MAAA,GAASA,SAAQ,EAAU;AACjC,EAAA,MAAM,iBAAA,GAAoB,UAAA,CAAW,OAAA,CAAQ,GAAA,EAAI;AAEjD,EAAA,MAAA,CAAO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package/dist/index34.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { getLogger } from './index47.js';
2
2
  import { create as create$1 } from './index13.js';
3
3
  import { create as create$2 } from './index14.js';
4
- import { transcribeAudio } from './index53.js';
5
- import { stringifyJSON } from './index54.js';
4
+ import { transcribeAudio } from './index54.js';
5
+ import { stringifyJSON } from './index55.js';
6
6
  import path__default from 'node:path';
7
7
  import { create as create$4 } from './index5.js';
8
8
  import { create as create$3 } from './index2.js';
package/dist/index35.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { getLogger } from './index47.js';
2
2
  import { create as create$1 } from './index13.js';
3
- import { create as create$2 } from './index55.js';
4
- import { create as create$3 } from './index56.js';
5
- import { create as create$4 } from './index57.js';
6
- import { stringifyJSON } from './index54.js';
3
+ import { create as create$2 } from './index56.js';
4
+ import { create as create$3 } from './index57.js';
5
+ import { create as create$4 } from './index58.js';
6
+ import { stringifyJSON } from './index55.js';
7
7
  import path from 'path';
8
8
 
9
9
  const create = (config, contextInstance) => {
package/dist/index36.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getLogger } from './index47.js';
2
2
  import { create as create$3 } from './index14.js';
3
3
  import { create as create$1 } from './index13.js';
4
- import { create as create$2 } from './index58.js';
4
+ import { create as create$2 } from './index59.js';
5
5
  import { DEFAULT_INTERMEDIATE_DIRECTORY } from './index18.js';
6
6
  import path__default from 'node:path';
7
7
 
package/dist/index53.js CHANGED
@@ -1,51 +1,8 @@
1
- import { OpenAI } from 'openai';
2
- import { create } from './index13.js';
3
- import { getLogger } from './index47.js';
4
- import { DEFAULT_TRANSCRIPTION_MODEL } from './index18.js';
1
+ import { create as create$1 } from './index60.js';
5
2
 
6
- class OpenAIError extends Error {
7
- constructor(message) {
8
- super(message);
9
- this.name = "OpenAIError";
10
- }
11
- }
12
- async function transcribeAudio(filePath, options = {}) {
13
- const logger = getLogger();
14
- const storage$1 = create({ log: logger.debug });
15
- try {
16
- const apiKey = process.env.OPENAI_API_KEY;
17
- if (!apiKey) {
18
- throw new OpenAIError("OPENAI_API_KEY environment variable is not set");
19
- }
20
- const openai = new OpenAI({
21
- apiKey
22
- });
23
- const model = options.model || DEFAULT_TRANSCRIPTION_MODEL;
24
- const fileName = filePath.split("/").pop() || filePath;
25
- logger.debug("Transcribing: %s (full path: %s)", fileName, filePath);
26
- const startTime = Date.now();
27
- const audioStream = await storage$1.readStream(filePath);
28
- const transcription = await openai.audio.transcriptions.create({
29
- model,
30
- file: audioStream,
31
- response_format: "json"
32
- });
33
- if (!transcription) {
34
- throw new OpenAIError("No transcription received from OpenAI");
35
- }
36
- const duration = ((Date.now() - startTime) / 1e3).toFixed(1);
37
- logger.info("%s (%ss, %d chars)", model, duration, transcription.text?.length || 0);
38
- if (options.debug && options.debugFile) {
39
- await storage$1.writeFile(options.debugFile, JSON.stringify(transcription, null, 2), "utf8");
40
- logger.debug("Wrote debug file to %s", options.debugFile);
41
- }
42
- logger.debug("Received transcription from OpenAI: %s", transcription);
43
- return transcription;
44
- } catch (error) {
45
- logger.error("Error transcribing audio file: %s %s", error.message, error.stack);
46
- throw new OpenAIError(`Failed to transcribe audio: ${error.message}`);
47
- }
48
- }
3
+ const create = (config) => {
4
+ return create$1(config);
5
+ };
49
6
 
50
- export { OpenAIError, transcribeAudio };
7
+ export { create };
51
8
  //# sourceMappingURL=index53.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index53.js","sources":["../src/util/openai.ts"],"sourcesContent":["import { OpenAI } from 'openai';\nimport { ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from 'openai/resources/chat/completions';\nimport * as Storage from '@/util/storage';\nimport { getLogger } from '@/logging';\nimport { DEFAULT_MODEL, DEFAULT_TRANSCRIPTION_MODEL } from '@/constants';\n\nexport interface Transcription {\n text: string;\n}\n\nexport class OpenAIError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OpenAIError';\n }\n}\n\n\nexport async function createCompletion(messages: ChatCompletionMessageParam[], options: { responseFormat?: any, model?: string, reasoningLevel?: 'none' | 'low' | 'medium' | 'high', maxTokens?: number, debug?: boolean, debugFile?: string, reason?: string } = {}): Promise<string | any> {\n const logger = getLogger();\n const storage = Storage.create({ log: logger.debug });\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n const openai = new OpenAI({\n apiKey: apiKey,\n });\n\n const model = options.model || DEFAULT_MODEL;\n \n // Check if model supports reasoning_effort\n const supportsReasoning = model.includes('gpt-5') || \n model.includes('o1') || model.includes('o3');\n const isReasoningCall = supportsReasoning && options.reasoningLevel && options.reasoningLevel !== 'none';\n \n logger.debug('Sending prompt to OpenAI: %j', messages);\n\n const startTime = Date.now();\n \n const requestParams: Record<string, unknown> = {\n model,\n messages,\n max_completion_tokens: options.maxTokens || 10000,\n response_format: options.responseFormat,\n };\n \n if (isReasoningCall) {\n requestParams.reasoning_effort = options.reasoningLevel;\n logger.debug('Using reasoning_effort: %s', options.reasoningLevel);\n }\n \n const completion = await openai.chat.completions.create(\n requestParams as unknown as ChatCompletionCreateParamsNonStreaming\n );\n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n\n // Log token usage with reason if provided\n const usage = completion.usage;\n const reasonSuffix = options.reason ? ` - ${options.reason}` : '';\n if (usage) {\n logger.info('%s (%ss, %d→%d tokens)%s', \n model, duration, usage.prompt_tokens, usage.completion_tokens, reasonSuffix);\n } else {\n logger.info('%s (%ss)%s', model, duration, reasonSuffix);\n }\n\n if (options.debug && options.debugFile) {\n await storage.writeFile(options.debugFile, JSON.stringify(completion, null, 2), 'utf8');\n logger.debug('Wrote debug file to %s', options.debugFile);\n }\n\n const response = completion.choices[0]?.message?.content?.trim();\n if (!response) {\n // Log the full completion object to help debug\n logger.error('Empty response from OpenAI. Full completion object: %j', completion);\n throw new OpenAIError('No response received from OpenAI');\n }\n\n logger.debug('Received response from OpenAI: %s', response);\n if (options.responseFormat) {\n return JSON.parse(response);\n } else {\n return response;\n }\n\n } catch (error: any) {\n logger.error('Error calling OpenAI API: %s %s', error.message, error.stack);\n throw new OpenAIError(`Failed to create completion: ${error.message}`);\n }\n}\n\nexport async function transcribeAudio(filePath: string, options: { model?: string, debug?: boolean, debugFile?: string } = {}): Promise<Transcription> {\n const logger = getLogger();\n const storage = Storage.create({ log: logger.debug });\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n const openai = new OpenAI({\n apiKey: apiKey,\n });\n\n const model = options.model || DEFAULT_TRANSCRIPTION_MODEL;\n const fileName = filePath.split('/').pop() || filePath;\n logger.debug('Transcribing: %s (full path: %s)', fileName, filePath);\n\n const startTime = Date.now();\n const audioStream = await storage.readStream(filePath);\n const transcription = await openai.audio.transcriptions.create({\n model,\n file: audioStream,\n response_format: \"json\",\n });\n \n if (!transcription) {\n throw new OpenAIError('No transcription received from OpenAI');\n }\n \n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n logger.info('%s (%ss, %d chars)', model, duration, transcription.text?.length || 0);\n\n if (options.debug && options.debugFile) {\n await storage.writeFile(options.debugFile, JSON.stringify(transcription, null, 2), 'utf8');\n logger.debug('Wrote debug file to %s', options.debugFile);\n }\n\n logger.debug('Received transcription from OpenAI: %s', transcription);\n return transcription;\n\n } catch (error: any) {\n logger.error('Error transcribing audio file: %s %s', error.message, error.stack);\n throw new OpenAIError(`Failed to transcribe audio: ${error.message}`);\n }\n}\n"],"names":["storage","Storage.create"],"mappings":";;;;;AAUO,MAAM,oBAAoB,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EAChB;AACJ;AA+EA,eAAsB,eAAA,CAAgB,QAAA,EAAkB,OAAA,GAAmE,EAAC,EAA2B;AACnJ,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,MAAMA,YAA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,SAAA,EAAW,IAAA,CAAK,UAAU,aAAA,EAAe,IAAA,EAAM,CAAC,CAAA,EAAG,MAAM,CAAA;AACzF,MAAA,MAAA,CAAO,KAAA,CAAM,wBAAA,EAA0B,OAAA,CAAQ,SAAS,CAAA;AAAA,IAC5D;AAEA,IAAA,MAAA,CAAO,KAAA,CAAM,0CAA0C,aAAa,CAAA;AACpE,IAAA,OAAO,aAAA;AAAA,EAEX,SAAS,KAAA,EAAY;AACjB,IAAA,MAAA,CAAO,KAAA,CAAM,sCAAA,EAAwC,KAAA,CAAM,OAAA,EAAS,MAAM,KAAK,CAAA;AAC/E,IAAA,MAAM,IAAI,WAAA,CAAY,CAAA,4BAAA,EAA+B,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,EACxE;AACJ;;;;"}
1
+ {"version":3,"file":"index53.js","sources":["../src/out/index.ts"],"sourcesContent":["/**\n * Output Management System\n *\n * Main entry point for the output management system. Handles intermediate\n * files and final output destinations.\n */\n\nimport { OutputConfig, OutputPaths, IntermediateFiles, RawTranscriptData } from './types';\nimport * as Manager from './manager';\nimport * as Metadata from '../util/metadata';\n\nexport interface OutputInstance {\n createOutputPaths(\n audioFile: string,\n routedDestination: string,\n hash: string,\n date: Date\n ): OutputPaths;\n ensureDirectories(paths: OutputPaths): Promise<void>;\n writeIntermediate(\n paths: OutputPaths,\n type: keyof IntermediateFiles,\n content: unknown\n ): Promise<string>;\n /**\n * Write the raw Whisper transcript to the .transcript/ directory alongside final output.\n * This enables compare and reanalyze workflows.\n */\n writeRawTranscript(paths: OutputPaths, data: RawTranscriptData): Promise<string>;\n writeTranscript(paths: OutputPaths, content: string, metadata?: Metadata.TranscriptMetadata): Promise<string>;\n /**\n * Read a previously stored raw transcript from the .transcript/ directory.\n * Returns null if no raw transcript exists.\n */\n readRawTranscript(finalOutputPath: string): Promise<RawTranscriptData | null>;\n cleanIntermediates(paths: OutputPaths): Promise<void>;\n}\n\nexport const create = (config: OutputConfig): OutputInstance => {\n return Manager.create(config);\n};\n\nexport const DEFAULT_OUTPUT_CONFIG: OutputConfig = {\n intermediateDir: './output/protokoll',\n keepIntermediates: true,\n timestampFormat: 'YYMMDD-HHmm',\n};\n\n// Re-export types\nexport * from './types';\n"],"names":["Manager.create"],"mappings":";;AAsCO,MAAM,MAAA,GAAS,CAAC,MAAA,KAAyC;AAC5D,EAAA,OAAOA,SAAe,MAAM,CAAA;AAChC;;;;"}
package/dist/index54.js CHANGED
@@ -1,39 +1,51 @@
1
- const stringifyJSON = function(obj) {
2
- const arrOfKeyVals = [];
3
- const arrVals = [];
4
- let objKeys = [];
5
- if (typeof obj === "number" || typeof obj === "boolean" || obj === null)
6
- return "" + obj;
7
- else if (typeof obj === "string")
8
- return '"' + obj + '"';
9
- else if (Array.isArray(obj)) {
10
- if (obj[0] === void 0)
11
- return "[]";
12
- else {
13
- obj.forEach(function(el) {
14
- arrVals.push(stringifyJSON(el));
15
- });
16
- return "[" + arrVals + "]";
1
+ import { OpenAI } from 'openai';
2
+ import { create } from './index13.js';
3
+ import { getLogger } from './index47.js';
4
+ import { DEFAULT_TRANSCRIPTION_MODEL } from './index18.js';
5
+
6
+ class OpenAIError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "OpenAIError";
10
+ }
11
+ }
12
+ async function transcribeAudio(filePath, options = {}) {
13
+ const logger = getLogger();
14
+ const storage$1 = create({ log: logger.debug });
15
+ try {
16
+ const apiKey = process.env.OPENAI_API_KEY;
17
+ if (!apiKey) {
18
+ throw new OpenAIError("OPENAI_API_KEY environment variable is not set");
17
19
  }
18
- } else if (obj instanceof Object) {
19
- objKeys = Object.keys(obj);
20
- objKeys.forEach(function(key) {
21
- const keyOut = '"' + key + '":';
22
- const keyValOut = obj[key];
23
- if (keyValOut instanceof Function || keyValOut === void 0)
24
- arrOfKeyVals.push("");
25
- else if (typeof keyValOut === "string")
26
- arrOfKeyVals.push(keyOut + '"' + keyValOut + '"');
27
- else if (typeof keyValOut === "boolean" || typeof keyValOut === "number" || keyValOut === null)
28
- arrOfKeyVals.push(keyOut + keyValOut);
29
- else if (keyValOut instanceof Object) {
30
- arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut));
31
- }
20
+ const openai = new OpenAI({
21
+ apiKey
22
+ });
23
+ const model = options.model || DEFAULT_TRANSCRIPTION_MODEL;
24
+ const fileName = filePath.split("/").pop() || filePath;
25
+ logger.debug("Transcribing: %s (full path: %s)", fileName, filePath);
26
+ const startTime = Date.now();
27
+ const audioStream = await storage$1.readStream(filePath);
28
+ const transcription = await openai.audio.transcriptions.create({
29
+ model,
30
+ file: audioStream,
31
+ response_format: "json"
32
32
  });
33
- return "{" + arrOfKeyVals + "}";
33
+ if (!transcription) {
34
+ throw new OpenAIError("No transcription received from OpenAI");
35
+ }
36
+ const duration = ((Date.now() - startTime) / 1e3).toFixed(1);
37
+ logger.info("%s (%ss, %d chars)", model, duration, transcription.text?.length || 0);
38
+ if (options.debug && options.debugFile) {
39
+ await storage$1.writeFile(options.debugFile, JSON.stringify(transcription, null, 2), "utf8");
40
+ logger.debug("Wrote debug file to %s", options.debugFile);
41
+ }
42
+ logger.debug("Received transcription from OpenAI: %s", transcription);
43
+ return transcription;
44
+ } catch (error) {
45
+ logger.error("Error transcribing audio file: %s %s", error.message, error.stack);
46
+ throw new OpenAIError(`Failed to transcribe audio: ${error.message}`);
34
47
  }
35
- return "";
36
- };
48
+ }
37
49
 
38
- export { stringifyJSON };
50
+ export { OpenAIError, transcribeAudio };
39
51
  //# sourceMappingURL=index54.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index54.js","sources":["../src/util/general.ts"],"sourcesContent":["// Utility function for deep merging two objects.\nexport function deepMerge(target: any, source: any): any {\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n // Block prototype-polluting keys\n if (key === '__proto__' || key === 'constructor') {\n continue;\n }\n if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\n if (!target[key]) {\n target[key] = {};\n }\n deepMerge(target[key], source[key]);\n } else {\n target[key] = source[key];\n }\n }\n }\n return target;\n}\n\n//Recursive implementation of jSON.stringify;\nexport const stringifyJSON = function (obj: any): string {\n\n const arrOfKeyVals: string[] = [];\n const arrVals: string[] = [];\n let objKeys: string[] = [];\n\n /*********CHECK FOR PRIMITIVE TYPES**********/\n if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)\n return '' + obj;\n else if (typeof obj === 'string')\n return '\"' + obj + '\"';\n\n /*********CHECK FOR ARRAY**********/\n else if (Array.isArray(obj)) {\n //check for empty array\n if (obj[0] === undefined)\n return '[]';\n else {\n obj.forEach(function (el) {\n arrVals.push(stringifyJSON(el));\n });\n return '[' + arrVals + ']';\n }\n }\n /*********CHECK FOR OBJECT**********/\n else if (obj instanceof Object) {\n //get object keys\n objKeys = Object.keys(obj);\n //set key output;\n objKeys.forEach(function (key) {\n const keyOut = '\"' + key + '\":';\n const keyValOut = obj[key];\n //skip functions and undefined properties\n if (keyValOut instanceof Function || keyValOut === undefined)\n arrOfKeyVals.push('');\n else if (typeof keyValOut === 'string')\n arrOfKeyVals.push(keyOut + '\"' + keyValOut + '\"');\n else if (typeof keyValOut === 'boolean' || typeof keyValOut === 'number' || keyValOut === null)\n arrOfKeyVals.push(keyOut + keyValOut);\n //check for nested objects, call recursively until no more objects\n else if (keyValOut instanceof Object) {\n arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut));\n }\n });\n return '{' + arrOfKeyVals + '}';\n }\n return '';\n};"],"names":[],"mappings":"AAsBO,MAAM,aAAA,GAAgB,SAAU,GAAA,EAAkB;AAErD,EAAA,MAAM,eAAyB,EAAC;AAChC,EAAA,MAAM,UAAoB,EAAC;AAC3B,EAAA,IAAI,UAAoB,EAAC;AAGzB,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,OAAO,GAAA,KAAQ,aAAa,GAAA,KAAQ,IAAA;AAC/D,IAAA,OAAO,EAAA,GAAK,GAAA;AAAA,OAAA,IACP,OAAO,GAAA,K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GAAA;AAAA,EAChC;AACA,EAAA,OAAO,EAAA;AACX;;;;"}
1
+ {"version":3,"file":"index54.js","sources":["../src/util/openai.ts"],"sourcesContent":["import { OpenAI } from 'openai';\nimport { ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from 'openai/resources/chat/completions';\nimport * as Storage from '@/util/storage';\nimport { getLogger } from '@/logging';\nimport { DEFAULT_MODEL, DEFAULT_TRANSCRIPTION_MODEL } from '@/constants';\n\nexport interface Transcription {\n text: string;\n}\n\nexport class OpenAIError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OpenAIError';\n }\n}\n\n\nexport async function createCompletion(messages: ChatCompletionMessageParam[], options: { responseFormat?: any, model?: string, reasoningLevel?: 'none' | 'low' | 'medium' | 'high', maxTokens?: number, debug?: boolean, debugFile?: string, reason?: string } = {}): Promise<string | any> {\n const logger = getLogger();\n const storage = Storage.create({ log: logger.debug });\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n const openai = new OpenAI({\n apiKey: apiKey,\n });\n\n const model = options.model || DEFAULT_MODEL;\n \n // Check if model supports reasoning_effort\n const supportsReasoning = model.includes('gpt-5') || \n model.includes('o1') || model.includes('o3');\n const isReasoningCall = supportsReasoning && options.reasoningLevel && options.reasoningLevel !== 'none';\n \n logger.debug('Sending prompt to OpenAI: %j', messages);\n\n const startTime = Date.now();\n \n const requestParams: Record<string, unknown> = {\n model,\n messages,\n max_completion_tokens: options.maxTokens || 10000,\n response_format: options.responseFormat,\n };\n \n if (isReasoningCall) {\n requestParams.reasoning_effort = options.reasoningLevel;\n logger.debug('Using reasoning_effort: %s', options.reasoningLevel);\n }\n \n const completion = await openai.chat.completions.create(\n requestParams as unknown as ChatCompletionCreateParamsNonStreaming\n );\n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n\n // Log token usage with reason if provided\n const usage = completion.usage;\n const reasonSuffix = options.reason ? ` - ${options.reason}` : '';\n if (usage) {\n logger.info('%s (%ss, %d→%d tokens)%s', \n model, duration, usage.prompt_tokens, usage.completion_tokens, reasonSuffix);\n } else {\n logger.info('%s (%ss)%s', model, duration, reasonSuffix);\n }\n\n if (options.debug && options.debugFile) {\n await storage.writeFile(options.debugFile, JSON.stringify(completion, null, 2), 'utf8');\n logger.debug('Wrote debug file to %s', options.debugFile);\n }\n\n const response = completion.choices[0]?.message?.content?.trim();\n if (!response) {\n // Log the full completion object to help debug\n logger.error('Empty response from OpenAI. Full completion object: %j', completion);\n throw new OpenAIError('No response received from OpenAI');\n }\n\n logger.debug('Received response from OpenAI: %s', response);\n if (options.responseFormat) {\n return JSON.parse(response);\n } else {\n return response;\n }\n\n } catch (error: any) {\n logger.error('Error calling OpenAI API: %s %s', error.message, error.stack);\n throw new OpenAIError(`Failed to create completion: ${error.message}`);\n }\n}\n\nexport async function transcribeAudio(filePath: string, options: { model?: string, debug?: boolean, debugFile?: string } = {}): Promise<Transcription> {\n const logger = getLogger();\n const storage = Storage.create({ log: logger.debug });\n try {\n const apiKey = process.env.OPENAI_API_KEY;\n if (!apiKey) {\n throw new OpenAIError('OPENAI_API_KEY environment variable is not set');\n }\n\n const openai = new OpenAI({\n apiKey: apiKey,\n });\n\n const model = options.model || DEFAULT_TRANSCRIPTION_MODEL;\n const fileName = filePath.split('/').pop() || filePath;\n logger.debug('Transcribing: %s (full path: %s)', fileName, filePath);\n\n const startTime = Date.now();\n const audioStream = await storage.readStream(filePath);\n const transcription = await openai.audio.transcriptions.create({\n model,\n file: audioStream,\n response_format: \"json\",\n });\n \n if (!transcription) {\n throw new OpenAIError('No transcription received from OpenAI');\n }\n \n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n logger.info('%s (%ss, %d chars)', model, duration, transcription.text?.length || 0);\n\n if (options.debug && options.debugFile) {\n await storage.writeFile(options.debugFile, JSON.stringify(transcription, null, 2), 'utf8');\n logger.debug('Wrote debug file to %s', options.debugFile);\n }\n\n logger.debug('Received transcription from OpenAI: %s', transcription);\n return transcription;\n\n } catch (error: any) {\n logger.error('Error transcribing audio file: %s %s', error.message, error.stack);\n throw new OpenAIError(`Failed to transcribe audio: ${error.message}`);\n }\n}\n"],"names":["storage","Storage.create"],"mappings":";;;;;AAUO,MAAM,oBAAoB,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EAChB;AACJ;AA+EA,eAAsB,eAAA,CAAgB,QAAA,EAAkB,OAAA,GAAmE,EAAC,EAA2B;AACnJ,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,MAAMA,YAAUC,MAAQ,CAAO,EAAE,GAAA,EAAK,MAAA,CAAO,OAAO,CAAA;AACpD,EAAA,IAAI;AACA,IAAA,MAAM,MAAA,GAAS,QAAQ,GAAA,CAAI,cAAA;AAC3B,IAAA,IAAI,CAAC,MAAA,EAAQ;AACT,MAAA,MAAM,IAAI,YAAY,gDAAgD,CAAA;AAAA,IAC1E;AAEA,IAAA,MAAM,MAAA,GAAS,IAAI,MAAA,CAAO;AAAA,MACtB;AAAA,KACH,CAAA;AAED,IAAA,MAAM,KAAA,GAAQ,QAAQ,KAAA,IAAS,2BAAA;AAC/B,IAAA,MAAM,WAAW,QAAA,CAAS,KAAA,CAAM,GAAG,CAAA,CAAE,KAAI,IAAK,QAAA;AAC9C,IAAA,MAAA,CAAO,KAAA,CAAM,kCAAA,EAAoC,QAAA,EAAU,QAAQ,CAAA;AAEnE,IAAA,MAAM,SAAA,GAAY,KAAK,GAAA,EAAI;AAC3B,IAAA,MAAM,WAAA,GAAc,MAAMD,SAAA,CAAQ,UAAA,CAAW,QAAQ,CAAA;AACrD,IAAA,MAAM,aAAA,GAAgB,MAAM,MAAA,CAAO,KAAA,CAAM,eAAe,MAAA,CAAO;AAAA,MAC3D,KAAA;AAAA,MACA,IAAA,EAAM,WAAA;AAAA,MACN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