@thanh01.pmt/curriculum-kit 1.0.14 → 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -3,7 +3,7 @@ export { ActiveLearningWorkflow, ActiveLearningWorkflowSchema, ActivityLabSchema
3
3
  import { A as AIProviderName, M as ModelResolutionOptions } from './provider-factory-DxzOVEmh.cjs';
4
4
  export { N as NVIDIA_MODELS, g as getAIModel } from './provider-factory-DxzOVEmh.cjs';
5
5
  export { ActivityPromptInput, AggregatedToolCall, AsyncLLMJudgeInput, AuditCurriculumQualityInput, CodeLabPromptInput, DEFAULT_ENABLED_PROVIDERS, DiagnosticQuizPromptInput, ExtensionPromptInput, GenerateActivityInput, GenerateCodeLabInput, GenerateDiagnosticQuizInput, GenerateExtensionInput, GenerateHandoutInput, GenerateLessonMasterInput, GenerateProjectInstructionInput, GenerateSelfLabInput, GenerateSlidesInput, GenerateTeacherGuideInput, GenerateWorksheetInput, HandoutPromptInput, JudgeEvaluationResult, JudgePromptInput, LLMJudgeEngine, LessonPromptInput, ModelPolicyResolution, ModelPolicyResolver, ModelProviderKey, MultiProviderPolicyResolution, ProjectInstructionPromptInput, SelfLabPromptInput, SlidesPromptInput, StreamDiagnosticQuizInput, StreamLessonMasterInput, StreamSelfLabInput, TeacherGuidePromptInput, ToolDefinition, ToolExecutionResult, ToolExecutor, ToolLoopConfig, WorksheetPromptInput, activityTools, analystTools, assessorTools, auditCurriculumQualityFlow, buildActivityPrompt, buildCodeLabPrompt, buildDiagnosticQuizPrompt, buildExtensionPrompt, buildHandoutPrompt, buildJudgePrompt, buildLessonMasterPrompt, buildProjectInstructionPrompt, buildSelfLabPrompt, buildSlidesPrompt, buildTeacherGuidePrompt, buildWorksheetPrompt, contentTools, designerTools, generateActivityFlow, generateCodeLabFlow, generateDiagnosticQuizFlow, generateExtensionFlow, generateHandoutFlow, generateLessonMasterFlow, generateProjectInstructionFlow, generateSelfLabFlow, generateSlidesFlow, generateTeacherGuideFlow, generateWorksheetFlow, illustratorTools, packagerTools, researcherTools, reviewerTools, streamCurriculumAIInferenceWithTools, streamDiagnosticQuizFlow, streamLessonMasterFlow, streamSelfLabFlow, techSmeTools } from './ai/index.cjs';
6
- export { C as ChatMessage, c as ChunkType, F as FallbackTarget, S as StreamRunnerOptions, e as extractThoughtAndContent, g as getDesignatedFallbackChain, b as getDesignatedFallbackConfig, a as isModelAllowed, i as isProviderEnabled, r as runCurriculumAIInference, s as streamCurriculumAIInference } from './streamRunner-CcpmxOf1.cjs';
6
+ export { C as ChatMessage, c as ChunkType, D as DEFAULT_ARTIFACT_STREAM_IDLE_MS, d as DEFAULT_ARTIFACT_STREAM_TOTAL_MS, F as FallbackTarget, I as IdleAbort, f as StreamAbortController, S as StreamRunnerOptions, j as createIdleAbortController, h as createStreamAbortController, e as extractThoughtAndContent, g as getDesignatedFallbackChain, b as getDesignatedFallbackConfig, a as isModelAllowed, i as isProviderEnabled, r as runCurriculumAIInference, s as streamCurriculumAIInference } from './streamRunner-DtQq0HV_.cjs';
7
7
  export { ArtifactLintReport, ConvertedSotBundle, GenerateProjectInstructionOptions, GenerateRoadmapCurriculumOptions, GenerateSelfPacedBundleInput, LintIssue, ProjectInstructionResult, RoadmapCurriculumOutput, SelfPacedBundleOutput, convertRoadmapToFoundationSot, generateProjectInstruction, generateRoadmapCurriculum, generateSelfPacedBundle, importRoadmapToProject, lintAndSanitizeArtifact, serializeActivityToMarkdown, serializeCodeLabToMarkdown, serializeDiagnosticQuizToMarkdown, serializeHandoutToMarkdown, serializeLessonToMarkdown, serializeProjectInstructionToMarkdown, serializeSelfLabToMarkdown, validateMarkdownTables, validateMermaidSyntax } from './pipeline/index.cjs';
8
8
  export { A as AutoRepairOptions, a as AutoRepairResult, B as BundleTier, G as GenerateMilestoneBundleOptions, M as MilestoneCurriculumBundle, g as generateMilestoneCurriculumBundle, w as withAutoRepair } from './milestoneBundleGenerator-CzSOeAzU.cjs';
9
9
  import { I as ICurriculumStorage, P as ProjectStatusReport, S as SmartResumeContext, Q as QualityAuditReport } from './types-BUJGYiep.cjs';
@@ -362,8 +362,17 @@ interface StreamBudget {
362
362
  totalMs?: number;
363
363
  }
364
364
  declare const DEFAULT_STREAM_IDLE_MS = 45000;
365
- declare const DEFAULT_STREAM_TOTAL_MS = 300000;
366
- /** Layer-aware total budget: Layer 2 is the largest prefill output (6 fields × options pros/cons). */
365
+ declare const DEFAULT_STREAM_TOTAL_MS = 420000;
366
+ /**
367
+ * Layer-aware total budget — uniform 7-minute hard cap for the WHOLE stream.
368
+ *
369
+ * Rationale: task duration is not predictable in advance (free-tier reasoning
370
+ * models like nemotron-ultra may think several minutes before/while streaming
371
+ * JSON), so the cap must be generous. Hang protection does NOT come from this
372
+ * number — it comes from the idle timer (45s, kicked on every chunk), which
373
+ * covers slow TTFT and mid-stream stalls. A mid-JSON abort here truncates the
374
+ * payload and was the root cause of ~90% wizard Layer prefill failures.
375
+ */
367
376
  declare const LAYER_TOTAL_BUDGET_MS: Record<number, number>;
368
377
  /**
369
378
  * Resolve the abort budget for a prefill run. Precedence: explicit options >
@@ -408,7 +417,28 @@ interface ExtractedStreamChunk {
408
417
  declare function extractStreamChunk(part: any): ExtractedStreamChunk;
409
418
  declare function createStreamAbortSignal(budget: Required<StreamBudget>): StreamAbortHandle;
410
419
  /**
411
- * Robust JSON extraction and repair helper
420
+ * Close an unterminated JSON object/array: append the delimiters that are
421
+ * still open, closing any open string first. Handles streams aborted
422
+ * mid-JSON (budget timeout) where the structure is otherwise valid.
423
+ * Returns the repaired candidate or null when unrecoverable.
424
+ */
425
+ declare function closeTruncatedJson(candidate: string): string | null;
426
+ /**
427
+ * Strip common LLM prose wrappers: code fences, leading "Here is ..." lines,
428
+ * <think> blocks. Returns the raw inner text (may still be imperfect JSON).
429
+ */
430
+ declare function stripLlmJsonWrappers(rawText: string): string;
431
+ /**
432
+ * Robust JSON extraction and repair helper.
433
+ *
434
+ * Tolerates every real-world LLM output defect observed with free-tier
435
+ * reasoning models (nemotron-ultra, OpenRouter :free presets):
436
+ * 1. code fences / <think> blocks / prose around the JSON,
437
+ * 2. trailing commas,
438
+ * 3. TRUNCATED output — the stream abort (idle/total budget) can cut the
439
+ * payload mid-JSON; open strings/braces are closed deterministically,
440
+ * 4. mixed defects — each candidate goes through jsonrepair last.
441
+ * Layered: cheap strict parse first, heavier repair only on failure.
412
442
  */
413
443
  declare function safeParseJson<T = any>(rawText: string | null): T | null;
414
444
 
@@ -914,4 +944,4 @@ declare function getSlideLayoutPresetById(id: string): SlideLayoutPreset | undef
914
944
  */
915
945
  declare function getSlideLayoutPresetsByCategory(category: SlideLayoutCategory): SlideLayoutPreset[];
916
946
 
917
- export { ACT_TEMPLATE, AIProviderName, ARTIFACT_EXECUTION_ORDER, type AcademicAuditFinding, AcademicAuditor, type AcademicDimension, ActivityLab, type ArtifactProductionSpec, type AuditBundleInput, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BloomTaxonomyEvaluator, type BuildContextOptions, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CodeHardwareFeasibilityEvaluator, CodeLab, type ComprehensiveAcademicReport, ConstructiveAlignmentEvaluator, CrossArtifactDriftEvaluator, CurriculumError, type CurriculumErrorCode, type CurriculumErrorDetail, CurriculumPlan, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdge, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuiz, DiagnosticQuizInput, type DimensionScore, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, type ExecuteCommandResult, ExpositionApprovalError, type ExpositionLlmFn, type ExpositionResult, type ExpositionStorage, type ExtractedStreamChunk, type FindingSeverity, FiveEInstructionalEvaluator, type FrameworkLintFinding, type FrameworkLintReport, FrameworkPack, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, type GenerateExpositionOptions, HANDOUT_TEMPLATE, ICurriculumStorage, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, type LayerChunkCallback, type LayerPrefillOptions, type LayerPrefillResult, type LayoutBoxConfig, LessonPlan, MisconceptionEvaluator, ModelResolutionOptions, PROJECT_INSTRUCTION_TEMPLATE, type PackingSpec, type PedagogicalModel, type PipelineExecutionProgress, PlanConstraints, type PlanOptions, type PlanResult, type PlannerLlmFn, PlanningGraph, PlanningNode, type PreliminaryResearchResult, type ProduceLessonOptions, type ProduceLessonResult, type ProjectBriefingData, type ProjectClarification, type ProjectCreationPayload, type ProjectIntentAnalysisResult, ProjectStatusReport, type ProjectionMeta, QUIZ_TEMPLATE, QualityAuditReport, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, ResolvedGateSettings, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STATION_ROTATION_TEMPLATE, type SlashCommandDefinition, SlideDeck, type SlideLayoutCategory, type SlideLayoutData, type SlideLayoutPreset, SmartResumeContext, type StreamAbortHandle, type StreamBudget, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TranslationPolicy, type TranslationTarget, type TranslationTrigger, WORKSHEET_TEMPLATE, analyzeProjectCreationIntent, assertAcyclic, auditQualityReport, buildCurriculumContext, buildCurriculumPlan, buildExpositionContext, buildSessionSliceContext, computePackingSpec, conductPreliminaryResearch, createAiInferenceError, createStreamAbortSignal, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, executeCurriculumCommand, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, generatePhase1SotArtifacts, generatePhase2SotArtifacts, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, ingestProjectGraphIntoProject, initializeProjectInStorage, isExpositionFresh, isTranslationDue, lintCurriculumFramework, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, renderFrameworkFromPlan, resolveStreamBudget, resolveTranslationTargets, safeParseJson, slugifyProjectName, streamLLMWithFallback, streamLayerPrefillWithFallback, topoSort };
947
+ export { ACT_TEMPLATE, AIProviderName, ARTIFACT_EXECUTION_ORDER, type AcademicAuditFinding, AcademicAuditor, type AcademicDimension, ActivityLab, type ArtifactProductionSpec, type AuditBundleInput, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BloomTaxonomyEvaluator, type BuildContextOptions, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CodeHardwareFeasibilityEvaluator, CodeLab, type ComprehensiveAcademicReport, ConstructiveAlignmentEvaluator, CrossArtifactDriftEvaluator, CurriculumError, type CurriculumErrorCode, type CurriculumErrorDetail, CurriculumPlan, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdge, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuiz, DiagnosticQuizInput, type DimensionScore, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, type ExecuteCommandResult, ExpositionApprovalError, type ExpositionLlmFn, type ExpositionResult, type ExpositionStorage, type ExtractedStreamChunk, type FindingSeverity, FiveEInstructionalEvaluator, type FrameworkLintFinding, type FrameworkLintReport, FrameworkPack, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, type GenerateExpositionOptions, HANDOUT_TEMPLATE, ICurriculumStorage, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, type LayerChunkCallback, type LayerPrefillOptions, type LayerPrefillResult, type LayoutBoxConfig, LessonPlan, MisconceptionEvaluator, ModelResolutionOptions, PROJECT_INSTRUCTION_TEMPLATE, type PackingSpec, type PedagogicalModel, type PipelineExecutionProgress, PlanConstraints, type PlanOptions, type PlanResult, type PlannerLlmFn, PlanningGraph, PlanningNode, type PreliminaryResearchResult, type ProduceLessonOptions, type ProduceLessonResult, type ProjectBriefingData, type ProjectClarification, type ProjectCreationPayload, type ProjectIntentAnalysisResult, ProjectStatusReport, type ProjectionMeta, QUIZ_TEMPLATE, QualityAuditReport, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, ResolvedGateSettings, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STATION_ROTATION_TEMPLATE, type SlashCommandDefinition, SlideDeck, type SlideLayoutCategory, type SlideLayoutData, type SlideLayoutPreset, SmartResumeContext, type StreamAbortHandle, type StreamBudget, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TranslationPolicy, type TranslationTarget, type TranslationTrigger, WORKSHEET_TEMPLATE, analyzeProjectCreationIntent, assertAcyclic, auditQualityReport, buildCurriculumContext, buildCurriculumPlan, buildExpositionContext, buildSessionSliceContext, closeTruncatedJson, computePackingSpec, conductPreliminaryResearch, createAiInferenceError, createStreamAbortSignal, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, executeCurriculumCommand, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, generatePhase1SotArtifacts, generatePhase2SotArtifacts, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, ingestProjectGraphIntoProject, initializeProjectInStorage, isExpositionFresh, isTranslationDue, lintCurriculumFramework, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, renderFrameworkFromPlan, resolveStreamBudget, resolveTranslationTargets, safeParseJson, slugifyProjectName, streamLLMWithFallback, streamLayerPrefillWithFallback, stripLlmJsonWrappers, topoSort };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export { ActiveLearningWorkflow, ActiveLearningWorkflowSchema, ActivityLabSchema
3
3
  import { A as AIProviderName, M as ModelResolutionOptions } from './provider-factory-DxzOVEmh.js';
4
4
  export { N as NVIDIA_MODELS, g as getAIModel } from './provider-factory-DxzOVEmh.js';
5
5
  export { ActivityPromptInput, AggregatedToolCall, AsyncLLMJudgeInput, AuditCurriculumQualityInput, CodeLabPromptInput, DEFAULT_ENABLED_PROVIDERS, DiagnosticQuizPromptInput, ExtensionPromptInput, GenerateActivityInput, GenerateCodeLabInput, GenerateDiagnosticQuizInput, GenerateExtensionInput, GenerateHandoutInput, GenerateLessonMasterInput, GenerateProjectInstructionInput, GenerateSelfLabInput, GenerateSlidesInput, GenerateTeacherGuideInput, GenerateWorksheetInput, HandoutPromptInput, JudgeEvaluationResult, JudgePromptInput, LLMJudgeEngine, LessonPromptInput, ModelPolicyResolution, ModelPolicyResolver, ModelProviderKey, MultiProviderPolicyResolution, ProjectInstructionPromptInput, SelfLabPromptInput, SlidesPromptInput, StreamDiagnosticQuizInput, StreamLessonMasterInput, StreamSelfLabInput, TeacherGuidePromptInput, ToolDefinition, ToolExecutionResult, ToolExecutor, ToolLoopConfig, WorksheetPromptInput, activityTools, analystTools, assessorTools, auditCurriculumQualityFlow, buildActivityPrompt, buildCodeLabPrompt, buildDiagnosticQuizPrompt, buildExtensionPrompt, buildHandoutPrompt, buildJudgePrompt, buildLessonMasterPrompt, buildProjectInstructionPrompt, buildSelfLabPrompt, buildSlidesPrompt, buildTeacherGuidePrompt, buildWorksheetPrompt, contentTools, designerTools, generateActivityFlow, generateCodeLabFlow, generateDiagnosticQuizFlow, generateExtensionFlow, generateHandoutFlow, generateLessonMasterFlow, generateProjectInstructionFlow, generateSelfLabFlow, generateSlidesFlow, generateTeacherGuideFlow, generateWorksheetFlow, illustratorTools, packagerTools, researcherTools, reviewerTools, streamCurriculumAIInferenceWithTools, streamDiagnosticQuizFlow, streamLessonMasterFlow, streamSelfLabFlow, techSmeTools } from './ai/index.js';
6
- export { C as ChatMessage, c as ChunkType, F as FallbackTarget, S as StreamRunnerOptions, e as extractThoughtAndContent, g as getDesignatedFallbackChain, b as getDesignatedFallbackConfig, a as isModelAllowed, i as isProviderEnabled, r as runCurriculumAIInference, s as streamCurriculumAIInference } from './streamRunner-CcpmxOf1.js';
6
+ export { C as ChatMessage, c as ChunkType, D as DEFAULT_ARTIFACT_STREAM_IDLE_MS, d as DEFAULT_ARTIFACT_STREAM_TOTAL_MS, F as FallbackTarget, I as IdleAbort, f as StreamAbortController, S as StreamRunnerOptions, j as createIdleAbortController, h as createStreamAbortController, e as extractThoughtAndContent, g as getDesignatedFallbackChain, b as getDesignatedFallbackConfig, a as isModelAllowed, i as isProviderEnabled, r as runCurriculumAIInference, s as streamCurriculumAIInference } from './streamRunner-DtQq0HV_.js';
7
7
  export { ArtifactLintReport, ConvertedSotBundle, GenerateProjectInstructionOptions, GenerateRoadmapCurriculumOptions, GenerateSelfPacedBundleInput, LintIssue, ProjectInstructionResult, RoadmapCurriculumOutput, SelfPacedBundleOutput, convertRoadmapToFoundationSot, generateProjectInstruction, generateRoadmapCurriculum, generateSelfPacedBundle, importRoadmapToProject, lintAndSanitizeArtifact, serializeActivityToMarkdown, serializeCodeLabToMarkdown, serializeDiagnosticQuizToMarkdown, serializeHandoutToMarkdown, serializeLessonToMarkdown, serializeProjectInstructionToMarkdown, serializeSelfLabToMarkdown, validateMarkdownTables, validateMermaidSyntax } from './pipeline/index.js';
8
8
  export { A as AutoRepairOptions, a as AutoRepairResult, B as BundleTier, G as GenerateMilestoneBundleOptions, M as MilestoneCurriculumBundle, g as generateMilestoneCurriculumBundle, w as withAutoRepair } from './milestoneBundleGenerator-Bkba8OPG.js';
9
9
  import { I as ICurriculumStorage, P as ProjectStatusReport, S as SmartResumeContext, Q as QualityAuditReport } from './types-BUJGYiep.js';
@@ -362,8 +362,17 @@ interface StreamBudget {
362
362
  totalMs?: number;
363
363
  }
364
364
  declare const DEFAULT_STREAM_IDLE_MS = 45000;
365
- declare const DEFAULT_STREAM_TOTAL_MS = 300000;
366
- /** Layer-aware total budget: Layer 2 is the largest prefill output (6 fields × options pros/cons). */
365
+ declare const DEFAULT_STREAM_TOTAL_MS = 420000;
366
+ /**
367
+ * Layer-aware total budget — uniform 7-minute hard cap for the WHOLE stream.
368
+ *
369
+ * Rationale: task duration is not predictable in advance (free-tier reasoning
370
+ * models like nemotron-ultra may think several minutes before/while streaming
371
+ * JSON), so the cap must be generous. Hang protection does NOT come from this
372
+ * number — it comes from the idle timer (45s, kicked on every chunk), which
373
+ * covers slow TTFT and mid-stream stalls. A mid-JSON abort here truncates the
374
+ * payload and was the root cause of ~90% wizard Layer prefill failures.
375
+ */
367
376
  declare const LAYER_TOTAL_BUDGET_MS: Record<number, number>;
368
377
  /**
369
378
  * Resolve the abort budget for a prefill run. Precedence: explicit options >
@@ -408,7 +417,28 @@ interface ExtractedStreamChunk {
408
417
  declare function extractStreamChunk(part: any): ExtractedStreamChunk;
409
418
  declare function createStreamAbortSignal(budget: Required<StreamBudget>): StreamAbortHandle;
410
419
  /**
411
- * Robust JSON extraction and repair helper
420
+ * Close an unterminated JSON object/array: append the delimiters that are
421
+ * still open, closing any open string first. Handles streams aborted
422
+ * mid-JSON (budget timeout) where the structure is otherwise valid.
423
+ * Returns the repaired candidate or null when unrecoverable.
424
+ */
425
+ declare function closeTruncatedJson(candidate: string): string | null;
426
+ /**
427
+ * Strip common LLM prose wrappers: code fences, leading "Here is ..." lines,
428
+ * <think> blocks. Returns the raw inner text (may still be imperfect JSON).
429
+ */
430
+ declare function stripLlmJsonWrappers(rawText: string): string;
431
+ /**
432
+ * Robust JSON extraction and repair helper.
433
+ *
434
+ * Tolerates every real-world LLM output defect observed with free-tier
435
+ * reasoning models (nemotron-ultra, OpenRouter :free presets):
436
+ * 1. code fences / <think> blocks / prose around the JSON,
437
+ * 2. trailing commas,
438
+ * 3. TRUNCATED output — the stream abort (idle/total budget) can cut the
439
+ * payload mid-JSON; open strings/braces are closed deterministically,
440
+ * 4. mixed defects — each candidate goes through jsonrepair last.
441
+ * Layered: cheap strict parse first, heavier repair only on failure.
412
442
  */
413
443
  declare function safeParseJson<T = any>(rawText: string | null): T | null;
414
444
 
@@ -914,4 +944,4 @@ declare function getSlideLayoutPresetById(id: string): SlideLayoutPreset | undef
914
944
  */
915
945
  declare function getSlideLayoutPresetsByCategory(category: SlideLayoutCategory): SlideLayoutPreset[];
916
946
 
917
- export { ACT_TEMPLATE, AIProviderName, ARTIFACT_EXECUTION_ORDER, type AcademicAuditFinding, AcademicAuditor, type AcademicDimension, ActivityLab, type ArtifactProductionSpec, type AuditBundleInput, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BloomTaxonomyEvaluator, type BuildContextOptions, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CodeHardwareFeasibilityEvaluator, CodeLab, type ComprehensiveAcademicReport, ConstructiveAlignmentEvaluator, CrossArtifactDriftEvaluator, CurriculumError, type CurriculumErrorCode, type CurriculumErrorDetail, CurriculumPlan, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdge, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuiz, DiagnosticQuizInput, type DimensionScore, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, type ExecuteCommandResult, ExpositionApprovalError, type ExpositionLlmFn, type ExpositionResult, type ExpositionStorage, type ExtractedStreamChunk, type FindingSeverity, FiveEInstructionalEvaluator, type FrameworkLintFinding, type FrameworkLintReport, FrameworkPack, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, type GenerateExpositionOptions, HANDOUT_TEMPLATE, ICurriculumStorage, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, type LayerChunkCallback, type LayerPrefillOptions, type LayerPrefillResult, type LayoutBoxConfig, LessonPlan, MisconceptionEvaluator, ModelResolutionOptions, PROJECT_INSTRUCTION_TEMPLATE, type PackingSpec, type PedagogicalModel, type PipelineExecutionProgress, PlanConstraints, type PlanOptions, type PlanResult, type PlannerLlmFn, PlanningGraph, PlanningNode, type PreliminaryResearchResult, type ProduceLessonOptions, type ProduceLessonResult, type ProjectBriefingData, type ProjectClarification, type ProjectCreationPayload, type ProjectIntentAnalysisResult, ProjectStatusReport, type ProjectionMeta, QUIZ_TEMPLATE, QualityAuditReport, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, ResolvedGateSettings, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STATION_ROTATION_TEMPLATE, type SlashCommandDefinition, SlideDeck, type SlideLayoutCategory, type SlideLayoutData, type SlideLayoutPreset, SmartResumeContext, type StreamAbortHandle, type StreamBudget, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TranslationPolicy, type TranslationTarget, type TranslationTrigger, WORKSHEET_TEMPLATE, analyzeProjectCreationIntent, assertAcyclic, auditQualityReport, buildCurriculumContext, buildCurriculumPlan, buildExpositionContext, buildSessionSliceContext, computePackingSpec, conductPreliminaryResearch, createAiInferenceError, createStreamAbortSignal, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, executeCurriculumCommand, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, generatePhase1SotArtifacts, generatePhase2SotArtifacts, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, ingestProjectGraphIntoProject, initializeProjectInStorage, isExpositionFresh, isTranslationDue, lintCurriculumFramework, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, renderFrameworkFromPlan, resolveStreamBudget, resolveTranslationTargets, safeParseJson, slugifyProjectName, streamLLMWithFallback, streamLayerPrefillWithFallback, topoSort };
947
+ export { ACT_TEMPLATE, AIProviderName, ARTIFACT_EXECUTION_ORDER, type AcademicAuditFinding, AcademicAuditor, type AcademicDimension, ActivityLab, type ArtifactProductionSpec, type AuditBundleInput, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BloomTaxonomyEvaluator, type BuildContextOptions, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CodeHardwareFeasibilityEvaluator, CodeLab, type ComprehensiveAcademicReport, ConstructiveAlignmentEvaluator, CrossArtifactDriftEvaluator, CurriculumError, type CurriculumErrorCode, type CurriculumErrorDetail, CurriculumPlan, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdge, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuiz, DiagnosticQuizInput, type DimensionScore, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, type ExecuteCommandResult, ExpositionApprovalError, type ExpositionLlmFn, type ExpositionResult, type ExpositionStorage, type ExtractedStreamChunk, type FindingSeverity, FiveEInstructionalEvaluator, type FrameworkLintFinding, type FrameworkLintReport, FrameworkPack, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, type GenerateExpositionOptions, HANDOUT_TEMPLATE, ICurriculumStorage, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, type LayerChunkCallback, type LayerPrefillOptions, type LayerPrefillResult, type LayoutBoxConfig, LessonPlan, MisconceptionEvaluator, ModelResolutionOptions, PROJECT_INSTRUCTION_TEMPLATE, type PackingSpec, type PedagogicalModel, type PipelineExecutionProgress, PlanConstraints, type PlanOptions, type PlanResult, type PlannerLlmFn, PlanningGraph, PlanningNode, type PreliminaryResearchResult, type ProduceLessonOptions, type ProduceLessonResult, type ProjectBriefingData, type ProjectClarification, type ProjectCreationPayload, type ProjectIntentAnalysisResult, ProjectStatusReport, type ProjectionMeta, QUIZ_TEMPLATE, QualityAuditReport, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, ResolvedGateSettings, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STATION_ROTATION_TEMPLATE, type SlashCommandDefinition, SlideDeck, type SlideLayoutCategory, type SlideLayoutData, type SlideLayoutPreset, SmartResumeContext, type StreamAbortHandle, type StreamBudget, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TranslationPolicy, type TranslationTarget, type TranslationTrigger, WORKSHEET_TEMPLATE, analyzeProjectCreationIntent, assertAcyclic, auditQualityReport, buildCurriculumContext, buildCurriculumPlan, buildExpositionContext, buildSessionSliceContext, closeTruncatedJson, computePackingSpec, conductPreliminaryResearch, createAiInferenceError, createStreamAbortSignal, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, executeCurriculumCommand, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, generatePhase1SotArtifacts, generatePhase2SotArtifacts, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, ingestProjectGraphIntoProject, initializeProjectInStorage, isExpositionFresh, isTranslationDue, lintCurriculumFramework, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, renderFrameworkFromPlan, resolveStreamBudget, resolveTranslationTargets, safeParseJson, slugifyProjectName, streamLLMWithFallback, streamLayerPrefillWithFallback, stripLlmJsonWrappers, topoSort };
package/dist/index.mjs CHANGED
@@ -129,6 +129,10 @@ var init_errors = __esm({
129
129
  // src/ai/streamRunner.ts
130
130
  var streamRunner_exports = {};
131
131
  __export(streamRunner_exports, {
132
+ DEFAULT_ARTIFACT_STREAM_IDLE_MS: () => DEFAULT_ARTIFACT_STREAM_IDLE_MS,
133
+ DEFAULT_ARTIFACT_STREAM_TOTAL_MS: () => DEFAULT_ARTIFACT_STREAM_TOTAL_MS,
134
+ createIdleAbortController: () => createIdleAbortController,
135
+ createStreamAbortController: () => createStreamAbortController,
132
136
  extractThoughtAndContent: () => extractThoughtAndContent,
133
137
  getDesignatedFallbackChain: () => getDesignatedFallbackChain,
134
138
  getDesignatedFallbackConfig: () => getDesignatedFallbackConfig,
@@ -280,29 +284,44 @@ function extractThoughtAndContent(rawText) {
280
284
  content: content.trim()
281
285
  };
282
286
  }
283
- function createIdleAbortController(idleMs) {
287
+ function createStreamAbortController(options) {
288
+ const envIdle = Number(process.env.ARTIFACT_STREAM_IDLE_TIMEOUT_MS || process.env.STREAM_IDLE_TIMEOUT_MS);
289
+ const envTotal = Number(process.env.ARTIFACT_STREAM_TOTAL_TIMEOUT_MS || process.env.STREAM_TOTAL_TIMEOUT_MS);
290
+ const idleMs = Number.isFinite(options?.idleMs) && options.idleMs > 0 ? options.idleMs : Number.isFinite(envIdle) && envIdle > 0 ? envIdle : DEFAULT_ARTIFACT_STREAM_IDLE_MS;
291
+ const totalMs = Number.isFinite(options?.totalMs) && options.totalMs > 0 ? options.totalMs : Number.isFinite(envTotal) && envTotal > 0 ? envTotal : DEFAULT_ARTIFACT_STREAM_TOTAL_MS;
284
292
  const controller = new AbortController();
285
- let timer = null;
286
- const arm = () => {
287
- if (timer) clearTimeout(timer);
288
- timer = setTimeout(
293
+ let idleTimer = null;
294
+ let totalTimer = null;
295
+ const armIdle = () => {
296
+ if (idleTimer) clearTimeout(idleTimer);
297
+ idleTimer = setTimeout(
289
298
  () => controller.abort(new Error(`Idle timeout: no data for ${Math.round(idleMs / 1e3)}s`)),
290
299
  idleMs
291
300
  );
292
- timer?.unref?.();
301
+ idleTimer?.unref?.();
293
302
  };
294
- arm();
303
+ armIdle();
304
+ if (totalMs > 0) {
305
+ totalTimer = setTimeout(
306
+ () => controller.abort(new Error(`Total stream timeout after ${Math.round(totalMs / 1e3)}s`)),
307
+ totalMs
308
+ );
309
+ totalTimer?.unref?.();
310
+ }
295
311
  return {
296
312
  signal: controller.signal,
297
- /** Reset the idle window (call on every received chunk). */
298
- kick: arm,
299
- /** Clear the pending timer once the request lifecycle is over. */
313
+ kick: armIdle,
300
314
  dispose: () => {
301
- if (timer) clearTimeout(timer);
302
- timer = null;
315
+ if (idleTimer) clearTimeout(idleTimer);
316
+ if (totalTimer) clearTimeout(totalTimer);
317
+ idleTimer = null;
318
+ totalTimer = null;
303
319
  }
304
320
  };
305
321
  }
322
+ function createIdleAbortController(idleMs, totalMs) {
323
+ return createStreamAbortController({ idleMs, totalMs });
324
+ }
306
325
  async function processOpenAISSEStream(response, onChunk, idle, toolCallCollector) {
307
326
  if (!response.body) return "";
308
327
  const reader = response.body.getReader();
@@ -486,7 +505,7 @@ Guidelines:
486
505
  if (isNvidiaPreferred || uniqueNvidiaModels.length > 0) {
487
506
  for (const model of uniqueNvidiaModels) {
488
507
  try {
489
- const idle = createIdleAbortController(18e4);
508
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
490
509
  const res = await fetch("https://integrate.api.nvidia.com/v1/chat/completions", {
491
510
  method: "POST",
492
511
  headers: {
@@ -530,7 +549,7 @@ Guidelines:
530
549
  const uniqueOrModels = Array.from(new Set(openrouterModels));
531
550
  for (const model of uniqueOrModels) {
532
551
  try {
533
- const idle = createIdleAbortController(18e4);
552
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
534
553
  const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
535
554
  method: "POST",
536
555
  headers: {
@@ -569,7 +588,7 @@ Guidelines:
569
588
  const dsModel = options.model?.includes("deepseek-reasoner") ? "deepseek-reasoner" : "deepseek-chat";
570
589
  if (isModelAllowed(dsModel)) {
571
590
  try {
572
- const idle = createIdleAbortController(18e4);
591
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
573
592
  const res = await fetch("https://api.deepseek.com/chat/completions", {
574
593
  method: "POST",
575
594
  headers: {
@@ -604,7 +623,7 @@ Guidelines:
604
623
  const baseUrl = alibabaKey.startsWith("sk-sp-") ? "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
605
624
  for (const qwenModel of qwenModels) {
606
625
  try {
607
- const idle = createIdleAbortController(18e4);
626
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
608
627
  const payload = {
609
628
  model: qwenModel,
610
629
  messages: formattedMessages,
@@ -647,7 +666,7 @@ Guidelines:
647
666
  ];
648
667
  for (const gModel of geminiModels) {
649
668
  try {
650
- const idle = createIdleAbortController(18e4);
669
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
651
670
  const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${gModel}:streamGenerateContent?alt=sse&key=${geminiKey}`, {
652
671
  method: "POST",
653
672
  headers: { "Content-Type": "application/json" },
@@ -683,7 +702,7 @@ Guidelines:
683
702
  const { provider, model } = target;
684
703
  if (provider === "nvidia" && nvidiaKey && isProviderEnabled("nvidia")) {
685
704
  try {
686
- const idle = createIdleAbortController(18e4);
705
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
687
706
  const res = await fetch("https://integrate.api.nvidia.com/v1/chat/completions", {
688
707
  method: "POST",
689
708
  headers: {
@@ -715,7 +734,7 @@ Guidelines:
715
734
  }
716
735
  } else if (provider === "openrouter" && openrouterKey && isProviderEnabled("openrouter")) {
717
736
  try {
718
- const idle = createIdleAbortController(18e4);
737
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
719
738
  const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
720
739
  method: "POST",
721
740
  headers: {
@@ -750,7 +769,7 @@ Guidelines:
750
769
  } else if ((provider === "alibaba" || provider === "dashscope") && alibabaKey && isProviderEnabled("alibaba")) {
751
770
  const baseUrl = alibabaKey.startsWith("sk-sp-") ? "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" : "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
752
771
  try {
753
- const idle = createIdleAbortController(18e4);
772
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
754
773
  const res = await fetch(baseUrl, {
755
774
  method: "POST",
756
775
  headers: {
@@ -782,7 +801,7 @@ Guidelines:
782
801
  }
783
802
  } else if ((provider === "google" || provider === "gemini") && geminiKey && (isProviderEnabled("gemini") || isProviderEnabled("google"))) {
784
803
  try {
785
- const idle = createIdleAbortController(18e4);
804
+ const idle = createStreamAbortController({ idleMs: options.idleTimeoutMs, totalMs: options.timeoutMs });
786
805
  const res = await fetch(
787
806
  `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${geminiKey}`,
788
807
  {
@@ -833,9 +852,12 @@ Guidelines:
833
852
  async function runCurriculumAIInference(messages, projectContext, options = {}, onChunk) {
834
853
  return await streamCurriculumAIInference(messages, projectContext, options, onChunk);
835
854
  }
855
+ var DEFAULT_ARTIFACT_STREAM_IDLE_MS, DEFAULT_ARTIFACT_STREAM_TOTAL_MS;
836
856
  var init_streamRunner = __esm({
837
857
  "src/ai/streamRunner.ts"() {
838
858
  init_errors();
859
+ DEFAULT_ARTIFACT_STREAM_IDLE_MS = 45e3;
860
+ DEFAULT_ARTIFACT_STREAM_TOTAL_MS = 42e4;
839
861
  }
840
862
  });
841
863
 
@@ -13514,11 +13536,11 @@ var DeterministicPipelineRunner = class {
13514
13536
  // src/services/prefillService.ts
13515
13537
  init_streamRunner();
13516
13538
  var DEFAULT_STREAM_IDLE_MS = 45e3;
13517
- var DEFAULT_STREAM_TOTAL_MS = 3e5;
13539
+ var DEFAULT_STREAM_TOTAL_MS = 42e4;
13518
13540
  var LAYER_TOTAL_BUDGET_MS = {
13519
- 1: 18e4,
13520
- 2: 36e4,
13521
- 3: 36e4
13541
+ 1: 42e4,
13542
+ 2: 42e4,
13543
+ 3: 42e4
13522
13544
  };
13523
13545
  function resolveStreamBudget(layer, opts) {
13524
13546
  const envIdle = Number(process.env.WIZARD_PREFILL_IDLE_TIMEOUT_MS);
@@ -13585,29 +13607,111 @@ function createStreamAbortSignal(budget) {
13585
13607
  }
13586
13608
  };
13587
13609
  }
13610
+ function closeTruncatedJson(candidate) {
13611
+ let inStr = false;
13612
+ let esc2 = false;
13613
+ const stack = [];
13614
+ for (let i = 0; i < candidate.length; i++) {
13615
+ const ch = candidate[i];
13616
+ if (esc2) {
13617
+ esc2 = false;
13618
+ continue;
13619
+ }
13620
+ if (inStr) {
13621
+ if (ch === "\\") esc2 = true;
13622
+ else if (ch === '"') inStr = false;
13623
+ continue;
13624
+ }
13625
+ if (ch === '"') inStr = true;
13626
+ else if (ch === "{" || ch === "[") stack.push(ch);
13627
+ else if (ch === "}" || ch === "]") stack.pop();
13628
+ }
13629
+ if (stack.length === 0 && !inStr) return null;
13630
+ let out = candidate;
13631
+ out = out.replace(/,\s*$/, "");
13632
+ if (inStr) {
13633
+ out = out.replace(/\\+$/, "");
13634
+ out += '"';
13635
+ }
13636
+ while (stack.length > 0) {
13637
+ out += stack.pop() === "{" ? "}" : "]";
13638
+ }
13639
+ return out;
13640
+ }
13641
+ function stripLlmJsonWrappers(rawText) {
13642
+ let cleaned = rawText.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/```json\s*/gi, "").replace(/```\s*/g, "").trim();
13643
+ const firstBrace = cleaned.indexOf("{");
13644
+ if (firstBrace > 0) {
13645
+ cleaned = cleaned.slice(firstBrace);
13646
+ }
13647
+ return cleaned.trim();
13648
+ }
13588
13649
  function safeParseJson(rawText) {
13589
13650
  if (!rawText) return null;
13590
- const cleaned = rawText.replace(/```json\s*/gi, "").replace(/```\s*/g, "").trim();
13651
+ const cleaned = stripLlmJsonWrappers(rawText);
13652
+ if (!cleaned) return null;
13591
13653
  try {
13592
13654
  return JSON.parse(cleaned);
13593
13655
  } catch {
13594
- const firstBrace = cleaned.indexOf("{");
13656
+ }
13657
+ const firstBrace = cleaned.indexOf("{");
13658
+ if (firstBrace === -1) return null;
13659
+ const buildCandidates = () => {
13660
+ const list = [];
13661
+ const closed = closeTruncatedJson(cleaned.slice(firstBrace));
13662
+ if (closed) list.push(closed);
13595
13663
  const lastBrace = cleaned.lastIndexOf("}");
13596
- if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) {
13597
- const candidate = cleaned.slice(firstBrace, lastBrace + 1);
13598
- try {
13599
- return JSON.parse(candidate);
13600
- } catch {
13664
+ if (lastBrace > firstBrace) {
13665
+ list.push(cleaned.slice(firstBrace, lastBrace + 1));
13666
+ }
13667
+ return list;
13668
+ };
13669
+ for (const candidate of buildCandidates()) {
13670
+ try {
13671
+ return JSON.parse(candidate);
13672
+ } catch {
13673
+ }
13674
+ try {
13675
+ return JSON.parse(jsonrepair(candidate));
13676
+ } catch {
13677
+ }
13678
+ }
13679
+ let depth = 0;
13680
+ let inStr = false;
13681
+ let esc2 = false;
13682
+ for (let i = firstBrace; i < cleaned.length; i++) {
13683
+ const ch = cleaned[i];
13684
+ if (esc2) {
13685
+ esc2 = false;
13686
+ continue;
13687
+ }
13688
+ if (inStr) {
13689
+ if (ch === "\\") esc2 = true;
13690
+ else if (ch === '"') inStr = false;
13691
+ continue;
13692
+ }
13693
+ if (ch === '"') inStr = true;
13694
+ else if (ch === "{") depth++;
13695
+ else if (ch === "}") {
13696
+ depth--;
13697
+ if (depth === 0) {
13698
+ const candidate = cleaned.slice(firstBrace, i + 1);
13699
+ try {
13700
+ return JSON.parse(candidate);
13701
+ } catch {
13702
+ }
13601
13703
  try {
13602
- const repaired = jsonrepair(candidate);
13603
- return JSON.parse(repaired);
13704
+ return JSON.parse(jsonrepair(candidate));
13604
13705
  } catch {
13605
- return null;
13606
13706
  }
13607
13707
  }
13608
13708
  }
13609
- return null;
13610
13709
  }
13710
+ try {
13711
+ return JSON.parse(jsonrepair(cleaned));
13712
+ } catch {
13713
+ }
13714
+ return null;
13611
13715
  }
13612
13716
  async function streamLLMWithFallback(systemPrompt, userPrompt, apiKeys = {}, onChunk, preferredModel, preferredProvider, budget) {
13613
13717
  const alibabaKey = apiKeys.alibaba || apiKeys.dashscope || process.env.ALIBABA_API_KEY || process.env.DASHSCOPE_API_KEY;
@@ -16120,6 +16224,10 @@ function resolveApiKey2(options) {
16120
16224
  }
16121
16225
  return { provider, key };
16122
16226
  }
16227
+ function resolveImageTimeout(options) {
16228
+ const envTimeout = Number(process.env.IMAGE_GEN_TIMEOUT_MS || process.env.ARTIFACT_STREAM_TOTAL_TIMEOUT_MS);
16229
+ return Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 42e4;
16230
+ }
16123
16231
  async function generateWithGemini(options, key) {
16124
16232
  const finalPrompt = buildImagePrompt(options);
16125
16233
  const model = "gemini-2.0-flash-exp";
@@ -16130,7 +16238,7 @@ async function generateWithGemini(options, key) {
16130
16238
  contents: [{ parts: [{ text: finalPrompt }] }],
16131
16239
  generationConfig: { responseModalities: ["TEXT", "IMAGE"] }
16132
16240
  }),
16133
- signal: AbortSignal.timeout(9e4)
16241
+ signal: AbortSignal.timeout(resolveImageTimeout(options))
16134
16242
  });
16135
16243
  if (!res.ok) {
16136
16244
  const body = await res.text().catch(() => "");
@@ -16163,7 +16271,7 @@ async function generateWithOpenAI(options, key) {
16163
16271
  size: sizeMap[options.aspectRatio || "1:1"] || "1024x1024",
16164
16272
  n: 1
16165
16273
  }),
16166
- signal: AbortSignal.timeout(9e4)
16274
+ signal: AbortSignal.timeout(resolveImageTimeout(options))
16167
16275
  });
16168
16276
  if (!res.ok) {
16169
16277
  const body = await res.text().catch(() => "");
@@ -16567,6 +16675,6 @@ function renderMediaPlaceholder(entry) {
16567
16675
  return `> \u{1F5BC}\uFE0F [\u1EA2nh \u0111ang ch\u1EDD: ${entry.name} \u2014 s\u1EBD \u0111\u01B0\u1EE3c t\u1EA1o sau khi duy\u1EC7t media]`;
16568
16676
  }
16569
16677
 
16570
- export { ACT_TEMPLATE, ARTIFACT_EXECUTION_ORDER, AcademicAuditor, ActiveLearningWorkflowSchema, ActivityLabSchema, ActivitySeqRowSchema, ActivityStepSchema, ArtifactContractRowSchema, AssessmentMapRowSchema, AssessmentObjectiveSchema, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BUNDLED_STANDARDS_PACK_IDS, BellRingerDaySchema, BellRingerSchema, BloomHintSchema, BloomLevelSchema, BloomTaxonomyEvaluator, BronzeTierSchema, CERConclusionSchema, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CardTierEnum, ChoiceBoardRubricRowSchema, ChoiceBoardSchema, ChoiceRuleSchema, ChoiceSquareSchema, ClassificationSchema, CodeHardwareFeasibilityEvaluator, CodeLabSchema, CodeSnippetSchema, CompetencyRubricRowSchema, ComputationalThinkingSchema, ConstructiveAlignmentEvaluator, CoreConceptSchema, CourseObjectiveSchema, CoverageReportSchema, CrossArtifactDriftEvaluator, CurriculumArtifactSchema, CurriculumError, CurriculumPlanSchema, CurriculumQualityReportSchema, DEFAULT_ENABLED_PROVIDERS, DEFAULT_GATE_SETTINGS, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdgeSchema, DepthAssignmentSchema, DepthLevelSchema, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuestionSchema, DiagnosticQuizSchema, EDPPhaseEnum, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, EntryLevelSchema, ExitTicketBugHuntSchema, ExitTicketMetacognitionSchema, ExitTicketQuickItemSchema, ExitTicketRecallPromptSchema, ExitTicketSchema, ExperimentalDesignSchema, ExpositionApprovalError, ExtensionChallengeSchema, ExtensionSchema, FileSystemCurriculumAdapter, FiveEFlowPhaseSchema, FiveEInstructionalEvaluator, FiveEPhaseEnum, FrameworkMappingSchema, FrameworkPackManifestSchema, FrameworkPackSchema, FrameworkStatementSchema, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, GlossaryQuickRefRowSchema, GlossarySchema, GlossaryTermSchema, GoldTierSchema, GradeBandSchema, GraphicOrganizerItemSchema, GraphicOrganizerSchema, HANDOUT_TEMPLATE, HandoutSchema, HandoutSectionSchema, InstructionSectionSchema, InstructionStepSchema, JudgeCriterionSchema, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, LLMJudgeEngine, LabTierTaskSchema, LearningObjectiveInputSchema, LearningObjectiveRowSchema, LessonFlowPhaseSchema, LessonPlan5ESchema, LessonPlanEDPSchema, LessonPlanSchema, LessonSectionSchema, LocalWorkspaceManager, MappingKindSchema, MarpSlideSchema, MediaError, MediaLedger, MentorCheatsheetSchema, MilestoneInputSchema, MisconceptionEvaluator, MisconceptionSchema, ModelPolicyResolver, NVIDIA_MODELS, NodeKindSchema, OrganizerTypeEnum, PROJECT_INSTRUCTION_TEMPLATE, PhaseInputSchema, PlanConstraintsSchema, PlannerInputSchema, PlanningGraphSchema, PlanningNodeSchema, PrerequisiteDecisionEntrySchema, PrerequisiteDecisionSchema, ProductGoalSchema, ProgressiveHintsSchema, ProjectGraphSchema, ProjectInstructionSchema, ProjectProfileSchema, QUIZ_TEMPLATE, QualityAuditVerdictSchema, QuizOptionSchema, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, RecordProvenanceSchema, ResourceMapRowSchema, ReviewGameExportRowSchema, ReviewGameQuestionSchema, ReviewGameSchema, RoadmapInputSchema, RotationStationSchema, RubricCriteriaSchema, RubricSchema, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STANDARD_SOT_FILES, STATION_ROTATION_TEMPLATE, ScaffoldDecisionEntrySchema, ScaffoldDecisionSchema, ScienceLabSchema, ScoringRubricRowSchema, SelfLabSchema, SelfPacedBundleSchema, SelfPacedChallengeSchema, SessionPlanSchema, SilverTierSchema, SlideDeckSchema, StandardizedTermRowSchema, StandardsRegistryAdapter, StationRecordRowSchema, StationRotationSchema, StationTypeEnum, SupabaseCurriculumAdapter, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TaskCardSchema, TaskCardsSchema, TeacherGuideSchema, TeachingScriptPhaseSchema, TierLevelEnum, TierObjectiveSchema, TieredPracticeSchema, TranslationPolicySchema, TroubleshootingEntrySchema, TroubleshootingRowSchema, UnitPlanSchema, UserJourneySchema, WORKSHEET_TEMPLATE, WorksheetItemSchema, WorksheetItemTypeEnum, WorksheetPartSchema, WorksheetSchema, activityTools, analystTools, analyzeProjectCreationIntent, assertAcyclic, assessorTools, auditCurriculumQualityFlow, auditQualityReport, buildActivityPrompt, buildCodeLabPrompt, buildCurriculumContext, buildCurriculumPlan, buildDeliveryPackages, buildDiagnosticQuizPrompt, buildExpositionContext, buildExtensionPrompt, buildHandoutPrompt, buildImagePrompt, buildJudgePrompt, buildLessonMasterPrompt, buildProjectInstructionPrompt, buildSelfLabPrompt, buildSessionSliceContext, buildSlidesPrompt, buildStandardStackMarkdown, buildStandardsContext, buildStandardsContextBlock, buildTeacherGuidePrompt, buildWorksheetPrompt, computeContentHash, computePackingSpec, conductPreliminaryResearch, contentTools, convertRoadmapToFoundationSot, createAiInferenceError, createCurriculumStorage, createStreamAbortSignal, curateMediaLedger, designerTools, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, evaluateStandardsCoverage, executeCurriculumCommand, exportAllProjectQuizzes, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, extractThoughtAndContent, formatQuizzesToCsv, fulfillMediaLedger, gateModeFor, generateActivityFlow, generateCodeLabFlow, generateDiagnosticQuizFlow, generateEducationalImage, generateExtensionFlow, generateHandoutFlow, generateLessonMasterFlow, generateMilestoneCurriculumBundle, generatePhase1SotArtifacts, generatePhase2SotArtifacts, generateProjectInstruction, generateProjectInstructionFlow, generateRoadmapCurriculum, generateSelfLabFlow, generateSelfPacedBundle, generateSingleArtifact, generateSlidesFlow, generateTeacherGuideFlow, generateWorksheetFlow, getAIModel, getArtifactMetadata, getDesignatedFallbackChain, getDesignatedFallbackConfig, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, illustratorTools, importRoadmapToProject, ingestProjectGraphIntoProject, initializeProjectInStorage, injectMediaIntoMarkdown, isExpositionFresh, isModelAllowed, isProviderEnabled, isTranslationDue, lintAndSanitizeArtifact, lintCurriculumFramework, lintFrameworkPack, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, packagerTools, parseGateSettings, parseQuizMarkdown, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, publishToGitHub, publishToSupabase, rankGenCandidates, renderFrameworkFromPlan, renderMediaPlaceholder, researcherTools, resolveGateSettings, resolveStandardsPacks, resolveStreamBudget, resolveTranslationTargets, reviewerTools, runCurriculumAIInference, safeParseJson, searchEducationalImages, searchEducationalVideos, selectStatementsForLesson, serializeActivityToMarkdown, serializeCodeLabToMarkdown, serializeDiagnosticQuizToMarkdown, serializeHandoutToMarkdown, serializeLessonToMarkdown, serializeProjectInstructionToMarkdown, serializeSelfLabToMarkdown, slugifyProjectName, streamCurriculumAIInference, streamCurriculumAIInferenceWithTools, streamDiagnosticQuizFlow, streamLLMWithFallback, streamLayerPrefillWithFallback, streamLessonMasterFlow, streamSelfLabFlow, techSmeTools, topoSort, uploadAssetToBucket, validateCurriculumPlan, validateFrameworkPack, validateMarkdownTables, validateMermaidSyntax, withAutoRepair };
16678
+ export { ACT_TEMPLATE, ARTIFACT_EXECUTION_ORDER, AcademicAuditor, ActiveLearningWorkflowSchema, ActivityLabSchema, ActivitySeqRowSchema, ActivityStepSchema, ArtifactContractRowSchema, AssessmentMapRowSchema, AssessmentObjectiveSchema, BELL_RINGER_TEMPLATE, BLOOM_ACTION_VERBS, BOM_TEMPLATE, BUNDLED_STANDARDS_PACK_IDS, BellRingerDaySchema, BellRingerSchema, BloomHintSchema, BloomLevelSchema, BloomTaxonomyEvaluator, BronzeTierSchema, CERConclusionSchema, CHOICE_BOARD_TEMPLATE, CODE_LAB_TEMPLATE, CURRICULUM_SLASH_COMMANDS, CardTierEnum, ChoiceBoardRubricRowSchema, ChoiceBoardSchema, ChoiceRuleSchema, ChoiceSquareSchema, ClassificationSchema, CodeHardwareFeasibilityEvaluator, CodeLabSchema, CodeSnippetSchema, CompetencyRubricRowSchema, ComputationalThinkingSchema, ConstructiveAlignmentEvaluator, CoreConceptSchema, CourseObjectiveSchema, CoverageReportSchema, CrossArtifactDriftEvaluator, CurriculumArtifactSchema, CurriculumError, CurriculumPlanSchema, CurriculumQualityReportSchema, DEFAULT_ARTIFACT_STREAM_IDLE_MS, DEFAULT_ARTIFACT_STREAM_TOTAL_MS, DEFAULT_ENABLED_PROVIDERS, DEFAULT_GATE_SETTINGS, DEFAULT_STREAM_IDLE_MS, DEFAULT_STREAM_TOTAL_MS, DependencyEdgeSchema, DepthAssignmentSchema, DepthLevelSchema, DeterministicPipelineRunner, DeterministicStructuralLinter, DiagnosticQuestionSchema, DiagnosticQuizSchema, EDPPhaseEnum, EXIT_TICKET_TEMPLATE, EXPOSITION_REL, EXT_TEMPLATE, EntryLevelSchema, ExitTicketBugHuntSchema, ExitTicketMetacognitionSchema, ExitTicketQuickItemSchema, ExitTicketRecallPromptSchema, ExitTicketSchema, ExperimentalDesignSchema, ExpositionApprovalError, ExtensionChallengeSchema, ExtensionSchema, FileSystemCurriculumAdapter, FiveEFlowPhaseSchema, FiveEInstructionalEvaluator, FiveEPhaseEnum, FrameworkMappingSchema, FrameworkPackManifestSchema, FrameworkPackSchema, FrameworkStatementSchema, GLOSSARY_TEMPLATE, GRAPHIC_ORGANIZER_TEMPLATE, GlossaryQuickRefRowSchema, GlossarySchema, GlossaryTermSchema, GoldTierSchema, GradeBandSchema, GraphicOrganizerItemSchema, GraphicOrganizerSchema, HANDOUT_TEMPLATE, HandoutSchema, HandoutSectionSchema, InstructionSectionSchema, InstructionStepSchema, JudgeCriterionSchema, LAYER_TOTAL_BUDGET_MS, LESSON_PLAN_TEMPLATE, LLMJudgeEngine, LabTierTaskSchema, LearningObjectiveInputSchema, LearningObjectiveRowSchema, LessonFlowPhaseSchema, LessonPlan5ESchema, LessonPlanEDPSchema, LessonPlanSchema, LessonSectionSchema, LocalWorkspaceManager, MappingKindSchema, MarpSlideSchema, MediaError, MediaLedger, MentorCheatsheetSchema, MilestoneInputSchema, MisconceptionEvaluator, MisconceptionSchema, ModelPolicyResolver, NVIDIA_MODELS, NodeKindSchema, OrganizerTypeEnum, PROJECT_INSTRUCTION_TEMPLATE, PhaseInputSchema, PlanConstraintsSchema, PlannerInputSchema, PlanningGraphSchema, PlanningNodeSchema, PrerequisiteDecisionEntrySchema, PrerequisiteDecisionSchema, ProductGoalSchema, ProgressiveHintsSchema, ProjectGraphSchema, ProjectInstructionSchema, ProjectProfileSchema, QUIZ_TEMPLATE, QualityAuditVerdictSchema, QuizOptionSchema, REVIEW_GAME_TEMPLATE, RUBRIC_TEMPLATE, RecordProvenanceSchema, ResourceMapRowSchema, ReviewGameExportRowSchema, ReviewGameQuestionSchema, ReviewGameSchema, RoadmapInputSchema, RotationStationSchema, RubricCriteriaSchema, RubricSchema, SCIENCE_LAB_TEMPLATE, SELF_LAB_TEMPLATE, SLIDE_LAYOUT_PRESETS, SLIDE_TEMPLATE, STANDARD_SOT_FILES, STATION_ROTATION_TEMPLATE, ScaffoldDecisionEntrySchema, ScaffoldDecisionSchema, ScienceLabSchema, ScoringRubricRowSchema, SelfLabSchema, SelfPacedBundleSchema, SelfPacedChallengeSchema, SessionPlanSchema, SilverTierSchema, SlideDeckSchema, StandardizedTermRowSchema, StandardsRegistryAdapter, StationRecordRowSchema, StationRotationSchema, StationTypeEnum, SupabaseCurriculumAdapter, TASK_CARDS_TEMPLATE, TEACHER_GUIDE_TEMPLATE, TIERED_PRACTICE_TEMPLATE, TaskCardSchema, TaskCardsSchema, TeacherGuideSchema, TeachingScriptPhaseSchema, TierLevelEnum, TierObjectiveSchema, TieredPracticeSchema, TranslationPolicySchema, TroubleshootingEntrySchema, TroubleshootingRowSchema, UnitPlanSchema, UserJourneySchema, WORKSHEET_TEMPLATE, WorksheetItemSchema, WorksheetItemTypeEnum, WorksheetPartSchema, WorksheetSchema, activityTools, analystTools, analyzeProjectCreationIntent, assertAcyclic, assessorTools, auditCurriculumQualityFlow, auditQualityReport, buildActivityPrompt, buildCodeLabPrompt, buildCurriculumContext, buildCurriculumPlan, buildDeliveryPackages, buildDiagnosticQuizPrompt, buildExpositionContext, buildExtensionPrompt, buildHandoutPrompt, buildImagePrompt, buildJudgePrompt, buildLessonMasterPrompt, buildProjectInstructionPrompt, buildSelfLabPrompt, buildSessionSliceContext, buildSlidesPrompt, buildStandardStackMarkdown, buildStandardsContext, buildStandardsContextBlock, buildTeacherGuidePrompt, buildWorksheetPrompt, closeTruncatedJson, computeContentHash, computePackingSpec, conductPreliminaryResearch, contentTools, convertRoadmapToFoundationSot, createAiInferenceError, createCurriculumStorage, createIdleAbortController, createStreamAbortController, createStreamAbortSignal, curateMediaLedger, designerTools, detectProjectPedagogy, ensureExpositionForLesson, ensureKnowledgeExposition, evaluateStandardsCoverage, executeCurriculumCommand, exportAllProjectQuizzes, expositionCacheKey, extractScopeSequenceRows, extractSessionSlice, extractStreamChunk, extractThoughtAndContent, formatQuizzesToCsv, fulfillMediaLedger, gateModeFor, generateActivityFlow, generateCodeLabFlow, generateDiagnosticQuizFlow, generateEducationalImage, generateExtensionFlow, generateHandoutFlow, generateLessonMasterFlow, generateMilestoneCurriculumBundle, generatePhase1SotArtifacts, generatePhase2SotArtifacts, generateProjectInstruction, generateProjectInstructionFlow, generateRoadmapCurriculum, generateSelfLabFlow, generateSelfPacedBundle, generateSingleArtifact, generateSlidesFlow, generateTeacherGuideFlow, generateWorksheetFlow, getAIModel, getArtifactMetadata, getDesignatedFallbackChain, getDesignatedFallbackConfig, getLessonMetadata, getProjectArtifactScope, getProjectStatusReport, getSlideLayoutPresetById, getSlideLayoutPresetsByCategory, getSmartResumeContext, glossaryTermsForSession, illustratorTools, importRoadmapToProject, ingestProjectGraphIntoProject, initializeProjectInStorage, injectMediaIntoMarkdown, isExpositionFresh, isModelAllowed, isProviderEnabled, isTranslationDue, lintAndSanitizeArtifact, lintCurriculumFramework, lintFrameworkPack, loadCurriculumTemplate, loadSotTemplate, normalizePlanningGraph, packagerTools, parseGateSettings, parseQuizMarkdown, parseRoadmapJsonToProjectPayload, produceBatchLessons, produceSingleLesson, publishToGitHub, publishToSupabase, rankGenCandidates, renderFrameworkFromPlan, renderMediaPlaceholder, researcherTools, resolveGateSettings, resolveStandardsPacks, resolveStreamBudget, resolveTranslationTargets, reviewerTools, runCurriculumAIInference, safeParseJson, searchEducationalImages, searchEducationalVideos, selectStatementsForLesson, serializeActivityToMarkdown, serializeCodeLabToMarkdown, serializeDiagnosticQuizToMarkdown, serializeHandoutToMarkdown, serializeLessonToMarkdown, serializeProjectInstructionToMarkdown, serializeSelfLabToMarkdown, slugifyProjectName, streamCurriculumAIInference, streamCurriculumAIInferenceWithTools, streamDiagnosticQuizFlow, streamLLMWithFallback, streamLayerPrefillWithFallback, streamLessonMasterFlow, streamSelfLabFlow, stripLlmJsonWrappers, techSmeTools, topoSort, uploadAssetToBucket, validateCurriculumPlan, validateFrameworkPack, validateMarkdownTables, validateMermaidSyntax, withAutoRepair };
16571
16679
  //# sourceMappingURL=index.mjs.map
16572
16680
  //# sourceMappingURL=index.mjs.map