refactor(generation): consume the package everywhere and delete lib/generation (#1090)

Part D of #1057 — the switch. All consumers import @openmaic/generation; lib/generation deleted (net -11,900 lines). PBL wiring preserved (single-call -> classified fallback -> injected loop), streaming outline route deduplicated onto buildOutlinePrompt, serverExternalPackages wired, and the change verified by a real-model four-kind end-to-end run against the production build with a rendered-classroom screenshot check. Closes #1057.
This commit is contained in:
wyuc 2026-08-10 03:58:33 -04:00 committed by GitHub
parent b64e787749
commit 3b4567076f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
115 changed files with 565 additions and 12488 deletions

View File

@ -128,24 +128,6 @@ jobs:
- name: Unit Tests (generation)
run: pnpm --filter @openmaic/generation test
# Remove this duplicate-asset guard in Part D with the app prompt copy.
- name: Prompt asset parity (generation)
shell: bash
run: |
set -euo pipefail
for path in templates/requirements-to-outlines snippets/{image-instructions,json-output-rules,media-safety-guidelines,slide-generated-image-instructions,slide-image-instructions,slide-video-instructions,video-instructions}.md; do
if ! diff -r "lib/prompts/$path" "packages/@openmaic/generation/$path"; then
echo "::error file=lib/prompts/$path::Prompt asset $path diverged; the app and package copies must be edited together until Part D removes the app copy."
exit 1
fi
done
for prompt in planner-single-call-system planner-scenario-single-call-system; do
if ! diff "lib/pbl/v2/prompts/$prompt.md" "packages/@openmaic/generation/prompts-pbl/$prompt.md"; then
echo "::error file=lib/pbl/v2/prompts/$prompt.md::PBL planner prompt $prompt diverged; the app and package copies must be edited together until Part D removes the app copy."
exit 1
fi
done
- name: Node consumer smoke (generation scene)
shell: bash
run: |

View File

@ -708,7 +708,7 @@ OpenMAIC/
### 核心架构
- **生成流水线** (`lib/generation/`) — 两阶段:大纲生成 → 场景内容生成
- **生成流水线** (`@openmaic/generation`) — 两阶段:大纲生成 → 场景内容生成
- **多智能体编排** (`lib/orchestration/`) — 基于 LangGraph 的状态机,管理智能体轮次和讨论
- **回放引擎** (`lib/playback/`) — 驱动课堂回放和实时互动的状态机
- **动作引擎** (`lib/action/`) — 执行 28+ 种动作类型(语音、白板绘图/文字/形状/图表、聚光灯、激光笔…)

View File

@ -784,7 +784,7 @@ OpenMAIC/
### Key Architecture
- **Generation Pipeline** (`lib/generation/`) — Two-stage: outline generation → scene content generation
- **Generation Pipeline** (`@openmaic/generation`) — Two-stage: outline generation → scene content generation
- **Multi-Agent Orchestration** (`lib/orchestration/`) — LangGraph state machine managing agent turns and discussions
- **Playback Engine** (`lib/playback/`) — State machine driving classroom playback and live interaction
- **Action Engine** (`lib/action/`) — Executes 28+ action types (speech, whiteboard draw/text/shape/chart, spotlight, laser …)

View File

@ -14,7 +14,7 @@ import {
buildVisionUserContent,
type SceneGenerationContext,
type AgentInfo,
} from '@/lib/generation/generation-pipeline';
} from '@openmaic/generation';
import type { SceneOutline } from '@/lib/types/generation';
import type {
GeneratedSlideContent,

View File

@ -12,8 +12,8 @@ import {
applyOutlineFallbacks,
generateSceneContent,
buildVisionUserContent,
} from '@/lib/generation/generation-pipeline';
import type { AgentInfo } from '@/lib/generation/generation-pipeline';
} from '@openmaic/generation';
import type { AgentInfo } from '@openmaic/generation';
import type {
SceneOutline,
PdfImage,
@ -26,6 +26,7 @@ import { llmApiError } from '@/lib/server/llm-error-response';
import { resolveModelFromRequest } from '@/lib/server/resolve-model';
import { resolveVocationalActive } from '@/lib/config/feature-flags';
import { sortDocumentImagesForVision } from '@/lib/document/bundle';
import { generatePBLV2Project } from '@/lib/pbl/v2/agents/planner';
const log = createLogger('Scene Content API');
@ -171,15 +172,19 @@ export async function POST(req: NextRequest) {
const content = await generateSceneContent(effectiveOutline, aiCall, {
assignedImages,
imageMapping,
languageModel: effectiveOutline.type === 'pbl' ? languageModel : undefined,
visionEnabled: hasVision,
generatedMediaMapping,
agents,
languageDirective,
thinkingConfig,
targetLanguage: userLocale || undefined,
userRequirements: requirements,
allowProceduralSkill: vocationalActive,
...(effectiveOutline.type === 'pbl'
? {
pblLoopFallback: (input) =>
generatePBLV2Project(input, languageModel, callLLM, { logger: log }, thinkingConfig),
}
: {}),
});
if (!content) {

View File

@ -20,11 +20,12 @@ import {
formatImageDescription,
formatImagePlaceholder,
buildVisionUserContent,
buildOutlinePrompt,
uniquifyMediaElementIds,
formatTeacherPersonaForPrompt,
} from '@/lib/generation/generation-pipeline';
import type { AgentInfo } from '@/lib/generation/generation-pipeline';
import { DEFAULT_LANGUAGE_DIRECTIVE } from '@/lib/generation/outline-generator';
} from '@openmaic/generation';
import type { AgentInfo } from '@openmaic/generation';
import { DEFAULT_LANGUAGE_DIRECTIVE } from '@openmaic/generation';
import { MAX_PDF_CONTENT_CHARS, MAX_VISION_IMAGES } from '@/lib/constants/generation';
import { nanoid } from 'nanoid';
import type {
@ -71,7 +72,7 @@ function extractLanguageDirective(buffer: string): string | null {
const COURSE_TITLE_RE = /"courseTitle"\s*:\s*"((?:[^"\\]|\\.)*)"/;
// Normalize a captured title identically to the non-streaming parser
// (lib/generation/outline-generator.ts): ignore whitespace-only titles and cap
// (@openmaic/generation outline parser): ignore whitespace-only titles and cap
// length defensively so a hallucinating model cannot push a blank or unbounded
// value into the stage name. Returning null lets callers fall back / keep scanning.
function normalizeStreamedTitle(raw: string): string | null {
@ -363,25 +364,37 @@ export async function POST(req: NextRequest) {
// Check if Interactive Mode or server-enabled Task Engine mode is enabled.
const interactiveMode = requirements.interactiveMode ?? false;
const taskEngineMode = resolveVocationalActive(requirements);
const promptId = taskEngineMode
? PROMPT_IDS.TASK_ENGINE_OUTLINES
: interactiveMode
? PROMPT_IDS.INTERACTIVE_OUTLINES
: PROMPT_IDS.REQUIREMENTS_TO_OUTLINES;
const prompts = buildPrompt(promptId, {
requirement: requirements.requirement,
pdfContent: pdfText ? pdfText.substring(0, MAX_PDF_CONTENT_CHARS) : 'None',
availableImages: availableImagesText,
researchContext: researchContext || 'None',
hasSourceImages,
imageEnabled: imageGenerationEnabled,
videoEnabled: videoGenerationEnabled,
mediaEnabled: mediaGenerationEnabled,
// Standard outline generation is byte-identical to the package path. The
// two app-only modes retain their own templates but share the same inputs.
let prompts: { system: string; user: string } | null = buildOutlinePrompt(requirements, {
pdfText,
pdfImages,
visionEnabled: hasVision,
imageMapping,
imageGenerationEnabled,
videoGenerationEnabled,
researchContext,
teacherContext,
userProfile: userProfileText,
});
if (taskEngineMode || interactiveMode) {
const promptId = taskEngineMode
? PROMPT_IDS.TASK_ENGINE_OUTLINES
: PROMPT_IDS.INTERACTIVE_OUTLINES;
prompts = buildPrompt(promptId, {
requirement: requirements.requirement,
pdfContent: pdfText ? pdfText.substring(0, MAX_PDF_CONTENT_CHARS) : 'None',
availableImages: availableImagesText,
researchContext: researchContext || 'None',
hasSourceImages,
imageEnabled: imageGenerationEnabled,
videoEnabled: videoGenerationEnabled,
mediaEnabled: mediaGenerationEnabled,
teacherContext,
userProfile: userProfileText,
});
}
if (!prompts) {
return apiError('INTERNAL_ERROR', 500, 'Prompt template not found');
}

View File

@ -21,7 +21,7 @@ import {
SEARCH_QUERY_REWRITE_EXCERPT_LENGTH,
} from '@/lib/server/search-query-builder';
import { resolveModelFromRequest } from '@/lib/server/resolve-model';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import type { AICallFn } from '@openmaic/generation';
import { WEB_SEARCH_PROVIDERS } from '@/lib/web-search/constants';
import type { BaiduSubSources, WebSearchProviderId } from '@/lib/web-search/types';
import { resolveWebSearchRouteBaseUrl } from '@/lib/server/web-search-config';

View File

@ -21,7 +21,7 @@ import {
fetchSceneContent,
generateTTSForScene,
} from '@/lib/hooks/use-scene-generator';
import { isAbortError } from '@/lib/generation/generation-retry';
import { isAbortError } from '@openmaic/generation';
import { FOREGROUND_SCENE_RETRY_OPTIONS } from './foreground-retry';
import {
loadImageMapping,

View File

@ -28,7 +28,7 @@ import { useI18n } from '@/lib/hooks/use-i18n';
import { cn } from '@/lib/utils';
import type { SceneOutline } from '@/lib/types/generation';
import type { WidgetType } from '@/lib/types/widgets';
import { changeOutlineType } from '@/lib/generation/outline-type';
import { changeOutlineType } from '@openmaic/generation';
import { countBlockingOutlines, validateOutline } from '@/lib/edit/content-validation';
type SceneType = SceneOutline['type'];

View File

@ -18,9 +18,9 @@
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { generateSceneOutlinesFromRequirements } from '@/lib/generation/outline-generator';
import { generateSceneOutlinesFromRequirements } from '@openmaic/generation';
import { callLLM } from '@/lib/ai/llm';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import type { AICallFn } from '@openmaic/generation';
import { resolveEvalModel } from '../shared/resolve-model';
import { createRunDir } from '../shared/run-dir';
import { judgeDirective } from './judge';

View File

@ -46,7 +46,7 @@ import { callLLM } from '@/lib/ai/llm';
import { generatePBLV2Project } from '@/lib/pbl/v2/agents/planner';
import { generatePBLV2ProjectSingleCall } from '@/lib/pbl/v2/agents/planner-single-call';
import { PlannerV2Error } from '@/lib/pbl/v2/agents/planner-core';
import { parseJsonResponse } from '@/lib/generation/json-repair';
import { parseJsonResponse } from '@openmaic/generation';
import { buildCompareHtml } from './compare-html';
import type { PBLPlannerV2Input, PBLProjectV2 } from '@/lib/pbl/v2/types';
import type { SceneOutline } from '@/lib/types/generation';
@ -457,7 +457,15 @@ function runVariant(
thinkingConfig?: ThinkingConfig,
): Promise<PBLProjectV2> {
return variant === 'single-call'
? generatePBLV2ProjectSingleCall(input, model, callLLM, undefined, thinkingConfig)
? generatePBLV2ProjectSingleCall(input, async (system, prompt) => {
const result = await callLLM(
{ model, system, prompt },
'pbl-v2-planner-single',
undefined,
thinkingConfig,
);
return result.text;
})
: generatePBLV2Project(input, model, callLLM, undefined, thinkingConfig);
}

View File

@ -109,7 +109,7 @@ consumes content from the **trusted source**. Both paths are needed.
- `V0_ALLOWLIST` → `new Set(['read_scene_content', 'regenerate_scene',
'regenerate_scene_actions'])`.
### 5.4 Generation pipeline — `lib/generation/scene-generator.ts`
### 5.4 Generation pipeline — `@openmaic/generation`
`generateSceneContent` already threads a `languageDirective` into its prompt;
this is the template for the new inputs. Add to `SceneContentOptions`:

View File

@ -24,7 +24,7 @@ import {
generateSceneActions,
type SceneGenerationContext,
type AgentInfo,
} from '@/lib/generation/generation-pipeline';
} from '@openmaic/generation';
import type { Action } from '@/lib/types/action';
import type {
SceneOutline,

View File

@ -20,8 +20,11 @@
import { Type, type Static } from 'typebox';
import type { AgentTool } from '@earendil-works/pi-agent-core';
import { generateSceneContent, generateSceneActions } from '@/lib/generation/scene-generator';
import type { SceneGenerationContext } from '@/lib/generation/generation-pipeline';
import {
generateSceneActions,
generateSceneContent,
type SceneGenerationContext,
} from '@openmaic/generation';
import type { Action } from '@/lib/types/action';
import type { GeneratedSlideContent, PdfImage, ImageMapping } from '@/lib/types/generation';
import type { SceneContent } from '@/lib/types/stage';

View File

@ -1,161 +0,0 @@
/**
* Action Parser - converts structured JSON Array output to Action[]
*
* Bridges the stateless-generate parser (used for online streaming) with the
* offline generation pipeline, producing typed Action objects that preserve
* the original interleaving order from the LLM output.
*
* For complete (non-streaming) responses, uses JSON.parse with partial-json
* fallback for robustness.
*/
import type { Action, ActionType } from '@/lib/types/action';
import { SLIDE_ONLY_ACTIONS } from '@/lib/types/action';
import { nanoid } from 'nanoid';
import { parse as parsePartialJson, Allow } from 'partial-json';
import { jsonrepair } from 'jsonrepair';
import { createLogger } from '@/lib/logger';
const log = createLogger('ActionParser');
/**
* Strip markdown code fences (```json ... ``` or ``` ... ```) from a response string.
*/
function stripCodeFences(text: string): string {
// Remove opening ```json or ``` and closing ```
return text.replace(/^```(?:json)?\s*\n?/i, '').replace(/\n?\s*```\s*$/i, '');
}
/**
* Parse a complete LLM response in JSON Array format into an ordered Action[] array.
*
* Expected format (new):
* [{"type":"action","name":"spotlight","params":{"elementId":"..."}},
* {"type":"text","content":"speech content"},...]
*
* Also supports legacy format:
* [{"type":"action","tool_name":"spotlight","parameters":{"elementId":"..."}},...]
*
* Text items become `speech` actions; action items are converted to their
* respective action types (spotlight, discussion, etc.).
* The original interleaving order is preserved.
*/
export function parseActionsFromStructuredOutput(
response: string,
sceneType?: string,
allowedActions?: string[],
): Action[] {
// Step 1: Strip markdown code fences if present
const cleaned = stripCodeFences(response.trim());
// Step 2: Find the JSON array range
const startIdx = cleaned.indexOf('[');
const endIdx = cleaned.lastIndexOf(']');
if (startIdx === -1) {
log.warn('No JSON array found in response');
return [];
}
const jsonStr = endIdx > startIdx ? cleaned.slice(startIdx, endIdx + 1) : cleaned.slice(startIdx); // unclosed array — let partial-json handle it
// Step 3: Parse — try JSON.parse first, then jsonrepair, fallback to partial-json
let items: unknown[];
try {
items = JSON.parse(jsonStr);
} catch {
// Try jsonrepair to fix malformed JSON (e.g. unescaped quotes in Chinese text)
try {
items = JSON.parse(jsonrepair(jsonStr));
log.info('Recovered malformed JSON via jsonrepair');
} catch {
try {
items = parsePartialJson(
jsonStr,
Allow.ARR | Allow.OBJ | Allow.STR | Allow.NUM | Allow.BOOL | Allow.NULL,
);
} catch (e) {
log.warn('Failed to parse JSON array:', (e as Error).message);
return [];
}
}
}
if (!Array.isArray(items)) {
log.warn('Parsed result is not an array');
return [];
}
// Step 4: Convert items to Action[]
const actions: Action[] = [];
for (const item of items) {
if (!item || typeof item !== 'object' || !('type' in item)) continue;
const typedItem = item as Record<string, unknown>;
if (typedItem.type === 'text') {
const text = ((typedItem.content as string) || '').trim();
if (text) {
actions.push({
id: `action_${nanoid(8)}`,
type: 'speech',
text,
});
}
} else if (typedItem.type === 'action') {
try {
// Support both new format (name/params) and legacy format (tool_name/parameters)
const actionName = typedItem.name || typedItem.tool_name;
const actionParams = (typedItem.params || typedItem.parameters || {}) as Record<
string,
unknown
>;
const action = {
id: (typedItem.action_id || typedItem.tool_id || `action_${nanoid(8)}`) as string,
type: actionName as Action['type'],
...actionParams,
} as Action;
// `widget_setState.state` is required by the type, but the LLM may omit it.
// The former TeacherAction→Action converter always defaulted it to `{}`;
// restore that guard so a missing `state` can't reach the iframe as
// `state: undefined` (SET_WIDGET_STATE handlers dereference it).
if (action.type === 'widget_setState' && action.state == null) {
action.state = {};
}
actions.push(action);
} catch (_e) {
log.warn('Invalid action item, skipping:', JSON.stringify(typedItem).slice(0, 100));
}
}
}
// Step 5: Post-processing — discussion must be the last action, and at most one
const discussionIdx = actions.findIndex((a) => a.type === 'discussion');
if (discussionIdx !== -1 && discussionIdx < actions.length - 1) {
actions.splice(discussionIdx + 1);
}
// Step 6: Filter out slide-only actions for non-slide scenes (defense in depth)
let result = actions;
if (sceneType && sceneType !== 'slide') {
const before = result.length;
result = result.filter((a) => !SLIDE_ONLY_ACTIONS.includes(a.type as ActionType));
if (result.length < before) {
log.info(`Stripped ${before - result.length} slide-only action(s) from ${sceneType} scene`);
}
}
// Step 7: Filter by allowedActions whitelist (defense in depth for role-based isolation)
// Catches hallucinated actions not in the agent's permitted set, e.g. a student agent
// mimicking spotlight/laser after seeing widget actions in chat history.
if (allowedActions && allowedActions.length > 0) {
const before = result.length;
result = result.filter((a) => a.type === 'speech' || allowedActions.includes(a.type));
if (result.length < before) {
log.info(
`Stripped ${before - result.length} disallowed action(s) by allowedActions whitelist`,
);
}
}
return result;
}

View File

@ -1,48 +0,0 @@
/**
* Two-Stage Generation Pipeline
*
* Barrel re-export — all symbols previously exported from this file
* are now spread across focused sub-modules.
*/
// Types
export type {
AgentInfo,
SceneGenerationContext,
GeneratedSlideData,
GenerationResult,
AICallFn,
} from './pipeline-types';
// Prompt formatters
export {
buildCourseContext,
formatAgentsForPrompt,
formatTeacherPersonaForPrompt,
formatImageDescription,
formatImagePlaceholder,
buildVisionUserContent,
buildLanguageText,
} from './prompt-formatters';
// JSON repair
export { parseJsonResponse, tryParseJson } from './json-repair';
// Outline generator (Stage 1)
export { generateSceneOutlinesFromRequirements, applyOutlineFallbacks } from './outline-generator';
// Scene generator (Stage 2)
export {
generateSceneContent,
generateSceneActions,
createSceneWithActions,
PBLGenerationError,
} from './scene-generator';
export type { SceneContentOptions, SceneActionsOptions } from './scene-generator';
// Scene builder (standalone)
export {
buildSceneFromOutline,
buildCompleteScene,
uniquifyMediaElementIds,
} from './scene-builder';

View File

@ -1,234 +0,0 @@
export interface GenerationRetryEvent {
label: string;
attempt: number;
maxAttempts: number;
nextDelayMs: number;
reason: string;
}
export interface GenerationRetryOptions<T> {
label: string;
maxRetries?: number;
baseDelayMs?: number;
maxDelayMs?: number;
signal?: AbortSignal;
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
random?: () => number;
shouldRetryResult?: (result: T) => boolean;
onRetry?: (event: GenerationRetryEvent) => Promise<void> | void;
}
const DEFAULT_MAX_RETRIES = 5;
const DEFAULT_BASE_DELAY_MS = 1000;
const DEFAULT_MAX_DELAY_MS = 16000;
const RETRYABLE_STATUS_CODES = new Set([408, 409, 425, 429]);
const NON_RETRYABLE_STATUS_CODES = new Set([400, 401, 403, 404, 422]);
const defaultSleep = (ms: number, signal?: AbortSignal) =>
new Promise<void>((resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException('Aborted', 'AbortError'));
return;
}
const onAbort = () => {
clearTimeout(timeoutId);
signal?.removeEventListener('abort', onAbort);
reject(new DOMException('Aborted', 'AbortError'));
};
const timeoutId = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw new DOMException('Aborted', 'AbortError');
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
/**
* Detect cancellation consistently across browser, Node, and test runtimes.
* Some runtimes expose AbortError as a DOMException, while others use a plain
* Error-shaped value, so relying on one prototype is not sufficient.
*/
export function isAbortError(error: unknown): boolean {
if (error instanceof Error && error.name === 'AbortError') return true;
if (
typeof DOMException !== 'undefined' &&
error instanceof DOMException &&
error.name === 'AbortError'
) {
return true;
}
return isRecord(error) && stringField(error, 'name') === 'AbortError';
}
function stringField(record: Record<string, unknown>, key: string): string | undefined {
const value = record[key];
return typeof value === 'string' ? value : undefined;
}
function booleanField(record: Record<string, unknown>, key: string): boolean | undefined {
const value = record[key];
return typeof value === 'boolean' ? value : undefined;
}
function statusCodeFrom(value: unknown): number | undefined {
if (!isRecord(value)) return undefined;
for (const key of ['statusCode', 'status', 'status_code']) {
const raw = value[key];
if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
if (typeof raw === 'string') {
const parsed = Number.parseInt(raw, 10);
if (Number.isFinite(parsed)) return parsed;
}
}
return undefined;
}
function messageFrom(value: unknown): string {
if (value instanceof Error) return value.message;
if (!isRecord(value)) return String(value);
const message = stringField(value, 'message') ?? stringField(value, 'statusText');
return message ?? '';
}
function retryableByMessage(value: unknown): boolean {
const message = messageFrom(value);
return /rate limit|too many requests|timeout|timed out|fetch failed|network|ECONNRESET|ECONNREFUSED|ECONNABORTED|ETIMEDOUT|ENOTFOUND|EPIPE|socket hang up/i.test(
message,
);
}
function unwrapErrors(value: unknown): unknown[] {
if (!isRecord(value)) return [];
const nested: unknown[] = [];
if ('lastError' in value) nested.push(value.lastError);
if ('cause' in value) nested.push(value.cause);
const errors = value.errors;
if (Array.isArray(errors)) nested.push(...errors);
return nested;
}
export function isRetryableGenerationError(error: unknown, seen = new Set<unknown>()): boolean {
if (!error || seen.has(error)) return false;
seen.add(error);
if (isAbortError(error)) return false;
if (isRecord(error)) {
const explicitRetryable = booleanField(error, 'isRetryable');
if (explicitRetryable !== undefined) return explicitRetryable;
}
const statusCode = statusCodeFrom(error);
if (statusCode !== undefined) {
if (RETRYABLE_STATUS_CODES.has(statusCode) || statusCode >= 500) return true;
if (NON_RETRYABLE_STATUS_CODES.has(statusCode) || (statusCode >= 400 && statusCode < 500)) {
return false;
}
}
const nested = unwrapErrors(error);
if (nested.length > 0) {
return nested.some((nestedError) => isRetryableGenerationError(nestedError, seen));
}
if (isRecord(error) && stringField(error, 'name') === 'TimeoutError') return true;
if (error instanceof Error && error.name === 'TimeoutError') return true;
return retryableByMessage(error);
}
function retryReason(error: unknown): string {
const statusCode = statusCodeFrom(error);
if (statusCode !== undefined) return `HTTP ${statusCode}`;
const message = messageFrom(error).trim();
return message || 'retryable error';
}
function retryDelayMs(
attempt: number,
baseDelayMs: number,
maxDelayMs: number,
random: () => number,
): number {
const exponentialDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempt - 1));
const jitter = Math.floor(exponentialDelay * Math.max(0, Math.min(random(), 1)) * 0.2);
return Math.min(maxDelayMs, exponentialDelay + jitter);
}
export async function withGenerationRetry<T>(
operation: (attempt: number) => Promise<T>,
options: GenerationRetryOptions<T>,
): Promise<T> {
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
const maxAttempts = maxRetries + 1;
const baseDelayMs = options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
const maxDelayMs = options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
const sleep = options.sleep ?? defaultSleep;
const random = options.random ?? Math.random;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
throwIfAborted(options.signal);
try {
const result = await operation(attempt);
throwIfAborted(options.signal);
if (!options.shouldRetryResult?.(result) || attempt >= maxAttempts) {
return result;
}
const nextDelayMs = retryDelayMs(attempt, baseDelayMs, maxDelayMs, random);
await options.onRetry?.({
label: options.label,
attempt,
maxAttempts,
nextDelayMs,
reason: 'empty result',
});
throwIfAborted(options.signal);
await sleep(nextDelayMs, options.signal);
} catch (error) {
if (isAbortError(error)) {
throw error;
}
throwIfAborted(options.signal);
if (attempt >= maxAttempts || !isRetryableGenerationError(error)) {
throw error;
}
const nextDelayMs = retryDelayMs(attempt, baseDelayMs, maxDelayMs, random);
await options.onRetry?.({
label: options.label,
attempt,
maxAttempts,
nextDelayMs,
reason: retryReason(error),
});
throwIfAborted(options.signal);
await sleep(nextDelayMs, options.signal);
}
}
throw new Error(`Generation retry loop exhausted for ${options.label}`);
}

View File

@ -1,157 +0,0 @@
/**
* Interactive HTML Post-Processor
*
* Ported from Python's PostProcessor class (learn-your-way/concept_to_html.py:287-385)
*
* Handles:
* - LaTeX delimiter conversion ($$...$$ -> \[...\], $...$ -> \(...\))
* - KaTeX CSS/JS injection with auto-render and MutationObserver
* - Script tag protection during LaTeX conversion
*/
/**
* Main entry point: post-process generated interactive HTML
* Converts LaTeX delimiters and injects KaTeX rendering resources.
*/
export function postProcessInteractiveHtml(html: string): string {
// Convert LaTeX delimiters while protecting script tags
let processed = convertLatexDelimiters(html);
// Inject KaTeX resources if not already present
if (!processed.toLowerCase().includes('katex')) {
processed = injectKatex(processed);
}
return processed;
}
/**
* Convert LaTeX delimiters while protecting <script> tags.
*
* - Protects script blocks from modification
* - Converts $$...$$ to \[...\] (display math)
* - Converts $...$ to \(...\) (inline math)
* - Restores script blocks after conversion
*/
function convertLatexDelimiters(html: string): string {
const scriptBlocks: string[] = [];
// Protect script tags by replacing them with placeholders
let processed = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, (match) => {
scriptBlocks.push(match);
return `__SCRIPT_BLOCK_${scriptBlocks.length - 1}__`;
});
// Convert display math: $$...$$ -> \[...\]
processed = processed.replace(/\$\$([^$]+)\$\$/g, '\\[$1\\]');
// Convert inline math: $...$ -> \(...\)
// Use non-greedy match and exclude newlines to avoid false positives
processed = processed.replace(/\$([^$\n]+?)\$/g, '\\($1\\)');
// Restore script blocks in a single pass. A replacer FUNCTION (not a string)
// is safe even when script content contains `$` — a function's return value
// is inserted literally, with no `$&`/`$1` substitution. The previous
// indexOf+substring loop rebuilt the entire string once per block, i.e.
// O(blocks × length), which balloons memory and blocks the event loop when
// the generated widget HTML contains many <script> tags.
processed = processed.replace(
/__SCRIPT_BLOCK_(\d+)__/g,
(whole, index) => scriptBlocks[Number(index)] ?? whole,
);
return processed;
}
/**
* Inject KaTeX CSS, JS, auto-render, and MutationObserver before </head>.
* Falls back to appending at end if </head> is not found.
*/
function injectKatex(html: string): string {
const katexInjection = `
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
const katexOptions = {
delimiters: [
{left: '\\\\[', right: '\\\\]', display: true},
{left: '\\\\(', right: '\\\\)', display: false},
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false}
],
throwOnError: false,
strict: false,
trust: true
};
let renderTimeout;
function safeRender() {
if (renderTimeout) clearTimeout(renderTimeout);
renderTimeout = setTimeout(() => {
renderMathInElement(document.body, katexOptions);
}, 100);
}
renderMathInElement(document.body, katexOptions);
const observer = new MutationObserver((mutations) => {
let shouldRender = false;
mutations.forEach((mutation) => {
if (mutation.target &&
mutation.target.className &&
typeof mutation.target.className === 'string' &&
mutation.target.className.includes('katex')) {
return;
}
shouldRender = true;
});
if (shouldRender) {
safeRender();
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true
});
setInterval(() => {
const text = document.body.innerText;
if (text.includes('\\\\(') || text.includes('$$')) {
safeRender();
}
}, 2000);
});
</script>`;
// Use indexOf + substring instead of String.replace() because the
// katexInjection string contains '$' characters that .replace() would
// interpret as special substitution patterns ($$ → $, $' → post-match text).
const headCloseIdx = html.indexOf('</head>');
if (headCloseIdx !== -1) {
return (
html.substring(0, headCloseIdx) +
katexInjection +
'\n</head>' +
html.substring(headCloseIdx + 7)
);
}
// Fallback: inject before </body> if </head> is missing
const bodyCloseIdx = html.indexOf('</body>');
if (bodyCloseIdx !== -1) {
return (
html.substring(0, bodyCloseIdx) +
katexInjection +
'\n</body>' +
html.substring(bodyCloseIdx + 7)
);
}
// Last resort: append at end
return html + katexInjection;
}

View File

@ -1,266 +0,0 @@
/**
* JSON parsing with fallback strategies for AI-generated responses.
*/
import { jsonrepair } from 'jsonrepair';
import { createLogger } from '@/lib/logger';
const log = createLogger('Generation');
function repairQuotedPropertyFragments(jsonStr: string): string {
return jsonStr.replace(
/([,{]\s*)"([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(true|false|null|[+-]?\d+(?:\.\d+)?)"(?=\s*[,}])/g,
(_match, prefix, key, value) => `${prefix}"${key}": ${value}`,
);
}
function logJsonParseError(stage: string, jsonStr: string, error: unknown): void {
const message = error instanceof Error ? error.message : String(error);
const positionMatch = message.match(/position\s+(\d+)/i);
const position = positionMatch ? Number(positionMatch[1]) : undefined;
if (typeof position === 'number' && Number.isFinite(position)) {
const start = Math.max(0, position - 120);
const end = Math.min(jsonStr.length, position + 120);
log.warn(
`${stage} parse error at position ${position}: ${message}. Context: ${jsonStr
.slice(start, end)
.replace(/\n/g, '\\n')}`,
);
return;
}
log.warn(`${stage} parse error: ${message}`);
}
export function parseJsonResponse<T>(response: string): T | null {
const exactParsed = tryParseExactJson<T>(response);
if (exactParsed !== null) return exactParsed;
const cleanedResponse = stripReasoningPrefix(response);
if (cleanedResponse !== response.trim()) {
const parsedCleaned = parseJsonResponseCandidate<T>(cleanedResponse);
if (parsedCleaned !== null) return parsedCleaned;
}
const parsed = parseJsonResponseCandidate<T>(response);
if (parsed !== null) return parsed;
log.error('Failed to parse JSON from response');
log.error('Raw response (first 500 chars):', cleanedResponse.substring(0, 500));
log.error(
'Raw response (last 500 chars):',
cleanedResponse.substring(Math.max(0, cleanedResponse.length - 500)),
);
return null;
}
function tryParseExactJson<T>(response: string): T | null {
try {
return JSON.parse(response.trim()) as T;
} catch {
return null;
}
}
function stripReasoningPrefix(response: string): string {
const trimmed = response.trim();
const matches = [...trimmed.matchAll(/<\/(?:think|thinking|reasoning)>\s*/gi)];
const lastMatch = matches.at(-1);
if (!lastMatch || lastMatch.index === undefined) return trimmed;
return trimmed.slice(lastMatch.index + lastMatch[0].length).trim();
}
function parseJsonResponseCandidate<T>(response: string): T | null {
const cleanedResponse = response.trim();
// Strategy 1: Try to extract JSON from markdown code blocks (may have multiple)
const codeBlockMatches = cleanedResponse.matchAll(/```(?:json)?\s*([\s\S]*?)```/g);
for (const match of codeBlockMatches) {
const extracted = match[1].trim();
// Only try if it looks like JSON (starts with { or [)
if (extracted.startsWith('{') || extracted.startsWith('[')) {
const result = tryParseJson<T>(extracted);
if (result !== null) {
log.debug('Successfully parsed JSON from code block');
return result;
}
}
}
// Strategy 2: Try to find JSON structure directly in response (no code block)
// Look for array or object start
const jsonStartArray = cleanedResponse.indexOf('[');
const jsonStartObject = cleanedResponse.indexOf('{');
if (jsonStartArray !== -1 || jsonStartObject !== -1) {
// Prefer the structure that appears first
const startIndex =
jsonStartArray === -1
? jsonStartObject
: jsonStartObject === -1
? jsonStartArray
: Math.min(jsonStartArray, jsonStartObject);
// Find the matching close bracket
let depth = 0;
let endIndex = -1;
let inString = false;
let escapeNext = false;
for (let i = startIndex; i < cleanedResponse.length; i++) {
const char = cleanedResponse[i];
if (escapeNext) {
escapeNext = false;
continue;
}
if (char === '\\' && inString) {
escapeNext = true;
continue;
}
if (char === '"' && !escapeNext) {
inString = !inString;
continue;
}
if (!inString) {
if (char === '[' || char === '{') depth++;
else if (char === ']' || char === '}') {
depth--;
if (depth === 0) {
endIndex = i;
break;
}
}
}
}
if (endIndex !== -1) {
const jsonStr = cleanedResponse.substring(startIndex, endIndex + 1);
const result = tryParseJson<T>(jsonStr);
if (result !== null) {
log.debug('Successfully parsed JSON from response body');
return result;
}
}
}
// Strategy 3: Last resort - try the whole response
const result = tryParseJson<T>(cleanedResponse.trim());
if (result !== null) {
log.debug('Successfully parsed raw response as JSON');
return result;
}
return null;
}
/**
* Try to parse JSON with various fixes for common AI response issues
*/
export function tryParseJson<T>(jsonStr: string): T | null {
// Attempt 1: Try parsing as-is
try {
return JSON.parse(jsonStr) as T;
} catch (error) {
logJsonParseError('Attempt 1', jsonStr, error);
// Continue to fix attempts
}
// Attempt 2: Fix common JSON issues from AI responses
try {
let fixed = jsonStr;
// Fix 0: Recover malformed property fragments that were accidentally
// emitted as standalone strings inside an object, such as:
// `"height: 76"` -> `"height": 76`
// `"fixedRatio: false"` -> `"fixedRatio": false`
// The object-context prefix/suffix guards keep valid JSON strings intact.
fixed = repairQuotedPropertyFragments(fixed);
// Fix 1: Handle LaTeX-style escapes that break JSON (e.g., \frac, \left, \right, \times, etc.)
// These are common in math content and need to be double-escaped
// Match backslash followed by letters (LaTeX commands) inside strings,
// but skip valid JSON escape sequences (\b, \f, \n, \r, \t, \u)
fixed = fixed.replace(/"([^"\\]*(?:\\.[^"\\]*)*)"/g, (_match, content) => {
// Double-escape backslash+letter ONLY for non-JSON-escape letters
const fixedContent = content.replace(/\\([a-zA-Z])/g, (_m: string, ch: string) => {
// Preserve valid JSON escape sequences
if ('bfnrtu'.includes(ch)) return `\\${ch}`;
return `\\\\${ch}`;
});
return `"${fixedContent}"`;
});
// Fix 2: Fix other invalid escape sequences (e.g., \S, \L, etc.)
// Valid JSON escapes: \", \\, \/, \b, \f, \n, \r, \t, \uXXXX
fixed = fixed.replace(/\\([^"\\\/bfnrtu\n\r])/g, (match, char) => {
// If it's a letter, it's likely a LaTeX command
if (/[a-zA-Z]/.test(char)) {
return '\\\\' + char;
}
return match;
});
// Fix 3: Try to fix truncated JSON arrays/objects
const trimmed = fixed.trim();
if (trimmed.startsWith('[') && !trimmed.endsWith(']')) {
const lastCompleteObj = fixed.lastIndexOf('}');
if (lastCompleteObj > 0) {
fixed = fixed.substring(0, lastCompleteObj + 1) + ']';
log.warn('Fixed truncated JSON array');
}
} else if (trimmed.startsWith('{') && !trimmed.endsWith('}')) {
// Try to close incomplete object
const openBraces = (fixed.match(/{/g) || []).length;
const closeBraces = (fixed.match(/}/g) || []).length;
if (openBraces > closeBraces) {
fixed += '}'.repeat(openBraces - closeBraces);
log.warn('Fixed truncated JSON object');
}
}
return JSON.parse(fixed) as T;
} catch (error) {
logJsonParseError('Attempt 2', jsonStr, error);
// Continue to next attempt
}
// Attempt 3: Use jsonrepair to fix malformed JSON (e.g. unescaped quotes in Chinese text)
try {
const repaired = jsonrepair(jsonStr);
return JSON.parse(repaired) as T;
} catch (error) {
logJsonParseError('Attempt 3', jsonStr, error);
// Continue to next attempt
}
// Attempt 4: More aggressive fixing - remove control characters
try {
let fixed = jsonStr;
// Remove or escape control characters
fixed = fixed.replace(/[\x00-\x1F\x7F]/g, (char) => {
switch (char) {
case '\n':
return '\\n';
case '\r':
return '\\r';
case '\t':
return '\\t';
default:
return '';
}
});
return JSON.parse(fixed) as T;
} catch (error) {
logJsonParseError('Attempt 4', jsonStr, error);
return null;
}
}

View File

@ -1,213 +0,0 @@
/**
* Stage 1: Generate scene outlines from user requirements.
* Also contains outline fallback logic.
*/
import { nanoid } from 'nanoid';
import { MAX_PDF_CONTENT_CHARS, MAX_VISION_IMAGES } from '@/lib/constants/generation';
import type {
UserRequirements,
SceneOutline,
PdfImage,
ImageMapping,
} from '@/lib/types/generation';
import { buildPrompt, PROMPT_IDS } from '@/lib/prompts';
import { formatImageDescription, formatImagePlaceholder } from './prompt-formatters';
import { sortDocumentImagesForVision } from '@/lib/document/bundle';
import { parseJsonResponse } from './json-repair';
import { uniquifyMediaElementIds } from './scene-builder';
import type { AICallFn, GenerationResult } from './pipeline-types';
import { createLogger } from '@/lib/logger';
const log = createLogger('Generation');
/**
* Used when the outline stage fails to produce an explicit directive (LLM
* schema regression, empty response, upstream error). Downstream prompts
* still need *something* that steers the model toward the requirement's
* language rather than defaulting to the training-distribution prior.
*/
export const DEFAULT_LANGUAGE_DIRECTIVE =
'Teach in the language that matches the user requirement.';
/**
* Generate scene outlines from user requirements
* Now uses simplified UserRequirements with just requirement text and language
*/
export async function generateSceneOutlinesFromRequirements(
requirements: UserRequirements,
pdfText: string | undefined,
pdfImages: PdfImage[] | undefined,
aiCall: AICallFn,
options?: {
visionEnabled?: boolean;
imageMapping?: ImageMapping;
imageGenerationEnabled?: boolean;
videoGenerationEnabled?: boolean;
researchContext?: string;
teacherContext?: string;
},
): Promise<
GenerationResult<{ languageDirective: string; courseTitle?: string; outlines: SceneOutline[] }>
> {
// Build available images description for the prompt
let availableImagesText = 'No images available';
let visionImages: Array<{ id: string; src: string }> | undefined;
if (pdfImages && pdfImages.length > 0) {
if (options?.visionEnabled && options?.imageMapping) {
// Vision mode: split into vision images (first N) and text-only (rest)
const sortedImages = sortDocumentImagesForVision(pdfImages);
const allWithSrc = sortedImages.filter((img) => options.imageMapping![img.id]);
const visionSlice = allWithSrc.slice(0, MAX_VISION_IMAGES);
const textOnlySlice = allWithSrc.slice(MAX_VISION_IMAGES);
const noSrcImages = sortedImages.filter((img) => !options.imageMapping![img.id]);
const visionDescriptions = visionSlice.map((img) => formatImagePlaceholder(img));
const textDescriptions = [...textOnlySlice, ...noSrcImages].map((img) =>
formatImageDescription(img),
);
availableImagesText = [...visionDescriptions, ...textDescriptions].join('\n');
visionImages = visionSlice.map((img) => ({
id: img.id,
src: options.imageMapping![img.id],
width: img.width,
height: img.height,
}));
} else {
// Text-only mode: full descriptions
availableImagesText = pdfImages.map((img) => formatImageDescription(img)).join('\n');
}
}
// Build user profile string for prompt injection
const userProfileText =
requirements.userNickname || requirements.userBio
? `## Student Profile\n\nStudent: ${requirements.userNickname || 'Unknown'}${requirements.userBio ? ` — ${requirements.userBio}` : ''}\n\nConsider this student's background when designing the course. Adapt difficulty, examples, and teaching approach accordingly.\n\n---`
: '';
// Build media snippet conditions based on enabled flags.
const imageEnabled = options?.imageGenerationEnabled ?? false;
const videoEnabled = options?.videoGenerationEnabled ?? false;
const mediaEnabled = imageEnabled || videoEnabled;
const hasSourceImages = (pdfImages?.length ?? 0) > 0;
// Use simplified prompt variables
const prompts = buildPrompt(PROMPT_IDS.REQUIREMENTS_TO_OUTLINES, {
// New simplified variables
requirement: requirements.requirement,
pdfContent: pdfText ? pdfText.substring(0, MAX_PDF_CONTENT_CHARS) : 'None',
availableImages: availableImagesText,
userProfile: userProfileText,
hasSourceImages,
imageEnabled,
videoEnabled,
mediaEnabled,
researchContext: options?.researchContext || 'None',
// Server-side generation populates this via options; client-side populates via formatTeacherPersonaForPrompt
teacherContext: options?.teacherContext || '',
});
if (!prompts) {
return { success: false, error: 'Prompt template not found' };
}
try {
const response = await aiCall(prompts.system, prompts.user, visionImages);
const parsed = parseJsonResponse<
{ languageDirective: string; courseTitle?: string; outlines: SceneOutline[] } | SceneOutline[]
>(response);
let languageDirective: string;
let courseTitle: string | undefined;
let rawOutlines: SceneOutline[];
if (Array.isArray(parsed)) {
// Fallback: LLM returned old flat array format
languageDirective = DEFAULT_LANGUAGE_DIRECTIVE;
rawOutlines = parsed;
} else if (parsed && parsed.outlines) {
languageDirective = parsed.languageDirective || DEFAULT_LANGUAGE_DIRECTIVE;
// courseTitle is optional — only honor a non-empty string, and cap its
// length defensively (the prompt asks for ≤30 chars, but older/hallucinating
// models may return far more). The downstream Stage.name column is bounded too.
const rawTitle = parsed.courseTitle;
courseTitle =
typeof rawTitle === 'string' && rawTitle.trim() ? rawTitle.trim().slice(0, 120) : undefined;
rawOutlines = parsed.outlines;
} else {
return { success: false, error: 'Failed to parse scene outlines response' };
}
if (!Array.isArray(rawOutlines)) {
return { success: false, error: 'Failed to parse scene outlines response' };
}
// Ensure IDs and order
const enriched = rawOutlines.map((outline, index) => ({
...outline,
id: outline.id || nanoid(),
order: index + 1,
}));
// Replace sequential gen_img_N/gen_vid_N with globally unique IDs
const result = uniquifyMediaElementIds(enriched);
return { success: true, data: { languageDirective, courseTitle, outlines: result } };
} catch (error) {
return { success: false, error: String(error) };
}
}
/**
* Apply type fallbacks for outlines that can't be generated as their declared type.
* - interactive without interactiveConfig OR widgetType+widgetOutline → slide
* - pbl without pblConfig or languageModel → slide
*/
export function sanitizeProceduralSkillOutline(outline: SceneOutline): SceneOutline {
const widgetOutline = { ...(outline.widgetOutline ?? {}) };
delete widgetOutline.procedureType;
delete widgetOutline.task;
delete widgetOutline.tools;
delete widgetOutline.steps;
delete widgetOutline.successCriteria;
delete widgetOutline.errorConsequences;
return {
...outline,
type: 'interactive',
widgetType: 'diagram',
description: outline.description
? `${outline.description} Present this as a process or structure diagram.`
: 'Present this topic as a process or structure diagram.',
widgetOutline,
};
}
export function applyOutlineFallbacks(
outline: SceneOutline,
hasLanguageModel: boolean,
options: { allowProceduralSkill?: boolean } = {},
): SceneOutline {
// Ultra Mode: interactive scenes with widgetType + widgetOutline are valid
const hasWidgetConfig = outline.widgetType && outline.widgetOutline;
if (outline.widgetType === 'procedural-skill' && !options.allowProceduralSkill) {
log.warn(`Procedural-skill outline "${outline.title}" is not enabled, falling back to diagram`);
return sanitizeProceduralSkillOutline(outline);
}
if (outline.type === 'interactive' && !outline.interactiveConfig && !hasWidgetConfig) {
log.warn(
`Interactive outline "${outline.title}" missing interactiveConfig and widget config, falling back to slide`,
);
return { ...outline, type: 'slide' };
}
if (outline.type === 'pbl' && (!outline.pblConfig || !hasLanguageModel)) {
log.warn(
`PBL outline "${outline.title}" missing pblConfig or languageModel, falling back to slide`,
);
return { ...outline, type: 'slide' };
}
return outline;
}

View File

@ -1,96 +0,0 @@
import type { SceneOutline, WidgetOutline } from '@/lib/types/generation';
type SceneType = SceneOutline['type'];
const DEFAULT_QUIZ_CONFIG = {
questionCount: 3,
difficulty: 'medium' as const,
questionTypes: ['single' as const],
};
const MAX_TARGET_SKILLS = 6;
/**
* Total constructor: returns a NEW outline of `newType` that is valid by
* construction. It strips every foreign per-type config and seeds the target
* type's required config from the shared fields (title / description /
* keyPoints), so the result survives `applyOutlineFallbacks` instead of being
* silently downgraded to a slide.
*
* Seeded values are pre-filled, user-editable defaults — not a hidden
* generation-time fallback. Switching away from a type therefore also clears
* its config so stale data is never persisted.
*/
export function changeOutlineType(outline: SceneOutline, newType: SceneType): SceneOutline {
// Re-selecting the current type is a no-op: return the outline untouched so a
// harmless menu click never rebuilds it and drops fields this constructor does
// not re-seed (e.g. legacy interactiveConfig, or a partial pblConfig whose
// projectTopic happens to be empty).
if (newType === outline.type) {
return outline;
}
// Shared fields only — every per-type config is intentionally dropped here and
// re-seeded per branch below.
const baseOutline: SceneOutline = {
id: outline.id,
type: newType,
title: outline.title,
description: outline.description,
keyPoints: outline.keyPoints ?? [],
order: outline.order,
...(outline.teachingObjective !== undefined && {
teachingObjective: outline.teachingObjective,
}),
...(outline.estimatedDuration !== undefined && {
estimatedDuration: outline.estimatedDuration,
}),
...(outline.languageNote !== undefined && { languageNote: outline.languageNote }),
...(outline.suggestedImageIds !== undefined && {
suggestedImageIds: outline.suggestedImageIds,
}),
...(outline.mediaGenerations !== undefined && { mediaGenerations: outline.mediaGenerations }),
};
switch (newType) {
case 'quiz':
return { ...baseOutline, quizConfig: outline.quizConfig ?? { ...DEFAULT_QUIZ_CONFIG } };
case 'interactive': {
// Preserve any already-valid widget config — including a gated
// procedural-skill one, whose task-engine fields must not be silently
// dropped when the type is re-selected. Otherwise seed a simulation widget.
// (The manual widget picker never *creates* procedural-skill.)
if (outline.widgetType && outline.widgetOutline) {
return {
...baseOutline,
widgetType: outline.widgetType,
widgetOutline: outline.widgetOutline,
};
}
const widgetOutline: WidgetOutline = { concept: outline.title || '' };
return { ...baseOutline, widgetType: 'simulation', widgetOutline };
}
case 'pbl': {
if (outline.pblConfig?.projectTopic) {
return { ...baseOutline, pblConfig: outline.pblConfig };
}
const targetSkills = Array.from(new Set((outline.keyPoints ?? []).filter(Boolean))).slice(
0,
MAX_TARGET_SKILLS,
);
return {
...baseOutline,
pblConfig: {
projectTopic: outline.title || '',
projectDescription: outline.description || '',
targetSkills,
},
};
}
case 'slide':
default:
return baseOutline;
}
}

View File

@ -1,64 +0,0 @@
/**
* Type definitions for the generation pipeline.
*/
// ==================== Agent Info ====================
/** Lightweight agent info passed to the generation pipeline */
export interface AgentInfo {
id: string;
name: string;
role: string;
persona?: string;
}
// ==================== Cross-Page Context ====================
/** Cross-page context for maintaining speech coherence across scenes */
export interface SceneGenerationContext {
pageIndex: number; // Current page (1-based)
totalPages: number; // Total number of pages
allTitles: string[]; // All page titles in order
previousSpeeches: string[]; // Speech texts from the previous page only
}
// ==================== Generated Slide Data Interface ====================
/**
* AI-generated slide data structure
* Used to parse AI responses
*/
export interface GeneratedSlideData {
elements: Array<{
type: 'text' | 'image' | 'video' | 'shape' | 'chart' | 'latex' | 'line';
left: number;
top: number;
width: number;
height: number;
[key: string]: unknown;
}>;
background?: {
type: 'solid' | 'gradient';
color?: string;
gradient?: {
type: 'linear' | 'radial';
colors: Array<{ pos: number; color: string }>;
rotate: number;
};
};
remark?: string;
}
// ==================== Types ====================
export interface GenerationResult<T> {
success: boolean;
data?: T;
error?: string;
}
export type AICallFn = (
systemPrompt: string,
userPrompt: string,
images?: Array<{ id: string; src: string }>,
) => Promise<string>;

View File

@ -1,152 +0,0 @@
/**
* Prompt and context building utilities for the generation pipeline.
*/
import type { PdfImage } from '@/lib/types/generation';
import type { AgentInfo, SceneGenerationContext } from './pipeline-types';
/** Build a course context string for injection into action prompts */
export function buildCourseContext(ctx?: SceneGenerationContext): string {
if (!ctx) return '';
const lines: string[] = [];
// Course outline with position marker
lines.push('Course Outline:');
ctx.allTitles.forEach((t, i) => {
const marker = i === ctx.pageIndex - 1 ? ' ← current' : '';
lines.push(` ${i + 1}. ${t}${marker}`);
});
// Position information
lines.push('');
lines.push(
'IMPORTANT: All pages belong to the SAME class session. Do NOT greet again after the first page. When referencing content from earlier pages, say "we just covered" or "as mentioned on page N" — NEVER say "last class" or "previous session" because there is no previous session.',
);
lines.push('');
if (ctx.pageIndex === 1) {
lines.push('Position: This is the FIRST page. Open with a greeting and course introduction.');
} else if (ctx.pageIndex === ctx.totalPages) {
lines.push('Position: This is the LAST page. Conclude the course with a summary and closing.');
lines.push(
'Transition: Continue naturally from the previous page. Do NOT greet or re-introduce.',
);
} else {
lines.push(`Position: Page ${ctx.pageIndex} of ${ctx.totalPages} (middle of the course).`);
lines.push(
'Transition: Continue naturally from the previous page. Do NOT greet or re-introduce.',
);
}
// Previous page speech for transition reference
if (ctx.previousSpeeches.length > 0) {
lines.push('');
lines.push('Previous page speech (for transition reference):');
const lastSpeech = ctx.previousSpeeches[ctx.previousSpeeches.length - 1];
lines.push(` "...${lastSpeech.slice(-150)}"`);
}
return lines.join('\n');
}
/** Format agent list for injection into action prompts */
export function formatAgentsForPrompt(agents?: AgentInfo[]): string {
if (!agents || agents.length === 0) return '';
const lines = ['Classroom Agents:'];
for (const a of agents) {
const personaPart = a.persona ? ` — ${a.persona}` : '';
lines.push(`- id: "${a.id}", name: "${a.name}", role: ${a.role}${personaPart}`);
}
return lines.join('\n');
}
/** Extract the teacher agent's persona for injection into outline/content prompts */
export function formatTeacherPersonaForPrompt(agents?: AgentInfo[]): string {
if (!agents || agents.length === 0) return '';
const teacher = agents.find((a) => a.role === 'teacher');
if (!teacher?.persona) return '';
return `Teacher Persona:\nName: ${teacher.name}\n${teacher.persona}\n\nAdapt the content style and tone to match this teacher's personality. IMPORTANT: The teacher's name and identity must NOT appear on the slides — no "Teacher ${teacher.name}'s tips", no "Teacher's message", etc. Slides should read as neutral, professional visual aids.`;
}
/**
* Format a single PdfImage description for prompt inclusion.
* Includes dimension/aspect-ratio info when available.
*/
export function formatImageDescription(img: PdfImage): string {
let dimInfo = '';
if (img.width && img.height) {
const ratio = (img.width / img.height).toFixed(2);
dimInfo = ` | size: ${img.width}×${img.height} (aspect ratio ${ratio})`;
}
const sourceInfo = img.sourceDocumentName ? ` from ${img.sourceDocumentName}` : ' from PDF';
const desc = img.description ? ` | ${img.description}` : '';
return `- **${img.id}**:${sourceInfo} page ${img.pageNumber}${dimInfo}${desc}`;
}
/**
* Format a short image placeholder for vision mode.
* Only ID + page + dimensions + aspect ratio (no description), since the model can see the actual image.
*/
export function formatImagePlaceholder(img: PdfImage): string {
let dimInfo = '';
if (img.width && img.height) {
const ratio = (img.width / img.height).toFixed(2);
dimInfo = ` | size: ${img.width}×${img.height} (aspect ratio ${ratio})`;
}
const sourceInfo = img.sourceDocumentName ? ` from ${img.sourceDocumentName}` : ' from PDF';
return `- **${img.id}**: image${sourceInfo} page ${img.pageNumber}${dimInfo} [see attached]`;
}
/**
* Build a multimodal user content array for the AI SDK.
* Interleaves text and images so the model can associate img_id with actual image.
* Each image label includes dimensions when available so the model knows the size
* before seeing the image (important for layout decisions).
*/
export function buildVisionUserContent(
userPrompt: string,
images: Array<{ id: string; src: string; width?: number; height?: number }>,
): Array<{ type: 'text'; text: string } | { type: 'image'; image: string; mimeType?: string }> {
const parts: Array<
{ type: 'text'; text: string } | { type: 'image'; image: string; mimeType?: string }
> = [{ type: 'text', text: userPrompt }];
if (images.length > 0) {
parts.push({ type: 'text', text: '\n\n--- Attached Images ---' });
for (const img of images) {
let dimInfo = '';
if (img.width && img.height) {
const ratio = (img.width / img.height).toFixed(2);
dimInfo = ` (${img.width}×${img.height}, aspect ratio ${ratio})`;
}
parts.push({ type: 'text', text: `\n**${img.id}**${dimInfo}:` });
// Strip data URI prefix — AI SDK only accepts http(s) URLs or raw base64
const dataUriMatch = img.src.match(/^data:([^;]+);base64,(.+)$/);
if (dataUriMatch) {
parts.push({
type: 'image',
image: dataUriMatch[2],
mimeType: dataUriMatch[1],
});
} else {
parts.push({ type: 'image', image: img.src });
}
}
}
return parts;
}
/**
* Build language instruction text from course-level directive and optional per-scene note.
* Used by scene content and action generators to inject into prompt templates.
*/
export function buildLanguageText(directive?: string, sceneNote?: string): string {
if (!directive && !sceneNote) return '';
let text = directive || '';
if (sceneNote) {
text += (text ? '\n\n' : '') + `Additional language note for this scene: ${sceneNote}`;
}
return text;
}

View File

@ -1,254 +0,0 @@
/**
* Standalone scene building and element normalization.
* Does NOT depend on store — returns complete Scene objects.
*/
import { nanoid } from 'nanoid';
import type {
SceneOutline,
GeneratedSlideContent,
GeneratedQuizContent,
GeneratedInteractiveContent,
GeneratedPBLContent,
PdfImage,
ImageMapping,
} from '@/lib/types/generation';
import type { LanguageModel } from 'ai';
import type { Slide, SlideTheme } from '@openmaic/dsl';
import type { Scene } from '@/lib/types/stage';
import type { Action } from '@/lib/types/action';
import { applyOutlineFallbacks } from './outline-generator';
import { generateSceneContent, generateSceneActions } from './scene-generator';
import type { AgentInfo, SceneGenerationContext, AICallFn } from './pipeline-types';
import { buildLanguageText } from './prompt-formatters';
import { createLogger } from '@/lib/logger';
import { resolvePBLContent } from '@/lib/pbl/legacy/read';
const log = createLogger('Generation');
/**
* Replace sequential gen_img_N / gen_vid_N IDs in outlines with globally unique IDs.
*
* The LLM generates sequential placeholder IDs (gen_img_1, gen_img_2, ...) which are
* only unique within a single course. Since the media store uses elementId as key
* without stageId scoping, identical IDs across different courses cause thumbnail
* contamination on the homepage. Using nanoid-based IDs ensures global uniqueness.
*/
export function uniquifyMediaElementIds(outlines: SceneOutline[]): SceneOutline[] {
const idMap = new Map<string, string>();
// First pass: collect all sequential media IDs and assign unique replacements
for (const outline of outlines) {
if (!outline.mediaGenerations) continue;
for (const mg of outline.mediaGenerations) {
if (!idMap.has(mg.elementId)) {
const prefix = mg.type === 'video' ? 'gen_vid_' : 'gen_img_';
idMap.set(mg.elementId, `${prefix}${nanoid(8)}`);
}
}
}
if (idMap.size === 0) return outlines;
// Second pass: replace IDs in mediaGenerations
return outlines.map((outline) => {
if (!outline.mediaGenerations) return outline;
return {
...outline,
mediaGenerations: outline.mediaGenerations.map((mg) => ({
...mg,
elementId: idMap.get(mg.elementId) || mg.elementId,
})),
};
});
}
/**
* Build a complete Scene object from an outline (for SSE streaming)
* This function does NOT depend on store - it returns a complete Scene object
*/
export async function buildSceneFromOutline(
outline: SceneOutline,
aiCall: AICallFn,
stageId: string,
assignedImages?: PdfImage[],
imageMapping?: ImageMapping,
languageModel?: LanguageModel,
visionEnabled?: boolean,
ctx?: SceneGenerationContext,
agents?: AgentInfo[],
onPhaseChange?: (phase: 'content' | 'actions') => void,
userProfile?: string,
languageDirective?: string,
): Promise<Scene | null> {
// Apply type fallbacks
outline = applyOutlineFallbacks(outline, !!languageModel);
const langText = buildLanguageText(languageDirective, outline.languageNote);
// Step 1: Generate content (with images if available)
onPhaseChange?.('content');
log.debug(`Step 1: Generating content for: ${outline.title}`);
if (assignedImages && assignedImages.length > 0) {
log.debug(
`Using ${assignedImages.length} assigned images: ${assignedImages.map((img) => img.id).join(', ')}`,
);
}
log.debug(
`imageMapping available: ${imageMapping ? Object.keys(imageMapping).length + ' keys' : 'undefined'}`,
);
const content = await generateSceneContent(outline, aiCall, {
assignedImages,
imageMapping,
languageModel,
visionEnabled,
agents,
languageDirective: langText,
});
if (!content) {
log.error(`Failed to generate content for: ${outline.title}`);
return null;
}
// Step 2: Generate Actions
onPhaseChange?.('actions');
log.debug(`Step 2: Generating actions for: ${outline.title}`);
const actions = await generateSceneActions(outline, content, aiCall, {
ctx,
agents,
userProfile,
languageDirective: langText,
});
log.debug(`Generated ${actions.length} actions for: ${outline.title}`);
// Build complete Scene object
return buildCompleteScene(outline, content, actions, stageId);
}
/**
* Build complete Scene object (without API/store).
*
* Stamps `outlineId` with the originating outline's id so editor agent tools
* can later resolve this scene's generation outline by identity rather than by
* the mutable `order` (which Pro-mode reorder/insert/delete rebalances).
*/
export function buildCompleteScene(
outline: SceneOutline,
content:
| GeneratedSlideContent
| GeneratedQuizContent
| GeneratedInteractiveContent
| GeneratedPBLContent,
actions: Action[],
stageId: string,
): Scene | null {
const scene = buildCompleteSceneInner(outline, content, actions, stageId);
return scene && { ...scene, outlineId: outline.id };
}
function buildCompleteSceneInner(
outline: SceneOutline,
content:
| GeneratedSlideContent
| GeneratedQuizContent
| GeneratedInteractiveContent
| GeneratedPBLContent,
actions: Action[],
stageId: string,
): Scene | null {
const sceneId = nanoid();
if (outline.type === 'slide' && 'elements' in content) {
// Build Slide object
const defaultTheme: SlideTheme = {
backgroundColor: '#ffffff',
themeColors: ['#5b9bd5', '#ed7d31', '#a5a5a5', '#ffc000', '#4472c4'],
fontColor: '#333333',
fontName: 'Microsoft YaHei',
outline: { color: '#d14424', width: 2, style: 'solid' },
shadow: { h: 0, v: 0, blur: 10, color: '#000000' },
};
const slide: Slide = {
id: nanoid(),
viewportSize: 1000,
viewportRatio: 0.5625,
theme: defaultTheme,
elements: content.elements,
background: content.background,
};
return {
id: sceneId,
stageId,
type: 'slide',
title: outline.title,
order: outline.order,
content: {
type: 'slide',
canvas: slide,
},
actions,
createdAt: Date.now(),
updatedAt: Date.now(),
};
}
if (outline.type === 'quiz' && 'questions' in content) {
return {
id: sceneId,
stageId,
type: 'quiz',
title: outline.title,
order: outline.order,
content: {
type: 'quiz',
questions: content.questions,
},
actions,
createdAt: Date.now(),
updatedAt: Date.now(),
};
}
if (outline.type === 'interactive' && 'html' in content) {
return {
id: sceneId,
stageId,
type: 'interactive',
title: outline.title,
order: outline.order,
content: {
type: 'interactive',
url: '',
html: content.html,
// Ultra Mode widget fields
widgetType: content.widgetType,
widgetConfig: content.widgetConfig,
},
actions,
createdAt: Date.now(),
updatedAt: Date.now(),
};
}
const resolvedPBL =
outline.type === 'pbl' ? resolvePBLContent(content as Partial<GeneratedPBLContent>) : undefined;
if (resolvedPBL?.kind === 'v2') {
return {
id: sceneId,
stageId,
type: 'pbl',
title: outline.title,
order: outline.order,
content: {
type: 'pbl',
projectV2: resolvedPBL.projectV2,
},
actions,
createdAt: Date.now(),
updatedAt: Date.now(),
};
}
return null;
}

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,7 @@ import type {
ImageMapping,
UserRequirements,
} from '@/lib/types/generation';
import type { AgentInfo } from '@/lib/generation/generation-pipeline';
import type { AgentInfo } from '@openmaic/generation';
import type { Scene } from '@/lib/types/stage';
import type { SpeechAction } from '@/lib/types/action';
import { splitLongSpeechActions } from '@/lib/audio/tts-utils';
@ -31,7 +31,7 @@ import {
isAbortError,
withGenerationRetry,
type GenerationRetryOptions,
} from '@/lib/generation/generation-retry';
} from '@openmaic/generation';
const log = createLogger('SceneGenerator');

View File

@ -12,7 +12,7 @@ import type { GeneratedAgentConfig } from '@/lib/types/stage';
import { USER_AVATAR } from '@/lib/types/roundtable';
import type { Participant, ParticipantRole } from '@/lib/types/roundtable';
import { useUserProfileStore } from '@/lib/store/user-profile';
import type { AgentInfo } from '@/lib/generation/pipeline-types';
import type { AgentInfo } from '@openmaic/generation';
interface AgentRegistryState {
agents: Record<string, AgentConfig>; // Map of agentId -> config

View File

@ -45,7 +45,7 @@ import type { LanguageModel } from 'ai';
import { createLogger } from '@/lib/logger';
import { streamLLM } from '@/lib/ai/llm';
import { buildVisionUserContent } from '@/lib/generation/prompt-formatters';
import { buildVisionUserContent } from '@openmaic/generation';
import type { ThinkingConfig } from '@/lib/types/provider';
import type {

View File

@ -1,484 +1,15 @@
/**
* PBL v2 — shared planner core.
*
* Pure project construction, prompt assembly, completion validation, and
* deterministic normalization shared by both planner call strategies. This
* module deliberately has no AI SDK, schema-library, or app LLM entry import.
*/
import { createLogger } from '@/lib/logger';
import { loadPBLV2Prompt } from '../prompts/loader';
import { computeInitialAssessment, reseatAssessmentTier } from '../operations/kernel/proficiency';
import { trimmedPBLText } from '../readers';
import type { PBLProjectV2, PBLPlannerV2Input, PBLProficiency, PBLRole } from '../types';
const log = createLogger('PBL v2 Planner');
/** SCENARIO ONLY. Packaged-format version stamped on scenario projects
* (`project.schemaVersion`). Absent on ordinary projects (baseline).
* Bump when the packaged scenario format changes so loaders can
* migrate. */
export const SCENARIO_SCHEMA_VERSION = 1;
// ---------------------------------------------------------------------------
// Callbacks (so the caller can stream progress to a UI later)
// ---------------------------------------------------------------------------
export interface PlannerV2Callbacks {
/** Fired on each successful tool call. Used by the future Generating
* page to show "Adding milestone: X" etc. */
onProgress?: (event: PlannerV2ProgressEvent) => void;
}
export type PlannerV2ProgressEvent =
| { kind: 'project_info'; title: string }
| { kind: 'role'; roleType: PBLRole['type']; name: string }
| { kind: 'milestone'; title: string; index: number }
| { kind: 'microtask'; milestoneTitle: string; title: string; index: number }
| { kind: 'complete'; milestoneCount: number; microtaskCount: number };
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
/** Thrown when the Planner finishes but the result is unusable (no
* Instructor, no milestones, etc.). The caller should fall back to v1
* or to a slide so the student is never stranded on an empty PBL. */
export class PlannerV2Error extends Error {
constructor(
message: string,
public readonly partial: PBLProjectV2,
) {
super(message);
this.name = 'PlannerV2Error';
}
}
// ---------------------------------------------------------------------------
// Empty / starter shape
// ---------------------------------------------------------------------------
export function emptyProject(input: PBLPlannerV2Input): PBLProjectV2 {
const now = new Date().toISOString();
// Compute the planner-time initial proficiency assessment from
// static signals (outline keywords + prior-scene difficulty + user
// bio). Quiz accuracy is not yet available — that's folded in at
// Hero entry by the pre-play recalibration path.
//
// See `lib/pbl/v2/operations/kernel/proficiency.ts` for the full algorithm
// and the calibration table. The Planner LLM does NOT decide this
// value: it consumes `assessment.tier` as a directive when
// dimensioning microtasks.
const assessment = computeInitialAssessment({
outline: input.outline,
priorScenes: input.courseContext.allOutlines,
userBio: input.user?.bio,
userRequirement: input.user?.requirement,
priorQuizResults: input.priorQuizResults,
source: 'planner',
});
const proficiency: PBLProficiency = assessment.tier;
// `languageDirective` is the SINGLE source of truth for content language —
// a free natural-language directive from the outline stage (e.g. "Reply in
// Simplified Chinese" / "中文为主,英文技术术语保留原文"). The Planner feeds it
// straight to the system prompt; there is no content-based locale guessing.
//
// `language` is only the BCP-47 locale the RUNTIME uses for deterministic
// platform strings (synthetic openers, divider labels). It is seeded from
// the authoritative UI locale (`targetLanguage`) when known and otherwise
// left blank for the Hero locale-sync (hero.tsx) to fill on entry — it is
// NEVER inferred from content here.
const languageDirective = input.courseContext.languageDirective?.trim();
const language = input.targetLanguage?.trim() ?? '';
log.info(
`Planner v2 initial assessment: tier=${assessment.tier} score=${assessment.score.toFixed(
2,
)} confidence=${assessment.confidence.toFixed(2)} signals=${assessment.signals.length} language=${language}`,
);
return {
uiPhase: 'hero',
title: '',
description: '',
learningObjective: '',
gains: [],
proficiency,
proficiencyAssessment: assessment,
language,
languageDirective: languageDirective || undefined,
tags: [],
status: 'designing',
roles: [],
milestones: [],
submissions: [],
evaluations: [],
threads: [],
engagementEvents: [],
createdAt: now,
updatedAt: now,
};
}
// ---------------------------------------------------------------------------
// Prompt assembly
// ---------------------------------------------------------------------------
function formatCourseContext(input: PBLPlannerV2Input): string {
const lines: string[] = [];
for (const o of input.courseContext.allOutlines) {
const marker = o.id === input.outline.id ? ' ← this PBL scene' : '';
lines.push(`- [${o.order}] ${o.type.toUpperCase()}: ${o.title}${marker}`);
if (o.description) {
lines.push(` ${o.description}`);
}
}
return lines.join('\n');
}
export async function buildPlannerSystemPrompt(
input: PBLPlannerV2Input,
proficiency: PBLProficiency,
contentLanguage: string,
scenarioRoleplay: boolean,
promptName: string = 'planner-system',
): Promise<string> {
const pblConfig = input.outline.pblConfig!;
// The adaptive engine decided the tier in `emptyProject`; pass it
// through as a directive so the LLM dimensions microtasks
// accordingly. The Planner is expected to mirror this value when it
// calls `set_project_info`; if it picks a different tier the tool
// accepts the value (it's a hint, not a hard contract) but the
// engine logs the divergence.
//
// `contentLanguage` is resolved by the caller from
// `project.languageDirective || project.language` (single source). It may be
// a BCP-47 locale or a nuanced directive like "中文为主,英文技术术语保留原文".
return loadPBLV2Prompt(promptName, {
projectTopic: pblConfig.projectTopic,
projectDescription: pblConfig.projectDescription,
targetSkills: (pblConfig.targetSkills ?? []).join(', '),
milestoneCount: pblConfig.issueCount ?? 3,
proficiency: proficiency === '' ? 'intermediate' : proficiency,
language: contentLanguage,
courseContext: formatCourseContext(input),
languageDirective: input.courseContext.languageDirective,
// Optional free-form scenario brief from the outline stage. Empty for
// ordinary projects / non-scenario prompts (the slot collapses).
scenarioBrief: input.outline.pblConfig?.scenarioBrief ?? '',
// SCENARIO ONLY. Empty string for ordinary PBL projects → the
// `{{scenarioDesign}}` slot collapses to nothing and the prompt is
// byte-identical to before. The slot must always be provided (the
// interpolator leaves unknown placeholders literal).
scenarioDesign: buildScenarioDesignBlock(pblConfig, scenarioRoleplay),
});
}
/** SCENARIO ONLY. Build the role-play scenario-design instruction block
* injected into the Planner system prompt. Returns '' for ordinary PBL
* projects (so the prompt is byte-identical to before). When the
* outline opted into `scenarioRoleplay`, it instructs the Planner to
* fully author the scenario AND lay it out as the fixed three-stage
* skeleton: prep → roleplay(×1..N) → wrapup. */
export function buildScenarioDesignBlock(
pblConfig: NonNullable<PBLPlannerV2Input['outline']['pblConfig']>,
scenarioRoleplay: boolean,
): string {
if (!scenarioRoleplay) return '';
const brief = pblConfig.scenarioBrief?.trim();
return [
'## SCENARIO MODE — role-play scenario (this project only)',
'',
'This PBL is a **role-play scenario**: the learner will step into a concrete situation and interact in-character with character(s) played by a separate Simulator agent. You author the WHOLE scenario now (it is frozen into the package); the runtime only produces the live dialogue. Two rules above all: (a) the premise is **given and concrete**, introduced to the learner by the Instructor — the learner must NEVER be asked to guess it; (b) every task must serve the real learning goal (how to do the thing well), not meta-guessing.',
'',
brief ? `Scenario brief from the platform: ${brief}\n` : '',
'### Step A — fully author the scenario with `set_scenario(...)`',
'Call **exactly once, right after `set_project_info` and before any `add_milestone`**:',
'- `setting`: the concrete overall premise / what is going on (in the project language).',
'- `goal` (optional): what the learner is practising.',
"- `rules` (optional but REQUIRED whenever the scenario has any defined rule-set — games / interviews / debates / structured negotiations / etc.): write the CONCRETE rules a newcomer needs to actually take part, specific enough that the Instructor can teach them verbatim in prep. Not a vague label — include the real mechanics (e.g. a card game: hand ranking, betting rounds, blinds, what terms like Pot Odds / Fold / Call / Raise / Check mean; a debate: the motion, each side's stance, the speaking format; an interview: the rounds and what each assesses). Omit ONLY for free scenarios with no special rules (e.g. comforting a friend).",
'- `learnerRole` (optional): the learner\'s OWN role/position (e.g. "you are their close friend" / "you are the 5th player, on the button").',
'- `characters`: **EXACTLY ONE character** — this version plays a single counterpart throughout (the runtime only ever voices one). It needs `name`, `persona` (stable identity / relationship / personality / speaking style), **`situation`** (their CONCRETE current circumstance the learner faces — e.g. "just broke up last week, low mood, says they\'re fine but aren\'t"). `situation` is shown to the learner up front (prep intro + the always-visible scenario briefing), so it must hold ONLY what the learner can see/know at the start — keep any fact a later beat is meant to make them uncover OUT of it (see the No-spoilers rule below). Plus strongly-recommended `boundaries` (hard safety rails), and optional `openingLine`.',
'',
'### Step B — lay out the FIXED three-stage skeleton (milestones in this exact order)',
'1. **Prep stage** — `add_milestone({ ..., scenarioStage: "prep" })` as the FIRST milestone. Its `briefing` is the Instructor intro that **introduces the concrete premise to the learner**: the situation, each character\'s `situation`, what the learner is there to do, plus `rules` / `learnerRole` when present. The intro MUST match the roleplay stages you design next. Give prep **exactly ONE light microtask** (e.g. "了解背景,准备开始" / "Understand the setup, ready to begin") — NO assessment; the learner just confirms and advances. **Do NOT set `coreConcept`.**',
'2. **Roleplay stage(s)** — one or MORE `add_milestone({ ..., scenarioStage: "roleplay" })` in the middle (split a long scenario into several roleplay stages by round/phase to avoid one giant stage). Each roleplay milestone\'s `briefing` brings the learner into the scene. **Design the beats as a DRAMATIC ARC, not a flat checklist**: an opening hook → rising stakes/complication → a turning point or decision → a resolution. Each beat should be a MEANINGFUL decision/action unit (something the learner can actually DO), never empty filler. For **each microtask (beat)** under a roleplay milestone, provide:',
' - `description`: the CONCRETE situation of this beat as the SYSTEM narrator states it to the learner — positions / cards / what just happened / whose turn (e.g. "你在 Button 位拿到 A♠ J♦;前面都 Fold,老周在 Cutoff 加注到 6 个筹码;轮到你决定 preflop"). The character NEVER states these facts — the system does; the character only reacts. Keep it factual scene-setting, not coaching.',
' - `successWhen` (REQUIRED for every roleplay beat): the CONCRETE, OBSERVABLE in-scene action the learner must SAY or DO for this beat to count as done — the scenario\'s "deliverable" (e.g. "做出 preflop 决定:跟注、加注或弃牌" / "对对方说出的感受做出共情回应,并问一个跟进问题"). State it in plain SCENE terms (what they do in the fiction), NOT as a teaching goal. This is exactly what the advance detector watches, so a crisp `successWhen` is what stops off-topic / small-talk turns from advancing the scene. Make it a real decision/action, not "they chatted a bit".',
' - `completionCriteria` (optional, legacy): a teaching-side note on what this beat is about; `successWhen` is preferred and takes precedence for advancing.',
' - `characterObjective` (recommended): what the character PRIVATELY wants — and privately KNOWS — this beat: their in-scene drive (e.g. "试探你是否在虚张声势" / "想确认你是否真的在乎"), plus any fact the learner is meant to UNCOVER this beat (the hidden cause / secret / backstory the character only reveals when probed — e.g. "你昨天在空调房待了很久才着凉,但只有被仔细询问才说出来"). It makes the character pursue a goal and hold its secrets in character; it is private to the character — NEVER narrated, shown in the briefing, evaluated, or coached.',
' - `skillFocus` (recommended): the single skill this beat practises (e.g. "底池赔率判断" / "积极倾听"). Surfaced to the learner (current-task panel + end-of-project per-act review); never spoken by the character.',
' - The scene is FREE-FIRST: the learner always speaks/types their OWN response to the character, which is how a real interaction is practised. (Some beats may instead ask the learner to hand in a real artefact, e.g. "write them a letter".)',
' - `narration` (optional): a short neutral scene-setting line the SYSTEM reads when this beat opens (e.g. "你们走进了一家安静的咖啡厅"). NEVER spoken by a character or the Instructor. All scene/state facts come from the system (narration + description), never from the character\'s mouth.',
' - `hints` (recommended for roleplay beats): 1–2 SHORT, learner-facing coaching tips for THIS beat — what skill to focus on or how to handle it well (e.g. "先共情、再问问题,别急着给建议" / "注意你的位置和底池赔率,再决定下注"). They appear in the "hints" card of the learner\'s current-task side panel, are NEVER spoken by the character, and are the learner\'s in-the-moment guidance. Keep them concrete to this beat, not generic.',
' - **Do NOT set `coreConcept`** on roleplay milestones.',
'3. **Wrapup stage** — `add_milestone({ ..., scenarioStage: "wrapup" })` as the LAST milestone. Its `debrief` holds the Instructor\'s light, encouraging feedback points (highlights / one thing to improve); the detailed report lives on the completion page. Give wrapup **exactly ONE light microtask** (e.g. "听取反馈,收尾" / "Hear the feedback, wrap up"). **Do NOT set `coreConcept`.**',
'',
'### Rules for scenario design',
'- The premise (situation / rules / positions) is GIVEN and introduced in prep — **never make a task that asks the learner to guess/invent it**.',
"- **No spoilers — never give away in learner-VISIBLE text what a beat is designed to make the learner discover.** The premise the learner can see up front — `setting`, each character's `situation` / `persona`, the prep `briefing`, and each beat's `description` / `narration` (and the always-visible scenario briefing built from these) — must contain ONLY what the learner already knows or can plainly observe at the outset. If any roleplay beat's `successWhen` requires the learner to UNCOVER something through the interaction (a hidden cause, a motive, a secret, the diagnosis, a backstory fact), that information MUST NOT appear in any learner-visible field. Put it ONLY in that beat's private `characterObjective`, where the character holds it and reveals it solely when the learner actually probes for it — never up front. E.g. a \"find out why\" beat: the real cause lives in `characterObjective`; `situation` states only the visible symptoms / where the character is right now.",
'- All scenario text (`setting`/`persona`/`situation`/`briefing`/narration/options…) follows the same content-language policy as Hard rule 1.',
'- Scene beats should feel like a real interaction unfolding, not a checklist; 2-4 beats per roleplay stage is plenty.',
'- **The roleplay character is a pure in-world participant, NEVER a coach.** When you write `persona` / `situation` / `openingLine` (and any character-facing text), the character must have its OWN motives and react like a real person in the scene. It must NEVER: ask the learner to explain/justify their reasoning ("说说你为什么这么选" / "一句话给我理由"), evaluate or grade the learner\'s moves ("这步打得对"), give strategy/meta hints ("想想我的范围里哪些牌会付钱"), or tell the learner it\'s their turn / what to decide. That is all out-of-scene/teaching content and it does NOT belong in the character\'s mouth.',
'- **Out-of-scene content has its own channels — never the character:** (a) the "this is a training table / I\'ll test you" framing and any rule teaching belong to the **prep Instructor** (`briefing`); (b) "it\'s your turn to act / a decision point has arrived" belongs to the **system `narration`** of that beat, stated neutrally; (c) strategy / what-to-watch-for hints belong to the microtask **`hints`** (side panel). Route each of these to its channel; the character only ever lives the scene.',
'',
'',
'### Step C — author ONE project-wide scene visual with `set_scene_visual(...)`',
'After ALL roleplay milestones/beats exist, call `set_scene_visual` exactly once. Read back over EVERY roleplay stage/task you just wrote and distil the ONE shared place/atmosphere they all happen in, then describe it: a `caption` (a short phrase in the project language fitting all stages — derived from the real tasks, e.g. "深夜,各自房间隔着手机聊到天亮" / "决赛辩论赛场" / "牌桌现金局"), a 3-colour `palette` (`bg1`/`bg2`/`accent` hex matching the mood), and 2–4 `motifs` (emoji that evoke this exact scene). Make it specific to THIS project — never a generic placeholder.',
'',
'### Scenario tool workflow (supersedes the order above for this project)',
'1. `set_project_info(...)`',
'2. `set_scenario({ setting, goal?, rules?, learnerRole?, characters })`',
'3. `add_role({ type: "instructor", ... })`',
'4. `add_milestone({ scenarioStage: "prep" })` + its one light microtask',
'5. one or more `add_milestone({ scenarioStage: "roleplay" })` + their beats as a dramatic arc (successWhen [required] / characterObjective / skillFocus / narration?)',
'6. `add_milestone({ scenarioStage: "wrapup" })` + its one light microtask',
'7. `set_scene_visual({ caption, bg1, bg2, accent, motifs })` — based on all the roleplay stages above',
'8. `mark_design_complete()`',
].join('\n');
}
function ordinaryPBLTextOnlyGaps(project: PBLProjectV2): string[] {
const gaps: string[] = [];
for (const milestone of project.milestones) {
if ((milestone.documents ?? []).length > 0) {
gaps.push(
`ordinary PBL milestone "${milestone.title}" has hidden documents; inline any required primer, sample data, or starter content in visible milestone/microtask text instead`,
);
}
}
return gaps;
}
// ---------------------------------------------------------------------------
// Tools (Zod-validated, share the same mutable `project`)
// ---------------------------------------------------------------------------
export function newId(prefix: string): string {
// Short, collision-resistant (12 hex chars). Avoids pulling in
// `nanoid` here so the planner stays dependency-free.
return (
prefix + '_' + Math.random().toString(16).slice(2, 8) + Math.random().toString(16).slice(2, 8)
);
}
export function instructorProjectAnchor(project: PBLProjectV2): string {
// Internal meta-instruction appended to the Instructor's system prompt. It is
// written in English (the model follows it regardless of content language);
// the embedded title / description are already in the project's content
// language, and the Instructor answers the learner in that language per its
// own language rule. No locale branching here.
return [
`You are the Instructor for THIS PBL project.`,
`Project title: ${project.title}`,
`Project description: ${project.description}`,
project.learningObjective ? `Learning objective: ${project.learningObjective}` : '',
'If the learner asks what project they are doing, answer directly from this information, in the project content language. Never say you do not know the project, and never ask them what project they want to do unless the project title and description are empty.',
]
.filter(Boolean)
.join('\n');
}
/**
* Apply the Planner's chosen proficiency tier onto the project, honoring
* the explicit-self-report lock and re-seating the adaptive assessment so
* score/counters stay consistent. Mirrors the decision logic inside the
* loop's `set_project_info` tool, factored out for the single-call planner.
*
* When the learner explicitly stated their level, that lock wins: the
* project is coerced to the locked tier regardless of the LLM's pick.
*/
export function applyPlannerProficiency(
project: PBLProjectV2,
proficiency: 'beginner' | 'intermediate' | 'advanced',
): void {
const assessment = project.proficiencyAssessment;
const explicitTierLocked = assessment?.signals[0]?.kind === 'user_level_explicit';
const effectiveProficiency: PBLProficiency =
explicitTierLocked && assessment ? assessment.tier : proficiency;
if (assessment && assessment.tier !== effectiveProficiency) {
log.info(
`Planner LLM overrode initial proficiency: engine=${assessment.tier} → llm=${effectiveProficiency}`,
);
project.proficiencyAssessment = reseatAssessmentTier(
assessment,
effectiveProficiency,
'planner',
);
}
project.proficiency = effectiveProficiency;
}
// ---------------------------------------------------------------------------
// Completion validation
// ---------------------------------------------------------------------------
export function plannerCompletionGaps(
project: PBLProjectV2,
opts?: { scenarioRoleplay?: boolean },
): string[] {
const errors: string[] = [];
if (!project.title) errors.push('title is empty');
if (!project.description) errors.push('description is empty');
if (!project.roles.some((r) => r.type === 'instructor')) {
errors.push('no Instructor role');
}
if (project.milestones.length === 0) {
errors.push('no milestones');
}
for (const m of project.milestones) {
if (m.microtasks.length === 0) {
errors.push(`milestone "${m.title}" has no microtasks`);
}
}
if (!opts?.scenarioRoleplay) {
errors.push(...ordinaryPBLTextOnlyGaps(project));
}
// SCENARIO ONLY. When scenario mode was requested, the design must be
// a coherent role-play scenario: a full cast + the fixed three-stage
// skeleton (prep → roleplay(s) → wrapup). These checks never fire for
// ordinary projects (opts.scenarioRoleplay falsy).
if (opts?.scenarioRoleplay) {
if (!project.scenario) {
errors.push('scenario project but set_scenario was never called');
} else {
const characters = project.scenario.characters ?? [];
if (characters.length === 0) {
errors.push('scenario has no characters (set_scenario needs at least one character)');
} else {
characters.forEach((c, i) => {
if (
!trimmedPBLText(c?.name) ||
!trimmedPBLText(c?.persona) ||
!trimmedPBLText(c?.situation)
) {
errors.push(`scenario character #${i + 1} is missing name, persona, or situation`);
}
});
}
}
// Fixed three-stage skeleton: first 'prep', last 'wrapup', ≥1 'roleplay'.
const stages = project.milestones.map((m) => m.scenarioStage);
const roleplayCount = stages.filter((s) => s === 'roleplay').length;
if (project.milestones.length < 3) {
errors.push(
'scenario project needs the three-stage skeleton: a prep stage, at least one roleplay stage, and a wrapup stage',
);
}
if (stages[0] !== 'prep') {
errors.push('scenario project: the FIRST milestone must be scenarioStage:"prep"');
}
if (stages[stages.length - 1] !== 'wrapup') {
errors.push('scenario project: the LAST milestone must be scenarioStage:"wrapup"');
}
if (roleplayCount === 0) {
errors.push('scenario project: needs at least one scenarioStage:"roleplay" milestone');
}
// The project-wide scene visual must be authored (caption + ≥1 emoji
// motif) so the entrance animation / banner fits this exact project.
const sv = project.scenario?.sceneVisual;
if (!trimmedPBLText(sv?.caption) || (sv?.motifs?.length ?? 0) === 0) {
errors.push(
'scenario project: call set_scene_visual once (a project-wide caption + 2–4 fitting emoji motifs + colours) AFTER authoring the roleplay stages',
);
}
}
return errors;
}
// ---------------------------------------------------------------------------
// Stage-synthesis normalization (deterministic "not too many / not too few")
// ---------------------------------------------------------------------------
/** Hard cap on how many stages may carry a `synthesisCheck`. The
* integrative stage-end reverse-question is meant for the 1-2 stages
* that hold the project's core knowledge; more than that re-introduces
* the over-questioning failure mode. */
export const MAX_SYNTHESIS_STAGES = 2;
/** Tokenize text into latin words (len ≥ 2) + CJK bigrams for a cheap,
* language-agnostic relevance overlap. Deterministic. */
function conceptTokens(text: string): Set<string> {
const out = new Set<string>();
const lower = (text ?? '').toLowerCase();
for (const w of lower.match(/[a-z0-9]{2,}/g) ?? []) out.add(w);
const cjk = lower.match(/[\u4e00-\u9fff]/g) ?? [];
for (let i = 0; i + 1 < cjk.length; i++) out.add(cjk[i] + cjk[i + 1]);
return out;
}
/** Count how many of `refTokens` appear in `text`. */
function overlapScore(text: string, refTokens: Set<string>): number {
if (refTokens.size === 0) return 0;
const t = conceptTokens(text);
let score = 0;
for (const tok of refTokens) if (t.has(tok)) score++;
return score;
}
/**
* Deterministically enforce "1-2 core stages get a synthesisCheck":
* - If the Planner over-flagged (> MAX), keep the MAX most relevant to
* the learning objective / project and drop `synthesisCheck` from
* the rest.
* - If the Planner flagged none, pick the single stage most aligned
* with the learning objective (avoiding the very first setup stage
* when there are ≥ 3 stages) and synthesise a `coreConcept` from the
* learning objective / that stage. This turns the "not too many /
* not too few" guarantee from a prompt hope into code.
*
* Exported for unit tests.
*/
export function normalizeSynthesisChecks(project: PBLProjectV2): void {
// SCENARIO ONLY exemption. Role-play scenario projects never carry a
// synthesisCheck on any stage (the integrative reflection is the light
// wrapup stage, not a mid-scenario reverse-question). Skip entirely so
// we never auto-attach one to a prep/roleplay/wrapup milestone.
if (project.scenario) return;
if (project.milestones.length === 0) return;
const refTokens = conceptTokens(
`${project.learningObjective ?? ''} ${project.title} ${project.description}`,
);
const flagged = project.milestones.filter((m) => m.synthesisCheck);
if (flagged.length > MAX_SYNTHESIS_STAGES) {
const ranked = flagged
.map((m) => ({
m,
score: overlapScore(
`${m.title} ${m.description ?? ''} ${m.synthesisCheck?.coreConcept ?? ''}`,
refTokens,
),
}))
.sort((a, b) => b.score - a.score || a.m.order - b.m.order);
for (const { m } of ranked.slice(MAX_SYNTHESIS_STAGES)) {
delete m.synthesisCheck;
}
return;
}
if (flagged.length === 0) {
const ordered = project.milestones.slice().sort((a, b) => a.order - b.order);
const ranked = ordered
.map((m) => ({ m, score: overlapScore(`${m.title} ${m.description ?? ''}`, refTokens) }))
.sort((a, b) => b.score - a.score || a.m.order - b.m.order);
let pick = ranked[0]?.m;
// When nothing aligns (all-zero overlap), avoid the first stage
// (usually setup) and the last (usually polish): take the median.
if ((!pick || ranked[0].score === 0) && ordered.length >= 3) {
pick = ordered[Math.floor(ordered.length / 2)];
}
if (pick) {
const coreConcept = (
trimmedPBLText(project.learningObjective) ||
trimmedPBLText(pick.description) ||
trimmedPBLText(pick.title)
).slice(0, 120);
pick.synthesisCheck = { coreConcept };
}
}
}
/** Compatibility re-exports for the package-owned PBL planning core. */
export {
MAX_SYNTHESIS_STAGES,
PlannerV2Error,
SCENARIO_SCHEMA_VERSION,
applyPlannerProficiency,
buildPlannerSystemPrompt,
buildScenarioDesignBlock,
emptyProject,
instructorProjectAnchor,
newId,
normalizeSynthesisChecks,
plannerCompletionGaps,
} from '@openmaic/generation';
export type { PlannerV2Callbacks, PlannerV2ProgressEvent } from '@openmaic/generation';

View File

@ -1,591 +1,3 @@
/**
* PBL v2 — Single-call Planner
*
* A single-shot alternative to the agentic tool-calling loop in
* `./planner.ts`. The LLM is asked to emit ONE JSON object describing the
* whole project (mirroring the slide-content generation pattern:
* `callLLM` with no tools → `parseJsonResponse` → deterministic
* post-processing). The same `PBLProjectV2` is produced, so this is a
* drop-in replacement for `generatePBLV2Project`.
*
* Why: the loop needs ~20-40 ordered, mutually-gated tool calls to
* succeed; any stall, stray narrative turn, or skipped
* `mark_design_complete` aborts the whole run. A single structured
* output collapses that failure surface to one call + one JSON parse.
*
* All the deterministic hydration (ids / status / order / assignee /
* thread bootstrap / proficiency re-seat) and post-processing
* (`normalizeProjectRuntime`, `normalizeSynthesisChecks`, completion
* gate) is shared with the loop via exported helpers in `./planner-core.ts`.
*/
import type { LanguageModel } from 'ai';
import { createLogger } from '@/lib/logger';
import { parseJsonResponse } from '@/lib/generation/json-repair';
import { normalizeProjectRuntime, normalizeScenario } from '../operations/kernel/progress';
import type { ThinkingConfig } from '@/lib/types/provider';
import {
PlannerV2Error,
SCENARIO_SCHEMA_VERSION,
emptyProject,
buildPlannerSystemPrompt,
newId,
instructorProjectAnchor,
applyPlannerProficiency,
normalizeSynthesisChecks,
plannerCompletionGaps,
type PlannerV2Callbacks,
} from './planner-core';
import type {
PBLProjectV2,
PBLPlannerV2Input,
PBLMilestone,
PBLMicrotask,
PBLRole,
PBLScenarioConfig,
PBLScenarioCharacter,
PBLSceneVisual,
} from '../types';
const log = createLogger('PBL v2 Planner (single-call)');
const SINGLE_CALL_PROMPT = 'planner-single-call-system';
const SCENARIO_PROMPT = 'planner-scenario-single-call-system';
/** Narrow call seam used by the untooled single-call planner. */
export type PlannerSingleCallFn = (
params: { model: LanguageModel; system: string; prompt: string },
source: 'pbl-v2-planner-single',
retryOptions: undefined,
thinkingConfig?: ThinkingConfig,
) => Promise<{ text: string }>;
function buildSingleCallUserPrompt(scenarioRoleplay: boolean): string {
const sharedChecklist = [
'projectInfo has non-empty title, description, learningObjective, 3-5 gains, and the exact requested proficiency',
'instructorRole.name is non-empty',
'milestones is a non-empty array',
'every milestone has title, briefing, completionCriteria, debrief, and at least one microtask',
'every microtask has a non-empty title',
];
const scenarioChecklist = scenarioRoleplay
? [
'scenario exists with setting, at least one character (name/persona/situation), and sceneVisual.caption plus emoji motifs',
'milestones follow the exact skeleton: first scenarioStage "prep", last "wrapup", and at least one middle "roleplay"',
'every roleplay microtask has non-empty successWhen',
]
: [];
const checklist = [...sharedChecklist, ...scenarioChecklist]
.map((item) => `- ${item}`)
.join('\n');
return [
'Design the PBL project now. Output the single JSON object described in the system prompt — no prose, no code fences.',
'',
'Before output, verify it passes this exact structural validator:',
checklist,
].join('\n');
}
// ---------------------------------------------------------------------------
// LLM output shape
// ---------------------------------------------------------------------------
/** The JSON object the single LLM call must produce. Only the fields the
* model actually decides — ids / status / order / assignee / timestamps /
* threads are all assigned by code during hydration. Milestones nest
* their microtasks (no milestoneId references needed). */
interface PlannerLLMOutput {
projectInfo?: {
title?: string;
description?: string;
learningObjective?: string;
gains?: string[];
proficiency?: 'beginner' | 'intermediate' | 'advanced';
};
instructorRole?: {
name?: string;
description?: string;
systemPrompt?: string;
};
/** SCENARIO ONLY. Present when the outline opted into role-play; hydrated
* onto `project.scenario`. Ordinary projects omit it. */
scenario?: {
setting?: string;
goal?: string;
rules?: string;
learnerRole?: string;
characters?: Array<{
name?: string;
persona?: string;
situation?: string;
boundaries?: string;
openingLine?: string;
}>;
sceneVisual?: {
caption?: string;
bg1?: string;
bg2?: string;
accent?: string;
motifs?: string[];
};
};
milestones?: Array<{
title?: string;
description?: string;
briefing?: string;
completionCriteria?: string;
debrief?: string;
coreConcept?: string;
/** SCENARIO ONLY. Stage role in the prep → roleplay → wrapup skeleton. */
scenarioStage?: 'prep' | 'roleplay' | 'wrapup';
microtasks?: Array<{
title?: string;
description?: string;
hints?: string[];
// SCENARIO ONLY beat fields (roleplay milestones).
successWhen?: string;
characterObjective?: string;
skillFocus?: string;
learnerBrief?: string;
narration?: string;
completionCriteria?: string;
}>;
}>;
}
/** LLM JSON has no runtime type guarantees (`parseJsonResponse` only
* confirms it parsed). Trim a parsed value ONLY if it is actually a string;
* a non-string scalar (e.g. `title: 123`) becomes '' instead of throwing a
* raw `TypeError` from `.trim()` — which would escape the PlannerV2Error /
* retry contract. */
function toText(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
/** Coerce an unknown value to a clean `string[]`: non-array → `[]`,
* non-string entries dropped, trimmed, empties removed. */
function toStringList(value: unknown): string[] {
if (!Array.isArray(value)) return [];
return value.map(toText).filter(Boolean);
}
// ---------------------------------------------------------------------------
// Validation (post-parse, pre-hydrate)
// ---------------------------------------------------------------------------
/** Structural + topic + language checks on the parsed LLM output. Returns
* a list of human-readable gaps (empty == valid). Mirrors the per-tool
* guards the loop applied inline. */
function validateLLMOutput(
parsed: PlannerLLMOutput | null,
project: PBLProjectV2,
scenarioRoleplay: boolean,
): string[] {
const gaps: string[] = [];
if (!parsed || typeof parsed !== 'object') {
return ['response was not a JSON object'];
}
const info = parsed.projectInfo;
const title = toText(info?.title);
const description = toText(info?.description);
const learningObjective = toText(info?.learningObjective);
if (!title) gaps.push('projectInfo.title is empty');
if (!description) gaps.push('projectInfo.description is empty');
if (!learningObjective) gaps.push('projectInfo.learningObjective is empty');
// Parity with the loop's set_project_info schema (`gains` is `.min(3).max(5)`):
// gains render on the Hero and feed the topic/language guards below, so a
// missing/short list is a real regression, not a cosmetic gap.
const gains = toStringList(info?.gains);
if (gains.length < 3 || gains.length > 5) {
gaps.push('projectInfo.gains must be a list of 3-5 non-empty learner-facing statements');
}
if (
info?.proficiency != null &&
!['beginner', 'intermediate', 'advanced'].includes(info.proficiency as string)
) {
gaps.push('projectInfo.proficiency must be beginner | intermediate | advanced');
}
// Parity with the loop's set_project_info: when the learner explicitly
// self-reported their level, that tier is authoritative. A different
// `proficiency` means the milestones were authored for the wrong
// difficulty — `applyPlannerProficiency` would only relabel the tier, not
// regenerate the tasks — so reject and let the retry rebuild at the locked
// tier (the loop returns ok:false here for the same reason).
const assessment = project.proficiencyAssessment;
const explicitTierLocked = assessment?.signals[0]?.kind === 'user_level_explicit';
if (explicitTierLocked && info?.proficiency && info.proficiency !== assessment!.tier) {
gaps.push(
`The learner explicitly stated their level as ${assessment!.tier}; set projectInfo.proficiency="${assessment!.tier}" and design the milestones for that tier.`,
);
}
if (!toText(parsed.instructorRole?.name)) {
gaps.push('instructorRole.name is empty');
}
// `parseJsonResponse` does not type-check: a non-array `milestones`
// (object / string from schema drift) would make `.forEach` throw a raw
// TypeError, escaping the PlannerV2Error contract and skipping the retry.
const milestones = Array.isArray(parsed.milestones) ? parsed.milestones : [];
if (milestones.length === 0) {
gaps.push('milestones must be a non-empty array');
}
milestones.forEach((m, i) => {
const label = toText(m?.title) || `#${i + 1}`;
if (!toText(m?.title)) gaps.push(`milestone ${label}: title is empty`);
if (!toText(m?.briefing)) gaps.push(`milestone ${label}: briefing is empty`);
if (!toText(m?.completionCriteria))
gaps.push(`milestone ${label}: completionCriteria is empty`);
if (!toText(m?.debrief)) gaps.push(`milestone ${label}: debrief is empty`);
const tasks = Array.isArray(m?.microtasks) ? m.microtasks : [];
if (tasks.length === 0) {
gaps.push(`milestone ${label}: has no microtasks`);
}
tasks.forEach((t, j) => {
if (!toText(t?.title)) gaps.push(`milestone ${label}: microtask #${j + 1} title is empty`);
});
});
// NOTE: topic-alignment and content-language are NOT policed here. Those
// are semantic "does the content match the outline" checks, and a lexical /
// character-scan heuristic is an unreliable proxy for them (faithful
// rephrases of sentence-like Chinese topics false-positive). Forcing a
// retry on a brittle heuristic does more harm than good — topic fidelity and
// content language are carried by the system prompt's hard rules instead.
// Only structural contracts the renderer needs are gated below.
// SCENARIO ONLY. Structural completeness checks that mirror the loop's
// scenario completion gate (cast + sceneVisual + prep→roleplay→wrapup
// skeleton + a successWhen on every roleplay beat) so the renderer always
// gets a coherent scenario.
if (scenarioRoleplay) {
const sc = parsed.scenario;
if (!sc || typeof sc !== 'object') {
gaps.push('scenario block is missing (a role-play project must include a `scenario`)');
} else {
if (!toText(sc.setting)) gaps.push('scenario.setting is empty');
const chars = Array.isArray(sc.characters) ? sc.characters : [];
if (chars.length === 0) gaps.push('scenario.characters must have at least one character');
chars.forEach((c, i) => {
if (!toText(c?.name) || !toText(c?.persona) || !toText(c?.situation)) {
gaps.push(`scenario character #${i + 1} needs name, persona, and situation`);
}
});
const sv = sc.sceneVisual;
if (!toText(sv?.caption) || toStringList(sv?.motifs).length === 0) {
gaps.push('scenario.sceneVisual needs a caption and at least one emoji motif');
}
}
const stages = milestones.map((m) => m?.scenarioStage);
if (milestones.length < 3) {
gaps.push(
'scenario needs the three-stage skeleton: prep + ≥1 roleplay + wrapup (≥3 milestones)',
);
}
if (stages[0] !== 'prep') {
gaps.push('scenario: the FIRST milestone must have scenarioStage:"prep"');
}
if (stages[stages.length - 1] !== 'wrapup') {
gaps.push('scenario: the LAST milestone must have scenarioStage:"wrapup"');
}
if (!stages.some((s) => s === 'roleplay')) {
gaps.push('scenario: needs at least one scenarioStage:"roleplay" milestone');
}
milestones.forEach((m, i) => {
if (m?.scenarioStage !== 'roleplay') return;
const tasks = Array.isArray(m?.microtasks) ? m.microtasks : [];
tasks.forEach((t, j) => {
if (!toText(t?.successWhen)) {
gaps.push(`roleplay milestone #${i + 1} beat #${j + 1}: successWhen is required`);
}
});
});
}
return gaps;
}
// ---------------------------------------------------------------------------
// Hydration (parity with the loop's six tools + mark_design_complete)
// ---------------------------------------------------------------------------
const HEX_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
type LLMScenario = NonNullable<PlannerLLMOutput['scenario']>;
/** Build the frozen `scenario` block from the LLM output: assign character
* ids, keep only valid hex colours, clamp motifs to 4. `normalizeScenario`
* later drops invalid characters / degrades to a plain project if needed. */
function hydrateScenario(raw: LLMScenario): PBLScenarioConfig {
const characters: PBLScenarioCharacter[] = (Array.isArray(raw.characters) ? raw.characters : [])
.filter((c) => toText(c?.name) && toText(c?.persona))
.map((c) => ({
id: newId('char'),
name: toText(c.name),
persona: toText(c.persona),
...(toText(c.situation) ? { situation: toText(c.situation) } : {}),
...(toText(c.boundaries) ? { boundaries: toText(c.boundaries) } : {}),
...(toText(c.openingLine) ? { openingLine: toText(c.openingLine) } : {}),
}))
// HARD CONSTRAINT: this version voices a SINGLE character (runtime
// `speakingCharacter` only ever uses characters[0]). Deterministically keep
// just the first, so a model that over-produces a cast can never leak extra
// characters into the package (dead data / wrong-name bubbles). The prompt
// also asks for exactly one; this guarantees it regardless.
.slice(0, 1);
const scenario: PBLScenarioConfig = { setting: toText(raw.setting), characters };
if (toText(raw.goal)) scenario.goal = toText(raw.goal);
if (toText(raw.rules)) scenario.rules = toText(raw.rules);
if (toText(raw.learnerRole)) scenario.learnerRole = toText(raw.learnerRole);
const sv = raw.sceneVisual;
if (sv && (toText(sv.caption) || toStringList(sv.motifs).length > 0)) {
const visual: PBLSceneVisual = {
caption: toText(sv.caption),
motifs: toStringList(sv.motifs).slice(0, 4),
};
if (typeof sv.bg1 === 'string' && HEX_RE.test(sv.bg1.trim())) visual.bg1 = sv.bg1.trim();
if (typeof sv.bg2 === 'string' && HEX_RE.test(sv.bg2.trim())) visual.bg2 = sv.bg2.trim();
if (typeof sv.accent === 'string' && HEX_RE.test(sv.accent.trim()))
visual.accent = sv.accent.trim();
scenario.sceneVisual = visual;
}
return scenario;
}
function hydrateProject(project: PBLProjectV2, parsed: PlannerLLMOutput): void {
const info = parsed.projectInfo!;
const isScenario = !!parsed.scenario;
// Project info — set title/description/objective BEFORE building the
// instructor anchor (which reads them) and before proficiency re-seat.
// All text reads go through `toText` (validation guarantees the required
// ones are non-empty strings; the coercion keeps optional / unvalidated
// fields type-safe too).
project.title = toText(info.title);
project.description = toText(info.description);
project.learningObjective = toText(info.learningObjective) || undefined;
project.gains = toStringList(info.gains);
const fallbackTier = project.proficiency === '' ? 'intermediate' : project.proficiency;
applyPlannerProficiency(project, info.proficiency ?? fallbackTier);
// Instructor role.
const llmRole = parsed.instructorRole!;
const anchoredSystemPrompt = [toText(llmRole.systemPrompt), instructorProjectAnchor(project)]
.filter(Boolean)
.join('\n\n');
const role: PBLRole = {
id: newId('role'),
type: 'instructor',
name: toText(llmRole.name),
description: toText(llmRole.description) || undefined,
systemPrompt: anchoredSystemPrompt,
};
project.roles.push(role);
// Milestones (+ nested microtasks). Array shapes are coerced defensively
// (hints are not pre-validated, and the LLM JSON carries no runtime type
// guarantees).
project.milestones = (Array.isArray(parsed.milestones) ? parsed.milestones : []).map(
(m, i): PBLMilestone => {
const microtasks: PBLMicrotask[] = (Array.isArray(m.microtasks) ? m.microtasks : []).map(
(t, j): PBLMicrotask => {
const mt: PBLMicrotask = {
id: newId('mt'),
title: toText(t.title),
description: toText(t.description) || undefined,
status: 'todo',
assignee: 'user',
hints: toStringList(t.hints),
order: j,
};
// SCENARIO ONLY beat fields — attached only when present (ordinary
// microtasks carry none). normalizeScenario degrades the project if
// the scenario turns out invalid, dropping these along with it.
const successWhen = toText(t.successWhen);
if (successWhen) mt.successWhen = successWhen;
const characterObjective = toText(t.characterObjective);
if (characterObjective) mt.characterObjective = characterObjective;
const skillFocus = toText(t.skillFocus);
if (skillFocus) mt.skillFocus = skillFocus;
const learnerBrief = toText(t.learnerBrief);
if (learnerBrief) mt.learnerBrief = learnerBrief;
const narration = toText(t.narration);
if (narration) mt.narration = narration;
const beatCriteria = toText(t.completionCriteria);
if (beatCriteria) mt.completionCriteria = beatCriteria;
return mt;
},
);
const coreConcept = toText(m.coreConcept);
const scenarioStage = (['prep', 'roleplay', 'wrapup'] as const).includes(
m.scenarioStage as never,
)
? m.scenarioStage
: undefined;
return {
id: newId('ms'),
title: toText(m.title),
description: toText(m.description) || undefined,
status: i === 0 ? 'active' : 'locked',
order: i,
microtasks,
briefing: toText(m.briefing),
completionCriteria: toText(m.completionCriteria),
debrief: toText(m.debrief),
// Scenario stages never carry a synthesisCheck (the wrapup stage is
// the integrative reflection) — guard even if the LLM leaks a
// coreConcept onto a scenario milestone.
...(coreConcept && !isScenario ? { synthesisCheck: { coreConcept } } : {}),
...(scenarioStage ? { scenarioStage } : {}),
};
},
);
// SCENARIO ONLY. Freeze the cast/premise/visual onto the project and stamp
// the scenario schema version (parity with the loop's set_scenario).
// normalizeScenario (run by the caller) assigns any gaps + degrades to a
// plain project if the cast/roleplay turn out invalid.
if (parsed.scenario) {
project.scenario = hydrateScenario(parsed.scenario);
project.schemaVersion = SCENARIO_SCHEMA_VERSION;
}
// Bootstrap the Instructor thread + flip lifecycle (= mark_design_complete).
const instructor = project.roles.find((r) => r.type === 'instructor');
if (instructor && !project.threads.some((t) => t.agentId === instructor.id)) {
project.threads.push({ agentId: instructor.id, messages: [] });
}
project.status = 'active';
project.uiPhase = 'hero';
project.updatedAt = new Date().toISOString();
}
// ---------------------------------------------------------------------------
// Public entrypoint
// ---------------------------------------------------------------------------
/**
* Single-call variant of `generatePBLV2Project`. Same signature and same
* `PBLProjectV2` output / `PlannerV2Error` failure contract.
*
* Strategy: one `callLLM` (no tools) → `parseJsonResponse` → validate
* (structure + topic + language) with at most one targeted retry → hydrate
* → deterministic post-processing → completion-gate. Throws
* `PlannerV2Error` if the model never produces a usable project; the
* caller falls back (to the loop, then v1).
*/
export async function generatePBLV2ProjectSingleCall(
input: PBLPlannerV2Input,
model: LanguageModel,
callLLM: PlannerSingleCallFn,
callbacks?: PlannerV2Callbacks,
thinkingConfig?: ThinkingConfig,
): Promise<PBLProjectV2> {
const pblConfig = input.outline.pblConfig;
if (!pblConfig) {
throw new PlannerV2Error(
'Planner v2 (single-call) invoked on an outline without pblConfig — this is a generation pipeline bug.',
emptyProject(input),
);
}
const scenarioRoleplay = pblConfig.scenarioRoleplay === true;
const project = emptyProject(input);
const contentLanguage =
project.languageDirective || 'Match the language of the outline content above.';
const systemPrompt = await buildPlannerSystemPrompt(
input,
project.proficiency,
contentLanguage,
scenarioRoleplay,
// Two prompts, one single-call path: scenario-roleplay outlines get the
// scenario authoring spec + scenario-augmented schema; everything else
// gets the ordinary project prompt.
scenarioRoleplay ? SCENARIO_PROMPT : SINGLE_CALL_PROMPT,
);
const basePrompt = buildSingleCallUserPrompt(scenarioRoleplay);
const callModel = async (prompt: string): Promise<PlannerLLMOutput | null> => {
const result = await callLLM(
{ model, system: systemPrompt, prompt },
'pbl-v2-planner-single',
undefined,
thinkingConfig,
);
return parseJsonResponse<PlannerLLMOutput>(result.text);
};
// First attempt.
let parsed = await callModel(basePrompt);
let gaps = validateLLMOutput(parsed, project, scenarioRoleplay);
// One targeted retry: hand the model its concrete problems back.
if (gaps.length > 0) {
log.warn(
`Single-call planner first attempt had ${gaps.length} gap(s); retrying once: ${gaps.join('; ')}`,
);
const retryPrompt = `${basePrompt}\n\nYour previous output had these problems:\n${gaps
.map((g) => `- ${g}`)
.join('\n')}\n\nFix every one of them and output the corrected single JSON object.`;
parsed = await callModel(retryPrompt);
gaps = validateLLMOutput(parsed, project, scenarioRoleplay);
}
if (!parsed || gaps.length > 0) {
throw new PlannerV2Error(
`Planner v2 (single-call) failed to produce a valid project: ${gaps.join('; ')}`,
project,
);
}
hydrateProject(project, parsed);
callbacks?.onProgress?.({ kind: 'project_info', title: project.title });
for (const milestone of project.milestones) {
callbacks?.onProgress?.({ kind: 'milestone', title: milestone.title, index: milestone.order });
for (const task of milestone.microtasks) {
callbacks?.onProgress?.({
kind: 'microtask',
milestoneTitle: milestone.title,
title: task.title,
index: task.order,
});
}
}
// Shared deterministic post-processing (identical order to the loop path).
normalizeProjectRuntime(project);
normalizeSynthesisChecks(project);
// SCENARIO ONLY safety net: assign any missing character ids, or degrade to
// a plain project if the cast / roleplay stage turned out invalid. No-op for
// ordinary projects.
normalizeScenario(project);
const finalGaps = plannerCompletionGaps(project, { scenarioRoleplay });
if (finalGaps.length > 0) {
throw new PlannerV2Error(
`Planner v2 (single-call) output failed validation: ${finalGaps.join('; ')}`,
project,
);
}
const microtaskCount = project.milestones.reduce((acc, m) => acc + m.microtasks.length, 0);
callbacks?.onProgress?.({
kind: 'complete',
milestoneCount: project.milestones.length,
microtaskCount,
});
log.info(
`Planner v2 (single-call) done: ${project.milestones.length} milestones, ${microtaskCount} microtasks, ${project.roles.length} roles.`,
);
return project;
}
/** Compatibility re-exports for the package-owned single-call PBL planner. */
export { generatePBLV2ProjectSingleCall } from '@openmaic/generation';
export type { PlannerSingleCallFn } from '@openmaic/generation';

View File

@ -23,7 +23,7 @@ import { tool, stepCountIs } from 'ai';
import { z } from 'zod';
import { createLogger } from '@/lib/logger';
import { normalizeProjectRuntime, normalizeScenario } from '../operations/kernel/progress';
import { normalizeProjectRuntime, normalizeScenario } from '@openmaic/generation';
import type { ThinkingConfig } from '@/lib/types/provider';
import {
@ -37,7 +37,7 @@ import {
normalizeSynthesisChecks,
plannerCompletionGaps,
type PlannerV2Callbacks,
} from './planner-core';
} from '@openmaic/generation';
import type {
PBLProjectV2,

View File

@ -1,185 +1,2 @@
/**
* PBL v2 — Engagement event ledger helpers.
*
* The Instructor records small "signals" during a microtask
* (learner_turn, observation_*, closing_check, microtask_opened,
* microtask_completed, microtask_skipped). Each signal is appended
* as a `PBLEngagementEvent` to `PBLProjectV2.engagementEvents`. The
* full ledger is the source of truth for the per-microtask summary
* cached on `PBLMicrotask.engagement` and for the evaluator prompt.
*
* To prevent `scene.content` from growing unbounded over a long
* session, the array is kept under a soft cap (`MAX_EVENTS`) by
* dropping the oldest events first. Cached per-microtask summaries
* preserve information that would otherwise be lost when older
* events fall off.
*/
import type {
PBLEngagementEvent,
PBLEngagementEventKind,
PBLEngagementSummary,
PBLProjectV2,
} from '../../types';
/** Soft cap on the engagement ledger size. Older events are dropped
* first; per-microtask summaries cache what's lost. Conservatively
* sized for IndexedDB / PG JSONB friendliness. */
export const MAX_ENGAGEMENT_EVENTS = 500;
function newId(prefix: string): string {
return (
prefix + '_' + Math.random().toString(16).slice(2, 8) + Math.random().toString(16).slice(2, 8)
);
}
/** Append a single engagement event, capping array size. */
export function recordEvent(
project: PBLProjectV2,
kind: PBLEngagementEventKind,
options: {
microtaskId?: string;
milestoneId?: string;
payload?: Record<string, unknown>;
} = {},
): PBLEngagementEvent {
const event: PBLEngagementEvent = {
id: newId('evt'),
kind,
microtaskId: options.microtaskId,
milestoneId: options.milestoneId,
ts: new Date().toISOString(),
payload: options.payload,
};
project.engagementEvents.push(event);
capEngagementEvents(project);
project.updatedAt = event.ts;
return event;
}
export function capEngagementEvents(project: PBLProjectV2): void {
if (project.engagementEvents.length > MAX_ENGAGEMENT_EVENTS) {
project.engagementEvents.splice(0, project.engagementEvents.length - MAX_ENGAGEMENT_EVENTS);
}
}
/** Read engagement signals for one microtask out of the ledger. */
export function microtaskEngagement(
project: PBLProjectV2,
microtaskId: string,
): PBLEngagementSummary {
const events = project.engagementEvents.filter((e) => e.microtaskId === microtaskId);
const summary: PBLEngagementSummary = {};
let learnerTurnCount = 0;
let errorCount = 0;
let questionsRaised = 0;
const errorSignatures: string[] = [];
const conceptsUnlocked: string[] = [];
const conceptUnlockLabels: Record<string, string> = {};
const struggles: string[] = [];
for (const e of events) {
switch (e.kind) {
case 'microtask_opened':
summary.startedAt = e.ts;
break;
case 'microtask_completed':
case 'microtask_skipped':
summary.completedAt = e.ts;
break;
case 'learner_turn': {
learnerTurnCount++;
break;
}
case 'observation_error': {
errorCount++;
const sig = String(e.payload?.signature ?? '');
if (sig) errorSignatures.push(sig);
break;
}
case 'observation_concept_unlocked': {
const sig = String(e.payload?.signature ?? '');
if (sig) {
conceptsUnlocked.push(sig);
const label = String(e.payload?.label ?? '').trim();
if (label && !(sig in conceptUnlockLabels)) conceptUnlockLabels[sig] = label;
}
break;
}
case 'observation_struggle': {
const sig = String(e.payload?.signature ?? '');
if (sig) struggles.push(sig);
break;
}
case 'observation_question':
questionsRaised++;
break;
case 'closing_check':
// A stage-synthesis check is recorded against the last microtask
// of a `synthesisCheck` stage as well as the milestone. Treating
// it like a closing check here means it clears this microtask's
// evidence gate (absorption — no separate microtask reverse-Q is
// needed) and reaches the evaluator the same way.
case 'stage_synthesis_check':
summary.closingQuestion = String(e.payload?.question ?? '');
summary.closingAnswer = String(e.payload?.learner_answer ?? '');
summary.closingQuality = e.payload?.quality as PBLEngagementSummary['closingQuality'];
break;
}
}
if (summary.startedAt && summary.completedAt) {
summary.durationSeconds = Math.max(
0,
Math.round(
(new Date(summary.completedAt).getTime() - new Date(summary.startedAt).getTime()) / 1000,
),
);
}
summary.learnerTurnCount = learnerTurnCount;
summary.errorCount = errorCount;
summary.repeatErrorCount = errorSignatures.length - new Set(errorSignatures).size;
summary.errorSignatures = Array.from(new Set(errorSignatures));
summary.conceptsUnlocked = Array.from(new Set(conceptsUnlocked));
if (Object.keys(conceptUnlockLabels).length > 0) {
summary.conceptUnlockLabels = conceptUnlockLabels;
}
summary.struggles = Array.from(new Set(struggles));
summary.questionsRaised = questionsRaised;
return summary;
}
/** True once the stage-level integrative checkpoint is on record for
* this milestone. The milestone seal gate uses this to refuse
* completing a `synthesisCheck` stage until the integrative
* reverse-question (or the escape-hatch capture of a spontaneous
* articulation) has landed. Deterministic — not a prompt hope.
*
* Satisfied by EITHER:
* - a dedicated `stage_synthesis_check` anywhere in the milestone
* (the intended path), OR
* - a plain `closing_check` on the milestone's last microtask
* (robustness: a model that asked an integrative question but
* logged it via `record_closing_check` instead of the dedicated
* tool must not get stuck looping on `stage_synthesis_required`).
* Note `concept_unlocked` does NOT satisfy this — the stage checkpoint
* requires an actual reverse-question, not a silent advance. */
export function milestoneSynthesisSatisfied(project: PBLProjectV2, milestoneId: string): boolean {
if (
project.engagementEvents.some(
(e) => e.kind === 'stage_synthesis_check' && e.milestoneId === milestoneId,
)
) {
return true;
}
const ms = project.milestones.find((m) => m.id === milestoneId);
if (!ms || ms.microtasks.length === 0) return false;
const lastMt = ms.microtasks.slice().sort((a, b) => b.order - a.order)[0];
if (!lastMt) return false;
return project.engagementEvents.some(
(e) => e.kind === 'closing_check' && e.microtaskId === lastMt.id,
);
}
/** Compatibility barrel for package-owned PBL engagement primitives. */
export * from '@openmaic/generation';

View File

@ -1,893 +1,2 @@
/**
* PBL v2 — Adaptive Proficiency Engine.
*
* Replaces "Planner LLM guesses a tier once" with a three-stage,
* evidence-driven assessment:
*
* Stage 1 (Planner-time, `source: 'planner'`)
* Static signals only: outline keywords + prior-scene difficulty
* gradient + user.bio. Used to seed `PBLProjectV2.proficiency`
* so the Planner can dimension microtasks appropriately.
*
* Stage 2 (Hero-time, `source: 'pre-play'`)
* Folds in quiz-accuracy snapshots from the learner's localStorage
* once they enter the PBL scene. Strongest pre-PBL signal.
*
* Stage 3 (Workspace runtime, `source: 'dynamic'`)
* Each Instructor turn translates `record_observation` /
* `record_closing_check` / force-advance / microtask completion
* speed into a `ProficiencySignal` and folds it into the score
* via EWMA. Hysteresis + cooldown + min-signal gating prevent
* tier oscillation.
*
* **All proficiency arithmetic is pure code, not LLM prompts.** The
* LLM only classifies observations (the existing `record_observation`
* tool); converting an observation to a signal is deterministic. This
* is the explicit fix for the previous "guess via heuristic" approach
* (see commit history for `lib/pbl/v2/agents/planner.ts`).
*
* The default with no evidence is intermediate: a learner who reaches a
* PBL scene has usually just been taught the material, so seeding beginner
* over-scaffolds them. The dynamic engine still drops to beginner quickly on
* the first signs of struggle, and an explicit learner self-report (in the
* requirement / bio) always overrides this default.
*
* The frontend never displays tier or score to the learner — by
* product decision, proficiency is an internal-only concept. Dev mode
* (`PBL_V2_DEV_PROFICIENCY_BADGE=true`) surfaces a debug badge.
*/
import type {
PBLProficiency,
PBLProficiencyAssessment,
PBLProjectV2,
PriorQuizResult,
ProficiencyAssessmentSource,
ProficiencySignal,
ProficiencySignalKind,
ProficiencyTransition,
} from '../../types';
import type { SceneOutline } from '@/lib/types/generation';
import { appendProficiencyUpdatedRuntimeEvent } from './runtime-events';
// ---------------------------------------------------------------------------
// Tunable constants — keep these grouped so the algorithm's behaviour
// is auditable from one place.
// ---------------------------------------------------------------------------
/** Exponential decay for the EWMA update. Each signal moves the
* score by at most `EWMA_ALPHA * direction * weight`. */
const EWMA_ALPHA = 0.2;
/** Per-signal confidence accrual factor. Each signal adds at most
* `weight * CONFIDENCE_GAIN` to confidence, capped at 1. */
const CONFIDENCE_GAIN = 0.5;
/** Hard ceiling on `assessment.signals` length to keep
* `scene.content` bounded. */
const MAX_SIGNAL_HISTORY = 50;
/** Tier bucket boundaries. A learner must cross the *outer*
* boundary to ENTER a tier, but only the *inner* boundary to
* LEAVE it — that's the hysteresis. */
const TIER_BOUNDS = {
/** Conservative enter-advanced threshold. The original hysteresis
* design called for 0.33, but early testing showed that a single
* strong quiz signal (~0.42) was too easily crossing into advanced,
* causing premature tier switches. Raised to 0.50 to require
* corroborating evidence before tier-up. */
enterAdvanced: 0.5,
leaveAdvanced: 0.2,
enterBeginner: -0.33,
leaveBeginner: -0.2,
} as const;
/** Confidence floor below which `shouldRetier` refuses to switch
* tier, regardless of where the score is. */
const MIN_CONFIDENCE_FOR_RETIER = 0.4;
/** Minimum number of dynamic signals (not counting pre-play ones)
* before the engine is allowed to switch tier dynamically. */
const MIN_DYNAMIC_SIGNALS = 3;
/** Minimum learner-turn count between tier switches. Prevents
* oscillation across the boundary on consecutive messages. */
const RETIER_COOLDOWN_TURNS = 5;
/** The teaching tier used when there is NO evidence at all — no explicit
* self-report, no static signals (outline / bio / quiz / prior scenes), or an
* old project read back without an assessment. A learner reaching a PBL scene
* has usually just been taught the material, so starting at beginner
* over-scaffolds them; the dynamic engine still drops to beginner quickly on
* the first real signs of struggle. Single source of truth — EVERY "no
* evidence" fallback (scoreToTier anchor, emptyAssessment, aggregateSignals,
* ensureAssessment, tierGuidanceBlock) must resolve through this. */
export const DEFAULT_TIER: PBLProficiency = 'intermediate';
/** Per-signal weight caps.
*
* Rough tiers (kept in lockstep with the shrinkage calibration
* table further down):
*
* 0.45 – 0.50 strong direct signals: outline keywords, user
* bio, quiz accuracy, submission score,
* concept_confusion (error / struggle — the
* learner is visibly stuck right now)
* 0.40 medium signals: prior-scene difficulty,
* self_correction (concept_unlocked),
* closing_check_quality
* 0.30 – 0.35 light signals: help_request, task_speed,
* force_advance
*
* Quiz accuracy was originally the singular strong signal (cap
* 0.6) but two corroborating cues now matter more — in-PBL
* observation signals are direct evidence the engine should weigh
* almost as heavily, so quiz drops to 0.5 and concept_confusion
* bumps to 0.45. */
const WEIGHT_CAPS: Record<ProficiencySignalKind, number> = {
outline_keyword: 0.5,
prior_scene_difficulty: 0.4,
user_bio: 0.5,
user_level_explicit: 1,
quiz_accuracy: 0.5,
submission_score: 0.5,
task_speed: 0.3,
help_request: 0.35,
concept_confusion: 0.45,
self_correction: 0.4,
force_advance: 0.3,
closing_check_quality: 0.4,
};
// ---------------------------------------------------------------------------
// Small helpers
// ---------------------------------------------------------------------------
function clamp(x: number, lo: number, hi: number): number {
return Math.max(lo, Math.min(hi, x));
}
function nowIso(): string {
return new Date().toISOString();
}
/** Map a continuous score to a tier bucket, respecting hysteresis.
* Advanced is intentionally harder to enter than beginner /
* intermediate. One good moment should improve support, not promote
* the learner to advanced by itself. When `currentTier` is unset we
* anchor on the no-evidence default (`DEFAULT_TIER`) — this path is
* defensive only; callers normally pass a concrete tier. */
export function scoreToTier(score: number, currentTier?: PBLProficiency): PBLProficiency {
const cur = currentTier === '' || !currentTier ? DEFAULT_TIER : currentTier;
if (cur === 'beginner') {
if (score > TIER_BOUNDS.leaveBeginner) return 'intermediate';
return 'beginner';
}
if (cur === 'advanced') {
if (score < TIER_BOUNDS.leaveAdvanced) return 'intermediate';
return 'advanced';
}
// intermediate (current) — needs to cross the outer bound to move
if (score > TIER_BOUNDS.enterAdvanced) return 'advanced';
if (score < TIER_BOUNDS.enterBeginner) return 'beginner';
return 'intermediate';
}
// ---------------------------------------------------------------------------
// Detectors — turn raw inputs into `ProficiencySignal`s.
// All detectors are pure and return `null` when they have no signal
// (rather than a zero-weight signal) so the caller can tell "absent"
// from "neutral".
// ---------------------------------------------------------------------------
const KEYWORDS_ADVANCED: ReadonlyArray<string> = [
'进阶',
'深入',
'高级',
'实战',
'精通',
'advanced',
'deep dive',
'production-grade',
'in-depth',
'expert',
];
const KEYWORDS_BEGINNER: ReadonlyArray<string> = [
'入门',
'基础',
'初学',
'小白',
'零基础',
'新手',
'beginner',
'from scratch',
'intro',
'introduction',
'getting started',
];
function scanKeywords(text: string): { direction: number; weight: number; hits: string[] } {
const lower = text.toLowerCase();
let direction = 0;
let weight = 0;
const hits: string[] = [];
for (const kw of KEYWORDS_ADVANCED) {
if (lower.includes(kw.toLowerCase())) {
direction += 1;
weight += 0.1;
hits.push(kw);
}
}
for (const kw of KEYWORDS_BEGINNER) {
if (lower.includes(kw.toLowerCase())) {
direction -= 1;
weight += 0.1;
hits.push(kw);
}
}
return { direction, weight, hits };
}
/** Scan the PBL outline's own difficulty cues. */
export function detectOutlineKeywords(outline: SceneOutline): ProficiencySignal | null {
const parts = [
outline.description,
outline.teachingObjective ?? '',
(outline.keyPoints ?? []).join(' '),
outline.pblConfig?.projectTopic ?? '',
outline.pblConfig?.projectDescription ?? '',
(outline.pblConfig?.targetSkills ?? []).join(' '),
];
const text = parts.filter(Boolean).join(' ').trim();
if (!text) return null;
const { direction, weight, hits } = scanKeywords(text);
if (weight === 0) return null;
return {
kind: 'outline_keyword',
direction: clamp(direction, -1, 1),
weight: Math.min(weight, WEIGHT_CAPS.outline_keyword),
note: `Outline keywords: ${hits.join(', ')}`,
ts: nowIso(),
};
}
/** Aggregate difficulty cues across the *prior* scenes (i.e. the
* PPT/quiz/interactive scenes that come before this PBL in the
* course outline). Argues "the course has been pitched at level X". */
export function analyzePriorScenes(
allOutlines: SceneOutline[],
currentOutlineId: string,
): ProficiencySignal | null {
const priorScenes = allOutlines.filter((o) => o.id !== currentOutlineId && o.type !== 'pbl');
// Only the scenes that come BEFORE this PBL — use `order` if set,
// else fall back to array index order which is already authored
// in playback order.
const me = allOutlines.find((o) => o.id === currentOutlineId);
const before =
me && typeof me.order === 'number'
? priorScenes.filter((o) => typeof o.order === 'number' && o.order < me.order)
: priorScenes;
if (before.length === 0) return null;
let direction = 0;
let weight = 0;
const hits: string[] = [];
for (const o of before) {
const text = [o.description, (o.keyPoints ?? []).join(' '), o.teachingObjective ?? '']
.filter(Boolean)
.join(' ');
const r = scanKeywords(text);
direction += r.direction;
weight += r.weight * 0.5; // each prior scene contributes half
hits.push(...r.hits);
}
if (weight === 0) return null;
return {
kind: 'prior_scene_difficulty',
direction: clamp(direction / Math.max(before.length, 1), -1, 1),
weight: Math.min(weight, WEIGHT_CAPS.prior_scene_difficulty),
note: `Prior ${before.length} scene(s) cues: ${hits.slice(0, 6).join(', ')}`,
ts: nowIso(),
};
}
/** Parse the learner's bio for specific experience markers.
* Returns null for empty or signal-less bios. */
export function analyzeBio(bio: string | undefined | null): ProficiencySignal | null {
if (!bio || !bio.trim()) return null;
const text = bio.trim();
let direction = 0;
let weight = 0;
const hits: string[] = [];
const yearMatch = text.match(/(\d+)\s*(?:年|years?)/i);
if (yearMatch) {
const years = parseInt(yearMatch[1], 10);
if (Number.isFinite(years)) {
if (years >= 5) {
direction += 0.8;
weight += 0.3;
hits.push(`${years}年经验`);
} else if (years >= 2) {
direction += 0.4;
weight += 0.2;
hits.push(`${years}年经验`);
}
}
}
if (/(博士|phd|高级工程师|架构师|principal|staff engineer|expert)/i.test(text)) {
direction += 0.8;
weight += 0.3;
hits.push('senior role');
}
if (/(初学|刚开始|零基础|just started|no background|新手)/i.test(text)) {
direction -= 0.8;
weight += 0.3;
hits.push('beginner cue');
}
if (weight === 0) return null;
return {
kind: 'user_bio',
direction: clamp(direction, -1, 1),
weight: Math.min(weight, WEIGHT_CAPS.user_bio),
note: `Bio cues: ${hits.join(', ')}`,
ts: nowIso(),
};
}
export function detectExplicitProficiency(text: string | undefined | null): PBLProficiency | null {
if (!text || !text.trim()) return null;
const s = text.toLowerCase();
if (
/(零基础|0基础|小白|新手|初学|刚开始|完全不会|没有基础|没基础|最简单|从零开始|beginner|novice|newbie|from scratch|no background|just started)/i.test(
s,
)
) {
return 'beginner';
}
if (
/(中级|有基础|有一点基础|学过一点|会一点|了解基础|intermediate|some experience|basic familiarity)/i.test(
s,
)
) {
return 'intermediate';
}
if (
/(高级|进阶学习者|资深|专家|熟练掌握|很熟|advanced learner|expert|senior|experienced|proficient)/i.test(
s,
)
) {
return 'advanced';
}
return null;
}
/** A learner-issued instruction about the teaching difficulty. Either an
* absolute target tier, or a one-step relative nudge. Produced by the
* `adjust_difficulty` tool's arg mapping (the LLM decides the intent — there
* is no longer any per-message regex detection). */
export type ProficiencyDirective =
| { kind: 'absolute'; tier: PBLProficiency }
| { kind: 'relative'; direction: 'up' | 'down' };
/** Shift a tier one step toward harder (`up`) / easier (`down`), clamped at the
* ends. Unset tier is treated as intermediate. Pure, for unit testing. */
export function stepProficiency(tier: PBLProficiency, direction: 'up' | 'down'): PBLProficiency {
const order: PBLProficiency[] = ['beginner', 'intermediate', 'advanced'];
const idx = order.indexOf(tier === '' ? 'intermediate' : tier);
const nextIdx = direction === 'up' ? Math.min(2, idx + 1) : Math.max(0, idx - 1);
return order[nextIdx];
}
/** Map the Instructor `adjust_difficulty` tool's `target` argument to a
* directive. The LLM resolves a learner's any-language difficulty request to
* one of these targets; this turns it into the `ProficiencyDirective` shape
* `applyProficiencyDirective` consumes. Pure. */
export function proficiencyDirectiveFromTarget(
target: 'beginner' | 'intermediate' | 'advanced' | 'easier' | 'harder',
): ProficiencyDirective {
if (target === 'easier') return { kind: 'relative', direction: 'down' };
if (target === 'harder') return { kind: 'relative', direction: 'up' };
return { kind: 'absolute', tier: target };
}
export function explicitAssessment(
tier: PBLProficiency,
source: ProficiencyAssessmentSource,
): PBLProficiencyAssessment {
const direction = tier === 'advanced' ? 1 : tier === 'intermediate' ? 0 : -1;
const signal: ProficiencySignal = {
kind: 'user_level_explicit',
direction,
weight: WEIGHT_CAPS.user_level_explicit,
note: `explicit learner level: ${tier}`,
ts: nowIso(),
};
return {
tier,
score: direction,
confidence: 1,
source,
signals: [signal],
lastUpdatedAt: signal.ts,
transitions: [],
dynamicSignalsSinceRetier: 0,
turnsSinceRetier: 0,
};
}
/** Re-seat an assessment onto a deliberately chosen tier — used when a
* decision-maker overrides the static-signal estimate (e.g. the Planner LLM
* picks a tier that differs from the engine's computed one).
*
* Without this, the override would set `tier` but leave the old `score`
* in place, so the assessment becomes internally contradictory (e.g.
* tier=advanced but score=0.1, which maps to intermediate). Once the dynamic
* retier gates later clear, `shouldRetier` reads that stale score and silently
* rebounds the learner back toward the old tier regardless of how they
* actually performed. We re-centre the score into the chosen tier's band
* (using the same direction mapping as an explicit self-report) and reset the
* retier counters, so the chosen tier holds until genuine dynamic evidence
* moves it. Unlike `explicitAssessment`, this does NOT inject a
* `user_level_explicit` signal — it is a heuristic override, not a hard
* learner self-report, so it must not lock out future re-evaluation. Pure. */
export function reseatAssessmentTier(
prev: PBLProficiencyAssessment,
tier: PBLProficiency,
source: ProficiencyAssessmentSource,
): PBLProficiencyAssessment {
const score = tier === 'advanced' ? 1 : tier === 'intermediate' ? 0 : -1;
return {
...prev,
tier,
score,
source,
dynamicSignalsSinceRetier: 0,
turnsSinceRetier: 0,
lastUpdatedAt: nowIso(),
};
}
/** Aggregate quiz-accuracy across all prior quizzes. */
export function analyzeQuizAccuracy(results: PriorQuizResult[]): ProficiencySignal | null {
if (!results || results.length === 0) return null;
let totalScored = 0;
let totalCorrect = 0;
for (const r of results) {
const scored = r.correctCount + r.incorrectCount;
if (scored <= 0) continue;
totalScored += scored;
totalCorrect += r.correctCount;
}
if (totalScored === 0) return null;
const accuracy = totalCorrect / totalScored;
// Map: 0% → -1 (strong beginner), 50% → 0, 100% → +1 (strong advanced).
// Cap at ±1 just in case of rounding artefacts.
const direction = clamp((accuracy - 0.5) * 2, -1, 1);
return {
kind: 'quiz_accuracy',
direction,
weight: WEIGHT_CAPS.quiz_accuracy,
note: `${totalCorrect}/${totalScored} correct across ${results.length} quiz(es), accuracy ${(
accuracy * 100
).toFixed(0)}%`,
ts: nowIso(),
};
}
// ---------------------------------------------------------------------------
// Dynamic signal builders — called from Instructor on each turn.
// Each takes the raw observation and returns a `ProficiencySignal`.
// ---------------------------------------------------------------------------
export function signalFromObservation(
kind: 'error' | 'concept_unlocked' | 'struggle' | 'question',
opts: { repeat?: boolean; note?: string } = {},
): ProficiencySignal {
switch (kind) {
case 'error':
return {
kind: 'concept_confusion',
direction: opts.repeat ? -0.7 : -0.4,
weight: opts.repeat ? WEIGHT_CAPS.concept_confusion : WEIGHT_CAPS.concept_confusion * 0.7,
note: opts.note ?? (opts.repeat ? 'repeat error' : 'first error'),
ts: nowIso(),
};
case 'concept_unlocked':
return {
kind: 'self_correction',
direction: 0.5,
weight: WEIGHT_CAPS.self_correction,
note: opts.note ?? 'concept unlocked',
ts: nowIso(),
};
case 'struggle':
return {
kind: 'concept_confusion',
direction: -0.5,
weight: WEIGHT_CAPS.concept_confusion * 0.8,
note: opts.note ?? 'struggle',
ts: nowIso(),
};
case 'question':
return {
kind: 'help_request',
direction: -0.3,
weight: WEIGHT_CAPS.help_request * 0.7,
note: opts.note ?? 'help question',
ts: nowIso(),
};
}
}
export function signalFromClosingCheck(quality: 'weak' | 'ok' | 'strong'): ProficiencySignal {
const dir = quality === 'weak' ? -0.6 : quality === 'strong' ? 0.6 : 0;
return {
kind: 'closing_check_quality',
direction: dir,
// OK quality is neutral but still consumed (with weight) so it
// contributes to confidence and signal count gating.
weight: WEIGHT_CAPS.closing_check_quality * (quality === 'ok' ? 0.4 : 1),
note: `closing check: ${quality}`,
ts: nowIso(),
};
}
export function signalFromForceAdvance(): ProficiencySignal {
return {
kind: 'force_advance',
direction: -0.4,
weight: WEIGHT_CAPS.force_advance * 0.9,
note: 'force-advance triggered',
ts: nowIso(),
};
}
/** Build a signal based on how many learner turns it took to clear a
* microtask. Fewer is faster (advanced-leaning); many is slow
* (beginner-leaning). The mapping is clamped — extreme outliers
* don't get extra weight. */
export function signalFromTaskSpeed(learnerTurns: number): ProficiencySignal | null {
if (!Number.isFinite(learnerTurns) || learnerTurns < 0) return null;
let direction = 0;
if (learnerTurns <= 2) direction = 0.5;
else if (learnerTurns <= 4) direction = 0.25;
else if (learnerTurns <= 7) direction = 0;
else if (learnerTurns <= 10) direction = -0.25;
else direction = -0.5;
if (direction === 0) return null;
return {
kind: 'task_speed',
direction,
weight: WEIGHT_CAPS.task_speed,
note: `${learnerTurns} learner turn(s) to clear microtask`,
ts: nowIso(),
};
}
/** Submission score (0–100). Higher → advanced-leaning. */
export function signalFromSubmissionScore(score: number): ProficiencySignal | null {
if (!Number.isFinite(score)) return null;
const normalized = clamp(score, 0, 100) / 100;
// 50% maps to 0; ≤30% maps to -1; ≥85% maps to +1
const direction = clamp((normalized - 0.5) * 2, -1, 1);
return {
kind: 'submission_score',
direction,
weight: WEIGHT_CAPS.submission_score,
note: `submission score ${score}/100`,
ts: nowIso(),
};
}
// ---------------------------------------------------------------------------
// Aggregation — combine signals into an assessment.
// ---------------------------------------------------------------------------
/** Bootstrap assessment for a project with no evidence yet: a neutral score
* at the no-evidence DEFAULT_TIER, with low confidence. Callers with real
* signals (aggregateSignals) or a known tier (ensureAssessment) override
* `tier` accordingly. */
export function emptyAssessment(): PBLProficiencyAssessment {
return {
tier: DEFAULT_TIER,
score: 0,
confidence: 0.1,
source: 'planner',
signals: [],
lastUpdatedAt: nowIso(),
transitions: [],
dynamicSignalsSinceRetier: 0,
turnsSinceRetier: 0,
};
}
/** Build an assessment from a fresh batch of signals (used by Stage 1
* and Stage 2). Confidence accrues from the sum of signal weights;
* score is the weighted average of `direction`s. Empty input is
* treated as the bootstrap default (intermediate, low confidence). */
export function aggregateSignals(
signals: ProficiencySignal[],
source: ProficiencyAssessmentSource,
): PBLProficiencyAssessment {
if (!signals || signals.length === 0) {
// No evidence at all — no explicit self-report (handled earlier in
// computeInitialAssessment) and no outline / prior-scene / bio / quiz
// cues. Fall back to the no-evidence default (DEFAULT_TIER, via
// emptyAssessment): see DEFAULT_TIER for the rationale.
return { ...emptyAssessment(), source };
}
// Static batch aggregation is NOT the same maths as the dynamic
// EWMA. EWMA is designed to resist single-observation flips over
// time; a static batch of "facts that all hold right now" should
// settle on a fixed point in one shot.
//
// We use weighted-mean direction × shrinkage(weightTotal). The
// shrinkage factor weightTotal/(weightTotal + SHRINK_K) pulls the
// score toward 0 when total evidence is thin: one lone bio signal
// of direction 0.4 / weight 0.2 yields score ≈ 0.07 (well inside
// intermediate); crossing the +0.50 enter-advanced threshold
// requires two near-maximal corroborating signals (e.g. quiz 100%
// + strong outline keywords: dir≈1, weight≈0.5 each → ≈0.59).
// K=0.7 calibration table (manually verified against the test
// cases — keep this in sync if K changes or WEIGHT_CAPS shift):
// - bio "5 yrs" → 0.4 × (0.2/0.9) ≈ 0.09 → intermediate
// - bio "10 yrs" → 0.8 × (0.3/1.0) = 0.24 → intermediate
// - quiz 100% → 1.0 × (0.5/1.2) ≈ 0.42 → intermediate
// - bio 10y + outline 进阶 → 0.88 × (0.5/1.2) ≈ 0.37 → intermediate
// The intent: a single strong measurement (e.g. quiz accuracy) is not
// enough alone to cross the 0.50 enter-advanced threshold; a single self-reported heuristic is
// not.
const SHRINK_K = 0.7;
let weightedSum = 0;
let weightTotal = 0;
for (const s of signals) {
weightedSum += s.direction * s.weight;
weightTotal += s.weight;
}
const rawDirection = weightTotal === 0 ? 0 : weightedSum / weightTotal;
const shrink = weightTotal / (weightTotal + SHRINK_K);
const score = clamp(rawDirection * shrink, -1, 1);
// Confidence also derives from weightTotal so callers can tell
// "low evidence intermediate" apart from "strong evidence
// intermediate". Same K → confidence ≈ shrink, capped at 1.
const confidence = clamp(shrink, 0, 1);
const tier = scoreToTier(score, DEFAULT_TIER);
return {
tier,
score,
confidence,
source,
signals: signals.slice(-MAX_SIGNAL_HISTORY),
lastUpdatedAt: signals[signals.length - 1]?.ts ?? nowIso(),
transitions: [],
dynamicSignalsSinceRetier: 0,
turnsSinceRetier: 0,
};
}
/** Stage 1 (Planner-time) / Stage 2 (Hero-time) initial assessment.
* Static signals only; dynamic ones are folded later via
* `applySignal`. */
export function computeInitialAssessment(input: {
outline: SceneOutline;
priorScenes: SceneOutline[];
userBio?: string;
userRequirement?: string;
priorQuizResults?: PriorQuizResult[];
source?: ProficiencyAssessmentSource;
}): PBLProficiencyAssessment {
const explicit = detectExplicitProficiency(
[input.userRequirement, input.userBio].filter(Boolean).join('\n'),
);
if (explicit) {
return explicitAssessment(explicit, input.source ?? 'planner');
}
const signals: ProficiencySignal[] = [];
const outlineSignal = detectOutlineKeywords(input.outline);
if (outlineSignal) signals.push(outlineSignal);
const priorSceneSignal = analyzePriorScenes(input.priorScenes, input.outline.id);
if (priorSceneSignal) signals.push(priorSceneSignal);
const bioSignal = analyzeBio(input.userBio);
if (bioSignal) signals.push(bioSignal);
const quizSignal = analyzeQuizAccuracy(input.priorQuizResults ?? []);
if (quizSignal) signals.push(quizSignal);
return aggregateSignals(signals, input.source ?? 'planner');
}
// ---------------------------------------------------------------------------
// EWMA update + tier-switch decision (Stage 3).
// ---------------------------------------------------------------------------
/** Fold one new signal into the EWMA score. Pure: returns a new
* assessment, does not mutate. */
export function applySignal(
current: PBLProficiencyAssessment,
signal: ProficiencySignal,
): PBLProficiencyAssessment {
const contribution = signal.direction * signal.weight;
const newScore = clamp(EWMA_ALPHA * contribution + (1 - EWMA_ALPHA) * current.score, -1, 1);
const newConfidence = clamp(current.confidence + signal.weight * CONFIDENCE_GAIN, 0, 1);
return {
...current,
score: newScore,
confidence: newConfidence,
signals: [...current.signals, signal].slice(-MAX_SIGNAL_HISTORY),
lastUpdatedAt: signal.ts,
dynamicSignalsSinceRetier: current.dynamicSignalsSinceRetier + 1,
};
}
/** Increment the learner-turn counter on the assessment. Called on
* every assistant turn so `shouldRetier` can enforce a cooldown. */
export function tickTurn(current: PBLProficiencyAssessment): PBLProficiencyAssessment {
return { ...current, turnsSinceRetier: current.turnsSinceRetier + 1 };
}
export interface RetierDecision {
switch: boolean;
newTier?: PBLProficiency;
reason?: string;
}
/** Decide whether the current score warrants a tier switch right now.
* Cooldown / min-signal gates only apply to `dynamic` sources —
* pre-play / planner refreshes are always allowed to set the tier. */
export function shouldRetier(assessment: PBLProficiencyAssessment): RetierDecision {
const desired = scoreToTier(assessment.score, assessment.tier);
if (desired === assessment.tier) {
return { switch: false, reason: 'same tier' };
}
if (assessment.confidence < MIN_CONFIDENCE_FOR_RETIER) {
return { switch: false, reason: 'low confidence' };
}
if (assessment.source === 'dynamic') {
if (assessment.dynamicSignalsSinceRetier < MIN_DYNAMIC_SIGNALS) {
return { switch: false, reason: 'min-signal gate' };
}
if (assessment.turnsSinceRetier < RETIER_COOLDOWN_TURNS) {
return { switch: false, reason: 'cooldown' };
}
}
return { switch: true, newTier: desired, reason: 'crossed bucket boundary' };
}
/** Commit a tier switch decision: returns a new assessment with the
* new tier, appended transition, and the gating counters reset.
* Caller is responsible for syncing `PBLProjectV2.proficiency` and
* appending a `proficiency_changed` engagement event. */
export function commitTierSwitch(
current: PBLProficiencyAssessment,
newTier: PBLProficiency,
reason: string,
): { next: PBLProficiencyAssessment; transition: ProficiencyTransition } {
const ts = nowIso();
const transition: ProficiencyTransition = {
from: current.tier,
to: newTier,
ts,
reason,
};
return {
next: {
...current,
tier: newTier,
transitions: [...current.transitions, transition],
dynamicSignalsSinceRetier: 0,
turnsSinceRetier: 0,
lastUpdatedAt: ts,
},
transition,
};
}
/** Top-level convenience used by Instructor: fold one signal and
* return the next assessment + optional tier transition. */
export function processDynamicSignal(
current: PBLProficiencyAssessment,
signal: ProficiencySignal,
): { next: PBLProficiencyAssessment; transition?: ProficiencyTransition } {
const dynamicAssessment: PBLProficiencyAssessment = {
...applySignal(current, signal),
source: 'dynamic',
};
const decision = shouldRetier(dynamicAssessment);
if (decision.switch && decision.newTier) {
return commitTierSwitch(dynamicAssessment, decision.newTier, decision.reason ?? 'unknown');
}
return { next: dynamicAssessment };
}
/** Glue used by Stage 2 / pre-play recalibration: applies a fresh
* quiz snapshot to an existing assessment, preserving the planner-time
* history but bumping the source to `'pre-play'`. */
export function applyQuizSnapshot(
current: PBLProficiencyAssessment,
results: PriorQuizResult[],
): PBLProficiencyAssessment {
const quizSignal = analyzeQuizAccuracy(results);
if (!quizSignal) return current;
const next = applySignal(current, quizSignal);
const newTier = scoreToTier(next.score, current.tier);
if (newTier === next.tier) {
return { ...next, source: 'pre-play' };
}
// Pre-play recalibration is allowed to skip the dynamic gates —
// quiz results are a high-quality measured behaviour, not noise.
const ts = nowIso();
return {
...next,
tier: newTier,
source: 'pre-play',
transitions: [
...next.transitions,
{ from: current.tier, to: newTier, ts, reason: 'pre-play quiz recalibration' },
],
dynamicSignalsSinceRetier: 0,
turnsSinceRetier: 0,
lastUpdatedAt: ts,
};
}
// ---------------------------------------------------------------------------
// Project-level helpers — these mutate-in-place to fit the existing
// operations module style (engagement.ts, progress.ts).
// ---------------------------------------------------------------------------
/** Ensure `project.proficiencyAssessment` exists and is in sync with
* `project.proficiency`. Used as a safety net when older v2 projects
* (pre-adaptive-engine) are read back. */
export function ensureAssessment(project: PBLProjectV2): PBLProficiencyAssessment {
if (project.proficiencyAssessment) {
return project.proficiencyAssessment;
}
const seed: PBLProficiencyAssessment = {
...emptyAssessment(),
tier: project.proficiency === '' ? DEFAULT_TIER : project.proficiency,
};
project.proficiencyAssessment = seed;
return seed;
}
/** Single entry point used by Instructor to fold one dynamic signal:
* mutates the project's assessment, syncs `project.proficiency`
* on a tier switch, and returns whether a switch happened (so the
* caller can append a `proficiency_changed` engagement event). */
export function updateProjectAssessment(
project: PBLProjectV2,
signal: ProficiencySignal,
): { transition?: ProficiencyTransition } {
const current = ensureAssessment(project);
const { next, transition } = processDynamicSignal(current, signal);
project.proficiencyAssessment = next;
if (transition) {
project.proficiency = transition.to;
}
appendProficiencyUpdatedRuntimeEvent(project);
project.updatedAt = next.lastUpdatedAt;
return { transition };
}
/** Public read-only view — what the dev badge consumes. */
export function describeAssessment(assessment: PBLProficiencyAssessment): {
tier: PBLProficiency;
score: number;
confidence: number;
source: ProficiencyAssessmentSource;
lastSignalKind?: ProficiencySignalKind;
} {
return {
tier: assessment.tier,
score: assessment.score,
confidence: assessment.confidence,
source: assessment.source,
lastSignalKind: assessment.signals[assessment.signals.length - 1]?.kind,
};
}
/** Compatibility barrel for package-owned PBL proficiency primitives. */
export * from '@openmaic/generation';

View File

@ -1,969 +1,2 @@
/**
* PBL v2 — Microtask / milestone progress operations.
*
* Pure functions that mutate `PBLProjectV2`. Called from:
* - the Instructor agent's `advance_micro_task` tool path
* - the `/api/pbl/v2/task/update` route (when the learner clicks
* Continue on a milestone handover card, or skips a task)
*
* Cross-milestone advance does NOT auto-open the next milestone.
* That gate is intentional: when a microtask is the last of its
* milestone, we mark the milestone completed and stage a
* `pendingHandover` payload that the workspace UI renders as a
* "Continue to Stage N+1" card. The next milestone stays LOCKED
* until the learner clicks Continue, at which point the API call
* sets the next milestone to ACTIVE and its first microtask to
* IN_PROGRESS.
*/
import type {
PBLChatMessage,
PBLProjectV2,
PBLMilestone,
PBLMicrotask,
PBLInternalAssessment,
PBLHandover,
} from '../../types';
import { microtaskEngagement, recordEvent } from './engagement';
import { clearPendingTaskCompletion } from './task-completion';
import {
appendRuntimeEvent,
appendStatusChangedRuntimeEvent,
milestoneIdForMicrotask,
mintRuntimeEventId,
normalizationRepairEventId,
patchStatusChangedRuntimeEventId,
} from './runtime-events';
export const MILESTONE_DIVIDER_PREFIX = '[MILESTONE_DIVIDER]';
export const TASK_DIVIDER_PREFIX = '[TASK_DIVIDER]';
/** SCENARIO ONLY. Synthetic agent id for the Simulator's own chat
* thread. It is NOT a `roles[]` record — the cast lives as data on
* `project.scenario.characters`. A dedicated thread keeps the
* role-play conversation isolated from the Instructor's teaching
* history (so neither prompt pollutes the other). Absent on all
* ordinary projects. */
export const PBL_SIMULATOR_AGENT_ID = 'simulator';
// ---------------------------------------------------------------------------
// Lookup helpers
// ---------------------------------------------------------------------------
export function currentMilestone(project: PBLProjectV2): PBLMilestone | undefined {
return project.milestones.find((m) => m.status === 'active');
}
export function currentMicrotask(
project: PBLProjectV2,
): { milestone: PBLMilestone; microtask: PBLMicrotask } | undefined {
const ms = currentMilestone(project);
if (!ms) return undefined;
const mt = ms.microtasks.find((t) => t.status === 'todo' || t.status === 'in_progress');
if (!mt) return undefined;
return { milestone: ms, microtask: mt };
}
/**
* Normalize runtime-only state that the UI and Instructor API both
* require after a project is generated or reloaded. Planner tools
* build the project structure, but the runtime contract is stricter:
* there must be one Instructor thread, one active milestone, and one
* current microtask. Keep this small and deterministic so normal
* generation and local test generation share the same behavior.
*/
export function normalizeProjectRuntime(project: PBLProjectV2): boolean {
let changed = false;
// Run the scenario skeleton repair on EVERY load (not just at generation):
// it deterministically fixes any milestone whose `scenarioStage` the planner
// left missing/invalid — which otherwise makes a middle act render as the
// Instructor (prep) thread instead of the live scene. Idempotent + a no-op
// for ordinary (non-scenario) projects, so it is safe to call here.
if (normalizeScenario(project)) changed = true;
const instructor = project.roles.find((r) => r.type === 'instructor');
if (instructor && !project.threads.some((t) => t.agentId === instructor.id)) {
project.threads.push({ agentId: instructor.id, messages: [] });
changed = true;
}
// SCENARIO ONLY. Role-play projects get an extra Simulator thread so
// the in-character conversation is stored apart from the Instructor's
// prep/wrapup teaching thread. Gated on `project.scenario`; ordinary
// projects never grow this thread and their runtime is byte-identical.
if (project.scenario && !project.threads.some((t) => t.agentId === PBL_SIMULATOR_AGENT_ID)) {
project.threads.push({ agentId: PBL_SIMULATOR_AGENT_ID, messages: [] });
changed = true;
}
if (project.pendingHandover && !project.pendingHandover.consumed) {
if (changed) {
project.updatedAt = new Date().toISOString();
}
return changed;
}
if (project.status !== 'completed' && project.milestones.length > 0) {
let active = project.milestones.find((m) => m.status === 'active');
if (!active) {
active =
project.milestones.find((m) => m.status !== 'completed') ??
project.milestones[project.milestones.length - 1];
if (active && active.status !== 'active') {
const from = active.status;
active.status = 'active';
appendStatusChangedRuntimeEvent(project, {
id: normalizationRepairEventId(project, 'milestone', active.id, from, active.status),
entityType: 'milestone',
entityId: active.id,
from,
to: active.status,
milestoneId: active.id,
});
changed = true;
}
}
const current = active?.microtasks.find(
(t) => t.status === 'todo' || t.status === 'in_progress',
);
const taskToOpen =
current ?? active?.microtasks.find((t) => t.status !== 'completed' && t.status !== 'skipped');
if (taskToOpen && taskToOpen.status !== 'in_progress') {
const from = taskToOpen.status;
taskToOpen.status = 'in_progress';
appendStatusChangedRuntimeEvent(project, {
id: normalizationRepairEventId(
project,
'microtask',
taskToOpen.id,
from,
taskToOpen.status,
),
entityType: 'microtask',
entityId: taskToOpen.id,
from,
to: taskToOpen.status,
microtaskId: taskToOpen.id,
milestoneId: active?.id,
});
changed = true;
}
}
if (changed) {
project.updatedAt = new Date().toISOString();
}
return changed;
}
/**
* Whether the learner has actually entered the project at least once.
* Drives the Hero's "Start project" vs "Continue project" button.
*
* NOTE: an `in_progress` microtask does NOT count — `normalizeProjectRuntime`
* opens the first task on a brand-new project too. The reliable signals
* are learner-produced or Instructor-delivered: a thread message (the
* GREETING opener), a submission / evaluation / engagement event, a
* terminal microtask, a completed milestone, a pending handover, or a
* finished project.
*/
export function hasStartedProject(project: PBLProjectV2): boolean {
if (project.uiPhase === 'completed' || project.status === 'completed') return true;
if (project.submissions.length > 0) return true;
if (project.evaluations.length > 0) return true;
if (project.engagementEvents.length > 0) return true;
if (project.pendingHandover) return true;
if (project.threads.some((thread) => thread.messages.length > 0)) return true;
return project.milestones.some(
(milestone) =>
milestone.status === 'completed' ||
milestone.microtasks.some(
(microtask) => microtask.status === 'completed' || microtask.status === 'skipped',
),
);
}
/**
* Wipe all learner PBL progress and return a fresh `hero`-phase project,
* equivalent to one that was just generated and never played. The
* project STRUCTURE (roles, milestone / microtask definitions, title,
* language, …) is preserved; only the runtime learning state is reset.
*
* Proficiency state (`proficiency` / `proficiencyAssessment`) is NOT
* touched: it belongs to the learner model, not PBL progress, and is
* owned by a separate runtime layer (PBL content vs learner runtime are
* being decoupled). Clearing it here would couple reset to profile /
* proficiency re-initialization and regress an intermediate/advanced
* learner back to the beginner tier on restart.
*
* Pure: returns a new project, does not mutate the input.
*/
export function resetProjectProgress(project: PBLProjectV2): PBLProjectV2 {
const reset: PBLProjectV2 = {
...project,
runtimeEvents: project.runtimeEvents ? [...project.runtimeEvents] : undefined,
runtimeResetEpoch: (project.runtimeResetEpoch ?? 0) + 1,
uiPhase: 'hero',
status: 'active',
submissions: [],
evaluations: [],
engagementEvents: [],
pendingHandover: undefined,
pendingTaskCompletion: undefined,
threads: project.threads.map((thread) => ({ agentId: thread.agentId, messages: [] })),
milestones: project.milestones.map((milestone, index) => ({
...milestone,
status: index === 0 ? 'active' : 'locked',
internalAssessment: undefined,
microtasks: milestone.microtasks.map((microtask) => ({
...microtask,
status: 'todo',
internalAssessment: undefined,
completionReason: undefined,
engagement: undefined,
})),
})),
updatedAt: new Date().toISOString(),
};
appendRuntimeEvent(reset, {
id: mintRuntimeEventId(),
kind: 'project_reset',
actorType: 'user',
ts: reset.updatedAt,
});
appendStatusChangedRuntimeEvent(reset, {
actorType: 'user',
entityType: 'ui_phase',
entityId: 'project',
from: project.uiPhase,
to: reset.uiPhase,
});
appendStatusChangedRuntimeEvent(reset, {
actorType: 'user',
entityType: 'project',
entityId: 'project',
from: project.status,
to: reset.status,
});
project.milestones.forEach((milestone, milestoneIndex) => {
const resetMilestone = reset.milestones[milestoneIndex];
if (!resetMilestone) return;
appendStatusChangedRuntimeEvent(reset, {
actorType: 'user',
entityType: 'milestone',
entityId: resetMilestone.id,
from: milestone.status,
to: resetMilestone.status,
milestoneId: resetMilestone.id,
});
milestone.microtasks.forEach((microtask, microtaskIndex) => {
const resetMicrotask = resetMilestone.microtasks[microtaskIndex];
if (!resetMicrotask) return;
appendStatusChangedRuntimeEvent(reset, {
actorType: 'user',
entityType: 'microtask',
entityId: resetMicrotask.id,
from: microtask.status,
to: resetMicrotask.status,
microtaskId: resetMicrotask.id,
milestoneId: resetMilestone.id,
});
});
});
return reset;
}
export function findMicrotask(
project: PBLProjectV2,
microtaskId: string,
): { milestone: PBLMilestone; microtask: PBLMicrotask } | undefined {
for (const ms of project.milestones) {
const mt = ms.microtasks.find((t) => t.id === microtaskId);
if (mt) return { milestone: ms, microtask: mt };
}
return undefined;
}
// ---------------------------------------------------------------------------
// Scenario (role-play) normalization — SCENARIO ONLY safety net
// ---------------------------------------------------------------------------
function genScenarioCharId(): string {
return 'char_' + Math.random().toString(16).slice(2, 8) + Math.random().toString(16).slice(2, 8);
}
/**
* SCENARIO ONLY. Idempotent safety net that keeps the role-play
* scenario data structurally coherent, degrading to a plain project
* (never crashing) when persisted / legacy / hand-edited data is
* incoherent. No-op for ordinary projects (no `scenario`, no `scene`).
*
* A scenario is *runnable* only when BOTH a cast (`project.scenario`
* with ≥1 valid character) AND ≥1 roleplay stage (`milestone.scenarioStage === 'roleplay'`)
* are present — the two must come as a pair. When that pairing is
* broken we restore consistency so the single gate
* "`project.scenario` present = scenario project" never lies:
*
* - No cast (`scenario` absent) but `scene` flags exist
* → clear the orphan `scene` flags (a scene with no cast can't
* run); the milestones become ordinary Instructor milestones.
* - `scenario` present but every character is structurally broken
* (missing `name` / `persona`)
* → the cast is unusable → drop `scenario` + `schemaVersion` and
* clear `scene` flags → clean ordinary project.
* - `scenario` + valid cast but NO scene milestone to host it
* → drop `scenario` + `schemaVersion` (cast has nowhere to
* appear) → clean ordinary project.
* - Coherent scenario → assign any missing character ids and keep it.
*
* On the happy path (Planner generated a coherent scenario, enforced by
* the completion gate + validation) this only assigns ids / is a no-op.
* Degradation therefore essentially never fires for freshly generated
* projects — it exists purely to make corrupt / legacy packages safe.
*
* Returns true if it mutated the project.
*/
export function normalizeScenario(project: PBLProjectV2): boolean {
let changed = false;
const stagedMilestones = project.milestones.filter((m) => m.scenarioStage !== undefined);
// No cast → any `scenarioStage` marker is an orphan. Clear it so the
// project is a clean ordinary project. (Also covers ordinary projects
// with no stage markers at all: the loop simply does nothing.)
if (!project.scenario) {
for (const m of stagedMilestones) {
delete m.scenarioStage;
changed = true;
}
if (changed) project.updatedAt = new Date().toISOString();
return changed;
}
const scenario = project.scenario;
// Drop structurally-broken characters (need name + persona); assign
// missing ids to the survivors.
const validChars = (scenario.characters ?? []).filter(
(c) =>
!!c &&
typeof c.name === 'string' &&
c.name.trim().length > 0 &&
typeof c.persona === 'string' &&
c.persona.trim().length > 0,
);
if (validChars.length !== (scenario.characters?.length ?? 0)) {
scenario.characters = validChars;
changed = true;
}
for (const c of scenario.characters) {
if (!c.id) {
c.id = genScenarioCharId();
changed = true;
}
}
const degradeToPlainProject = () => {
delete project.scenario;
delete project.schemaVersion;
for (const m of stagedMilestones) delete m.scenarioStage;
changed = true;
};
// Cast unusable (no valid characters) → degrade.
if (scenario.characters.length === 0) {
degradeToPlainProject();
if (changed) project.updatedAt = new Date().toISOString();
return changed;
}
// SCENARIO SKELETON REPAIR (deterministic; runs on every load → fixes new
// AND already-generated projects). The skeleton is FIXED: prep → roleplay(s)
// → wrapup. The planner occasionally omits or mangles a MIDDLE milestone's
// `scenarioStage`, leaving it undefined. At runtime an undefined-stage
// milestone is treated as non-roleplay (Instructor thread), so entering it
// mid-scene wrongly shows the prep briefing instead of the live scene (the
// act-transition bug). Coerce any milestone with a missing/invalid stage by
// position: first → prep, last → wrapup, everything in between → roleplay.
const allMs = project.milestones;
allMs.forEach((m, i) => {
if (
m.scenarioStage === 'prep' ||
m.scenarioStage === 'roleplay' ||
m.scenarioStage === 'wrapup'
) {
return;
}
m.scenarioStage = i === 0 ? 'prep' : i === allMs.length - 1 ? 'wrapup' : 'roleplay';
changed = true;
});
// Need at least one immersive roleplay stage to host the cast; otherwise
// the cast has nowhere to appear → degrade (keeps the single gate
// "`project.scenario` present = scenario project" honest). Read fresh after
// the skeleton repair above.
const hasRoleplay = allMs.some((m) => m.scenarioStage === 'roleplay');
if (!hasRoleplay) {
degradeToPlainProject();
if (changed) project.updatedAt = new Date().toISOString();
return changed;
}
// Coherent scenario. (Creating the Simulator thread + routing is wired
// in the increment that introduces the Simulator; nothing to do here.)
if (changed) project.updatedAt = new Date().toISOString();
return changed;
}
// ---------------------------------------------------------------------------
// State transitions
// ---------------------------------------------------------------------------
/** Mark a microtask `in_progress` (idempotent). */
export function startMicrotask(project: PBLProjectV2, microtaskId: string): void {
const found = findMicrotask(project, microtaskId);
if (!found) return;
const { milestone, microtask } = found;
// Activate parent milestone if it was LOCKED — happens after a
// milestone handover click.
if (milestone.status === 'locked') {
const from = milestone.status;
milestone.status = 'active';
appendStatusChangedRuntimeEvent(project, {
entityType: 'milestone',
entityId: milestone.id,
from,
to: milestone.status,
milestoneId: milestone.id,
});
}
if (microtask.status === 'todo') {
const from = microtask.status;
microtask.status = 'in_progress';
appendStatusChangedRuntimeEvent(project, {
entityType: 'microtask',
entityId: microtask.id,
from,
to: microtask.status,
microtaskId,
milestoneId: milestone.id,
});
recordEvent(project, 'microtask_opened', {
microtaskId,
milestoneId: milestone.id,
});
}
project.updatedAt = new Date().toISOString();
}
/** Advance the current microtask to `completed`. If this was the
* last microtask of the milestone, complete the milestone too and
* stage a `pendingHandover` for the workspace UI. */
export function advanceMicrotask(
project: PBLProjectV2,
microtaskId: string,
reason: string,
assessment: PBLInternalAssessment,
):
| {
ok: true;
milestoneCompleted: boolean;
projectCompleted: boolean;
nextMicrotaskId?: string;
}
| {
ok: false;
error: string;
} {
const found = findMicrotask(project, microtaskId);
if (!found) return { ok: false, error: 'microtask_not_found' };
const { milestone, microtask } = found;
if (microtask.status === 'completed' || microtask.status === 'skipped') {
return { ok: false, error: 'already_terminal' };
}
clearPendingTaskCompletion(project, microtaskId);
const microtaskStatusFrom = microtask.status;
microtask.status = 'completed';
appendStatusChangedRuntimeEvent(project, {
id: patchStatusChangedRuntimeEventId(
project,
'microtask',
microtask.id,
microtaskStatusFrom,
microtask.status,
),
entityType: 'microtask',
entityId: microtask.id,
from: microtaskStatusFrom,
to: microtask.status,
microtaskId,
milestoneId: milestone.id,
});
microtask.completionReason = reason;
microtask.internalAssessment = assessment;
recordEvent(project, 'microtask_completed', {
microtaskId,
milestoneId: milestone.id,
payload: { reason },
});
// Freeze the engagement summary onto the microtask itself once it's
// done. The engagement events ledger is a ring buffer (500-entry cap
// in engagement.ts) and a long project can roll its early task
// events off the back. By caching the summary at completion time we
// guarantee the milestone evaluator still has telemetry to feed the
// LLM, even when the underlying ledger has overflowed. This is the
// PR 6 evaluator's lifeline — without it, long projects evaluate
// against partial data and the LLM falls back to generic praise.
// We call microtaskEngagement AFTER recording the completion event
// so the snapshot includes a populated `completedAt` (used to
// derive `durationSeconds`).
microtask.engagement = microtaskEngagement(project, microtaskId);
// Find next not-yet-terminal microtask in the same milestone.
const next = milestone.microtasks.find((t) => t.status === 'todo' || t.status === 'in_progress');
if (next) {
const nextStatusFrom = next.status;
next.status = 'in_progress';
appendStatusChangedRuntimeEvent(project, {
id: patchStatusChangedRuntimeEventId(
project,
'microtask',
next.id,
nextStatusFrom,
next.status,
),
entityType: 'microtask',
entityId: next.id,
from: nextStatusFrom,
to: next.status,
microtaskId: next.id,
milestoneId: milestone.id,
});
recordEvent(project, 'microtask_opened', {
microtaskId: next.id,
milestoneId: milestone.id,
});
project.updatedAt = new Date().toISOString();
return {
ok: true,
milestoneCompleted: false,
projectCompleted: false,
nextMicrotaskId: next.id,
};
}
// No next microtask in this milestone — complete the milestone.
const milestoneStatusFrom = milestone.status;
milestone.status = 'completed';
appendStatusChangedRuntimeEvent(project, {
id: patchStatusChangedRuntimeEventId(
project,
'milestone',
milestone.id,
milestoneStatusFrom,
milestone.status,
),
entityType: 'milestone',
entityId: milestone.id,
from: milestoneStatusFrom,
to: milestone.status,
milestoneId: milestone.id,
microtaskId,
});
milestone.internalAssessment = assessment;
// Look for the next milestone in order.
const nextMs = project.milestones
.filter((m) => m.status === 'locked')
.sort((a, b) => a.order - b.order)[0];
if (nextMs) {
const firstTodo = nextMs.microtasks.find((t) => t.status === 'todo');
const handover: PBLHandover = {
completedMilestoneId: milestone.id,
completedMilestoneTitle: milestone.title,
nextMilestoneId: nextMs.id,
nextMilestoneTitle: nextMs.title,
nextTaskId: firstTodo?.id,
nextTaskTitle: firstTodo?.title,
consumed: false,
};
project.pendingHandover = handover;
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'handover_staged',
actorType: 'system',
completedMilestoneId: handover.completedMilestoneId,
nextMilestoneId: handover.nextMilestoneId,
nextMicrotaskId: handover.nextTaskId,
ts: new Date().toISOString(),
milestoneId: milestone.id,
microtaskId,
});
project.updatedAt = new Date().toISOString();
return { ok: true, milestoneCompleted: true, projectCompleted: false };
}
// No next milestone — project is complete. Keep the UI in the
// workspace so the chained milestone/final evaluators can render
// their cards in chat. The learner enters the completion report
// explicitly via the final-evaluation CTA.
const projectStatusFrom = project.status;
project.status = 'completed';
appendStatusChangedRuntimeEvent(project, {
id: patchStatusChangedRuntimeEventId(
project,
'project',
'project',
projectStatusFrom,
project.status,
),
entityType: 'project',
entityId: 'project',
from: projectStatusFrom,
to: project.status,
milestoneId: milestone.id,
microtaskId,
});
project.updatedAt = new Date().toISOString();
return { ok: true, milestoneCompleted: true, projectCompleted: true };
}
/** SCENARIO ONLY. Complete an ENTIRE roleplay act (milestone) in one
* deterministic step, when the learner clicks "finish this act".
*
* The act model treats a roleplay milestone as ONE continuous scene whose
* beats are background checkpoints, NOT sequentially-advanced units — so the
* learner is never auto-advanced mid-scene. Progression is fully
* deterministic and user-driven: this marks every not-yet-terminal beat of
* the active roleplay milestone `completed`, then seals the milestone and
* stages the handover (reusing the exact same path `advanceMicrotask` uses
* for a milestone's last beat — so the existing "next stage" button picks it
* up unchanged). No LLM, no per-beat judgement: which checkpoints were
* actually met is judged later by the final evaluator for SCORING only, never
* for progression. Caller must have verified the active milestone is a
* roleplay stage; returns the same shape as `advanceMicrotask`. */
export function completeRoleplayAct(
project: PBLProjectV2,
reason: string,
):
| { ok: true; milestoneCompleted: boolean; projectCompleted: boolean }
| { ok: false; error: string } {
const milestone = currentMilestone(project);
if (!milestone || milestone.scenarioStage !== 'roleplay') {
return { ok: false, error: 'not_in_roleplay_act' };
}
const open = milestone.microtasks.filter(
(t) => t.status === 'todo' || t.status === 'in_progress',
);
if (open.length === 0) return { ok: false, error: 'already_terminal' };
// Server-side engagement gate: the learner must have actually played THIS act
// (≥1 learner message tagged to one of its beats) before it can be finished.
// The simulator thread is shared across all roleplay acts, so we scope by the
// act's beat ids — otherwise a later act could be completed without playing
// it (earlier acts' messages would satisfy a thread-wide check). This mirrors
// the sidebar's per-act button gate; it is the authoritative server check.
const beatIds = new Set(milestone.microtasks.map((b) => b.id));
const simThread = project.threads.find((t) => t.agentId === PBL_SIMULATOR_AGENT_ID);
const engagedThisAct = (simThread?.messages ?? []).some(
(m) => m.roleType === 'user' && !!m.microtaskId && beatIds.has(m.microtaskId),
);
if (!engagedThisAct) return { ok: false, error: 'act_not_engaged' };
// Complete every remaining beat deterministically (checkpoints, not gates).
// Freeze each beat's engagement snapshot exactly like advanceMicrotask, so
// the scenario final evaluator still has per-beat telemetry to score against.
for (const beat of open) {
const from = beat.status;
beat.status = 'completed';
appendStatusChangedRuntimeEvent(project, {
entityType: 'microtask',
entityId: beat.id,
from,
to: beat.status,
microtaskId: beat.id,
milestoneId: milestone.id,
});
beat.completionReason = reason;
recordEvent(project, 'microtask_completed', {
microtaskId: beat.id,
milestoneId: milestone.id,
payload: { reason },
});
beat.engagement = microtaskEngagement(project, beat.id);
}
// Seal the milestone, then advance to the next stage in ONE step. The act
// model treats a roleplay milestone as a self-contained scene, so finishing
// it should go straight to the next stage — no separate "continue" click.
// We stage the handover and immediately consume it (activating the next
// milestone's first task), exactly as if the learner had clicked Continue.
const milestoneStatusFrom = milestone.status;
milestone.status = 'completed';
appendStatusChangedRuntimeEvent(project, {
entityType: 'milestone',
entityId: milestone.id,
from: milestoneStatusFrom,
to: milestone.status,
milestoneId: milestone.id,
});
const nextMs = project.milestones
.filter((m) => m.status === 'locked')
.sort((a, b) => a.order - b.order)[0];
if (nextMs) {
const firstTodo = nextMs.microtasks.find((t) => t.status === 'todo');
project.pendingHandover = {
completedMilestoneId: milestone.id,
completedMilestoneTitle: milestone.title,
nextMilestoneId: nextMs.id,
nextMilestoneTitle: nextMs.title,
nextTaskId: firstTodo?.id,
nextTaskTitle: firstTodo?.title,
consumed: false,
};
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'handover_staged',
actorType: 'system',
completedMilestoneId: milestone.id,
nextMilestoneId: nextMs.id,
nextMicrotaskId: firstTodo?.id,
ts: new Date().toISOString(),
milestoneId: milestone.id,
});
// One-step: consume the handover now so no "next stage" button is needed.
continueAfterHandover(project);
project.updatedAt = new Date().toISOString();
return { ok: true, milestoneCompleted: true, projectCompleted: false };
}
// No next milestone (shouldn't happen — a coherent scenario ends in wrapup).
const projectStatusFrom = project.status;
project.status = 'completed';
appendStatusChangedRuntimeEvent(project, {
entityType: 'project',
entityId: 'project',
from: projectStatusFrom,
to: project.status,
milestoneId: milestone.id,
});
project.updatedAt = new Date().toISOString();
return { ok: true, milestoneCompleted: true, projectCompleted: true };
}
/** Open the next milestone after the learner clicks Continue. */
export function continueAfterHandover(project: PBLProjectV2): {
ok: boolean;
activatedMicrotaskId?: string;
} {
const h = project.pendingHandover;
if (!h || h.consumed) return { ok: false };
const nextMs = project.milestones.find((m) => m.id === h.nextMilestoneId);
if (!nextMs) return { ok: false };
const nextMilestoneStatusFrom = nextMs.status;
nextMs.status = 'active';
appendStatusChangedRuntimeEvent(project, {
entityType: 'milestone',
entityId: nextMs.id,
from: nextMilestoneStatusFrom,
to: nextMs.status,
milestoneId: nextMs.id,
});
const first =
(h.nextTaskId && nextMs.microtasks.find((t) => t.id === h.nextTaskId)) ||
nextMs.microtasks.find((t) => t.status === 'todo');
if (first) {
const firstStatusFrom = first.status;
first.status = 'in_progress';
appendStatusChangedRuntimeEvent(project, {
entityType: 'microtask',
entityId: first.id,
from: firstStatusFrom,
to: first.status,
microtaskId: first.id,
milestoneId: nextMs.id,
});
recordEvent(project, 'microtask_opened', {
microtaskId: first.id,
milestoneId: nextMs.id,
});
}
project.pendingHandover = { ...h, consumed: true };
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'handover_consumed',
actorType: 'system',
completedMilestoneId: h.completedMilestoneId,
nextMilestoneId: h.nextMilestoneId,
activatedMicrotaskId: first?.id,
ts: new Date().toISOString(),
milestoneId: nextMs.id,
microtaskId: first?.id,
});
appendMilestoneDividerMessage(project, h, first?.id);
project.updatedAt = new Date().toISOString();
return { ok: true, activatedMicrotaskId: first?.id };
}
export function appendTaskDividerMessage(
project: PBLProjectV2,
args: {
completedMicrotaskId: string;
nextMicrotaskId?: string;
completedTitle?: string;
nextTitle?: string;
},
): void {
if (!args.nextMicrotaskId) return;
const instructor = project.roles.find((r) => r.type === 'instructor');
if (!instructor) return;
const thread = project.threads.find((t) => t.agentId === instructor.id);
if (!thread) return;
const labels = taskDividerLabels(project.language);
const left = args.completedTitle
? `${labels.completedPrefix}${args.completedTitle}`
: labels.completedFallback;
const right = args.nextTitle ? `${labels.nextPrefix}${args.nextTitle}` : labels.nextFallback;
const content = `${TASK_DIVIDER_PREFIX}${left} | ${right}`;
if (thread.messages.some((m) => m.content === content)) return;
const message: PBLChatMessage = {
id: 'msg_' + Date.now().toString(16) + Math.random().toString(16).slice(2, 6),
agentId: instructor.id,
roleType: 'instructor',
content,
ts: new Date().toISOString(),
microtaskId: args.nextMicrotaskId,
};
thread.messages.push(message);
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'message_created',
actorType: 'agent',
actorRoleId: instructor.id,
messageId: message.id,
threadId: thread.agentId,
ts: message.ts,
microtaskId: message.microtaskId,
milestoneId: milestoneIdForMicrotask(project, message.microtaskId),
});
}
function taskDividerLabels(language: string | undefined): {
completedPrefix: string;
completedFallback: string;
nextPrefix: string;
nextFallback: string;
} {
switch (language) {
case 'zh-CN':
return {
completedPrefix: '任务完成:',
completedFallback: '当前任务已完成',
nextPrefix: '开始下一任务:',
nextFallback: '开始下一任务',
};
case 'zh-TW':
return {
completedPrefix: '任務完成:',
completedFallback: '目前任務已完成',
nextPrefix: '開始下一任務:',
nextFallback: '開始下一任務',
};
case 'ja-JP':
return {
completedPrefix: 'タスク完了: ',
completedFallback: '現在のタスクが完了しました',
nextPrefix: '次のタスクへ: ',
nextFallback: '次のタスクへ',
};
case 'ru-RU':
return {
completedPrefix: 'Задача завершена: ',
completedFallback: 'Текущая задача завершена',
nextPrefix: 'Следующая задача: ',
nextFallback: 'Следующая задача',
};
case 'ar-SA':
return {
completedPrefix: 'اكتملت المهمة: ',
completedFallback: 'اكتملت المهمة الحالية',
nextPrefix: 'بدء المهمة التالية: ',
nextFallback: 'بدء المهمة التالية',
};
default:
return {
completedPrefix: 'Task complete: ',
completedFallback: 'Current task complete',
nextPrefix: 'Next task: ',
nextFallback: 'Next task',
};
}
}
function appendMilestoneDividerMessage(
project: PBLProjectV2,
handover: PBLHandover,
microtaskId: string | undefined,
): void {
// SCENARIO ONLY: never add an in-chat stage-advance divider for a role-play
// project. The three acts (prep → roleplay → wrapup) are already made legible
// by the left roadmap's stage labels and, on entering wrapup, by the
// collapsible "role-play history" block embedded in the Instructor feed — so
// a "[stage advance]" divider in the conversation is redundant noise (it used
// to appear when crossing into wrapup). Ordinary projects keep their
// Instructor-thread milestone divider exactly as before.
if (project.scenario) return;
const content = `${MILESTONE_DIVIDER_PREFIX}${milestoneDividerLabel(project.language, handover)}`;
const instructor = project.roles.find((r) => r.type === 'instructor');
if (!instructor) return;
const thread = project.threads.find((t) => t.agentId === instructor.id);
if (!thread) return;
if (thread.messages.some((m) => m.content === content)) return;
const message: PBLChatMessage = {
id: 'msg_' + Date.now().toString(16) + Math.random().toString(16).slice(2, 6),
agentId: instructor.id,
roleType: 'instructor',
content,
ts: new Date().toISOString(),
microtaskId,
};
thread.messages.push(message);
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'message_created',
actorType: 'agent',
actorRoleId: instructor.id,
messageId: message.id,
threadId: thread.agentId,
ts: message.ts,
microtaskId: message.microtaskId,
milestoneId: milestoneIdForMicrotask(project, message.microtaskId),
});
}
function milestoneDividerLabel(language: string | undefined, handover: PBLHandover): string {
const transition = `${handover.completedMilestoneTitle} → ${handover.nextMilestoneTitle}`;
switch (language) {
case 'zh-CN':
return `阶段推进:${transition}`;
case 'zh-TW':
return `階段推進:${transition}`;
case 'ja-JP':
return `ステージ進行: ${transition}`;
case 'ru-RU':
return `Продвижение этапа: ${transition}`;
case 'ar-SA':
return `تقدم المرحلة: ${transition}`;
default:
return `Stage progression: ${transition}`;
}
}
/** Compatibility barrel for package-owned PBL progress primitives. */
export * from '@openmaic/generation';

View File

@ -1,125 +1,2 @@
import type { PBLProjectV2, PBLRuntimeActorType, PBLRuntimeEvent, PBLUiPhase } from '../../types';
export const MAX_RUNTIME_EVENTS = 500;
export function mintRuntimeEventId(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
return crypto.randomUUID();
}
return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
export function appendRuntimeEvent(project: PBLProjectV2, event: PBLRuntimeEvent): PBLRuntimeEvent {
project.runtimeEvents ??= [];
const existing = project.runtimeEvents.find((candidate) => candidate.id === event.id);
if (existing) {
capRuntimeEvents(project);
return existing;
}
project.runtimeEvents.push(event);
capRuntimeEvents(project);
return event;
}
function capRuntimeEvents(project: PBLProjectV2): void {
if (!project.runtimeEvents) return;
if (project.runtimeEvents.length > MAX_RUNTIME_EVENTS) {
project.runtimeEvents.splice(0, project.runtimeEvents.length - MAX_RUNTIME_EVENTS);
}
}
export function runtimeEventEpoch(project: PBLProjectV2): number {
return project.runtimeResetEpoch ?? 0;
}
export function milestoneIdForMicrotask(
project: PBLProjectV2,
microtaskId: string | undefined,
): string | undefined {
if (!microtaskId) return undefined;
return project.milestones.find((milestone) =>
milestone.microtasks.some((microtask) => microtask.id === microtaskId),
)?.id;
}
export function normalizationRepairEventId(
project: PBLProjectV2,
entityType: 'project' | 'milestone' | 'microtask' | 'ui_phase',
entityId: string,
from: string,
to: string,
): string {
return `norm:${runtimeEventEpoch(project)}:${entityType}:${entityId}:${from}:${to}`;
}
export function patchStatusChangedRuntimeEventId(
project: PBLProjectV2,
entityType: Extract<PBLRuntimeEvent, { kind: 'status_changed' }>['entityType'],
entityId: string,
from: string,
to: string,
): string {
return `patch:${runtimeEventEpoch(project)}:${entityType}:${entityId}:${from}:${to}`;
}
export function appendStatusChangedRuntimeEvent(
project: PBLProjectV2,
args: {
entityType: Extract<PBLRuntimeEvent, { kind: 'status_changed' }>['entityType'];
entityId: string;
from: string;
to: string;
actorType?: PBLRuntimeActorType;
actorRoleId?: string;
microtaskId?: string;
milestoneId?: string;
id?: string;
},
): PBLRuntimeEvent | undefined {
if (args.from === args.to) return undefined;
return appendRuntimeEvent(project, {
id: args.id ?? mintRuntimeEventId(),
kind: 'status_changed',
actorType: args.actorType ?? 'system',
actorRoleId: args.actorRoleId,
entityType: args.entityType,
entityId: args.entityId,
from: args.from,
to: args.to,
ts: new Date().toISOString(),
microtaskId: args.microtaskId,
milestoneId: args.milestoneId,
});
}
export function appendProficiencyUpdatedRuntimeEvent(
project: PBLProjectV2,
): PBLRuntimeEvent | undefined {
const assessment = project.proficiencyAssessment;
if (!assessment) return undefined;
return appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'proficiency_updated',
actorType: 'system',
tier: assessment.tier,
score: assessment.score,
confidence: assessment.confidence,
ts: new Date().toISOString(),
});
}
export function transitionProjectUiPhase(project: PBLProjectV2, uiPhase: PBLUiPhase): PBLProjectV2 {
const next: PBLProjectV2 = {
...project,
runtimeEvents: project.runtimeEvents ? [...project.runtimeEvents] : undefined,
uiPhase,
};
appendStatusChangedRuntimeEvent(next, {
actorType: 'user',
entityType: 'ui_phase',
entityId: 'project',
from: project.uiPhase,
to: uiPhase,
});
return next;
}
/** Compatibility barrel for package-owned PBL runtime-event primitives. */
export * from '@openmaic/generation';

View File

@ -1,187 +1,2 @@
import type {
PBLChatMessage,
PBLEvaluation,
PBLInternalAssessment,
PBLMilestone,
PBLMicrotask,
PBLPendingTaskCompletion,
PBLProjectV2,
} from '../../types';
import { recordEvent } from './engagement';
import { appendRuntimeEvent, milestoneIdForMicrotask, mintRuntimeEventId } from './runtime-events';
import { trimmedPBLText } from '../../readers';
export const TASK_EVAL_PASS_SCORE = 60;
export function taskEvaluationCanComplete(evaluation: PBLEvaluation | undefined): boolean {
return (
evaluation?.kind === 'task' &&
typeof evaluation.score === 'number' &&
evaluation.score >= TASK_EVAL_PASS_SCORE
);
}
export function orderedMicrotasks(milestone: PBLMilestone): PBLMicrotask[] {
return milestone.microtasks.slice().sort((a, b) => a.order - b.order);
}
export function isLastMicrotaskOfMilestone(milestone: PBLMilestone, microtaskId: string): boolean {
const tasks = orderedMicrotasks(milestone);
return tasks.length > 0 && tasks[tasks.length - 1]?.id === microtaskId;
}
export function isCoreMilestoneFinalMicrotask(
milestone: PBLMilestone,
microtaskId: string,
): boolean {
return !!milestone.synthesisCheck && isLastMicrotaskOfMilestone(milestone, microtaskId);
}
export function currentPendingTaskCompletion(
project: PBLProjectV2,
microtaskId: string | undefined,
): PBLPendingTaskCompletion | undefined {
if (!microtaskId) return undefined;
const pending = project.pendingTaskCompletion;
return pending?.microtaskId === microtaskId ? pending : undefined;
}
export function setPendingTaskCompletion(
project: PBLProjectV2,
args: {
microtaskId: string;
milestoneId: string;
reason: string;
assessment?: PBLInternalAssessment;
evidence?: PBLPendingTaskCompletion['evidence'];
},
): PBLPendingTaskCompletion {
const existing = currentPendingTaskCompletion(project, args.microtaskId);
const pending: PBLPendingTaskCompletion = {
microtaskId: args.microtaskId,
milestoneId: args.milestoneId,
reason: args.reason,
assessment: args.assessment,
evidence: args.evidence,
createdAt: existing?.createdAt ?? new Date().toISOString(),
};
project.pendingTaskCompletion = pending;
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'task_completion_staged',
actorType: 'system',
reason: pending.reason,
ts: pending.createdAt,
microtaskId: pending.microtaskId,
milestoneId: pending.milestoneId,
});
project.updatedAt = new Date().toISOString();
return pending;
}
export function taskCompletionReadyText(language: string | undefined): string {
switch (language) {
case 'zh-CN':
return '这个任务已经完成了。如果你准备好了,也没有其他问题了,请点击左侧当前任务里的「完成」按钮进入下一步。';
case 'zh-TW':
return '這個任務已經完成了。如果你準備好了,也沒有其他問題了,請點擊左側目前任務裡的「完成」按鈕進入下一步。';
case 'ja-JP':
return 'このタスクは完了です。準備ができていて、ほかに質問がなければ、左側の現在のタスクにある「完了」ボタンを押して次へ進んでください。';
case 'ru-RU':
return 'Эта задача завершена. Если вы готовы и больше нет вопросов, нажмите кнопку «Готово» у текущей задачи слева, чтобы перейти дальше.';
case 'ar-SA':
return 'اكتملت هذه المهمة. إذا كنت مستعدًا ولا توجد لديك أسئلة أخرى، فاضغط زر «تم» في المهمة الحالية على اليسار للانتقال إلى الخطوة التالية.';
case 'en-US':
default:
return 'This task is complete. When you are ready and have no other questions, click Done on the current task in the left sidebar to move on.';
}
}
const TASK_COMPLETION_READY_TEXTS = new Set(
['zh-CN', 'zh-TW', 'ja-JP', 'ru-RU', 'ar-SA', 'en-US', undefined].map((language) =>
taskCompletionReadyText(language),
),
);
export function isTaskCompletionReadyMessageContent(content: unknown): boolean {
return TASK_COMPLETION_READY_TEXTS.has(trimmedPBLText(content));
}
function isoAfter(previous?: string): string {
const now = Date.now();
const previousMs = previous ? Date.parse(previous) : NaN;
const min = Number.isFinite(previousMs) ? previousMs + 1 : 0;
return new Date(Math.max(now, min)).toISOString();
}
export function appendTaskCompletionReadyMessage(
project: PBLProjectV2,
microtaskId: string,
options: { afterTs?: string } = {},
): PBLChatMessage | undefined {
const instructor = project.roles.find((r) => r.type === 'instructor');
if (!instructor) return undefined;
const thread = project.threads.find((t) => t.agentId === instructor.id);
if (!thread) return undefined;
const content = taskCompletionReadyText(project.language);
const exists = thread.messages.some(
(m) => m.microtaskId === microtaskId && m.content === content,
);
if (exists) return undefined;
const message: PBLChatMessage = {
id: 'msg_' + Date.now().toString(16) + Math.random().toString(16).slice(2, 6),
agentId: instructor.id,
roleType: 'instructor',
content,
ts: isoAfter(options.afterTs),
microtaskId,
};
thread.messages.push(message);
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'message_created',
actorType: 'agent',
actorRoleId: instructor.id,
messageId: message.id,
threadId: thread.agentId,
ts: message.ts,
microtaskId: message.microtaskId,
milestoneId: milestoneIdForMicrotask(project, message.microtaskId),
});
project.updatedAt = message.ts;
return message;
}
export function recordPendingTaskCompletionEvidence(
project: PBLProjectV2,
milestone: PBLMilestone,
microtask: PBLMicrotask,
evidence: PBLPendingTaskCompletion['evidence'] | undefined,
): void {
if (!evidence) return;
recordEvent(project, 'observation_concept_unlocked', {
microtaskId: microtask.id,
milestoneId: milestone.id,
payload: {
signature: evidence.signature,
label: evidence.label,
note: evidence.note,
},
});
}
export function clearPendingTaskCompletion(project: PBLProjectV2, microtaskId?: string): void {
if (!project.pendingTaskCompletion) return;
if (microtaskId && project.pendingTaskCompletion.microtaskId !== microtaskId) return;
const pending = project.pendingTaskCompletion;
delete project.pendingTaskCompletion;
appendRuntimeEvent(project, {
id: mintRuntimeEventId(),
kind: 'task_completion_cleared',
actorType: 'system',
ts: new Date().toISOString(),
microtaskId: pending.microtaskId,
milestoneId: pending.milestoneId,
});
project.updatedAt = new Date().toISOString();
}
/** Compatibility barrel for package-owned PBL task-completion primitives. */
export * from '@openmaic/generation';

View File

@ -23,7 +23,7 @@
* we encode them all up front here.
*/
import { parseJsonResponse } from '@/lib/generation/json-repair';
import { parseJsonResponse } from '@openmaic/generation';
const FENCED_JSON_RE = /```json\s*\n([\s\S]*?)\n\s*```/g;
const ANY_FENCED_JSON_RE = /```(?:json)?\s*([\s\S]*?)```/g;

View File

@ -1,123 +0,0 @@
You are the Planner of a Project-Based Learning (PBL) course module on the OpenMAIC platform, authoring a **role-play scenario** project.
The learner steps into a concrete situation and interacts in-character with character(s) played by a separate Simulator agent at play time. You author the WHOLE scenario now — it is frozen into the project package; the runtime only produces the live dialogue. Two rules above all: (a) the premise is **given and concrete**, introduced to the learner by the Instructor — the learner must NEVER be asked to guess it; (b) every task serves the real learning goal (how to do the thing well), not meta-guessing.
## The 3 mistakes that sink role-play scenarios — check every output against these
1. **Spoiler in visible text** (rule 3): putting a fact the learner is meant to UNCOVER (the hidden cause, motive, opponent's cards) into any learner-visible field — `setting`, a character's `persona`/`situation`/`openingLine`, the prep `briefing`, or a beat's `description`/`narration`. The hidden fact goes ONLY in that beat's private `characterObjective`. This is the most common failure.
2. **Thin `successWhen`** (§5): a beat whose success is "they chatted / discussed", or that only restates content to mention, instead of a concrete observable in-scene action.
3. **Prep that gates or coaches** (rule 1 of the skeleton): prep with a do-before-advance task, more than one microtask, a `completionCriteria` written as a click-gate, or tactics that belong in beat `hints`. Prep only lets the learner UNDERSTAND, then click to advance.
## What the platform gives you
- **Project topic**: {{projectTopic}}
- **Project description**: {{projectDescription}}
- **Target skills**: {{targetSkills}}
- **Suggested milestone count**: {{milestoneCount}}
- **Student proficiency tier** (set by the platform): {{proficiency}}
Course context (other scenes in playback order — source material, not a checklist):
{{courseContext}}
Scenario brief from the platform (may be empty — extra context on situation / characters / tone): {{scenarioBrief}}
## What you must produce
Project info + ONE Instructor role + a frozen `scenario` block + the FIXED three-stage milestone skeleton (prep → roleplay×1..N → wrapup).
### 1. Project info
`title`, `description`, `learningObjective` (the skill practised), `gains` (3-5 learner-facing "what you'll gain" statements — each an ability/awareness the learner BUILDS, NOT the deliverable, NOT a terse keyword), and `proficiency` (mirror `{{proficiency}}`).
### 2. Instructor role
`name` (SHORT descriptive guide title tied to this scenario, ending in a guide word — 教练/导师/coach — never generic "Instructor"/"AI", never a personal human name), `description` (2-3 sentence learner-facing avatar tooltip, written TO the learner, warm, no internal mechanics), `systemPrompt` (internal persona, not shown to the learner).
### 3. The `scenario` block (frozen)
- `setting`: the concrete overall premise, in the project language.
- `goal` (optional): what the learner practises.
- `rules` (optional, but REQUIRED whenever the scenario has a defined rule-set — games / interviews / debates / structured negotiations): the CONCRETE mechanics a newcomer needs to take part, specific enough for the Instructor to teach verbatim in prep (a card game: hand ranking, betting rounds, blinds, what Fold/Call/Raise/Pot Odds mean; a debate: the motion, each side's stance, the format; an interview: the rounds and what each assesses). Omit ONLY for free scenarios with no special rules (e.g. comforting a friend).
- `learnerRole` (optional): the learner's OWN role/position (e.g. "you are their close friend" / "you are the 5th player, on the button").
- `characters`: **EXACTLY ONE character** — this version plays a single counterpart throughout (the runtime only ever voices one). Author one rich, believable person, never a cast of several. The one character: `name`; `persona` (stable identity / relationship / personality / speaking style); **`situation`** (their CONCRETE current circumstance the learner faces — visible symptoms only, NOT the hidden cause); optional `boundaries` (hard safety rails — strongly recommended); optional `openingLine` (first line when the scene opens).
- `sceneVisual`: ONE project-wide visual fitting ALL roleplay stages — `caption` (short phrase in the project language, <~16 words, e.g. "牌桌现金局"), `bg1`/`bg2`/`accent` (three mood hex colours), `motifs` (2-4 emoji evoking THIS scene, e.g. `["🃏","♠️","🪙"]`). Specific to THIS project, never a placeholder.
### 4. The FIXED three-stage skeleton (this exact order)
1. **Prep** — FIRST milestone, `scenarioStage: "prep"`. Its `briefing` introduces the concrete premise to the learner (the situation, each character's `situation`, what the learner is there to do, plus `rules`/`learnerRole` when present) and MUST match the roleplay stages. Prep exists ONLY to UNDERSTAND background/scene/characters/rules. Give it **exactly ONE understanding-only microtask** (e.g. "了解背景,准备开始"): the learner reads, then clicks to advance. It does nothing and gates nothing — give it NO `successWhen`, and author NO "do X before proceeding" task.
2. **Roleplay** — one or MORE middle milestones, `scenarioStage: "roleplay"` (split a long scenario by round/phase). Each `briefing` brings the learner into the scene. Design the beats (microtasks) as a **DRAMATIC ARC** — hook → rising stakes → turning point/decision → resolution — never a flat checklist; 2-4 beats per stage, each carrying the §5 fields.
3. **Wrapup** — LAST milestone, `scenarioStage: "wrapup"`. Its `debrief` holds the Instructor's light, encouraging feedback (highlights + one improvement; the detailed report lives elsewhere). Give it **exactly ONE light microtask** (e.g. "听取反馈,收尾").
**Never set `coreConcept` on any scenario milestone.**
### 5. Roleplay beat fields (each microtask under a `roleplay` milestone)
- `title`: short beat name.
- `description`: the CONCRETE situation of this beat as the SYSTEM narrator states it — positions / what just happened / whose turn (e.g. "你在 Button 位拿到 A♠ J♦;前面都 Fold,老周在 Cutoff 加注到 6 个筹码;轮到你决定 preflop"). Factual scene-setting ONLY — NOT coaching, NOT the action the learner should take, NOT the character's lines. (This text doubles as the character's established facts, so it must stay pure scene-state.)
- `successWhen` (**REQUIRED on every roleplay beat**): the CONCRETE, OBSERVABLE in-scene action the learner must SAY or DO for the beat to count — the scenario's "deliverable" (e.g. "做出 preflop 决定:跟注、加注或弃牌" / "对对方说出的感受做出共情回应,并问一个跟进问题"). Plain SCENE terms, NOT a teaching goal. It is the advance GATE — name a real action; HOW WELL it was done is judged separately, so it need not embed the full rubric, but it must never reduce to "chatted". This field is HIDDEN from the learner.
- `characterObjective` (recommended): what the character PRIVATELY wants AND privately KNOWS this beat — their in-scene drive PLUS any fact the learner is meant to UNCOVER (the hidden cause/secret, revealed only when probed). Private to the character — NEVER narrated, shown, evaluated, or coached. This is the correct home for hidden facts.
- `skillFocus` (recommended): the single skill this beat practises (e.g. "底池赔率判断"). Surfaced to the learner (current-task panel + end-of-project per-act review); never spoken by the character.
- `learnerBrief` (recommended): the learner-facing "current task" blurb in the side panel. Say WHAT this beat is about and WHY it matters (the stakes / what they are practising), in 1-2 warm sentences addressed to the learner. You MAY orient them or raise something to keep in mind, but NEVER name the exact action/answer (that is the hidden `successWhen`) and NEVER reveal a `characterObjective` fact they are meant to discover. Frame, don't solve (e.g. "小皮看起来不太舒服,也有点紧张。先想想怎么让他放松下来,再慢慢了解他的情况。" — NOT "问他来之前去哪玩了"). Distinct from `description`: this is pure display (never seen by the character), `description` is the scene fact.
- The scene is FREE-FIRST: the learner always types their OWN response. Some beats may instead ask the learner to hand in a real artefact ("write them a letter").
- `narration` (optional): a short neutral scene-setting line the SYSTEM reads when the beat opens. Never spoken by a character or the Instructor.
- `hints` (**REQUIRED on every roleplay beat**, 1-2): SHORT learner-facing coaching tips shown in the "hints" card of the current-task side panel (never spoken by the character). Point the learner in the right DIRECTION of thinking for this beat — what to focus on, what matters, what to keep in mind — aligned with what `successWhen` is really after, so a thoughtful learner following them naturally gets there. CRITICAL: a hint is GUIDANCE, never a SCRIPT. NEVER write a ready-to-send line the learner could copy-paste into the chat, never quote example dialogue, never paste the literal `successWhen`, and never reveal a `characterObjective` fact. Say HOW TO THINK, not WHAT TO SAY (e.g. "先共情再了解情况,别急着下结论" — NOT "可以试着问:'你来之前去哪玩了?'").
## Hard rules
1. **Content language — strict.** Policy: **`{{language}}`** (BCP-47 code → only that language; nuanced directive → follow literally). EVERY text field follows it — project info + `gains`, role fields, `scenario` (`setting`/`goal`/`rules`/`learnerRole`/each character's fields/`sceneVisual.caption`), every milestone field, every beat field (`successWhen`/`characterObjective`/`skillFocus`/`learnerBrief`/`narration`/`hints`). Well-known technical terms stay native. Classroom context: `{{languageDirective}}`.
2. **Stay on the actual topic — no template substitution.** Project info + scenario derive from the outline metadata + scenario brief above; never swap in a different "common teaching scenario".
3. **No spoilers.** Learner-VISIBLE text — `setting`, each character's `persona`/`situation`/`openingLine`, the prep `briefing`, each beat's `description`/`narration` — contains ONLY what the learner already knows or can plainly observe at the outset. A fact a beat's `successWhen` requires UNCOVERING (a hidden cause, motive, secret, diagnosis, backstory, an opponent's hand) goes ONLY in that beat's private `characterObjective` — never up front. A "find out why" beat: the real cause lives in `characterObjective`; `situation` states only the visible symptoms.
4. **The character is a pure in-world participant, NEVER a coach.** In all character fields and speech it has its OWN motives and reacts like a real person. It must NEVER ask the learner to explain/justify their reasoning, evaluate/grade their moves, give strategy/meta hints, tell them it's their turn, or imply it can see info it shouldn't (e.g. the learner's hole cards). An in-world evaluative drive (an interviewer assessing the candidate) is fine — that's its motive, not coaching of the learner. Route out-of-scene content to its channel: rule-teaching → prep `briefing`; "a decision point has arrived" → system `narration`; strategy tips → beat `hints`.
5. **Use the proficiency tier `{{proficiency}}`** — adapt beat difficulty and how much prep/hints scaffold. Mirror the value.
6. **Keep scope tight** — finishable in one sitting (~15-45 min). 2-4 roleplay beats per stage is plenty.
7. **`hints` guide thinking, never hand over a line.** Hints must align with what `successWhen` is really after (so following them leads there) WITHOUT ever being a copy-paste-ready reply, quoted example line, the literal `successWhen`, or a `characterObjective` spoiler. Say how to think, not what to say. Likewise `learnerBrief` frames the beat (what + why) without naming the action/answer.
## Output format — STRICT
Output **exactly one JSON object** and nothing else. No markdown, no ```json fences. First character `{`, last character `}`.
```
{
"projectInfo": {
"title": string, "description": string, "learningObjective": string,
"gains": [string, ...], // 3-5
"proficiency": "beginner" | "intermediate" | "advanced"
},
"instructorRole": { "name": string, "description": string, "systemPrompt": string },
"scenario": {
"setting": string,
"goal": string, // OPTIONAL
"rules": string, // OPTIONAL (required for rule-based scenarios)
"learnerRole": string, // OPTIONAL
"characters": [
{ "name": string, "persona": string, "situation": string, "boundaries": string, "openingLine": string }
],
"sceneVisual": { "caption": string, "bg1": string, "bg2": string, "accent": string, "motifs": [string, ...] }
},
"milestones": [
{
"title": string, "description": string, "briefing": string,
"completionCriteria": string, "debrief": string,
"scenarioStage": "prep" | "roleplay" | "wrapup",
"microtasks": [
{
"title": string, "description": string,
"learnerBrief": string, // recommended; learner-facing what+why, NO answer
"hints": [string, ...], // REQUIRED on roleplay beats; guide thinking, never a copy-paste line
"successWhen": string, // REQUIRED on every roleplay beat (HIDDEN from learner)
"characterObjective": string, // recommended on roleplay beats
"skillFocus": string, // recommended on roleplay beats
"narration": string // OPTIONAL
}
]
}
]
}
```
Shape rules: FIRST milestone `scenarioStage: "prep"`, LAST `"wrapup"`, one or more `"roleplay"` between. **Every milestone includes non-empty `briefing`, `completionCriteria`, and `debrief`.** Prep and wrapup each have exactly ONE light microtask (no beat fields). Every roleplay beat carries the §5 fields. Never set `coreConcept`. Do not include `id`, `status`, `order`, `assignee`, `schemaVersion`, or timestamps. Omit optional fields entirely rather than passing empty strings.
Now author the scenario and output the single JSON object.
</content>

View File

@ -1,143 +0,0 @@
You are the Planner of a Project-Based Learning (PBL) course module on the OpenMAIC platform.
Your job: from the outline the platform has produced, **autonomously** design a complete, ready-to-run learning project. The student is not consulted during design — by the time they reach the PBL scene the project must already exist as a coherent, scaffolded plan. You are a **project designer**, not a course-outline generator: slides and quizzes teach; your scene turns that learning into a project with a beginning, a middle, and an end.
## The 5 mistakes that sink these projects — check every output against these
1. **Answer-leak** (rule 9): a hint or description that hands the literal code/method/operator to type. The single most common failure. Guide, never solve.
2. **Worksheet fragmentation** (rule 11): splitting tiny mechanics such as variable setup / loop header / one print / one sentence into separate microtasks instead of one meaningful step.
3. **Fake deliverable / shape mismatch** (rules 14, 15): forcing an arbitrary report, pseudo-code worksheet, or explanation-only output onto work that should be a real build / decision / analysis / plan.
4. **No judgeable "done"** (rule 14): a task with no clear, checkable thing the learner produces/decides — so the runtime can't tell when it's complete.
5. **Invisible resource dependency** (rule 16): a task that tells the learner to use a right-side briefing, image, attachment, starter file, reference tab, or provided dataset that the ordinary PBL workspace does not render.
## What the platform gives you
- **Project topic**: {{projectTopic}}
- **Project description (what students build)**: {{projectDescription}}
- **Target skills**: {{targetSkills}}
- **Suggested milestone count**: {{milestoneCount}}
- **Student proficiency tier** (set by the platform's adaptive engine): {{proficiency}}
Course context — every other scene in the course, in playback order:
{{courseContext}}
Read the course context as **source material, not a checklist to copy**. Scenes before this PBL teach the prerequisites; scenes after build on its outcome. Do NOT turn the outline into another mini-course: if it says "concept A → operation B → review C", your project is still a purposeful path where the learner investigates / decides / sets up / builds / drafts / tests / presents / reflects toward ONE coherent outcome (code, a short text answer, a plan, a research question, a configured environment, an analysis, a presentation, a decision, or another domain-appropriate product).
## Actual ordinary PBL workspace — text-only contract
The ordinary PBL workspace gives the learner:
- left: milestone/task roadmap
- center: Instructor chat
- right: current task submission area where they can paste text or upload their own work
It does **NOT** provide a right-side briefing tab, resource tab, reference drawer, preloaded image, attached PDF, starter file download, or built-in dataset. Therefore the project must be completable from the visible milestone/task/instructor text plus the learner's own external tools. If a task needs a tiny sample dataset, prompt template, constraints list, scenario facts, rubric, or starter content, include that material directly inside the milestone/task text. Never tell the learner to open/read/view/download/inspect a provided resource that is not written in your JSON text.
## What you must produce
1. **Project info** — `title`, `description` (must name the outcome the student works toward), `learningObjective` (the verb they master, distinct from what they build), `gains`, and the `proficiency` tier. `gains` is a SHORT list of **3-5 learner-facing "what you'll gain" statements** for the project Hero — each ONE ability/awareness/knowledge the learner BUILDS and can use afterwards, as a readable phrase in the project language (typically each terse target skill expanded into plain competency language). A gain is **NOT** the final deliverable (that's `description`), not a task title, not a terse keyword. E.g. for game theory: "理解纳什均衡并能在具体场景中求解" — NOT "完成一份定价方案".
2. **One Instructor role** (exactly one):
- `name` — a SHORT descriptive guide title tied to THIS topic, ending in a guide word in the project language (教练 / 导师 / coach / mentor) — e.g. "排序项目教练", "RAG 项目导师". NOT a generic "Instructor"/"AI", NOT an invented human name ("林岚", "Alex").
- `description` — a SHORT learner-facing avatar tooltip, written TO the learner, 2-3 sentences: who the guide is (use the name), that they accompany the learner through the project and each task, that the learner can ask anything anytime, and that they give feedback and check understanding. Warm, concrete to this topic. Do NOT expose internal mechanics (reading history, scoring, advancing tasks, evaluation).
- `systemPrompt` — the Instructor's internal persona/voice (NOT shown to the learner); richer detail lives here.
3. **Milestones** — major phases (aim for the suggested count). Each has: an action-oriented `title`; a 1-2 sentence `description`; a `briefing` (Instructor's opening for the stage); a `completionCriteria` (how the Instructor knows the student is done); a `debrief` (Instructor's closing); **optional** `coreConcept`; and `microtasks`.
- `coreConcept` — set on **only the 1-2 stages carrying the project's CORE knowledge point** (e.g. "为什么循环能避免重复代码"). When set, the Instructor runs ONE integrative reverse-question about it at stage end. **Omit it** on ordinary setup/build/polish stages — most projects mark just one.
- `microtasks` — 2-4 specific, actionable steps per milestone. Each has a `title`, a 1-2 sentence `description`, and `hints` (1-3 hints if the student is stuck). The FINAL milestone ends on a consolidation step (run/test/reflect). See rules 9-14.
## Hard rules
1. **Content language — strict, EVERY text field.** Policy: **`{{language}}`**. A BCP-47 code (`zh-CN`, `zh-TW`, `en-US`, `ja-JP`, `ru-RU`, `ar-SA`) → reply only in that language; a nuanced instruction (e.g. "中文为主,英文技术术语保留原文") → follow it literally. Applies to every field — project info, `gains`, role fields, every milestone field, every microtask field. Code samples, API names, well-known technical terms (`HashMap`, `pandas`, `React`) stay native. Classroom context: `{{languageDirective}}`.
2. **Stay on the actual topic — no template substitution.** `title` / `description` / `learningObjective` and every milestone/microtask/hint must derive from the outline metadata above. Rephrase, tighten, translate — but NEVER swap in a different "common teaching project" from training data.
3. **Project, not lesson sequence.** The project has a named outcome and milestones feel like stages of doing it. Good shape: clarify goal / gather inputs / set up / decide / build or draft / test or critique / revise / present or reflect. Bad shape: "understand the concept → learn the operation → review" with no outcome tying it together.
4. **Use the given proficiency tier** — `{{proficiency}}`; mirror it in the `proficiency` field. `beginner` → smaller concrete steps, more hints, no assumed tool knowledge. `intermediate` → assume basic familiarity, broader tasks. `advanced` → high-level tasks, fewer hints.
5. **Keep scope tight** — finishable in one sitting (~15-45 min). Prefer fewer, deeper microtasks over many shallow ones.
6. **Instructor voice = warm coach, not lecturer.** Write `briefing` / `completionCriteria` / `debrief` in the Instructor's voice, addressing the student in second person.
7. **Microtasks build on each other.** Earlier ones create context/decisions/setup/materials/attempts that later ones use. No floating tasks.
8. **Reference the course context.** Rely on concepts prior scenes taught without re-teaching; if a later scene depends on this project's output, end on something that connects to it.
9. **Hints and descriptions GUIDE, never SOLVE — the #1 failure.** A hint or `description` must NEVER contain the literal token the learner types: no method/function name, no operator, no syntax template, no exact variable name, no ready-to-paste line, and no control-flow scaffolding. State the GOAL and point at the concept. Test EVERY hint/description: *"Could the learner copy this straight into their editor and pass?"* If yes, rewrite as a question or a where-to-look pointer.
- ❌ `"试试 unique = set(orders)"` → ✅ `"哪种数据结构天然不允许重复?怎么把列表转换过去?"`
- ❌ `"先 if not comment.strip(): 再 continue"` → ✅ `"清洗后怎样识别一条其实是空的评论并跳过它?"`
- ❌ `"用 split() 不带参数来自动合并连续空格"` → ✅ `"有没有字符串处理方式能把多余空白自然折叠掉?查查文档。"`
- ❌ `"先写 for score in scores: 再在循环里累加"` → ✅ `"怎样让程序对每个分数重复同一判断,并把符合条件的结果累计起来?"`
Naming a library to INSTALL or a concept to UNDERSTAND is fine; handing the exact line/method/operator/loop/conditional is not.
10. **Leave the learner real choices (agency).** Don't dictate every variable name, exact output wording, or data value. Each milestone gives at least one genuine decision: their own sample data, scenario, naming, or which of several valid approaches to try. Every-token-dictated = a worksheet, not a project.
11. **Right-sized microtasks.** Each is ONE substantive step that produces or demonstrates something real. NEVER make `"打印结果"` / `"运行一下"` its own microtask — fold display + a quick check into the step that produced the thing. Don't split a chain of trivial one-liners into separate tasks (combine "定义字符串 / 调用 strip / 转小写" into one "准备并规整样本数据"), and don't bundle unrelated goals into one task. 2-4 meaningful microtasks per milestone.
- Bad coding fragmentation: `"定义变量"` → `"写循环头"` → `"累加结果"` → `"打印答案"` as four tasks.
- Bad open-task fragmentation: `"表态一句"` → `"补一个理由"` → `"再补一个例子"` as three fake steps.
- Good shape: one microtask = one meaningful move in the workflow (set up a usable sample, make a justified decision, implement one coherent chunk, test one behavior, revise one argument).
12. **End with consolidation — every project needs a real "done".** The FINAL milestone MUST contain a closing microtask that consolidates the whole project: run it end-to-end, test against ≥1 input (include an obvious edge case where the domain has one — e.g. an empty list), and/or a short reflection — converging on ONE nameable deliverable the learner SEES working. A congratulatory `debrief` is not closure on its own.
13. **Build phases, not lecture chapters.** Milestones are stages of building the product. `"布尔基础 → 逻辑运算 → if/else"` is a textbook outline; `"设定规则输入 → 组合出准入规则 → 根据判断给出结果"` is a project. If titles read like chapter headings, reshape them around what the learner DOES.
14. **Every task has a concrete, judgeable "done" (the design→runtime contract).** Each `description` must make clear WHAT the learner produces/demonstrates/decides and what "done well" looks like — this written done-definition IS the contract the runtime advance + feedback depend on; leave it implicit and scoring drifts. Judge "done" on TWO axes — (A) NATURE and (B) DELIVERY FORM (rule 15) — never literally. Classify the nature and match the criteria:
- **Convergent** (one checkable answer: code runs, calc correct, fact right) → done = correct/works.
- **Gradable-open** (no single answer but clear better/worse by domain standards — a decision + rationale, an argument, an analysis, a plan) → done = reasoning quality + meeting domain criteria; you MUST STATE the criteria separating strong from weak. NOT "one right answer" and NOT "any stance passes". Most skill/analysis/decision tasks live here. Name the criteria explicitly: relevance, specificity, tradeoff awareness, evidence quality, feasibility, or another domain-fit standard.
- **Open-reflective** (genuinely no right/wrong: an ethical stance, interpretation, reflection) → done = depth/honesty + a clearly stated position; NEVER "matched the expected answer".
✘ Forbidden: vague tasks ("了解X" / "探索Y") with no checkable done-state; a gradable-open task with no stated criteria; a description/hint that hands the full answer.
15. **Never manufacture a fake deliverable for open work, and never de-grade a build into prose-only work.** "Must be evaluable" does NOT mean forcing a tangible artifact onto open/reflective work (a mandatory 500-word report, a quiz tacked onto a discussion). Design gradable-open as "make a real decision / take a position + justify it" with the domain rubric; design open-reflective as a stance / decision+rationale / plan / refined question / structured reflection, judged on reasoning. Match the DELIVERY FORM to the work — artifact (checkable product) / argument (written reasoning trace) / performance (a graceful action in a situated interaction) — and label the nature correctly. A truly outcome-less chat topic is a poor PBL fit; if you must, give it a process destination (explore angles → weigh tensions → land on a stated personal view).
- If the project outcome is software / data / configuration / another executable build, the learner should actually build, test, inspect, debug, or revise the real thing — not merely write pseudo-code, describe a process, or simulate the answer on paper.
- If the project outcome is analysis / planning / writing / research framing, do NOT force an arbitrary report length or fake "product" just to make it feel concrete; require a real decision, argument, plan, question, or structured rationale with quality criteria.
16. **Text-only resource grounding.** Do NOT mention a right-side briefing, resource panel, reference tab, preloaded image, screenshot, PDF, attachment, downloadable starter file, or provided dataset. If the learner needs information, make it visible in `briefing`, `completionCriteria`, `debrief`, a microtask `description`, or a `hint`. If the learner needs data, either ask them to create a small sample themselves or give the sample inline as text. If you write "read the following/below/given brief/material/case/dataset" or "阅读下面/以下/给定/提供的简报/资料/材料/案例/数据", the actual brief/material must appear immediately in that same visible text — do not refer to an implied brief that is not written out.
## Silent self-check before output
Before you output the JSON, silently inspect every field and fix these failure modes:
1. If any hint/description contains an exact method name, operator, syntax pattern, or near-copyable code fragment, rewrite it more abstractly.
2. If any milestone contains a trivial mechanics-only microtask, merge it into the surrounding substantive step.
3. If any open task says only "write a report/summary/essay" without strong-vs-weak criteria, rewrite it as a real decision / argument / analysis / plan with explicit quality standards.
4. If any build/software task could be completed by prose alone, rewrite it so the learner must build/test/debug/revise the actual artifact.
5. If any visible text refers to a missing brief/material/dataset, inline that material immediately.
## Output format — STRICT
Output **exactly one JSON object** and nothing else. No explanation, no markdown, no ```json fences. First character `{`, last character `}`.
```
{
"projectInfo": {
"title": string,
"description": string,
"learningObjective": string,
"gains": [string, ...], // 3-5
"proficiency": "beginner" | "intermediate" | "advanced"
},
"instructorRole": { "name": string, "description": string, "systemPrompt": string },
"milestones": [
{
"title": string,
"description": string,
"briefing": string,
"completionCriteria": string,
"debrief": string,
"coreConcept": string, // OPTIONAL — only the 1-2 core stages
"microtasks": [
{ "title": string, "description": string, "hints": [string, ...] } // 1-3 hints
]
}
]
}
```
Do not include `id`, `status`, `order`, `assignee`, or timestamps — the platform assigns ids/status/order. Every milestone has ≥1 microtask. Omit optional fields entirely rather than passing empty strings.
## Calibration (do not echo)
"Build a Python CSV analyser", beginner → M1 "Read the data" (open CSV / inspect columns / spot quality issues), M2 "Clean and aggregate" (handle missing / group by month / sum revenue), M3 "Visualise and report" (plot trend / write 3-sentence summary). Small, sequential, one coherent outcome. NOT: "M1 Learn what a CSV is → M2 Learn grouping → M3 Review charts" — that's an outline, not a project.
Now design the project and output the single JSON object.
</content>

View File

@ -1,7 +1,7 @@
# `lib/prompts`
File-based prompt loader + templates shared by both the generation pipeline and
the runtime orchestration layer.
File-based prompt loader + templates for the runtime orchestration layer and
app-only outline modes. Generation templates live in `@openmaic/generation`.
## Directory layout
@ -38,10 +38,9 @@ Conditional blocks read from the same `variables` record passed to
## Naming conventions
- **Placeholder names use `camelCase`.** Example: `{{agentName}}`, `{{stateContext}}`.
- **Template IDs use `kebab-case`.** Example: `agent-system`, `slide-content`.
- `lib/prompts/templates/slide-content/{system,user}.md` still uses legacy
`snake_case` placeholders (`{{canvas_width}}`, `{{canvas_height}}`). This
predates the camelCase convention; don't imitate it when writing new templates.
- **Template IDs use `kebab-case`.** Example: `agent-system`, `interactive-outlines`.
- Package-owned generation templates follow the same placeholder conventions;
edit them under `packages/@openmaic/generation/templates/`.
## Adding a new prompt
@ -77,9 +76,10 @@ interpolate('hello {{missing}}', {}) === 'hello {{missing}}'
This is intentional for partial-render scenarios but means a typo in a
placeholder name ships literal `{{…}}` text to the LLM. Defence:
- Tests in `tests/prompts/templates.test.ts` assert that the fully-rendered
agent-system / director / slide-content prompts contain no surviving
`{{…}}` tokens. Keep that check passing when adding variables.
- Tests in `tests/prompts/templates.test.ts` and
`packages/@openmaic/generation/test/` assert that fully rendered app and
generation prompts contain no surviving `{{…}}` tokens. Keep those checks
passing when adding variables.
- `{{snippet:name}}` lookups **throw** on a missing snippet file rather than
passing through silently, so a typo like `{{snippet:speach-guidelines}}`
fails at load time instead of reaching the LLM.

View File

@ -24,22 +24,9 @@ export {
// Prompt IDs constant
export const PROMPT_IDS = {
REQUIREMENTS_TO_OUTLINES: 'requirements-to-outlines',
INTERACTIVE_OUTLINES: 'interactive-outlines',
TASK_ENGINE_OUTLINES: 'task-engine-outlines',
WEB_SEARCH_QUERY_REWRITE: 'web-search-query-rewrite',
SLIDE_CONTENT: 'slide-content',
QUIZ_CONTENT: 'quiz-content',
SLIDE_ACTIONS: 'slide-actions',
QUIZ_ACTIONS: 'quiz-actions',
INTERACTIVE_ACTIONS: 'interactive-actions',
SIMULATION_CONTENT: 'simulation-content',
DIAGRAM_CONTENT: 'diagram-content',
CODE_CONTENT: 'code-content',
GAME_CONTENT: 'game-content',
VISUALIZATION3D_CONTENT: 'visualization3d-content',
PROCEDURAL_SKILL_CONTENT: 'procedural-skill-content',
PBL_ACTIONS: 'pbl-actions',
AGENT_SYSTEM: 'agent-system',
AGENT_SYSTEM_WB_TEACHER: 'agent-system-wb-teacher',
AGENT_SYSTEM_WB_ASSISTANT: 'agent-system-wb-assistant',

View File

@ -10,17 +10,14 @@
import fs from 'fs';
import path from 'path';
import type { PromptId, LoadedPrompt, PromptVariableDefaults, SnippetId } from './types';
import type { PromptId, LoadedPrompt, SnippetId } from './types';
import { createLogger } from '@/lib/logger';
import {
loadSnippet as loadGenerationSnippet,
type SnippetId as GenerationSnippetId,
} from '@openmaic/generation';
const log = createLogger('PromptLoader');
const PROMPT_VARIABLE_DEFAULTS = {
'pbl-actions': {
projectSummary:
'(No generated milestones are available; introduce the project topic without inventing any.)',
},
} satisfies PromptVariableDefaults;
/**
* Get the prompts directory path
*/
@ -38,9 +35,9 @@ export function loadSnippet(snippetId: SnippetId): string {
try {
return fs.readFileSync(snippetPath, 'utf-8').trim();
} catch {
// Fail loud rather than silently shipping `{{snippet:foo}}` to the LLM.
// A missing snippet is always a config/typo bug — surface at load time.
throw new Error(`Snippet not found: ${snippetId}`);
// App-only templates can reuse package-owned generation snippets without
// retaining a second on-disk copy.
return loadGenerationSnippet(snippetId as GenerationSnippetId);
}
}
@ -125,17 +122,10 @@ export function interpolateVariables(template: string, variables: Record<string,
}
function applyPromptVariableDefaults(
promptId: PromptId,
_promptId: PromptId,
variables: Record<string, unknown>,
): Record<string, unknown> {
const defaults = PROMPT_VARIABLE_DEFAULTS[promptId as keyof typeof PROMPT_VARIABLE_DEFAULTS];
if (!defaults) return variables;
const resolved = { ...variables };
for (const [key, value] of Object.entries(defaults)) {
if (resolved[key] === undefined) resolved[key] = value;
}
return resolved;
return variables;
}
/**

View File

@ -1,27 +0,0 @@
### AI-Generated Image Requests
Use image generation only for slide scenes that need a static visual and have no suitable source image.
- Prefer `suggestedImageIds` when a suitable source/PDF image exists
- Add a `mediaGenerations` entry only when a generated image genuinely enhances the content
- Use `type: "image"`
- Each image request specifies: `prompt` (description for the generation model), `elementId` (unique placeholder), and optionally `aspectRatio` (default "16:9") and `style`
- **Image IDs**: use `"gen_img_1"`, `"gen_img_2"`, etc. IDs are globally unique across the entire course, not reset per scene
- The prompt should describe the desired image clearly and specifically
- **Language in images**: If the image contains text, labels, or annotations, the prompt must explicitly specify that all text in the image should be in the course language (for example, "all labels in Chinese" for zh-CN courses, "all labels in English" for en-US courses). For purely visual images without text, language does not matter
- **Avoid duplicate images across slides**: Each generated image must be visually distinct. Do not request near-identical images for different slides. If multiple slides cover the same topic, vary the visual angle, scope, or style
- **Cross-scene reuse**: To reuse a generated image in a different scene, reference the same `elementId` in the later scene's content without adding a new `mediaGenerations` entry. Only the scene that first defines the `elementId` in its `mediaGenerations` should include the generation request
- Use generated images for static content: diagrams, charts, illustrations, portraits, landscapes
Image example:
```json
"mediaGenerations": [
{
"type": "image",
"prompt": "A colorful diagram showing the water cycle with evaporation, condensation, and precipitation arrows",
"elementId": "gen_img_1",
"aspectRatio": "16:9"
}
]
```

View File

@ -1,6 +0,0 @@
## Output Format Requirements (Must Follow Strictly)
1. Output pure JSON directly, no explanations or descriptions
2. Do NOT wrap with ```json code blocks
3. Do NOT add any text before or after the JSON
4. Ensure JSON format is correct and can be parsed directly

View File

@ -1,10 +0,0 @@
### Content Safety Guidelines for Generation Prompts
To avoid blocked requests from the generation model:
- Do not describe specific human facial features, body details, or physical appearance; use abstract or iconographic representations such as "a silhouette of a person"
- Do not include violence, weapons, blood, or gore
- Do not reference politically sensitive content: national flags, military imagery, or real political figures
- Do not depict real public figures or celebrities by name or likeness
- Prefer abstract, diagrammatic, infographic, or icon-based styles for educational illustrations
- Keep all prompts academic and education-oriented in tone

View File

@ -1,10 +0,0 @@
#### AI-Generated Images (`gen_img_*`)
If the scene outline includes image entries in `mediaGenerations`, you may use those generated image placeholders:
- `src` can be a generated image ID like `"gen_img_1"`, `"gen_img_2"`, etc.
- These placeholders will be replaced with actual generated images after slide creation
- Use the same positioning rules as source images
- Default aspect ratio for generated images: 16:9 (width:height = 16:9)
- For generated images, calculate `height = width / 1.778` unless a different ratio is specified
- Text-to-image spacing: 25-35px vertically and 30-40px horizontally

View File

@ -1,27 +0,0 @@
### ImageElement
```json
{
"id": "image_001",
"type": "image",
"left": 100,
"top": 150,
"width": 400,
"height": 300,
"src": "img_1",
"fixedRatio": true
}
```
**Required Fields**: `id`, `type`, `left`, `top`, `width`, `height`, `src` (source image ID like "img_1"), `fixedRatio` (always true)
**Source Image Sizing Rules (keep original aspect ratio)**:
- `src` must be an image ID from the assigned media list (for example, "img_1"). Do not use URLs or invented IDs
- If no suitable source image exists, do not create image elements; use text and shapes only
- When dimensions are provided (for example, "img_1: 884x424, ratio 2.08"):
- Choose a width based on layout needs, typically 300-500px
- Calculate `height = width / aspect_ratio`
- Example: ratio 2.08, width 400 -> height = 400 / 2.08 ~= 192
- When dimensions are not provided, use 4:3 default (width:height ~= 1.33)
- Ensure the image stays within canvas margins (50px from each edge)

View File

@ -1,24 +0,0 @@
### VideoElement
```json
{
"id": "video_001",
"type": "video",
"left": 100,
"top": 150,
"width": 500,
"height": 281,
"mediaRef": "<VIDEO_MEDIA_REF_FROM_ASSIGNED_MEDIA>",
"autoplay": false
}
```
**Required Fields**: `id`, `type`, `left`, `top`, `width`, `height`, `mediaRef` (generated video media ref copied exactly from the assigned media list), `autoplay` (boolean)
**Video Sizing Rules**:
- `mediaRef` must be copied exactly from the assigned video media list
- Default aspect ratio: 16:9 -> `height = width / 1.778`
- Typical video width: 400-600px (prominent on slide)
- Position video as a focal element, usually centered or in the main content area
- Leave space for a title and optional caption text

View File

@ -1,26 +0,0 @@
### AI-Generated Video Requests
Use video generation only for slide scenes where motion is essential to understanding.
- Add a `mediaGenerations` entry only when a generated video genuinely enhances the content
- Use `type: "video"`
- Each video request specifies: `prompt` (description for the generation model), `elementId` (unique placeholder), and optionally `aspectRatio` (default "16:9") and `style`
- **Video IDs**: use `"gen_vid_1"`, `"gen_vid_2"`, etc. IDs are globally unique across the entire course, not reset per scene
- The prompt should describe the desired motion clearly and specifically
- Video generation is slow (1-2 minutes each), so request videos sparingly
- **Avoid duplicate videos across slides**: Each generated video must be visually distinct. Do not request near-identical videos for different slides. If multiple slides cover the same topic, vary the motion, scope, or style
- **Cross-scene reuse**: To reuse a generated video in a different scene, reference the same `elementId` in the later scene's content without adding a new `mediaGenerations` entry. Only the scene that first defines the `elementId` in its `mediaGenerations` should include the generation request
- Use video for content that benefits from motion or animation: physical processes, step-by-step demonstrations, biological movements, chemical reactions, mechanical operations
Video example:
```json
"mediaGenerations": [
{
"type": "video",
"prompt": "A smooth animation showing water molecules evaporating from the ocean surface, rising into the atmosphere, and forming clouds",
"elementId": "gen_vid_1",
"aspectRatio": "16:9"
}
]
```

View File

@ -1,217 +0,0 @@
# Code Playground Widget Generator
Generate a self-contained HTML code editor with execution and test validation.
## Supported Languages
- Python (via Pyodide CDN)
- JavaScript (native browser execution)
- TypeScript (via Babel CDN transpilation)
## Widget Config Schema
```json
{
"type": "code",
"language": "python",
"description": "...",
"starterCode": "def solution(x):\n # Your code here\n pass",
"testCases": [
{ "id": "t1", "input": "5", "expected": "25", "description": "Square the input" }
],
"hints": ["Think about multiplication", "What is x * x?"],
"solution": "def solution(x):\n return x * x"
}
```
## Python Execution Requirements (CRITICAL)
When generating Python widgets using Pyodide, follow these **mandatory patterns**:
### 1. Proper Stdout Capture Setup
**ALWAYS use this exact pattern for stdout capture:**
```javascript
// CORRECT - imports both sys AND io
await pyodide.runPythonAsync(`
import sys
import io
sys.stdout = io.StringIO()
`);
```
**NEVER do this (causes NameError):**
```javascript
// WRONG - missing import io
pyodide.runPython('import sys; sys.stdout = io.StringIO()');
```
### 2. Use Async Execution
- Always use `pyodide.runPythonAsync()` instead of `pyodide.runPython()`
- Async execution is more reliable and handles module loading correctly
- All Pyodide operations should be wrapped in async functions
### 3. Load Required Packages Before Execution
If user code needs packages like numpy, load them during initialization:
```javascript
await pyodide.loadPackage(['numpy']);
```
### 4. Wait for Pyodide Initialization
- Disable the run button until Pyodide is fully loaded
- Show loading status to users
- Check `pyodide !== null` before running code
### 5. Retrieve Output Correctly
```javascript
const output = pyodide.runPython('sys.stdout.getvalue()');
```
## Complete Python Widget Runtime Pattern
```javascript
let pyodide = null;
async function initPyodide() {
pyodide = await loadPyodide();
// Load any packages user code might need
await pyodide.loadPackage(['numpy']);
document.getElementById('run-btn').disabled = false;
document.getElementById('status').textContent = 'Python ready';
}
initPyodide();
async function runCode() {
if (!pyodide) {
alert('Python environment not ready');
return;
}
const code = editor.getValue();
try {
// MUST import sys AND io before using StringIO
await pyodide.runPythonAsync(`
import sys
import io
sys.stdout = io.StringIO()
`);
await pyodide.runPythonAsync(code);
const output = pyodide.runPython('sys.stdout.getvalue()');
document.getElementById('output').textContent = output;
} catch (e) {
document.getElementById('output').textContent = `Error: ${e.message}`;
}
}
```
## Technical Requirements
- Use CodeMirror or Monaco via CDN for editing
- Syntax highlighting for the language
- Run button with output display
- Test case validation with pass/fail indicators
- Hint button that reveals hints progressively
- Mobile-responsive layout
## Layout Guidelines
- Code editor should be visible and not overlap with output panel
- On mobile, stack editor above output (not side-by-side)
- Ensure editor has minimum height of 200px on mobile
- Test cases should be collapsible on small screens
## CRITICAL: postMessage Listener for Widget Actions (REQUIRED)
The platform drives this widget by posting messages into the iframe
(`SET_WIDGET_STATE`, `HIGHLIGHT_ELEMENT`, `ANNOTATE_ELEMENT`, `REVEAL_ELEMENT`).
Your HTML MUST register this listener, or those actions silently do nothing.
For a code playground, `SET_WIDGET_STATE` typically loads code into the editor and
optionally runs it:
```javascript
window.addEventListener('message', function(event) {
const { type, target, state, content } = event.data;
switch (type) {
case 'SET_WIDGET_STATE':
// e.g. { code: "...", run: true } — set editor contents, optionally run.
if (state && typeof state.code === 'string') {
// Guard the identifier itself: `editor?.setValue` still throws
// ReferenceError when no `editor` variable is declared (e.g. a
// textarea-only widget). `typeof editor` is safe for that case.
if (typeof editor !== 'undefined' && typeof editor.setValue === 'function') editor.setValue(state.code);
else { const ta = document.getElementById('code-input'); if (ta) ta.value = state.code; }
}
if (state && state.run && typeof runCode === 'function') runCode();
break;
case 'HIGHLIGHT_ELEMENT':
const highlightEl = document.querySelector(target);
if (highlightEl) {
highlightEl.style.outline = '3px solid rgba(139, 92, 246, 0.8)';
highlightEl.style.outlineOffset = '4px';
highlightEl.style.animation = 'pulse-highlight 2s infinite';
setTimeout(() => {
highlightEl.style.outline = '';
highlightEl.style.animation = '';
}, 3000);
}
break;
case 'ANNOTATE_ELEMENT':
const annotateEl = document.querySelector(target);
if (annotateEl && content) {
const rect = annotateEl.getBoundingClientRect();
const tooltip = document.createElement('div');
tooltip.className = 'teacher-annotation';
tooltip.style.cssText = 'position:fixed; top:' + (rect.top - 40) + 'px; left:' + rect.left + 'px; background:rgba(139,92,246,0.95); color:white; padding:8px 12px; border-radius:8px; font-size:14px; z-index:1000; animation:fadeIn 0.3s;';
tooltip.textContent = content;
document.body.appendChild(tooltip);
setTimeout(() => tooltip.remove(), 4000);
}
break;
case 'REVEAL_ELEMENT':
// Reveal a hidden element (e.g. the solution or a hint panel)
const revealEl = document.querySelector(target);
if (revealEl) {
revealEl.style.display = '';
revealEl.style.opacity = '1';
}
break;
}
});
const style = document.createElement('style');
style.textContent = '@keyframes pulse-highlight { 0%, 100% { outline-color: rgba(139, 92, 246, 0.8); } 50% { outline-color: rgba(139, 92, 246, 0.4); } } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }';
document.head.appendChild(style);
```
### Element Naming Convention
So highlight/annotate/reveal can target UI, use consistent ids:
- Run button: `id="run-btn"`, output panel: `id="output"`, editor host: `id="code-input"`.
- Solution/hint panels: `id="solution"`, `id="hint-{n}"`.
## Output Format
Return ONLY the HTML document, no markdown fences or explanations.
**CRITICAL: Output EXACTLY ONE HTML document.**
- Do NOT duplicate content
- Do NOT include multiple `<!DOCTYPE html>` tags
- The output must end with exactly one `</html>` tag
## Quality Checklist
- [ ] Code editor is visible and usable on mobile
- [ ] Run button works correctly
- [ ] Output panel doesn't overlap editor
- [ ] Test cases show pass/fail clearly
- [ ] Hints reveal progressively
- [ ] **NO DUPLICATED HTML** - exactly ONE `<!DOCTYPE html>` tag
- [ ] **Python stdout uses correct import pattern** - imports BOTH `sys` AND `io`
- [ ] **Pyodide uses async execution** - `runPythonAsync()` not `runPython()`

View File

@ -1,40 +0,0 @@
Create a code playground widget for: {{title}}
## Programming Language
{{programmingLanguage}}
## Challenge Description
{{description}}
## Key Points
{{keyPoints}}
## Starter Code Template
```{{programmingLanguage}}
{{starterCode}}
```
## Test Cases
{{testCases}}
## Hints
{{hints}}
## Course Language
{{languageDirective}}
---
Generate a complete, interactive HTML code editor with:
1. Code editor with syntax highlighting
2. Run button with output display
3. Test case validation
4. Progressive hint system
5. Embedded widget configuration JSON

View File

@ -1,132 +0,0 @@
# Interactive Diagram Generator
Generate a self-contained HTML diagram with connected nodes.
## Data Schema
```json
{
"nodes": [
{ "id": "n1", "label": "Label", "icon": "🎯", "details": "Description" }
],
"edges": [
{ "from": "n1", "to": "n2", "label": "next" }
],
"revealOrder": ["n1", "n2"]
}
```
## Core Requirements
1. **SVG-based** with embedded JSON config
2. **First node visible** on load
3. **High contrast**: White nodes on dark background, light edge labels
4. **Edges connect to node edges** (account for node dimensions and arrow offset)
5. **Mobile**: Sidebar/panel collapsible, doesn't block diagram
6. **No jitter**: Avoid hover transform conflicts on click
7. **All nodes connected**: No orphan nodes
## Edge Connection Code
```javascript
const NODE_WIDTH = 180, NODE_HEIGHT = 70, ARROW_OFFSET = 10;
function getEdgePoints(from, to) {
const dx = to.x - from.x, dy = to.y - from.y;
let sx, sy, ex, ey;
if (Math.abs(dy) > Math.abs(dx)) { // Vertical
sx = from.x;
sy = dy > 0 ? from.y + NODE_HEIGHT/2 : from.y - NODE_HEIGHT/2;
ex = to.x;
ey = dy > 0 ? to.y - NODE_HEIGHT/2 - ARROW_OFFSET : to.y + NODE_HEIGHT/2 + ARROW_OFFSET;
} else { // Horizontal
sx = dx > 0 ? from.x + NODE_WIDTH/2 : from.x - NODE_WIDTH/2;
sy = from.y;
ex = dx > 0 ? to.x - NODE_WIDTH/2 - ARROW_OFFSET : to.x + NODE_WIDTH/2 + ARROW_OFFSET;
ey = to.y;
}
return `M ${sx} ${sy} L ${ex} ${ey}`;
}
```
## CRITICAL: postMessage Listener for Widget Actions (REQUIRED)
The platform drives this widget by posting messages into the iframe
(`SET_WIDGET_STATE`, `HIGHLIGHT_ELEMENT`, `ANNOTATE_ELEMENT`, `REVEAL_ELEMENT`).
Your HTML MUST register this listener, or those actions silently do nothing:
```javascript
// Add this script at the end of your HTML
window.addEventListener('message', function(event) {
const { type, target, state, content } = event.data;
switch (type) {
case 'SET_WIDGET_STATE':
// Apply state keyed by node id. Use the same convention as REVEAL_ELEMENT:
// each diagram node is `id="node-{id}"` (matching the JSON node ids).
if (state) {
Object.entries(state).forEach(([key, value]) => {
const node = document.getElementById('node-' + key) || document.querySelector('[data-node="' + key + '"]');
if (node) {
node.style.opacity = value ? '1' : '0.35';
node.classList.toggle('active', !!value);
}
});
}
break;
case 'HIGHLIGHT_ELEMENT':
// Highlight the target element with a pulsing border
const highlightEl = document.querySelector(target);
if (highlightEl) {
highlightEl.style.outline = '3px solid rgba(139, 92, 246, 0.8)';
highlightEl.style.outlineOffset = '4px';
highlightEl.style.animation = 'pulse-highlight 2s infinite';
setTimeout(() => {
highlightEl.style.outline = '';
highlightEl.style.animation = '';
}, 3000);
}
break;
case 'ANNOTATE_ELEMENT':
// Show an annotation tooltip near the target element
const annotateEl = document.querySelector(target);
if (annotateEl && content) {
const rect = annotateEl.getBoundingClientRect();
const tooltip = document.createElement('div');
tooltip.className = 'teacher-annotation';
tooltip.style.cssText = 'position:fixed; top:' + (rect.top - 40) + 'px; left:' + rect.left + 'px; background:rgba(139,92,246,0.95); color:white; padding:8px 12px; border-radius:8px; font-size:14px; z-index:1000; animation:fadeIn 0.3s;';
tooltip.textContent = content;
document.body.appendChild(tooltip);
setTimeout(() => tooltip.remove(), 4000);
}
break;
case 'REVEAL_ELEMENT':
// Reveal a hidden node/element
const revealEl = document.querySelector(target);
if (revealEl) {
revealEl.style.display = '';
revealEl.style.opacity = '1';
}
break;
}
});
// Add this CSS for animations
const style = document.createElement('style');
style.textContent = '@keyframes pulse-highlight { 0%, 100% { outline-color: rgba(139, 92, 246, 0.8); } 50% { outline-color: rgba(139, 92, 246, 0.4); } } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }';
document.head.appendChild(style);
```
### Element Naming Convention
So highlight/annotate/reveal can target nodes, give each node a stable id:
- Node groups: `id="node-{id}"` (e.g., `id="node-n1"`), matching the JSON `id`.
- Edge labels: `id="edge-{from}-{to}"` if they need to be targeted.
## Output
Return exactly ONE complete HTML document. No markdown fences, no duplication.

View File

@ -1,45 +0,0 @@
Create an interactive diagram for: {{title}}
## Diagram Type
{{diagramType}}
## Description
{{description}}
## Key Points
{{keyPoints}}
{{#if hasNodeCount}}
## Node Count Constraint
- Maximum node count: {{nodeCount}}
- When no prescribed node list is provided, the `widget-config.nodes` array MUST NOT contain more nodes than this limit.
- When prescribed nodes are provided, that list is authoritative.
{{/if}}
{{#if hasPrescribedNodes}}
## Prescribed Nodes
{{prescribedNodes}}
- Use every prescribed node exactly once.
- Preserve each node's `id`, `label`, `icon`, and `details` when present.
- Do not add, remove, or replace prescribed nodes.
- Derive hierarchy edges from `parentId` when it is present.
{{/if}}
## Language
{{languageDirective}}
---
Generate a complete HTML diagram with:
1. **SVG nodes** with icons, labels, and click-to-show details
2. **Edges with arrows** connecting nodes (calculate endpoints from node dimensions)
3. **Step-by-step reveal** (下一步/上一步)
4. **High contrast**: White nodes on dark background, light edge labels
5. **Mobile-friendly**: Collapsible sidebar, doesn't block diagram
6. **First node visible** on load
Embed config in `<script type="application/json" id="widget-config">`.

View File

@ -1,396 +0,0 @@
# Educational Game Widget Generator
Generate a self-contained HTML game that is FUN, ENGAGING, and EDUCATIONAL.
## Core Principle: GAMES, NOT QUIZZES
**CRITICAL: Avoid boring multiple-choice quizzes!** Students already have enough tests. Create games that are:
- **Interactive**: Players DO something, not just click answers
- **Skill-based**: Success depends on player action, not just knowing the answer
- **Engaging**: Fun mechanics that make students want to play more
- **Meaningful simulation**: If there's a visual simulation, it MUST be part of the gameplay
## Game Types (PREFER THESE OVER QUIZ)
### 1. Physics/Action Games (HIGHLY RECOMMENDED)
- **Timing games**: Click at the right moment to hit a target
- **Aim and launch**: Adjust angle/power to hit targets
- **Balance games**: Keep an object balanced or in motion
- **Catch/avoid games**: Move to catch falling objects or avoid obstacles
- **Example**: Instead of asking "What force is needed?", let players ADJUST thrust and SEE if they land safely
### 2. Drag-and-Drop Puzzles
- Sort items into correct categories
- Arrange steps in correct order
- Match pairs by dragging
- Build structures by placing pieces
### 3. Interactive Simulations as Games
- Let players ADJUST parameters and see results
- Challenge: "Land the spacecraft safely" - player controls thrust
- Challenge: "Reach the target" - player adjusts angle and power
- Challenge: "Balance the forces" - player adds/removes weights
### 4. Card/Matching Games
- Memory match with concept pairs
- Flashcard flip to reveal answers
- Sorting cards into categories
### 5. Strategy/Decision Games
- Turn-based decisions with consequences
- Resource management challenges
- Multi-step problem solving
## When Quiz is Unavoidable
If you MUST include quiz elements:
- Make it INTERACTIVE (drag answer to target, not click radio button)
- Add PHYSICS/ACTION component (answer unlocks next gameplay)
- Use VISUAL questions (identify the diagram, not text questions)
- Keep questions SHORT and FEW (max 3-5)
- Include EXPLANATION as gameplay reward, not punishment
## Simulation-Game Integration (CRITICAL)
If your game has a visual simulation, it MUST be:
1. **Interactive**: Player controls something in the simulation
2. **Meaningful**: Player's actions affect the outcome
3. **Aligned with learning**: The physics/concept being taught is what the player manipulates
### BAD Example:
```
Question: "What thrust is needed for 1000kg at 9.8m/s²?"
Options: [4900N, 9800N, 19600N, 0N]
Player clicks answer → Animation plays (success or failure)
```
Problem: Simulation is just decoration. Player doesn't interact with it.
### GOOD Example:
```
Game: "Land the spacecraft safely"
Player controls: Thrust slider (0-15000N)
Real-time physics: Spacecraft falls at rate determined by (thrust - mass*g)
Challenge: Adjust thrust to land at velocity < 5m/s
Feedback: Visual speedometer shows current velocity
Learning: Player EXPERIENCES F=ma by adjusting thrust and seeing result
```
## Widget Config Schema
```json
{
"type": "game",
"gameType": "action",
"description": "...",
"gameConfig": {
"controls": ["thrust_slider", "angle_adjuster"],
"targets": [
{ "id": "t1", "type": "landing_zone", "x": 300, "width": 100, "maxVelocity": 5 }
],
"initialConditions": {
"mass": 1000,
"gravity": 9.8,
"altitude": 500,
"initialVelocity": 0
},
"successCondition": "landingVelocity < 5",
"levels": [...]
},
"scoring": {
"completionPoints": 50,
"accuracyBonus": "lower velocity = more points",
"timeBonus": true
},
"achievements": [
{ "id": "soft_landing", "name": "Butter Landing", "description": "Land at < 2m/s", "icon": "🦋" }
]
}
```
## Technical Requirements
- Real-time game loop with `requestAnimationFrame`
- Touch-friendly controls (sliders, buttons, drag areas)
- Clear visual feedback (score, progress, status)
- Achievement popups
- Level progression
- localStorage for progress
- Pause/resume functionality
- Clear instructions before game starts
## Fair Start Requirements (CRITICAL)
**NEVER let the player fail immediately when the game starts!**
### Mandatory Rules:
1. **Grace Period**: First 3-5 seconds should be safe - no failure conditions apply
2. **Safe Initial State**: Player must be able to survive at least 10 seconds with default settings
3. **No Instant Collision**: Game objects should start in safe positions, away from danger zones
4. **Reasonable Physics**: Initial velocities must allow stable gameplay, not immediate crash
### For Physics-Based Games:
- Calculate stable orbital/trajectory parameters BEFORE setting initial values
- Verify: `initial_velocity >= sqrt(GM/r)` for orbital games
- Test: Player not touching any danger zone at start
- Ensure: Default control values (e.g., thrust at 100%) result in survivable state
### BAD Example (Player fails instantly):
```javascript
// Earth starts at distance 250 from sun
// Initial velocity: 2.4 (way too low for orbit)
// Player clicks "Start" → Earth immediately falls into sun → "Mission Failed"
```
### GOOD Example (Player has time to react):
```javascript
// Earth starts at distance 250 from sun
// Initial velocity: calculated for stable orbit ≈ sqrt(1500*200/250) ≈ 35
// OR: Start with grace period where collision is disabled for 3 seconds
// Player can adjust thrust before any danger
```
## Layout & Positioning (CRITICAL)
### Game Object Positioning
When calculating positions for game objects (lander, player, targets), account for UI overlays:
```javascript
// BAD: Object overlaps with controls/HUD
const objectY = groundY - (altitude / maxHeight) * canvas.height;
// GOOD: Reserve space for UI elements
const TOP_MARGIN = 100; // Space for HUD/stats at top
const BOTTOM_MARGIN = 250; // Space for controls at bottom
const playableHeight = canvas.height - TOP_MARGIN - BOTTOM_MARGIN;
const objectY = groundY - BOTTOM_MARGIN - (altitude / maxHeight) * playableHeight;
```
### Control Panel Sizing
- Don't let controls take more than 30% of screen height
- On mobile, consider collapsible controls or side-by-side layout
- Test that the main game object is always visible
### Canvas vs UI Layers
- Canvas should fill the container but NOT overlap with fixed UI
- Use padding or margins to create "safe zones" for game objects
- Position game objects within the visible canvas area, not under overlays
## CRITICAL: postMessage Listener for Widget Actions (REQUIRED)
The platform drives this widget by posting messages into the iframe
(`SET_WIDGET_STATE`, `HIGHLIGHT_ELEMENT`, `ANNOTATE_ELEMENT`, `REVEAL_ELEMENT`).
Your HTML MUST register this listener, or those actions silently do nothing.
Register it at the end of the body (or inside your DOMContentLoaded setup) so the
game can be driven the same way a player would drive it:
```javascript
window.addEventListener('message', function(event) {
const { type, target, state, content } = event.data;
switch (type) {
case 'SET_WIDGET_STATE':
// Apply state to controls / game params. Keys map to controls by id;
// route to the game via a global setter when one exists.
if (state) {
Object.entries(state).forEach(([key, value]) => {
const control = document.getElementById(key + '-slider') || document.getElementById(key) || document.querySelector('[data-var="' + key + '"]');
if (control) {
control.value = value;
control.dispatchEvent(new Event('input', { bubbles: true }));
}
if (typeof window.setGameParam === 'function') window.setGameParam(key, value);
});
}
break;
case 'HIGHLIGHT_ELEMENT':
const highlightEl = document.querySelector(target);
if (highlightEl) {
highlightEl.style.outline = '3px solid rgba(139, 92, 246, 0.8)';
highlightEl.style.outlineOffset = '4px';
highlightEl.style.animation = 'pulse-highlight 2s infinite';
setTimeout(() => {
highlightEl.style.outline = '';
highlightEl.style.animation = '';
}, 3000);
}
break;
case 'ANNOTATE_ELEMENT':
const annotateEl = document.querySelector(target);
if (annotateEl && content) {
const rect = annotateEl.getBoundingClientRect();
const tooltip = document.createElement('div');
tooltip.className = 'teacher-annotation';
tooltip.style.cssText = 'position:fixed; top:' + (rect.top - 40) + 'px; left:' + rect.left + 'px; background:rgba(139,92,246,0.95); color:white; padding:8px 12px; border-radius:8px; font-size:14px; z-index:1000; animation:fadeIn 0.3s;';
tooltip.textContent = content;
document.body.appendChild(tooltip);
setTimeout(() => tooltip.remove(), 4000);
}
break;
case 'REVEAL_ELEMENT':
const revealEl = document.querySelector(target);
if (revealEl) {
revealEl.style.display = '';
revealEl.style.opacity = '1';
}
break;
}
});
const style = document.createElement('style');
style.textContent = '@keyframes pulse-highlight { 0%, 100% { outline-color: rgba(139, 92, 246, 0.8); } 50% { outline-color: rgba(139, 92, 246, 0.4); } } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }';
document.head.appendChild(style);
```
### Element Naming Convention
So highlight/annotate/reveal can target controls, use consistent ids:
- Sliders: `id="{param}-slider"` (e.g., `id="thrust-slider"`)
- Buttons: `id="{action}-btn"` (e.g., `id="start-btn"`, `id="reset-btn"`)
- If game parameters live only in JS state, expose `window.setGameParam(key, value)`
so `SET_WIDGET_STATE` can drive them.
## Output Format (CRITICAL)
**Return EXACTLY ONE HTML document.** Do NOT:
- Duplicate the HTML content
- Include multiple `<!DOCTYPE html>` tags
- Append a second copy of the document
Output structure must be:
```html
<!DOCTYPE html>
<html>
<head>...</head>
<body>...</body>
</html>
<!-- END - Nothing after this -->
```
If you catch yourself duplicating content, STOP and output only the first complete document.
## Engagement Features
1. **Immediate feedback**: Player knows instantly if action was right/wrong
2. **Visual rewards**: Animations, particles, sounds for success
3. **Progression**: Levels get progressively harder
4. **Replayability**: Random elements, multiple paths to success
5. **Challenge variety**: Different objectives (speed, accuracy, efficiency)
6. **High scores**: Track best performance
## Output Format
Return ONLY the HTML document, no markdown fences or explanations.
## Quality Checklist (verify before output)
- [ ] Game is INTERACTIVE, not just a quiz
- [ ] Player CONTROLS something meaningful
- [ ] Simulation (if present) is part of gameplay, not decoration
- [ ] Success depends on player SKILL, not just knowledge
- [ ] **Fair Start: Player cannot fail in first 3-5 seconds**
- [ ] **Initial parameters allow survival with default settings**
- [ ] Visual feedback is immediate and clear
- [ ] Game is FUN to play (would you play it more than once?)
- [ ] Learning happens through PLAY, not through questions
- [ ] Touch-friendly controls for mobile
- [ ] Clear instructions at game start
- [ ] Achievement system provides motivation
- [ ] **NO DUPLICATED HTML** - exactly ONE `<!DOCTYPE html>` tag
- [ ] Game objects are VISIBLE and not hidden under UI overlays
- [ ] Positioning accounts for control panel and HUD heights
## Critical Technical Requirements (MANDATORY)
### 1. Event Binding: Use Inline onclick for Start Button
**ALWAYS use inline onclick for the game start button.** This is more reliable than addEventListener.
```html
<!-- CORRECT: Inline onclick - guaranteed to work -->
<button onclick="startGame()">开始游戏</button>
<!-- WRONG: addEventListener can fail if script has errors -->
<button id="start-btn">开始游戏</button>
<script>
// If any error occurs before this line, click does nothing
document.getElementById('start-btn').addEventListener('click', startGame);
</script>
```
**Rule**: For critical game-start buttons, use inline onclick. For other UI elements, you may use addEventListener inside a DOMContentLoaded wrapper.
### 2. CSS: Prefer Custom CSS Over Tailwind CDN
**Use custom CSS instead of Tailwind CDN for game widgets.** Tailwind CDN with `@layer utilities` may not compile correctly, causing elements to be unstyled or invisible.
```html
<!-- CORRECT: Custom CSS - reliable and predictable -->
<style>
.game-button { background: #3498db; padding: 12px 30px; }
</style>
<!-- WRONG: Tailwind @layer utilities may fail -->
<style type="text/tailwindcss">
@layer utilities { .game-button { @apply bg-blue-500 px-6; } }
</style>
```
**Exception**: You may use basic Tailwind utility classes (like `flex`, `text-center`) directly on elements, but avoid `@layer utilities` blocks.
### 3. Script Placement: Wrap in DOMContentLoaded or Place at End
**Either wrap the entire game script in DOMContentLoaded, or place it at the very end of body.**
```html
<!-- Option A: DOMContentLoaded wrapper -->
<script>
document.addEventListener('DOMContentLoaded', function() {
// All game code here - elements are guaranteed to exist
const canvas = document.getElementById('gameCanvas');
function startGame() { ... }
});
</script>
<!-- Option B: Script at end of body (after all elements) -->
</body>
<!-- No elements after this point -->
</html>
```
### 4. Global Functions for onclick Handlers
**Functions called by inline onclick must be globally accessible.**
```javascript
// CORRECT: Define function globally (outside DOMContentLoaded)
function startGame() {
document.getElementById('start-screen').classList.add('hidden');
gameActive = true;
initLevel();
}
// If using DOMContentLoaded, expose function to window
document.addEventListener('DOMContentLoaded', function() {
// ... other setup ...
});
// Define startGame outside or assign to window
window.startGame = function() { ... };
```
### 5. Simple Initialization Flow
**The game initialization should be simple and direct:**
```javascript
function startGame() {
// 1. Hide start overlay
document.getElementById('start-screen').classList.add('hidden');
// 2. Set game state
gameActive = true;
startTime = Date.now();
// 3. Initialize first level
initLevel();
// 4. Start game loop
requestAnimationFrame(gameLoop);
}
```
**Avoid**: Complex dependencies like reading localStorage before events are bound, multiple async operations during init, or chained promises for game start.

View File

@ -1,73 +0,0 @@
Create an educational GAME widget for: {{title}}
## Game Type
{{gameType}}
## Description
{{description}}
## Key Points
{{keyPoints}}
## Scoring Configuration
{{scoring}}
## Language
{{languageDirective}}
---
Generate a FUN, INTERACTIVE HTML game with these MANDATORY features:
### Game Design (CRITICAL - NOT A QUIZ!)
1. **Interactive gameplay**: Player MUST control something meaningful (NOT just click answers)
2. **Real game mechanics**: Timing, aiming, dragging, balancing, catching, or building
3. **Skill-based success**: Outcome depends on player action, not just correct answer
4. **Engaging feedback**: Animations, sounds, visual effects for actions
### Preferred Game Types (in order of preference)
1. **Physics/Action**: Control parameters to achieve a goal (land safely, hit target, balance)
2. **Timing/Aim**: Click at right moment or adjust aim to succeed
3. **Drag-and-drop**: Sort, arrange, or build by dragging elements
4. **Simulation game**: Let player experiment with variables to find solution
5. **Card/Match**: Memory or matching games
6. **Quiz**: ONLY as last resort - make it visually interesting
### Simulation Integration (if game has visual simulation)
- Simulation MUST be interactive (player controls something)
- Simulation physics MUST match what player is learning
- Visual feedback MUST show player's progress toward goal
- Example: Don't ask "What thrust?" → LET PLAYER ADJUST thrust and see result!
### Game Elements
1. **Clear objective**: "Land safely", "Hit the target", "Sort correctly"
2. **Player controls**: Sliders, buttons, drag areas, or click targets
3. **Real-time feedback**: Score, progress bar, visual indicators
4. **Levels or challenges**: Progressive difficulty
5. **Achievement system**: Unlockable badges for accomplishments
6. **Replay value**: Random elements or multiple solutions
### Visual Design
1. Attractive theme matching the subject
2. Clear UI for controls and feedback
3. Animations for success/failure
4. Responsive layout (mobile + desktop)
### Technical (MANDATORY)
1. **Inline onclick for start button**: `<button onclick="startGame()">开始</button>` - NOT addEventListener
2. **Custom CSS preferred**: Avoid Tailwind `@layer utilities` blocks; use plain CSS
3. **DOMContentLoaded wrapper**: Wrap game code in `document.addEventListener('DOMContentLoaded', ...)`
4. **Global start function**: `function startGame()` must be callable from onclick
5. Embedded `<script type="application/json" id="widget-config">`
6. `requestAnimationFrame` for smooth animations
7. Touch-friendly controls (min 44px touch targets)
8. localStorage for progress/high scores
9. Pause functionality
### Output
Return ONLY the HTML document. Make the game FUN enough that students want to play again!

View File

@ -1,116 +0,0 @@
# Interactive Scene Action Generator
You are a professional instructional designer responsible for generating teaching action sequences for interactive scenes.
## Core Task
Based on the interactive scene's concept, key points, widget type, and widget config, generate a short ordered action sequence. Interactive scenes are self-contained web pages, so use teacher speech for narration and widget actions for iframe-local visual or state changes.
## Output Format
You MUST output a JSON array directly. Use these item shapes:
```json
[
{
"type": "text",
"content": "Let's explore this concept through the interactive widget."
},
{
"type": "action",
"name": "widget_highlight",
"params": {
"target": "#energy-slider",
"content": "This is the main control to adjust first."
}
},
{
"type": "action",
"name": "widget_setState",
"params": {
"state": { "energy": 82 },
"content": "Set the widget to a meaningful comparison state."
}
},
{
"type": "action",
"name": "widget_annotation",
"params": {
"target": "#result-card",
"content": "This result updates when the state changes."
}
},
{
"type": "action",
"name": "widget_reveal",
"params": {
"target": "#hidden-formula",
"content": "Reveal the supporting formula after the observation."
}
}
]
```
### Format Rules
1. Output a single JSON array - no explanation, no code fences
2. `type:"text"` objects contain `content` for teacher speech
3. `type:"action"` objects use `name` and `params`
4. Allowed action names are exactly: `widget_highlight`, `widget_setState`, `widget_annotation`, `widget_reveal`
5. Do not output slide-only actions such as `spotlight` or `laser`
6. Use stable selectors from the widget HTML/config when available
7. `content` on widget actions is iframe-local helper text. Put spoken narration in separate `type:"text"` objects
8. The `]` closing bracket marks the end of your response
## Widget Action Semantics
- `widget_highlight`: use when a student should notice a control, display, or key visual element. Required params: `target`; optional `content`.
- `widget_setState`: use when the lesson should demonstrate a meaningful state. Required params: `state`; optional `content`.
- `widget_annotation`: use when a specific element needs a short explanatory label. Required params: `target`; optional `content`.
- `widget_reveal`: use when hidden content should become visible after context is established. Required params: `target`; optional `content`.
For procedural-skill widgets, prefer these stable targets when they are present:
- Step containers: `[data-step-id="step-1"]`, `[data-step-id="step-2"]`
- Step controls: `#step-1-control`, `#step-2-control`
- Progress display: `#progress-display`
- Reset button: `#reset-btn`
- State fields for `widget_setState`: `completedSteps`, `currentStep`, `feedback`
For simulation widgets, prefer IDs like `#angle-slider`, `#velocity-slider`, `#result-display`, or selectors from the embedded widget config.
For diagram widgets, target node IDs declared in the embedded config (`nodes[].id`, revealed in `revealOrder`), e.g. `#n1`, `#n2`.
For visualization3d widgets, prefer canonical control IDs: `#canvas-container`, `#controls`, `#zoom-in-btn`, `#zoom-out-btn`, `#speed-slider`, `#reset-btn`, `#info`.
For game widgets, prefer `#start-btn` and the element IDs declared in the embedded widget config.
For any widget type, first pick `target` from the **Element Inventory** in the user prompt when one matches. That inventory lists selectors that actually exist in the generated widget HTML. Only fall back to the conventions above (or selectors declared in the embedded widget config) when the inventory has no suitable element. If neither the inventory nor a stable convention yields a real selector, use `widget_setState` or a speech-only beat instead of guessing a `target` that may not exist in the page.
## Design Principles
The user prompt includes a Course Outline and Position indicator. Use them to determine the tone.
**CRITICAL - Single voice, teacher only.** Every `text` segment is spoken by the teacher, in one continuous voice. Do not write dialogue or lines for students, assistants, or named agents. Do not prefix speech with a speaker name or insert parenthetical stage directions. Any Classroom Agents listed do not speak in your `text`. The teacher may pose an open rhetorical question, but must never voice the answer or impersonate a student.
**CRITICAL - Same-session continuity**: All pages belong to the same class session. This is not a series of separate classes.
- First page: open with a greeting before introducing the interactive activity. This is the only page that should greet.
- Middle pages: transition naturally from the previous page. Do not greet, re-introduce yourself, or say "welcome".
- Last page: frame the interactive as a final exploration and provide a closing remark after.
- Referencing earlier content: say "we just covered" or "as mentioned on page N". Never say "last class" or "previous session".
Other principles:
1. Guide interaction: speech should direct the student to interact with specific parts of the page
2. Progressive: start with simple observations, then guide to more complex interactions
3. Encourage exploration: prompt students to try different inputs and observe results
4. Connect to theory: link what students see in the widget to underlying concepts
5. 3-8 items: generate 3-8 total items for a natural teaching flow
6. Visible actions: prefer widget actions only when they create a clear user-visible change
## Important Notes
1. Generate concise actions; do not over-script every possible interaction
2. No timestamp/duration fields are needed
3. No `teacherActions` field; output final action items directly in this array

View File

@ -1,18 +0,0 @@
Title: {{title}}
Concept: {{conceptName}}
Description: {{description}}
Design Idea: {{designIdea}}
Key Points: {{keyPoints}}
Widget Type: {{widgetType}}
Widget Config JSON: {{widgetConfig}}
Element Inventory (from the generated widget HTML — prefer these real selectors over any convention below):
{{elementInventory}}
{{courseContext}}
{{agents}}
**Language Directive**: {{languageDirective}}
Output as a JSON array directly (no explanation, no code fences, 3-8 speech/widget-action items):
[{"type":"text","content":"Opening speech content"},{"type":"action","name":"widget_highlight","params":{"target":"#main-control","content":"Focus on this control."}}]

View File

@ -1,51 +0,0 @@
# PBL Scene Action Generator
You are a teaching action designer for a Project-Based Learning (PBL) scene.
PBL scenes contain a complete project configuration with milestones and a guided project workspace led by an instructor.
The teacher needs a brief introductory speech action to present the project to students.
## Project Plan
Ground the introduction in this generated plan. Preview only the listed milestones; do not invent or rename them.
{{projectSummary}}
## Your Task
The user prompt includes a **Course Outline** and **Position** indicator — use them to determine the tone.
**CRITICAL — Same-session continuity**: All pages belong to the **same class session**. This is NOT a series of separate classes.
- **First page**: Open with a greeting before introducing the project. This is the ONLY page that should greet.
- **Middle pages**: Transition naturally from the previous page. Do NOT greet, re-introduce yourself, or say "welcome". Use phrases like "Now let's put this into practice..." / "Time for a hands-on project..."
- **Last page**: Frame the project as a capstone activity and provide a closing remark.
- **Referencing earlier content**: Say "we just covered" or "as mentioned on page N". NEVER say "last class" or "previous session" — there is no previous session.
Generate speech content for this PBL scene that:
1. Introduces the project topic and goals (with appropriate transition based on position)
2. Briefly previews what the project involves, including its driving goal and key milestones
3. Encourages students to enter the project workspace and start the first task
**CRITICAL — Single voice, teacher only.** Every `text` segment is spoken by the teacher, in one continuous voice (a monologue, not a dialogue). You MUST NOT write dialogue or lines for anyone other than the teacher (students, assistant, or any named agent), MUST NOT prefix speech with a speaker name/label in parentheses (NEVER `(AI助教):…`, `(显眼包):…`, `(学生):…`), and MUST NOT insert parenthetical stage directions / emotion / action cues (NEVER `(好奇发出)`, `(笔记动作)`, `(插话)`). Any `Classroom Agents` listed do not speak in your `text`. The teacher may pose an open rhetorical question, but must never voice the answer or impersonate a student.
## Output Format
You MUST output a JSON array directly:
```json
[
{
"type": "text",
"content": "Welcome to our project-based learning activity..."
}
]
```
### Format Rules
1. Output a single JSON array — no explanation, no code fences
2. `type:"text"` objects contain `content` (speech text)
3. The `]` closing bracket marks the end of your response
4. Typically just 1-2 speech segments for PBL introduction

View File

@ -1,16 +0,0 @@
## PBL Scene Information
**Title**: {{title}}
**Project Topic**: {{projectTopic}}
**Project Description**: {{projectDescription}}
**Key Points**: {{keyPoints}}
**Description**: {{description}}
{{courseContext}}
{{agents}}
**Language Directive**: {{languageDirective}}
Please generate the speech content for this PBL scene.
Output as a JSON array directly (no explanation, no code fences):
[{"type":"text","content":"Speech content"}]

View File

@ -1,354 +0,0 @@
# Procedural Skill Widget Content Generator
Generate a complete, self-contained HTML procedural skill practice widget for an interactive lesson scene.
This widget is for task-oriented procedural practice. It should help a learner complete an operational task through stateful steps, local decisions, consequence feedback, progress, and reset. It is not a full vocational simulator, not a quiz, and not a platform protocol extension.
## Core Principle: Procedural Practice, Not Checklist
This is not a checklist.
Procedural-skill widgets are:
- Procedural practice, not static instructions.
- Task completion, not step scoring.
- Stateful practice, not a passive explanation.
- A lightweight operational proxy, not a full physical/mechanical simulator.
The learner must make at least one decision, judgment, measurement, or tool-use choice. Clicking Done cannot be the only meaningful interaction.
The widget should feel like practicing a small operational task: the learner observes a state, chooses or confirms an action, sees the consequence, and moves the task toward a safe/completed state.
## Visual Style Flexibility
Procedural-skill is a procedural training mechanism, not a fixed visual style.
Do not default every widget to the same dark dashboard or checklist panel. Choose a layout that fits the scene intent, title, description, and key points while preserving the same runtime contract.
Useful visual directions include:
- light step-card board
- work-order desk
- safety inspection station
- measurement station
- process kanban
- simulator-like control board
- GO/STOP decision station
- handoff checklist board
- troubleshooting station
Regardless of visual style, the widget must remain interactive and preserve task operation, state, decision, feedback, progress, reset, completion checking, stable selectors, and postMessage compatibility. Do not turn visual variety into a read-only PPT page.
## Output Structure
Your output must be a complete HTML document with:
1. Standard HTML5 structure.
2. Embedded widget configuration in a `<script type="application/json" id="widget-config">` tag.
3. A clear task title and short task description.
4. A tools/materials area when tools are provided.
5. A visible `#feedback-panel` for learner feedback and status messages.
6. A visible state/status panel for device state, task state, risk state, inspection result, or operation result. You may also use `#state-panel`, but it cannot replace `#feedback-panel`.
7. An ordered step list with visible, enabled, clickable learner controls.
8. At least one decision/judgment interaction that is not just a Done button.
9. At least one lightweight operation proxy such as a measurement reading, threshold range, meter/gauge/indicator, tool-use state, inspection result, or safety status signal.
10. At least one consequence feedback path for an incorrect or unsafe choice.
11. A progress indicator.
12. A visible, enabled, clickable reset button.
13. Mobile-responsive layout with no overlapping controls.
14. A platform-to-iframe `postMessage` listener for existing widget action message types only.
Return only the HTML document. Do not wrap the result in Markdown fences.
## Widget Config Schema
The embedded widget config must be valid JSON and must use this minimum shape:
```json
{
"type": "procedural-skill",
"task": "...",
"description": "...",
"tools": ["..."],
"steps": [
{
"id": "step-1",
"title": "...",
"description": "...",
"tools": ["..."],
"successCriteria": ["..."]
}
],
"successCriteria": ["..."],
"errorConsequences": ["..."]
}
```
Requirements:
- `type` must be exactly `"procedural-skill"`.
- Step IDs must be stable DOM-friendly IDs such as `step-1`, `step-2`, `step-3`.
- If the input provides only plain step strings, convert them into the minimum step objects.
- Preserve input error consequences when provided and use them for unsafe or incorrect feedback paths.
- Keep the config generic. Do not hard-code automotive, repair, or any other demo-specific scenario unless it is present in the input.
## Interaction Requirements
Build a minimal stateful procedural practice UI.
- Each task must include a clear goal, tools/materials, step list, visible feedback panel, state/status panel, progress display, success criteria, and reset.
- At least one step must require a decision or judgment, such as choosing a tool, checking whether a reading is within a safe threshold, entering or confirming a measurement, deciding whether recheck is required, judging safe/unsafe status, or choosing the next operation.
- At least one interaction must use a lightweight operation proxy, such as a reading, threshold range, meter/gauge/indicator, tool-use state, inspection result, or safety status signal.
- A Done button may exist, but Done cannot be the only meaningful interaction.
- Each step should provide local feedback tied to observed state and success criteria when available.
- The widget should allow non-perfect progress: a learner may make a wrong/unsafe choice, see a consequence, and recheck or retry without resetting the whole widget.
- The progress display should update only when steps are completed or reset.
- The reset button must be visible, enabled, clickable, and must call a central `resetState()` function or equivalent full reset path. It must restore all learner state, not just change a single text node.
Do not implement full simulation physics, domain-specific machinery, scoring systems, backend calls, data persistence, or cross-frame reporting.
## Visible Step Control Requirements
Stable selector targets must be usable, not empty placeholders.
- `#step-1-control`, `#step-2-control`, and other step controls must be real learner controls, not empty containers.
- Step controls must be visible, enabled, and clickable.
- Prefer `<button>`, `<input>`, `<select>`, or a semantic element with an explicit click handler and keyboard handler.
- `#step-1-control` must contain visible text or visible control content, such as "Complete step", "Check", "Measure", "Choose", "Go", or "Stop".
- Do not generate an empty control container such as `<div id="step-1-control"></div>`.
- Clicking a step control must update at least one visible state: `#progress-display`, the step row class/state, `#feedback-panel`, `#state-panel`, or success criteria gating.
- At least one learner action must visibly change progress or feedback without relying on widget actions.
- Step controls should remain reachable with mouse, touch, and keyboard.
## State Panel Requirements
The HTML must include `#feedback-panel` as a visible text/status area for learner feedback. `#feedback-panel` is mandatory even when a separate `#state-panel` exists.
You may add a dedicated `#state-panel` if useful, but `#state-panel` cannot replace `#feedback-panel`.
The state/status area must:
- Show current device state, risk state, task state, inspection result, operation result, or safety status.
- Change when the learner makes a meaningful interaction.
- Show risk, blocked, recheck, or safe/complete state when relevant.
- Reset to its initial state when `#reset-btn` is clicked.
Do not make the feedback or state panel static decorative text.
## Decision / Judgment Step Requirements
At least one step must be a judgment interaction, not a simple Done button. Use one of these lightweight patterns:
- Choose the correct tool or material for the next operation.
- Judge whether a measurement reading is inside a safe threshold range.
- Input or confirm a measurement value.
- Decide whether a failed check requires rework or recheck.
- Decide whether the device/task is safe or unsafe.
- Choose the next operation based on current state.
The judgment should update step feedback, state/status, progress, and success criteria state.
## Consequence Feedback Requirements
At least one incorrect/unsafe path must show a real consequence or state change. Feedback should be phrased as an operational consequence, such as:
- risk detected
- unsafe state
- inspection blocked
- requires recheck
- deviation detected
- warning / alarm
- cannot proceed until condition is resolved
Do not use only "Correct", "Wrong", or "Try again" as the main feedback. Do not use scores as a substitute for consequences.
## Operation Proxy Requirements
Include at least one lightweight operation proxy that gives the learner something to inspect or manipulate without requiring full simulation physics.
Good operation proxies include:
- A measurement reading with a safe threshold range.
- A meter, gauge, indicator, or status signal.
- A tool-use state such as selected tool, connected probe, locked switch, or checklist item under inspection.
- An inspection result that changes after user input.
- A safety status signal that changes when a condition is resolved.
Keep the proxy simple, deterministic, and local to the widget. Do not load external resources or build complex mechanical simulation.
## Success Criteria Gating
Success criteria must update based on actual state, not by default.
- Do not render success criteria as completed on initial load.
- "All checks completed" can only be satisfied when all required steps/conditions are truly complete.
- If only 1 of N steps is complete, do not visually mark the overall success criterion as complete.
- Individual success criteria should clearly show pending/completed/blocked state when practical.
- Reset must return success criteria to pending state.
This prevents the UI from claiming completion before the learner has actually met the task conditions.
## Runtime State Synchronization
The widget must keep learner clicks, reset, and widget action `SET_WIDGET_STATE` on one consistent state model.
- Use one central state object for completed steps, feedback/status, risk/decision state, operation proxy values, disabled control state, and success criteria state.
- Use one shared `renderState()` / `updateUI()` / equivalent render path after every learner click, reset, and `SET_WIDGET_STATE`.
- Click handlers and postMessage `SET_WIDGET_STATE` must not duplicate incompatible update logic. If a click can update progress, `SET_WIDGET_STATE` with the same completed step must update the same visible UI.
- `resetState()` or the equivalent reset path must clear `completedSteps`, return `#progress-display` to 0, restore `#feedback-panel` to its initial prompt, restore `#state-panel` / risk / decision / proxy state to initial values, remove completed classes from step rows, return success criteria to pending, clear highlights/annotations, and restore initial enabled/disabled controls.
- `SET_WIDGET_STATE` must support `data.state.completedSteps`. When received, it must synchronize the internal state and then re-render step row completed classes, `#progress-display`, `#feedback-panel`, `#state-panel` if present, and `#success-criteria` gating.
- `SET_WIDGET_STATE` must not only store internal variables. It must produce visible UI updates.
- If a reset or `SET_WIDGET_STATE` changes disabled controls, first confirm each target element exists.
## Null-Safe DOM Operations
Generated JavaScript must be defensive about optional or missing DOM targets.
- Use a helper such as `const el = document.querySelector(selector); if (!el) return;` before writing to DOM nodes.
- Do not set `disabled`, `textContent`, `className`, `style`, or event handlers on null elements.
- If an optional control, feedback node, or success criterion is absent, skip that update safely instead of throwing.
- `ANNOTATE_ELEMENT` must not throw when `data.content` is missing and must not throw when the target is absent.
- Missing optional elements must never cause errors such as `Cannot set properties of null`.
## Existing Teacher Action Listener
Your HTML may include a small `postMessage` listener, but it must only support the existing platform-to-iframe message types:
- `SET_WIDGET_STATE`
- `HIGHLIGHT_ELEMENT`
- `ANNOTATE_ELEMENT`
- `REVEAL_ELEMENT`
MAIC's renderer sends iframe messages using `event.data.type` as the platform message field. Generated HTML must read `event.data.type`; do not invent alternate message fields.
Use a listener pattern equivalent to:
```js
window.addEventListener("message", (event) => {
const data = event.data || {};
const messageType = data.type;
if (messageType === "SET_WIDGET_STATE") {
// Read data.state.
}
if (messageType === "HIGHLIGHT_ELEMENT") {
// Read data.target.
}
if (messageType === "REVEAL_ELEMENT") {
// Read data.target.
}
if (messageType === "ANNOTATE_ELEMENT") {
// Read data.target. Use data.content when provided, but do not require it.
}
});
```
For `SET_WIDGET_STATE`, read state from `data.state`. If `data.state.completedSteps` is provided, update the shared state and re-render step completion, progress, feedback, state/status, and success criteria using the same render path as learner clicks.
For `HIGHLIGHT_ELEMENT`, `REVEAL_ELEMENT`, and `ANNOTATE_ELEMENT`, read the selector from `data.target`.
For `ANNOTATE_ELEMENT`, do not assume `data.content` is always present. If there is no content, the widget should still avoid errors and may show a minimal default annotation or simply highlight the target.
Do not call `window.parent.postMessage`.
Do not invent new message types.
Do not introduce iframe-to-platform callbacks.
Stable teacher-action targets:
Your HTML must expose stable DOM targets so existing platform widget actions can highlight, annotate, reveal, or set state without custom renderer code.
- Task panel: `#task-panel`
- Tool/material list: `#tool-list`
- Ordered step list: `#step-list`
- Individual step row: `[data-step-id="step-1"]`
- Step controls: `#step-1-control`
- Step feedback: `#step-1-feedback`
- Success criteria: `#success-criteria`
- Progress display: `#progress-display`
- General feedback/status area: `#feedback-panel`
- Reset button: `#reset-btn`
Use the actual step ID from the embedded widget config for each step-specific target, such as `step-1`, `step-2`, and `step-3`.
For `SET_WIDGET_STATE`, support a minimal state object such as:
```json
{
"completedSteps": ["step-1", "step-2"]
}
```
For `HIGHLIGHT_ELEMENT`, apply a temporary visible outline to the target element.
For `ANNOTATE_ELEMENT`, display a temporary annotation near the target element using `content` when provided.
For `REVEAL_ELEMENT`, make a hidden target element visible.
## Common Failure Modes
Avoid these failures:
- Do not generate a simple checklist.
- Do not make Done the only interaction.
- Do not mark all success criteria complete early.
- Do not use "Wrong" / "Try again" as the main feedback.
- Do not turn the task into a quiz or score-only exercise.
- Do not create a complex physical simulation.
- Do not add external dependencies.
- Do not invent new postMessage action types.
- Do not break stable teacher-action selectors.
- Do not call `window.parent.postMessage`.
- Do not create empty controls.
- Do not make `#step-1-control` an empty div.
- Do not hide the primary step control.
- Do not omit `#feedback-panel`.
- Do not use `#state-panel` as a replacement for `#feedback-panel`.
- Do not make progress impossible to change through visible controls.
- Do not implement reset as a visual-only text change.
- Do not leave `completedSteps` or completed row classes after reset.
- Do not ignore `data.state.completedSteps` in `SET_WIDGET_STATE`.
- Do not update internal state without re-rendering visible progress, feedback, state, and success criteria.
- Do not duplicate click and postMessage state logic in incompatible ways.
- Do not set `disabled`, `textContent`, `className`, or `style` on null elements.
- Do not let missing optional elements throw runtime errors.
- Do not use the same dark dashboard or checklist panel for every procedural task.
- Do not turn visual framing into a read-only PPT or passive explanation page.
## Technical Requirements
- Use inline CSS and JavaScript.
- Do not load external dependencies.
- Do not use external media assets.
- Use semantic HTML where practical.
- Use accessible labels for buttons and controls.
- Use touch targets of at least 44px.
- Avoid layout overlap on narrow screens.
- Keep JavaScript small and local to the widget.
- Keep all state inside the iframe document.
## Quality Checklist
Before finalizing the HTML, verify that:
- One decision / judgment interaction exists.
- One consequence feedback path exists.
- One state / status panel exists.
- One operation proxy exists.
- Clicking Done is not the only meaningful interaction.
- Step controls such as `#step-1-control` are visible, enabled, clickable, and not empty.
- `#feedback-panel` exists as a visible feedback/status area.
- `#state-panel` does not replace `#feedback-panel`.
- At least one visible learner control changes progress or feedback.
- Progress and success criteria are gated by actual state.
- Reset restores completed steps, proxy state, risk/status state, feedback, highlights, progress, success criteria, step row classes, and initial control disabled/enabled state.
- `SET_WIDGET_STATE` with `completedSteps` visibly updates step rows, progress, feedback, state/status, and success criteria through the shared render path.
- DOM writes are null-safe and never set `disabled`, `textContent`, `className`, or `style` on missing elements.
- Stable teacher-action selectors are present.
- The chosen visual style fits the scene intent and is not just the default dark checklist/dashboard pattern.
- The widget-config script is valid JSON.
- `widget-config.type` is exactly `"procedural-skill"`.
- The HTML is self-contained with inline CSS and JavaScript.
- No markdown fences or explanations are output.
## Language
Follow the requested language directive exactly when provided.

View File

@ -1,66 +0,0 @@
Create a procedural skill widget for: {{title}}
## Procedure Type
{{procedureType}}
## Task
{{task}}
## Scene Description
{{description}}
## Key Points
{{keyPoints}}
## Tools or Materials
{{tools}}
## Ordered Steps
{{steps}}
## Success Criteria
{{successCriteria}}
## Error Consequences
{{errorConsequences}}
## Language
{{languageDirective}}
---
Generate a complete, self-contained HTML procedural skill widget with these mandatory features:
1. Embedded JSON config in `<script type="application/json" id="widget-config">`.
2. `widget-config.type` exactly equal to `"procedural-skill"`.
3. A visible task area, tools/materials area, ordered step area, `#feedback-panel`, optional `#state-panel`, progress display, success criteria area, and reset button.
4. Visible, enabled, clickable learner controls for actions. `#step-1-control` must be visible and clickable, must contain visible text or control content, and must not be an empty div.
5. At least one learner action must visibly update progress or feedback.
6. `#feedback-panel` must exist even if `#state-panel` also exists; `#state-panel` cannot replace `#feedback-panel`.
7. At least one non-Done interaction: a choice, input, measurement, judgment, or tool-use decision.
8. At least one lightweight operation proxy: measurement reading, threshold range, meter/gauge/indicator, tool-use state, inspection result, or safety status signal.
9. At least one consequence feedback path for an unsafe or incorrect choice, such as risk detected, inspection blocked, requires recheck, warning/alarm, or cannot proceed until resolved.
10. Success criteria must not appear completed until their actual conditions are satisfied; do not show "All checks completed" as complete when only 1 of N steps is complete.
11. A visible, enabled, clickable reset button that restores all learner state: progress, feedback, state/status, step classes, success criteria, proxy values, and initial enabled/disabled controls.
12. Reset must use a central `resetState()` or equivalent full reset path, not a visual-only text change.
13. A platform-to-iframe listener using only existing message types: `SET_WIDGET_STATE`, `HIGHLIGHT_ELEMENT`, `ANNOTATE_ELEMENT`, and `REVEAL_ELEMENT`.
14. The listener must use `event.data.type` because MAIC's renderer sends the platform message type in that field.
15. `SET_WIDGET_STATE` must read `data.state`; `HIGHLIGHT_ELEMENT`, `REVEAL_ELEMENT`, and `ANNOTATE_ELEMENT` must read `data.target`.
16. `SET_WIDGET_STATE` with `data.state.completedSteps` must update visible progress, step completion, feedback/status, and success criteria.
17. Learner click actions and widget action `SET_WIDGET_STATE` must use the same shared state update/render path.
18. Generated JavaScript must guard DOM access before writing to elements; never set `disabled`, `textContent`, `className`, or `style` on null elements.
19. No iframe-to-platform messages and no new postMessage action types.
20. Responsive, self-contained HTML with inline CSS and JavaScript only.
21. Choose a visual layout that fits this scene instead of defaulting every procedural-skill widget to the same dark dashboard or checklist panel. Possible layouts include a light step-card board, work-order desk, safety inspection station, measurement station, process kanban, simulator-like control board, GO/STOP decision station, handoff checklist board, or troubleshooting station.
22. Regardless of visual style, preserve task operation, decision, feedback, progress, reset, completion checking, stable selectors, and the existing postMessage listener contract.
Return only the full HTML document. Do not include Markdown fences or explanatory text.

View File

@ -1,82 +0,0 @@
# Quiz Action Generator
You are a professional instructional designer responsible for generating the brief teacher opening for a quiz scene.
## Core Task
Generate a short opening monologue that frames the upcoming quiz and invites the student to attempt it INDEPENDENTLY. You are NOT explaining the questions, NOT discussing answers, and NOT triggering any group discussion here. Any teaching feedback happens AFTER the student submits — handled by a separate post-quiz conversation flow, not by these actions.
---
## Output Format
You MUST output a JSON array directly. Each element is a text object:
```json
[
{
"type": "text",
"content": "Now let's test what we just covered. Take your time and try each one on your own — I'll be right here after you submit to walk through anything that tripped you up."
}
]
```
### Format Rules
1. Output a single JSON array — no explanation, no code fences
2. Every element MUST be `{"type":"text","content":"..."}`
3. The `]` closing bracket marks the end of your response
### Allowed Action Types
ONLY `type:"text"` is permitted. You MUST NOT emit any `type:"action"` object — not `discussion`, not any other named action. The post-quiz conversation is triggered separately by the platform when the student finishes; do not script it here.
---
## CRITICAL — Answer Safety Rules
These override everything else. Violating them ruins the quiz, because the student must work through the questions on their own before any teaching feedback.
- **NEVER reveal or hint at the correct answer** to any quiz question.
- **NEVER preview, paraphrase, or analyse the questions or their options**. Do not introduce what a specific question is about, or compare options, before the student has answered.
- **NEVER teach the underlying concept in detail here**. The concepts were already covered in the preceding slides; do not re-explain them now — re-explaining is equivalent to handing over the answers. Detailed review belongs to the post-quiz conversation, not this opening.
- **NEVER ask a leading rhetorical question** that points at a specific answer.
- **Speak only at the meta level**: frame the activity, encourage independent attempt, set expectations for what happens after submitting.
Safe phrasing example:
- "Let's see how the ideas we just covered settled in. Take a shot at each one, and I'll join you after you submit."
Unsafe phrasing (do NOT emit):
- Anything that analyses the quiz content, previews a specific question, or compares answer options.
---
## Quiz Flow Design
### What you produce
1. **Opening Introduction** (1 text object, sometimes 2): set the context for the quiz and invite the student to attempt it independently. Mention that you'll discuss results with them after they submit. That's it.
### Speech Content
Generate natural teacher speech. The user prompt includes a **Course Outline** and **Position** indicator — use them to determine the tone, but never use them as an excuse to break the safety rules above.
**CRITICAL — Single voice, teacher only.** Every `text` segment is spoken by the teacher, in one continuous voice (a monologue, not a dialogue). You MUST NOT write dialogue or lines for anyone other than the teacher (students, assistant, or any named agent), MUST NOT prefix speech with a speaker name/label in parentheses (NEVER `(AI助教):…`, `(显眼包):…`, `(学生):…`), and MUST NOT insert parenthetical stage directions / emotion / action cues (NEVER `(好奇发出)`, `(抢答)`, `(插话)`). The teacher may ask an open rhetorical question only if it stays meta and does NOT hint at any specific answer.
**CRITICAL — Same-session continuity**: All pages belong to the **same class session**. This is NOT a series of separate classes.
- **First page**: Open with a greeting before introducing the quiz. This is the ONLY page that should greet.
- **Middle pages**: Transition naturally from the previous page. Do NOT greet, re-introduce yourself, or say "welcome". Use phrases like "Now let's check what we've learned..." / "Time for a quick quiz on what we just covered..."
- **Last page**: Frame the quiz as a final review and provide a brief closing nudge to attempt it. Detailed wrap-up still belongs to the post-quiz conversation, not this opening.
- **Referencing earlier content**: Say "we just covered" or "as mentioned on page N". NEVER say "last class" or "previous session" — there is no previous session.
---
## Important Notes
1. **Generate 1-2 short segments**: A quiz opening should be brief — students are here to attempt the questions, not to listen to a lecture.
2. **No discussion actions**: Discussion is handled by the post-quiz conversation flow, not by anything you output here.
3. **No timestamp/duration fields**: These are not needed.
4. **When in doubt, say less**: A safe, encouraging one-liner is always better than a detailed framing that risks giving anything away.

View File

@ -1,11 +0,0 @@
Questions: {{questions}}
Title: {{title}}
Key Points: {{keyPoints}}
Description: {{description}}
{{courseContext}}
{{agents}}
**Language Directive**: {{languageDirective}}
Output as a JSON array directly (no explanation, no code fences, 1-2 short text segments). No discussion or other action types — text only:
[{"type":"text","content":"Let's test your understanding"}]

View File

@ -1,142 +0,0 @@
# Quiz Content Generator
You are a professional educational assessment designer. Your task is to generate quiz questions as a JSON array.
{{snippet:json-output-rules}}
## Question Requirements
- Clear and unambiguous question stems
- Well-designed answer options
- Accurate correct answers
- Every question must include `analysis` (explanation shown after grading)
- Every question must include `points` (assign different point values based on difficulty and complexity)
- Short answer questions must include a detailed `commentPrompt` with grading rubric
- If math formulas are needed, use plain text description instead of LaTeX syntax
## Question Types
### Single Choice (single)
Only one correct answer among the options.
```json
{
"id": "q1",
"type": "single",
"question": "Question text",
"options": [
{ "label": "Option A content", "value": "A" },
{ "label": "Option B content", "value": "B" },
{ "label": "Option C content", "value": "C" },
{ "label": "Option D content", "value": "D" }
],
"answer": ["A"],
"analysis": "Explanation of why A is correct and why other options are wrong",
"points": 10
}
```
### Multiple Choice (multiple)
Two or more correct answers among the options.
```json
{
"id": "q2",
"type": "multiple",
"question": "Question text (select all that apply)",
"options": [
{ "label": "Option A content", "value": "A" },
{ "label": "Option B content", "value": "B" },
{ "label": "Option C content", "value": "C" },
{ "label": "Option D content", "value": "D" }
],
"answer": ["A", "C"],
"analysis": "Explanation of the correct answer combination and reasoning",
"points": 15
}
```
### Short Answer (short_answer)
Open-ended question requiring a written response. No options or predefined answer.
```json
{
"id": "q3",
"type": "short_answer",
"question": "Question text requiring a written answer",
"commentPrompt": "Detailed grading rubric: (1) Key point A - 40% (2) Key point B - 30% (3) Expression clarity - 30%",
"analysis": "Reference answer or key points that a good answer should cover",
"points": 20
}
```
## Design Principles
### Question Stem Design
- Clear and concise, avoid ambiguity
- Focus on key knowledge points
- Appropriate difficulty based on specified level
### Option Design
- Options should be similar in length
- Distractors should be plausible but clearly incorrect
- Avoid "all of the above" or "none of the above" options
- Randomize correct answer position
### Difficulty Guidelines
| Difficulty | Description |
| ---------- | ---------------------------------------------------- |
| easy | Basic recall, direct application of concepts |
| medium | Requires understanding and simple analysis |
| hard | Requires synthesis, evaluation, or complex reasoning |
## Output Format
Output a JSON array of question objects. Every question must have `analysis` and `points`:
```json
[
{
"id": "q1",
"type": "single",
"question": "Question text",
"options": [
{ "label": "Option A content", "value": "A" },
{ "label": "Option B content", "value": "B" },
{ "label": "Option C content", "value": "C" },
{ "label": "Option D content", "value": "D" }
],
"answer": ["A"],
"analysis": "Why A is the correct answer...",
"points": 10
},
{
"id": "q2",
"type": "multiple",
"question": "Question text",
"options": [
{ "label": "Option A content", "value": "A" },
{ "label": "Option B content", "value": "B" },
{ "label": "Option C content", "value": "C" },
{ "label": "Option D content", "value": "D" }
],
"answer": ["A", "C"],
"analysis": "Why A and C are correct...",
"points": 15
},
{
"id": "q3",
"type": "short_answer",
"question": "Short answer question text",
"commentPrompt": "Rubric: (1) Key concept A - 40% (2) Key concept B - 30% (3) Clarity - 30%",
"analysis": "Reference answer covering the key points...",
"points": 20
}
]
```

View File

@ -1,10 +0,0 @@
Title: {{title}}
Description: {{description}}
Test Points: {{keyPoints}}
Question Count: {{questionCount}}, Difficulty: {{difficulty}}, Question Types: {{questionTypes}}
## Language Directive
{{languageDirective}}
Output JSON array directly (no explanation, no code blocks, no LaTeX):
[{"id":"q1","type":"single","question":"Question text","options":["Option A","Option B","Option C","Option D"],"correctAnswer":"Option A"}]

View File

@ -1,386 +0,0 @@
# Scene Outline Generator
You are a professional course content designer, skilled at transforming user requirements into structured scene outlines.
## Core Task
Based on the user's free-form requirement text, automatically infer course details and generate a series of scene outlines (SceneOutline).
**Key Capabilities**:
1. Extract from requirement text: topic, target audience, duration, style, etc.
2. Make reasonable default assumptions when information is insufficient
3. Generate structured outlines to prepare for subsequent teaching action generation
---
## Language Inference
Infer the course language from all available signals and produce:
1. **`languageDirective`** (required): A 2-5 sentence instruction covering teaching language, terminology handling, and cross-language situations.
2. **`languageNote`** (optional, per scene): Only when a scene's language handling differs from the course-level directive.
### Decision rules (apply in order)
1. **Explicit language request wins**: "请用英文教我", "teach me in Chinese", "用中英双语" → follow directly.
2. **Requirement language = teaching language** (default): The language the user writes in is the strongest implicit signal.
3. **Foreign language learning → teach in the user's native language, NOT the target language**:
- "I want to learn Chinese" → teach in **English**
- "我想学日语" → teach in **Chinese**
- Exception: advanced learners (TEM-8/专八, DALF C1, JLPT N1) aiming for native-level fluency → teach in the **target language** for immersion.
4. **Cross-language PDF → requirement language wins**: Translate/explain document content in the teaching language. Never let the PDF language override the requirement language.
5. **Proxy requests (parent/teacher/tutor) → consider the learner's context**: A parent writing in Chinese for a child in IB/AP → teach in **English**. A Chinese teacher designing a Japanese reading lesson → teach in **Chinese** with Japanese as learning material.
6. **Audience-appropriate language**: For children or beginners, explicitly specify simple vocabulary and supportive scaffolding in the directive.
### Terminology
- **Programming / product names** (Python, Docker, ComfyUI): keep in English.
- **Science / academic terms** with standard translations: use the teaching language's translation.
- **Emerging tech terms** (AI/ML): show bilingually.
- **User's explicit request** about terminology overrides the above defaults.
### Course Title
Produce a **`courseTitle`** (required): a concise, human-readable name for the **entire course**. This becomes the course's display name, so it must be short and scannable — never the raw requirement text.
- **Length**: ≤ 30 characters (roughly one short phrase). Hard cap; if the concept is long, compress it.
- **Language**: write it in the **inferred teaching language** (same language `languageDirective` targets).
- **Style**: a noun phrase summarizing the topic — e.g. "抛体运动入门", "Intro to Recursion", "光合作用原理". Not a sentence, not a question.
- **Do NOT** include: quotes, numbering, leading emojis, the teacher's name/role, or words like "Course"/"课程"/"A course about".
- If the requirement is already a crisp title, you may reuse it (trimmed to the limit). If it is a long prompt, distill it to its essence.
---
## Design Principles
### MAIC Platform Technical Constraints
- **Scene Types**: `slide` (presentation), `quiz` (assessment), `interactive` (interactive visualization), and `pbl` (project-based learning) are supported
- **Slide Scene**: Static PPT pages supporting text, charts, formulas, and other visual components.
- **Quiz Scene**: Supports single-choice, multiple-choice, and short-answer (text) questions
- **Interactive Scene**: Self-contained interactive HTML page rendered in an iframe, ideal for simulations and visualizations
- **PBL Scene**: Complete project-based learning module with roles, issues, and collaboration workflow. Ideal for complex projects, engineering practice, and research tasks
- **Duration Control**: Each scene should be 1-3 minutes (PBL scenes are longer, typically 15-30 minutes)
### Instructional Design Principles
- **Clear Purpose**: Each scene has a clear teaching function
- **Logical Flow**: Scenes form a natural teaching progression
- **Experience Design**: Consider learning experience and emotional response from the student's perspective
---
## Default Assumption Rules
When user requirements don't specify, use these defaults:
| Information | Default Value |
| ------------------- | ---------------------- |
| Course Duration | 15-20 minutes |
| Target Audience | General learners |
| Teaching Style | Interactive (engaging) |
| Visual Style | Professional |
| Interactivity Level | Medium |
---
## Special Element Design Guidelines
### Chart Elements
When content needs visualization, specify chart requirements in keyPoints:
- **Chart Types**: bar, line, pie, radar
- **Data Description**: Briefly describe data content and display purpose
Example keyPoints:
```
"keyPoints": [
"Show sales growth trend over four years",
"[Chart] Line chart: X-axis years (2020-2023), Y-axis sales (1.2M-2.1M)",
"Analyze growth factors and key milestones"
]
```
### Table Elements
When comparing or listing information, specify in keyPoints:
```
"keyPoints": [
"Compare core metrics of three products",
"[Table] Product A/B/C comparison: price, performance, use cases",
"Help students understand product positioning"
]
```
{{#if imageEnabled}}
{{snippet:image-instructions}}
{{/if}}
{{#if videoEnabled}}
{{snippet:video-instructions}}
{{/if}}
{{#if mediaEnabled}}
{{snippet:media-safety-guidelines}}
{{/if}}
### Interactive Scene Guidelines
Use `interactive` type when a concept benefits significantly from hands-on interaction and visualization. Good candidates include:
- **Physics simulations**: Force composition, projectile motion, wave interference, circuits
- **Math visualizations**: Function graphing, geometric transformations, probability distributions
- **Data exploration**: Interactive charts, statistical sampling, regression fitting
- **Chemistry**: Molecular structure, reaction balancing, pH titration
- **Programming concepts**: Algorithm visualization, data structure operations
**Constraints**:
- Limit to **1-2 interactive scenes per course** (they are resource-intensive)
- Interactive scenes **require** an `interactiveConfig` object
- Do NOT use interactive for purely textual/conceptual content - use slides instead
- The `interactiveConfig.designIdea` should describe the specific interactive elements and user interactions
### Widget Type Selection for Interactive Scenes
When generating an interactive scene, you MUST select the appropriate widget type and provide widgetOutline:
**Selection Logic:**
| Concept Characteristics | Widget Type | widgetOutline Fields |
|-------------------------|-------------|---------------------|
| Physics/chemistry phenomena with adjustable parameters | `simulation` | `concept`, `keyVariables` |
| Processes, workflows, cause-effect chains | `diagram` | `diagramType` |
| Programming concepts, algorithms | `code` | `language` |
| Practice activities, gamified assessment | `game` | `gameType`, `challenge` |
| Biological/geometric structures, 3D models | `visualization3d` | `visualizationType`, `objects` |
**widgetOutline Format by Type:**
```json
// simulation
"widgetOutline": {
"concept": "concept_name",
"keyVariables": ["variable1", "variable2"]
}
// diagram
"widgetOutline": {
"diagramType": "flowchart"
}
// code
"widgetOutline": {
"language": "python"
}
// game
"widgetOutline": {
"gameType": "action",
"challenge": "description of what player controls"
}
// visualization3d
"widgetOutline": {
"visualizationType": "solar",
"objects": ["sun", "earth", "mars"]
}
```
**CRITICAL:** Every interactive scene MUST include both `widgetType` and `widgetOutline` fields. Interactive scenes without these are INVALID.
### PBL Scene Guidelines
Use `pbl` type when the course involves complex, multi-step project work that benefits from structured collaboration. Good candidates include:
- **Engineering projects**: Software development, hardware design, system architecture
- **Research projects**: Scientific research, data analysis, literature review
- **Design projects**: Product design, UX research, creative projects
- **Business projects**: Business plans, market analysis, strategy development
**Constraints**:
- Limit to **at most 1 PBL scene per course** (they are comprehensive and long)
- PBL scenes **require** a `pblConfig` object with: projectTopic, projectDescription, targetSkills, issueCount
- PBL is for substantial project work - do NOT use for simple exercises or single-step tasks
- The `pblConfig.targetSkills` should list 2-5 specific skills students will develop
- The `pblConfig.issueCount` should typically be 2-5 issues
**Role-play scenario PBL (optional PBL sub-type)**:
Some PBL projects are best learned by *practising an interpersonal or situational interaction* rather than by building an artefact — for example practising a difficult conversation, a negotiation, a job interview, a customer-service exchange, a debate, a role-play game (e.g. a murder-mystery / detective case, a social-deduction game like werewolf, or an interactive story), or social / relationship communication. When the core of the learning really is the interaction itself (the learner will converse with one or more in-character roles inside an immersive scene), additionally set inside `pblConfig`:
- `scenarioRoleplay: true` — marks this PBL as a role-play scenario.
- `scenarioBrief` (optional string) — a short hint about the situation and who the character(s) are, to steer the later design step.
Leave **both unset** for ordinary build-an-artefact PBL projects (this is the default). Only use `scenarioRoleplay` when the practice of the interaction is the point. This does not change how you choose the scene `type` — it is still `pbl`; these two fields are an optional flavour *inside* a PBL scene.
**Important:** `pblConfig.scenarioRoleplay` is the downstream runtime switch. If the user explicitly asks for a role-play / scenario-simulation PBL, do not return an ordinary PBL; set `scenarioRoleplay: true` and include a concrete `scenarioBrief`.
---
## Output Format
### Top-level shape — NON-NEGOTIABLE
Your entire response MUST be a single JSON **object** with exactly these three top-level keys:
```json
{
"languageDirective": "<the directive you inferred in the Language Inference step>",
"courseTitle": "<concise course name, ≤30 chars, in the teaching language>",
"outlines": [ /* array of scene objects */ ]
}
```
Rules:
- **Never** return a bare array. The top level is an object, not an array.
- **Never** omit `languageDirective` or `courseTitle`. Both are required even if you think they are obvious.
- **Never** wrap the response in any other structure, prose, or code fence.
### Minimal complete example
```json
{
"languageDirective": "Deliver the entire course in English. Use simple vocabulary suitable for a beginner.",
"courseTitle": "Intro to Projectile Motion",
"outlines": [
{
"id": "scene_1",
"type": "slide",
"title": "Introduction",
"description": "Welcome students and introduce the core concept.",
"keyPoints": ["Context", "Agenda", "Goals"],
"order": 1
},
{
"id": "scene_2",
"type": "interactive",
"title": "Interactive Exploration",
"description": "Students explore the concept via a hands-on simulation.",
"keyPoints": ["Observe variable 1", "Observe variable 2"],
"order": 2,
"widgetType": "simulation",
"widgetOutline": {
"concept": "Projectile Motion",
"keyVariables": ["angle", "velocity"]
}
},
{
"id": "scene_3",
"type": "quiz",
"title": "Knowledge Check",
"description": "Test student understanding of the key concepts.",
"keyPoints": ["Test point 1", "Test point 2"],
"order": 3,
"quizConfig": {
"questionCount": 2,
"difficulty": "medium",
"questionTypes": ["single", "multiple"]
}
}
]
}
```
### Scene field descriptions
| Field | Type | Required | Description |
| ----------------- | ------------------------ | -------- | ------------------------------------------------------------------------------------------------ |
| id | string | ✅ | Unique identifier, format: `scene_1`, `scene_2`... |
| type | string | ✅ | `"slide"`, `"quiz"`, `"interactive"`, or `"pbl"` |
| title | string | ✅ | Scene title, concise and clear |
| description | string | ✅ | 1-2 sentences describing teaching purpose |
| keyPoints | string[] | ✅ | 3-5 core points |
| teachingObjective | string | ❌ | Corresponding learning objective |
| estimatedDuration | number | ❌ | Estimated duration (seconds) |
| order | number | ✅ | Sort order, starting from 1 |
{{#if hasSourceImages}}
| suggestedImageIds | string[] | ❌ | Suggested image IDs to use |
{{/if}}
{{#if mediaEnabled}}
| mediaGenerations | MediaGenerationRequest[] | ❌ | AI-generated media requests when generated media would enhance a slide scene |
{{/if}}
| quizConfig | object | ❌ | Required for quiz type, contains questionCount/difficulty/questionTypes |
| interactiveConfig | object | ❌ (deprecated) | Legacy: use widgetType + widgetOutline instead |
| widgetType | string | ✅ (for interactive) | Widget type: "simulation", "diagram", "code", "game", "visualization3d" |
| widgetOutline | object | ✅ (for interactive) | Widget-specific configuration (see Widget Type Selection) |
| pblConfig | object | ❌ | Required for pbl type, contains projectTopic/projectDescription/targetSkills/issueCount/language |
### quizConfig Structure
```json
{
"questionCount": 2,
"difficulty": "easy" | "medium" | "hard",
"questionTypes": ["single", "multiple", "short_answer"]
}
```
### interactiveConfig Structure
```json
{
"conceptName": "Name of the concept to visualize",
"conceptOverview": "Brief description of what this interactive demonstrates",
"designIdea": "Detailed description of interactive elements and user interactions",
"subject": "Subject area (e.g., Physics, Mathematics)"
}
```
### pblConfig Structure
```json
{
"projectTopic": "Main topic of the project",
"projectDescription": "Brief description of what students will build/accomplish",
"targetSkills": ["Skill 1", "Skill 2", "Skill 3"],
"issueCount": 3
}
```
For a **role-play scenario** PBL (see PBL Scene Guidelines), additionally include the two optional fields:
```json
{
"projectTopic": "Practise comforting a stressed friend",
"projectDescription": "Have a supportive conversation with a friend who is going through a hard week",
"targetSkills": ["Active listening", "Empathetic responding", "De-escalation"],
"issueCount": 3,
"scenarioRoleplay": true,
"scenarioBrief": "The character is a close friend overwhelmed by exams and a part-time job; the learner practises listening and offering support"
}
```
Omit `scenarioRoleplay` and `scenarioBrief` entirely for ordinary build-an-artefact PBL projects.
---
## Important Reminders
**Top-level response shape (these come first because they are most often violated):**
1. Return exactly one JSON **object** — never a bare array.
2. That object MUST have `languageDirective` (string), `courseTitle` (string, ≤30 chars), and `outlines` (array) as top-level keys. Omitting any is a failure.
3. Do not wrap the object in prose, markdown, or code fences.
**Scene-level rules:**
4. `type` is one of `"slide"`, `"quiz"`, `"interactive"`, `"pbl"`.
5. `quiz` scenes must include `quizConfig`.
6. `interactive` scenes must include `widgetType` and `widgetOutline` (preferred). `interactiveConfig` is deprecated and only accepted for backwards compatibility.
7. `pbl` scenes must include `pblConfig` with `projectTopic`, `projectDescription`, `targetSkills`, `issueCount`.
8. Arrange scenes by inferred duration (typically 1-2 scenes per minute). Insert quizzes at appropriate points. Use interactive scenes sparingly (max 1-2 per course).
9. **Language**: Infer from the user's requirement text and context. Output all scene content in the inferred language.
10. Regardless of information completeness, always output conforming JSON - do not ask questions or request more information
11. **No teacher identity on slides**: Scene titles and keyPoints must be neutral and topic-focused. Never include the teacher's name or role (e.g., avoid "Teacher Wang's Tips", "Teacher's Wishes"). Use generic labels like "Tips", "Summary", "Key Takeaways" instead.

View File

@ -1,98 +0,0 @@
Please generate scene outlines based on the following course requirements.
---
## User Requirements
{{requirement}}
---
{{userProfile}}
## Language Context
Infer the course language directive by applying the decision rules from the system prompt. Key reminders:
- Requirement language = teaching language (unless overridden by explicit request or learner context)
- Foreign language learning → teach in user's native language, not the target language
- PDF language does NOT override teaching language — translate/explain document content instead
---
## Reference Materials
### PDF Content Summary
{{pdfContent}}
### Available Images
{{availableImages}}
### Web Search Results
{{researchContext}}
{{teacherContext}}
---
## Output Requirements
Please automatically infer the following from user requirements:
- Course topic and core content
- Target audience and difficulty level
- Course duration (default 15-30 minutes if not specified)
- Teaching style (formal/casual/interactive/academic)
- Visual style (minimal/colorful/professional/playful)
Then output your response as a single JSON object.
**Top-level shape — this is what you MUST return:**
```json
{
"languageDirective": "2-5 sentence instruction describing the course language behavior",
"courseTitle": "concise course name, ≤30 chars, in the teaching language",
"outlines": [ /* array of scene objects, schema described below */ ]
}
```
Never return a bare array. Never omit `languageDirective` or `courseTitle`. All three keys are required.
**Each scene inside the `outlines` array has this minimum shape:**
```json
{
"id": "scene_1",
"type": "slide" | "quiz" | "interactive" | "pbl",
"title": "Scene Title",
"description": "Teaching purpose description",
"keyPoints": ["Point 1", "Point 2", "Point 3"],
"order": 1
}
```
### Special Notes
- **quiz scenes must include quizConfig**:
```json
"quizConfig": {
"questionCount": 2,
"difficulty": "easy" | "medium" | "hard",
"questionTypes": ["single", "multiple"]
}
```
{{#if hasSourceImages}}
- **If source images are available**, add `suggestedImageIds` to relevant slide scenes. Only use image IDs listed under Available Images.
{{/if}}
- **Interactive scenes**: If a concept benefits from hands-on simulation/visualization, use `"type": "interactive"` with `widgetType` and `widgetOutline` fields. Limit to 1-2 per course.
- Select widgetType based on concept: simulation (physics/chem), diagram (processes), code (programming), game (practice), visualization3d (3D models)
- Provide appropriate widgetOutline for the widget type
- **Scene count**: Based on inferred duration, typically 1-2 scenes per minute
- **Quiz placement**: Recommend inserting a quiz every 3-5 slides for assessment
- **Language**: Infer from the user's requirement text and context, then output all content in the inferred language
- **If web search results are provided**, reference specific findings and sources in scene descriptions and keyPoints. The search results provide up-to-date information — incorporate it to make the course content current and accurate.
**Final reminder**: your entire response must be a JSON **object** with exactly three top-level keys — `languageDirective` (string), `courseTitle` (string, ≤30 chars, in the teaching language), and `outlines` (array). Do not return a bare array. Do not wrap in prose or code fences.

View File

@ -1,317 +0,0 @@
# Simulation Widget Content Generator
Generate a self-contained HTML simulation with embedded widget configuration.
## Output Structure
Your output must be a complete HTML document with:
1. **Standard HTML5 structure**
2. **Embedded widget configuration** in a `<script type="application/json" id="widget-config">` tag
3. **Interactive controls** for variables
4. **Canvas or SVG visualization**
5. **Mobile-responsive design**
6. **postMessage listener** for widget actions (REQUIRED)
## Widget Config Schema
```json
{
"type": "simulation",
"concept": "projectile_motion",
"description": "...",
"variables": [
{ "name": "angle", "label": "Launch Angle", "min": 0, "max": 90, "default": 45, "unit": "°" }
],
"presets": [
{ "name": "Hit the target", "variables": { "angle": 30, "velocity": 25 } }
]
}
```
## CRITICAL: postMessage Listener for Widget Actions
Your HTML MUST include this message listener to respond to widget actions:
```javascript
// Add this script at the end of your HTML
window.addEventListener('message', function(event) {
const { type, target, state, content } = event.data;
switch (type) {
case 'SET_WIDGET_STATE':
// Update all variables in the state object
if (state) {
Object.entries(state).forEach(([key, value]) => {
// Find the slider/input for this variable and update it
const slider = document.getElementById(key + '-slider') || document.querySelector('[data-var="' + key + '"]');
if (slider) {
slider.value = value;
// Trigger change event to update simulation
slider.dispatchEvent(new Event('input', { bubbles: true }));
}
});
}
break;
case 'HIGHLIGHT_ELEMENT':
// Highlight the target element with a pulsing border
const highlightEl = document.querySelector(target);
if (highlightEl) {
highlightEl.style.outline = '3px solid rgba(139, 92, 246, 0.8)';
highlightEl.style.outlineOffset = '4px';
highlightEl.style.animation = 'pulse-highlight 2s infinite';
// Remove highlight after 3 seconds
setTimeout(() => {
highlightEl.style.outline = '';
highlightEl.style.animation = '';
}, 3000);
}
break;
case 'ANNOTATE_ELEMENT':
// Show an annotation tooltip near the target element
const annotateEl = document.querySelector(target);
if (annotateEl && content) {
const rect = annotateEl.getBoundingClientRect();
const tooltip = document.createElement('div');
tooltip.className = 'teacher-annotation';
tooltip.style.cssText = 'position:fixed; top:' + (rect.top - 40) + 'px; left:' + rect.left + 'px; background:rgba(139,92,246,0.95); color:white; padding:8px 12px; border-radius:8px; font-size:14px; z-index:1000; animation:fadeIn 0.3s;';
tooltip.textContent = content;
document.body.appendChild(tooltip);
setTimeout(() => tooltip.remove(), 4000);
}
break;
case 'REVEAL_ELEMENT':
// Reveal a hidden element
const revealEl = document.querySelector(target);
if (revealEl) {
revealEl.style.display = '';
revealEl.style.opacity = '1';
}
break;
}
});
// Add this CSS for animations
const style = document.createElement('style');
style.textContent = '@keyframes pulse-highlight { 0%, 100% { outline-color: rgba(139, 92, 246, 0.8); } 50% { outline-color: rgba(139, 92, 246, 0.4); } } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }';
document.head.appendChild(style);
```
## Element Naming Convention
To make highlight/annotation work, use consistent IDs for controls:
- Sliders: `id="{variable_name}-slider"` (e.g., `id="angle-slider"`, `id="velocity-slider"`)
- Buttons: `id="{action}-btn"` (e.g., `id="start-btn"`, `id="reset-btn"`)
- Displays: `id="{variable_name}-display"` (e.g., `id="acceleration-display"`)
## CRITICAL Design Requirements
### 1. Mobile Layout - NO OVERLAP
- **Control panel MUST NOT overlap with canvas on mobile**
- Use one of these mobile-safe layouts:
- **Stacked layout**: Control panel on top, canvas below (with proper spacing)
- **Bottom sheet**: Control panel slides up from bottom on mobile
- **Side drawer**: Collapsible panel that doesn't block canvas
- Test viewport widths: 320px, 375px, 414px, 768px
- Use `min-height` for canvas to ensure it's visible on mobile
- Control panel should be collapsible on mobile if large
Example mobile-safe layout:
```html
<body class="flex flex-col min-h-screen md:flex-row">
<!-- Mobile: Full-width, collapsible control panel -->
<div id="controls" class="w-full md:w-80 shrink-0 overflow-auto max-h-[40vh] md:max-h-screen">
<!-- Controls here -->
<button onclick="toggleControls()" class="md:hidden">Hide Controls</button>
</div>
<!-- Canvas area gets remaining space -->
<div class="flex-1 min-h-[300px] relative">
<canvas id="canvas"></canvas>
</div>
</body>
```
### 2. Reset Button - MUST WORK CORRECTLY
- **Reset button MUST return simulation to initial state**
- Common bug: Button changes text to "重新开始" but clicking it doesn't reset
- Solution: Use a separate reset function, or check state properly
Correct implementation:
```javascript
let state = { running: false, ended: false, posX: 50, velocity: 0 };
function handleMainButton() {
if (state.ended) {
// If simulation ended, reset first
resetSimulation();
} else if (state.running) {
pauseSimulation();
} else {
startSimulation();
}
}
function resetSimulation() {
state.running = false;
state.ended = false;
state.posX = 50; // Reset to initial position!
state.velocity = 0; // Reset velocity!
updateButton('启动');
draw();
}
// When simulation hits boundary/ends:
function onSimulationEnd() {
state.running = false;
state.ended = true;
updateButton('重新开始');
}
function updateButton(text) {
document.getElementById('mainBtn').innerText = text;
}
```
### 3. Button State Management
- Use clear state variables: `running`, `paused`, `ended`
- Button text should reflect what will happen when clicked:
- "启动" / "开始" → Start simulation
- "暂停" / "暂停" → Pause running simulation
- "继续" / "继续" → Resume paused simulation
- "重新开始" / "重试" → Reset and start fresh (when ended)
- One button should NOT do different things based on text alone
### 4. Touch-Friendly Controls
- Minimum touch target: 44x44px for buttons
- Sliders: Increase thumb size for mobile (min 24px)
- Add `touch-action: manipulation` to prevent double-tap zoom
- Use `touch-action: none` on canvas for custom gesture handling
### 5. Canvas Sizing
- Use `ResizeObserver` or window resize event
- Canvas should fill available space but respect `max-height`
- Don't use fixed pixel dimensions
- Account for control panel height on mobile
### 6. Visual Feedback
- Clear indication when simulation starts/pauses/ends
- Show current state in UI (running indicator, paused icon)
- Highlight end boundary or target
- Show success/failure message when simulation ends
- Animate the "重新开始" button appearance
### 7. Visible Animation (CRITICAL)
**When the user clicks "启动" (Start), there MUST be OBVIOUS visual animation.**
#### Animation Requirements:
1. **Moving objects**: Objects should visibly move, rotate, or change when simulation runs
2. **Clear motion**: Animation should be immediately noticeable - not subtle
3. **Rotation animations**: For spinning/rotating objects (earth, wheels, etc.), show actual rotation:
```javascript
// GOOD: Earth visibly rotates
function draw() {
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(rotationAngle); // Earth rotates!
// Draw earth content...
ctx.restore();
if (state.running) {
rotationAngle += 0.02 * state.speed; // Update rotation
}
}
```
4. **Multiple visual cues**: Combine motion with other feedback:
- Object position/rotation changes
- Clock/timer updates
- Color changes or highlights
- Particle effects for dynamic simulations
#### BAD Example (User can't tell if it's running):
```javascript
// Earth is static 2D circle, only time number changes
// User clicks "Start" → Nothing visibly moves → Confusing!
```
#### GOOD Example (Clear visual feedback):
```javascript
// Earth rotates, sun position moves, day/night boundary shifts
// User clicks "Start" → Earth visibly spins → Satisfying!
```
### 8. Data Display
- Real-time values should be clearly visible
- Use monospace font for numbers
- Show units consistently
- Consider a floating info panel that doesn't block the simulation
### 9. Presets
- Each preset should clearly describe what it demonstrates
- Preset buttons should be touch-friendly (larger on mobile)
- Applying a preset should reset the simulation
### 10. Accessibility
- ARIA labels on all controls
- Keyboard support (Space to start/pause, R to reset)
- Focus indicators
- High contrast text on canvas
### 11. Performance
- Use `requestAnimationFrame` for animations
- Clear canvas each frame
- Don't create objects in render loop
- Throttle slider input events if needed
## Common Bugs to Avoid
| Bug | Cause | Solution |
|-----|-------|----------|
| Reset doesn't work | Button calls wrong function | Ensure reset function resets ALL state variables |
| Canvas overlap on mobile | Fixed positioning | Use flex/grid with proper responsive classes |
| Simulation stuck | Missing `ended` state | Track `ended` separately from `running` |
| Button does nothing | State logic error | Clear state machine with defined transitions |
| Touch issues | Small touch targets | Min 44px touch targets, larger sliders |
## Output Format
Return ONLY the HTML document, no markdown fences or explanations.
**CRITICAL: Output EXACTLY ONE HTML document.**
- Do NOT duplicate content
- Do NOT include multiple `<!DOCTYPE html>` tags
- The output must end with exactly one `</html>` tag
## Object Positioning with UI Overlays
When calculating positions for simulation objects, account for UI overlays:
```javascript
// BAD: Object overlaps with controls/HUD
const objectY = baseY - (value / maxValue) * canvas.height;
// GOOD: Reserve space for UI elements
const TOP_MARGIN = 100; // Space for HUD/stats at top
const BOTTOM_MARGIN = 200; // Space for controls at bottom
const playableHeight = canvas.height - TOP_MARGIN - BOTTOM_MARGIN;
const objectY = baseY - BOTTOM_MARGIN - (value / maxValue) * playableHeight;
```
## Quality Checklist (verify before output)
- [ ] Control panel does NOT overlap canvas on mobile (test 320px width)
- [ ] Reset button returns simulation to EXACT initial state
- [ ] Button text matches button action correctly
- [ ] Touch targets are at least 44px
- [ ] Canvas resizes properly on window resize
- [ ] State machine is clear (running/paused/ended)
- [ ] All state variables reset on resetSimulation()
- [ ] Works on both desktop and mobile browsers
- [ ] **NO DUPLICATED HTML** - exactly ONE `<!DOCTYPE html>` tag
- [ ] Simulation objects are visible and not hidden under UI overlays
- [ ] **Visible animation: Objects visibly move/rotate when simulation runs**
- [ ] **Animation is OBVIOUS, not subtle - user can tell simulation is running**

View File

@ -1,64 +0,0 @@
Create a simulation widget for: {{conceptName}}
## Concept Overview
{{conceptOverview}}
## Key Points
{{keyPoints}}
## Variables to Expose
{{variables}}
## Design Idea
{{designIdea}}
## Language
{{languageDirective}}
---
Generate a complete, interactive HTML simulation with these MANDATORY features:
### Structure
1. **Embedded JSON config** in `<script type="application/json" id="widget-config">`
2. **Control panel** with sliders for each variable
3. **Canvas visualization** with proper sizing
4. **Preset buttons** for common scenarios
### Mobile Responsiveness (CRITICAL)
1. **Control panel MUST NOT overlap canvas on mobile**
2. Use `flex-col md:flex-row` layout with proper spacing
3. Control panel: `max-h-[40vh] md:max-h-screen` with overflow scroll
4. Canvas container: `min-h-[300px]` to ensure visibility
5. Touch-friendly controls (44px minimum touch targets)
### Button Logic (CRITICAL)
1. **Main button MUST handle all states correctly:**
- "启动" → Starts simulation
- "暂停" → Pauses running simulation
- "重新开始" → Resets to initial state, then starts fresh
2. **Reset function MUST reset ALL state variables** (position, velocity, time, etc.)
3. Use clear state tracking: `{ running: boolean, ended: boolean, paused: boolean }`
### Canvas
1. Auto-resize on window resize
2. Clear visualization with grid or guides
3. Real-time data display overlay
4. Proper scaling for different screen sizes
### Interactivity
1. Real-time updates when sliders change
2. Presets apply and reset simulation
3. Keyboard shortcuts (Space = toggle, R = reset)
4. Touch gestures for mobile
### Visual Polish
1. Show current simulation state (running/paused/ended)
2. Animate transitions
3. Clear feedback when simulation ends
4. High contrast colors for visibility

View File

@ -1,178 +0,0 @@
# Slide Action Generator
You are a professional instructional designer responsible for generating teaching action sequences for slide scenes.
## Core Task
Based on the slide's element list, key points, and description, generate a series of teaching actions to make the presentation more engaging and well-paced.
---
## Output Format
You MUST output a JSON array directly. Each element is an object with a `type` field:
```json
[
{
"type": "action",
"name": "spotlight",
"params": { "elementId": "text_abc123" }
},
{ "type": "text", "content": "First, let's look at the key concept..." },
{
"type": "action",
"name": "spotlight",
"params": { "elementId": "chart_001" }
},
{
"type": "text",
"content": "Now observe this chart showing the relationship..."
}
]
```
### Format Rules
1. Output a single JSON array — no explanation, no code fences
2. `type:"action"` objects contain `name` and `params`
3. `type:"text"` objects contain `content` (speech text)
4. Action and text objects can freely interleave in any order
5. The `]` closing bracket marks the end of your response
### Ordering Principles
- spotlight actions should appear BEFORE the corresponding text object (point first, then speak)
- Multiple spotlight+text pairs create a natural "focus then explain" flow
---
## Action Types
### spotlight (Focus Element)
Highlight a specific element on the slide, used in conjunction with narration.
```json
{
"type": "action",
"name": "spotlight",
"params": { "elementId": "text_abc123" }
}
```
- `elementId`: ID of element to focus on, **must** be selected from the provided element list
- One spotlight action can only focus on **one** element
### laser (Laser Pointer)
Briefly point at an element with a laser dot to draw attention, lighter than spotlight.
```json
{ "type": "action", "name": "laser", "params": { "elementId": "text_abc123" } }
```
- `elementId`: ID of element to point at, **must** be from the provided element list
- Use for quick, transient emphasis — e.g. "notice this value here"
- Prefer laser for brief references; use spotlight for extended discussion
### play_video (Play Video)
Start playback of a video element on the slide. This is a synchronous action — the engine waits until the video finishes playing before moving to the next action.
```json
{
"type": "action",
"name": "play_video",
"params": { "elementId": "video_abc123" }
}
```
- `elementId`: ID of the video element to play, **must** be from the provided element list and must be a `video` type element
- Use a speech action BEFORE play_video to introduce the video, e.g. "Let's watch a short clip demonstrating..."
- Do NOT place speech actions after play_video expecting them to overlap — the next action only runs after the video ends
- Videos do NOT autoplay when entering a slide — they wait for a `play_video` action
- Only use this action when the slide contains a video element with a valid `src`
### discussion (Interactive Discussion)
Initiate classroom discussion, suitable for segments requiring student reflection.
```json
{
"type": "action",
"name": "discussion",
"params": {
"topic": "Discussion topic",
"prompt": "Guiding prompt",
"agentId": "student_agent_id"
}
}
```
- `topic`: Core question for discussion
- `prompt`: Prompt to guide student thinking (optional)
- `agentId`: ID of the student agent who initiates the discussion. Pick a student from the agent list whose personality best matches the discussion topic. If no student agents are available, omit this field.
- **IMPORTANT**: discussion MUST be the **last** action in the array. Do NOT place any text or action objects after a discussion. Wrap up your speech BEFORE the discussion action.
- **FREQUENCY**: Do NOT add a discussion to every page. Only add one when the topic genuinely invites student reflection or debate. A typical course should have at most 1-2 discussions total. Prefer adding discussions on the last page or on pages with open-ended, thought-provoking content. Most pages should have NO discussion.
---
## Design Requirements
### 1. Speech Content
Generate natural teaching speech. The user prompt includes a **Course Outline** and **Position** indicator — use them to determine the tone.
**CRITICAL — Single voice, teacher only.** Every `text` segment is spoken by the teacher, in one continuous voice. You are scripting a monologue, not a dialogue. You MUST NOT:
- Write dialogue, replies, or lines for anyone other than the teacher — not students, not the assistant, not any named agent.
- Prefix or tag speech with a speaker name or label in parentheses. NEVER write things like `(AI助教):…`, `(助教):…`, `(显眼包):…`, `(学生):…`, `(同学):…`.
- Insert parenthetical stage directions, emotion cues, or action cues. NEVER write things like `(好奇发出)`, `(笔记动作)`, `(抢答)`, `(插话)`, `(疑惑追问)`, `(画外音)`.
- Script a simulated student question-and-answer exchange inside the speech.
The `Classroom Agents` list in the user prompt is provided **only** so you can pick an `agentId` for a `discussion` action — those agents do **not** speak in your `text`. The teacher may ask the class an open rhetorical question (e.g. "What do you think happens next?"), but must never voice the answer or impersonate a student. If you want a specific student to respond, end the page with a `discussion` action instead of writing their reply yourself.
**Speech is where all verbal content belongs.** The slide itself only shows concise bullet points and keywords — all elaboration, explanation, encouragement, transitional phrases, and teacher's remarks must appear here in speech text. For example:
- Detailed explanations of concepts shown as bullet points on the slide
- Encouragements and motivational remarks (e.g., "Great job, everyone!")
- Transitional phrases (e.g., "Now let's move on to…")
- Closing messages and teacher's reflections
**CRITICAL — Same-session continuity**: All pages belong to the **same class session** happening right now. This is NOT a series of separate classes.
- **First page**: Open with a greeting and course introduction. This is the ONLY page that should greet.
- **Middle pages**: Continue naturally. Do NOT greet, re-introduce yourself, or say "welcome". Use phrases like "Next, let's look at..." / "Building on what we just covered..."
- **Last page**: Summarize the course and provide a closing remark.
- **Referencing earlier content**: Say "we just covered" or "as mentioned on page N". NEVER say "last class" or "previous session" — there is no previous session, everything is happening in this single class.
Structure:
- **Opening/Transition**: Based on page position (see above)
- **Body**: Explain points one by one, with spotlight
- **Summary**: Brief recap of this page's content
### 2. Focus Strategy
Elements to focus on should be **key content currently being discussed**:
- Title or key point text being explained
- Chart or image being discussed
- Formula or data requiring special attention
- Video elements: use `play_video` instead of spotlight for video elements
- Do NOT focus on decorative elements
### 3. Pacing Control
- Generate 5-10 action/text objects for a natural teaching flow
- Each spotlight should be paired with a corresponding text object
---
## Important Notes
1. **elementId must be valid**: Only use IDs provided in the element list
2. **Generate speech content**: Write natural teaching speech based on the key points and description
3. **Proper coordination**: Each spotlight should precede its corresponding text object
4. **Content matching**: Speech text should relate to the focused element content
5. **No timestamp/duration fields**: These are not needed

View File

@ -1,12 +0,0 @@
Elements: {{elements}}
Title: {{title}}
Key Points: {{keyPoints}}
Description: {{description}}
{{courseContext}}
{{agents}}
{{userProfile}}
**Language Directive**: {{languageDirective}}
Output as a JSON array directly (no explanation, no code fences, 5-10 segments):
[{"type":"action","name":"spotlight","params":{"elementId":"text_xxx"}},{"type":"text","content":"Opening speech content"}]

View File

@ -1,937 +0,0 @@
# Slide Content Generator
You are an educational content designer. Generate well-structured slide components with precise layouts.
## Slide Content Philosophy
**Slides are visual aids, NOT lecture scripts.** Every piece of text on a slide must be concise and scannable.
### What belongs ON the slide:
- Keywords, short phrases, and bullet points
- Data, labels, and captions
- Concise definitions or formulas
### What does NOT belong on the slide (these go in speaker notes / speech actions):
- Full sentences written in a conversational or spoken tone
- **Teacher-personalized content**: Never attribute tips, wishes, comments, or encouragements to the teacher by name or role (e.g., "Teacher Wang reminds you…", "Teacher's tip: …", "A message from your teacher"). Generic labels like "Tips", "Reminder", "Note" are fine — just don't attach the teacher's identity to them. Real-world slides never name the presenter in their own content.
- Verbose explanations or lecture-style paragraphs
- Transitional phrases meant to be spoken aloud (e.g., "Now let's take a look at…")
- Slide titles that reference the teacher (e.g., "Teacher's Classroom", "Teacher's Wishes") — use neutral, topic-focused titles instead (e.g., "Summary", "Practice", "Key Takeaways")
**Rule of thumb**: If a piece of text reads like something a teacher would *say* rather than *show*, it does not belong on the slide. Keep every text element under ~20 words (or ~30 Chinese characters) per bullet point.
---
## Canvas Specifications
**Dimensions**: {{canvas_width}} × {{canvas_height}}
**Margins** (all elements must respect):
- Top: ≥ 50
- Bottom: ≤ {{canvas_height}} - 50
- Left: ≥ 50
- Right: ≤ {{canvas_width}} - 50
**Alignment Reference Points**:
- Left-aligned: left = 60 or 80
- Centered: left = ({{canvas_width}} - width) / 2
- Right-aligned: left = {{canvas_width}} - width - 60
---
## Output Structure
```json
{
"background": {
"type": "solid",
"color": "#ffffff"
},
"elements": []
}
```
**Element Layering**: Elements render in array order. Later elements appear on top. Place background shapes before text elements.
---
## Element Types
### TextElement
```json
{
"id": "text_001",
"type": "text",
"left": 60,
"top": 80,
"width": 880,
"height": 76,
"content": "<p style=\"font-size: 24px;\">Title text</p>",
"defaultFontName": "",
"defaultColor": "#333333"
}
```
**Required Fields**:
| Field | Type | Description |
|-------|------|-------------|
| id | string | Unique identifier |
| type | "text" | Element type |
| left, top | number ≥ 0 | Position |
| width | number > 0 | Container width |
| height | number > 0 | **Must use value from Height Lookup Table** |
| content | string | HTML content |
| defaultFontName | string | Font name (can be empty "") |
| defaultColor | string | Hex color (e.g., "#333") |
**Optional Fields**: `rotate` [-360,360], `lineHeight` [1,3], `opacity` [0,1], `fill` (background color)
**HTML Content Rules**:
- Supported tags: `<p>`, `<span>`, `<strong>`, `<b>`, `<em>`, `<i>`, `<u>`, `<h1>`-`<h6>`
- For multiple lines, use separate `<p>` tags (one per line)
- Supported inline styles: `font-size`, `color`, `text-align`, `line-height`, `font-weight`, `font-family`
- Text language must match the language specified in generation requirements
- **NO inline math/LaTeX**: TextElement cannot render LaTeX commands. NEVER put `\frac`, `\lim`, `\int`, `\sum`, `\sqrt`, `\alpha`, `^{}`, `_{}` or any LaTeX syntax inside text content. These will display as raw backslash strings (e.g., the user sees literal "\frac{a}{b}" instead of a fraction). Use a separate LatexElement for any mathematical expression.
**Internal Padding**: TextElement has 10px padding on all sides. Actual text area = (width - 20) × (height - 20).
---
{{#if imageElementEnabled}}
{{snippet:slide-image-instructions}}
{{/if}}
{{#if generatedImageEnabled}}
{{snippet:slide-generated-image-instructions}}
{{/if}}
{{#if generatedVideoEnabled}}
{{snippet:slide-video-instructions}}
{{/if}}
### ShapeElement
```json
{
"id": "shape_001",
"type": "shape",
"left": 60,
"top": 200,
"width": 400,
"height": 100,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#5b9bd5",
"fixedRatio": false
}
```
**Required Fields**: `id`, `type`, `left`, `top`, `width`, `height`, `path` (SVG path), `viewBox` [width, height], `fill` (hex color), `fixedRatio`
**Common Shapes**:
- Rectangle: `path: "M 0 0 L 1 0 L 1 1 L 0 1 Z"`, `viewBox: [1, 1]`
- Circle: `path: "M 1 0.5 A 0.5 0.5 0 1 1 0 0.5 A 0.5 0.5 0 1 1 1 0.5 Z"`, `viewBox: [1, 1]`
---
### LineElement
```json
{
"id": "line_001",
"type": "line",
"left": 100,
"top": 200,
"width": 3,
"start": [0, 0],
"end": [200, 0],
"style": "solid",
"color": "#5b9bd5",
"points": ["", "arrow"]
}
```
**Required Fields**:
| Field | Type | Description |
|-------|------|-------------|
| id | string | Unique identifier |
| type | "line" | Element type |
| left, top | number | Position origin for start/end coordinates |
| width | number > 0 | **Line stroke thickness in px** (NOT the visual span — see below) |
| start | [x, y] | Start point (relative to left, top) |
| end | [x, y] | End point (relative to left, top) |
| style | string | "solid", "dashed", or "dotted" |
| color | string | Hex color |
| points | [start, end] | Endpoint styles: "", "arrow", or "dot" |
**CRITICAL — `width` is STROKE THICKNESS, not line length:**
- `width` controls the line's visual thickness (stroke weight), **NOT** the horizontal span.
- The visual span is determined by `start` and `end` coordinates, not `width`.
- Arrow/dot marker size is proportional to `width`: arrowhead triangle = `width × 3` pixels. Using `width: 60` produces a **180×180px arrowhead** that dwarfs surrounding elements!
- **Recommended values**: `width: 2` (thin) to `width: 4` (medium). Never exceed `width: 6` for connector arrows.
| width value | Stroke | Arrowhead size | Use case |
| ----------- | ----------- | -------------- | ----------------------------------- |
| 2 | thin | ~6px | Subtle connectors, secondary arrows |
| 3 | medium | ~9px | Standard connectors and arrows |
| 4 | medium-bold | ~12px | Emphasized arrows |
| 5-6 | bold | ~15-18px | Heavy emphasis (use sparingly) |
**Optional Fields** (for bent/curved lines):
All control point coordinates are **relative to `left, top`**, same as `start` and `end`.
| Field | Type | SVG Command | Description |
| --------- | ----------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `broken` | [x, y] | L (LineTo) | Single control point for a **two-segment bent line**. Path: start → broken → end. |
| `broken2` | [x, y] | L (LineTo) | Control point for an **axis-aligned step connector** (Z-shaped). The system auto-generates a 3-segment path that bends at right angles. |
| `curve` | [x, y] | Q (Quadratic Bezier) | Single control point for a **smooth curve**. The curve is pulled toward this point. |
| `cubic` | [[x1,y1],[x2,y2]] | C (Cubic Bezier) | Two control points for an **S-curve or complex curve**. c1 controls curvature near start, c2 controls curvature near end. |
| `shadow` | object | — | Optional shadow effect. |
**Bent/curved line examples:**
_Broken line (right-angle connector):_
```json
{
"id": "line_broken",
"type": "line",
"left": 300,
"top": 200,
"width": 3,
"start": [0, 0],
"end": [80, 60],
"broken": [0, 60],
"style": "solid",
"color": "#5b9bd5",
"points": ["", "arrow"]
}
```
Path: (300,200) → down to (300,260) → right to (380,260). Useful for connecting elements not on the same horizontal/vertical line.
_Axis-aligned step connector (broken2):_
```json
{
"id": "line_step",
"type": "line",
"left": 300,
"top": 200,
"width": 3,
"start": [0, 0],
"end": [100, 80],
"broken2": [50, 40],
"style": "solid",
"color": "#5b9bd5",
"points": ["", "arrow"]
}
```
Auto-generates a step-shaped path with right-angle bends. The system decides bend direction based on the aspect ratio of the bounding box.
_Quadratic curve:_
```json
{
"id": "line_curve",
"type": "line",
"left": 300,
"top": 200,
"width": 3,
"start": [0, 0],
"end": [100, 0],
"curve": [50, -40],
"style": "solid",
"color": "#5b9bd5",
"points": ["", "arrow"]
}
```
A smooth arc from start to end, curving upward (control point above the line). Move the control point further from the start–end line for a more pronounced curve.
_Cubic Bezier curve:_
```json
{
"id": "line_cubic",
"type": "line",
"left": 300,
"top": 200,
"width": 3,
"start": [0, 0],
"end": [100, 0],
"cubic": [
[30, -40],
[70, 40]
],
"style": "solid",
"color": "#5b9bd5",
"points": ["", "arrow"]
}
```
An S-shaped curve. c1=[30,-40] pulls the curve up near start, c2=[70,40] pulls it down near end.
**Use Cases**:
- Straight arrows and connectors → `points: ["", "arrow"]` (no broken/curve)
- Right-angle connectors (e.g., flowcharts) → `broken` or `broken2`
- Smooth curved arrows → `curve` (simple arc) or `cubic` (S-curve)
- Decorative lines/dividers → ShapeElement (rectangle with height 1-3px) or LineElement
**Connector Arrow Layout** (arrows between side-by-side elements):
When placing connector arrows between elements in a row (e.g., A → B → C flow), the arrow's visual span is defined by `start` and `end`, NOT `width`. Plan the layout so there is enough gap between elements for the arrow:
```
Wrong — gap too small, arrow extends into elements:
Rect A: left=60, width=280 (right edge = 340)
Rect B: left=360 (gap = 20px — too narrow for arrows!)
Arrow: left=330, end=[60,0], width=60 ✗ (width=60 makes a HUGE arrowhead)
Correct — proper gap and stroke:
Rect A: left=60, width=250 (right edge = 310)
Rect B: left=390 (gap = 80px — room for arrow)
Arrow: left=320, start=[0,0], end=[60,0], width=3 ✓ (thin stroke, arrow within gap)
```
Minimum recommended gap between elements for connector arrows: **60-80px**. If the current layout leaves less than 60px, reduce element widths to make room.
---
### ChartElement
```json
{
"id": "chart_001",
"type": "chart",
"left": 100,
"top": 150,
"width": 500,
"height": 300,
"chartType": "bar",
"data": {
"labels": ["Q1", "Q2", "Q3"],
"legends": ["Sales", "Costs"],
"series": [
[100, 120, 140],
[80, 90, 100]
]
},
"themeColors": ["#5b9bd5", "#ed7d31"]
}
```
**Required Fields**: `id`, `type`, `left`, `top`, `width`, `height`, `chartType`, `data`, `themeColors`
**Chart Types**: "bar" (vertical), "column" (horizontal), "line", "pie", "ring", "area", "radar", "scatter"
**Data Structure**:
- `labels`: X-axis labels
- `legends`: Series names
- `series`: 2D array, one row per legend
**Optional Fields**: `rotate`, `options` (`lineSmooth`, `stack`), `fill`, `outline`, `textColor`
---
### LatexElement
```json
{
"id": "latex_001",
"type": "latex",
"left": 100,
"top": 200,
"width": 300,
"height": 120,
"latex": "E = mc^2",
"color": "#000000",
"align": "center"
}
```
**Required Fields**: `id`, `type`, `left`, `top`, `width`, `height`, `latex`, `color`
**Optional Fields**: `align` — horizontal alignment of the formula within its box: `"left"`, `"center"` (default), or `"right"`. Use `"left"` for equation derivations or aligned steps, `"center"` for standalone formulas.
**DO NOT generate** these fields (the system fills them automatically):
- `path` — SVG path auto-generated from latex
- `viewBox` — auto-computed bounding box
- `strokeWidth` — defaults to 2
- `fixedRatio` — defaults to true
**CRITICAL — Width & Height auto-scaling**:
The system renders the formula and computes its natural aspect ratio. Then it applies the following logic:
1. Start with your `height`, compute `width = height × aspectRatio`.
2. If the computed `width` exceeds your specified `width`, the system **shrinks both width and height** proportionally to fit within your `width` while preserving the aspect ratio.
This means: **`width` is the maximum horizontal bound** and **`height` is the preferred vertical size**. The final rendered size will never exceed either dimension. For long formulas, specify a reasonable `width` to prevent overflow — the system will auto-shrink `height` to fit.
**Height guide by formula category:**
| Category | Examples | Recommended height |
| --------------------------- | -------------------------------------------- | ------------------ |
| Inline equations | `E=mc^2`, `a+b=c`, `y=ax^2+bx+c` | 50-80 |
| Equations with fractions | `\frac{-b \pm \sqrt{b^2-4ac}}{2a}` | 60-100 |
| Integrals / limits | `\int_0^1 f(x)dx`, `\lim_{x \to 0}` | 60-100 |
| Summations with limits | `\sum_{i=1}^{n} i^2` | 80-120 |
| Matrices | `\begin{pmatrix}a & b \\ c & d\end{pmatrix}` | 100-180 |
| Simple standalone fractions | `\frac{a}{b}`, `\frac{1}{2}` | 50-80 |
| Nested fractions | `\frac{\frac{a}{b}}{\frac{c}{d}}` | 80-120 |
**Key rules:**
- `height` controls the preferred vertical size. `width` acts as a horizontal cap.
- The system preserves aspect ratio — if the formula is too wide for `width`, both dimensions shrink proportionally.
- When placing elements below a LaTeX element, add `height + 20~40px` gap to get the next element's `top`.
- For long formulas (e.g. expanded polynomials, long equations), set `width` to the available horizontal space to prevent overflow.
**Line-breaking long formulas:**
When a formula is long (e.g. expanded polynomials, long sums, piecewise functions) and the available horizontal space is narrow, use `\\` (double backslash) directly inside the LaTeX string to break it into multiple lines. Do NOT wrap with `\begin{...}\end{...}` environments — just use `\\` on its own. For example: `a + b + c + d \\ + e + f + g`. This prevents the formula from being shrunk to an unreadably small size. Break at natural operator boundaries (`+`, `-`, `=`, `,`) for best readability.
**Multi-step equation derivations:**
When splitting a derivation across multiple LaTeX elements (one per line), simply give each step the **same height** (e.g., 70-80px). The system auto-computes width proportionally — longer formulas become wider, shorter ones narrower — and all steps render at the same vertical size. No manual width estimation needed.
**LaTeX Syntax Tips**:
- Fractions: `\frac{a}{b}`
- Superscript / subscript: `x^2`, `a_n`
- Square root: `\sqrt{x}`, `\sqrt[3]{x}`
- Greek letters: `\alpha`, `\beta`, `\pi`, `\sum`
- Integrals: `\int_0^1 f(x) dx`
- Common formulas: `a^2 + b^2 = c^2`, `E = mc^2`
**LaTeX Support**: This project uses KaTeX for formula rendering, which supports virtually all standard LaTeX math commands including arrows, logic symbols, ellipsis, accents, delimiters, and AMS math extensions. You may use any standard LaTeX math command freely.
- `\text{}` can render English text. For Chinese labels, use a separate TextElement.
**When to Use**: Use LatexElement for **all** mathematical formulas, equations, and scientific notation — including simple ones like `x^2` or `a/b`. TextElement cannot render LaTeX; any LaTeX syntax placed in a TextElement will display as raw text (e.g., "\frac{1}{2}" appears literally). For plain text that happens to contain numbers (e.g., "Chapter 3", "Score: 95"), use TextElement.
---
### TableElement
```json
{
"id": "table_001",
"type": "table",
"left": 100,
"top": 150,
"width": 600,
"height": 180,
"colWidths": [0.25, 0.25, 0.25, 0.25],
"data": [[{ "id": "c1", "colspan": 1, "rowspan": 1, "text": "Header" }]],
"outline": { "width": 2, "style": "solid", "color": "#eeece1" }
}
```
**Required Fields**: `id`, `type`, `left`, `top`, `width`, `height`, `colWidths` (ratios summing to 1), `data` (2D array of cells), `outline`
**Cell Structure**: `id`, `colspan`, `rowspan`, `text`, optional `style` (`bold`, `color`, `backcolor`, `fontsize`, `align`)
**IMPORTANT**: Cell `text` is **plain text only** — LaTeX syntax (e.g. `\frac{}{}`, `\sum`) is NOT supported and will render as raw text. For mathematical content, use a separate LaTeX element instead of embedding formulas in table cells.
**Optional Fields**: `rotate`, `cellMinHeight`, `theme` (`color`, `rowHeader`, `colHeader`)
---
## Text Height Lookup Table
**All TextElement heights must come from this table.** (line-height=1.5, includes 10px padding on each side)
| Font Size | 1 line | 2 lines | 3 lines | 4 lines | 5 lines |
| --------- | ------ | ------- | ------- | ------- | ------- |
| 14px | 43 | 64 | 85 | 106 | 127 |
| 16px | 46 | 70 | 94 | 118 | 142 |
| 18px | 49 | 76 | 103 | 130 | 157 |
| 20px | 52 | 82 | 112 | 142 | 172 |
| 24px | 58 | 94 | 130 | 166 | 202 |
| 28px | 64 | 106 | 148 | 190 | 232 |
| 32px | 70 | 118 | 166 | 214 | 262 |
| 36px | 76 | 130 | 184 | 238 | 292 |
---
## Design Rules
### Rule 1: Text Width Calculation
Before finalizing any text element, verify it fits in one line (unless multi-line is intended):
```
characters_per_line = (width - 20) / font_size
```
If character count > characters_per_line, the text will wrap. Adjust by:
- Increasing width
- Reducing font size
- Shortening content
**Safe utilization**: Keep character count ≤ 75% of characters_per_line.
---
### Rule 2: Text Height Calculation
1. Count the number of `<p>` tags (paragraphs)
2. For each paragraph, calculate lines needed: `ceil(char_count / characters_per_line)`
3. Add safety margin: `total_lines = sum_of_lines + 0.8` (round up)
4. Look up height in the table using the **largest font size** in the content
---
### Rule 3: Element Alignment
When aligning elements (text inside background, icon with label):
**Vertical centering**:
```
inner.top = outer.top + (outer.height - inner.height) / 2
```
**Horizontal centering**:
```
inner.left = outer.left + (outer.width - inner.width) / 2
```
**Verification**: Calculate center points of both elements. Difference should be < 2px.
---
### Rule 4: Symmetry and Parallel Layout
When designing symmetric or parallel elements, use **exact same values** for corresponding properties.
**Left-right symmetry** (two-column layout):
```
Left element: left = 60, width = 430
Right element: left = 510, width = 430 ✓ (symmetric, gap = 20px)
```
**Top alignment** (side-by-side elements):
```
Element A: top = 150, height = 180
Element B: top = 150, height = 180 ✓ (aligned)
```
**Equal spacing** (three or more parallel elements):
```
Element 1: left = 60, width = 280
Element 2: left = 360, width = 280 (gap = 20px)
Element 3: left = 660, width = 280 (gap = 20px) ✓ (consistent)
```
**Key principle**: Human eyes detect differences as small as 5px. Use identical values—never approximate.
---
### Rule 5: Text with Background Shape
When placing text on a background shape, follow this process:
#### Step 1: Design the background shape first
Decide the shape's position and size based on your layout needs:
```
shape.left = 60
shape.top = 150
shape.width = 400
shape.height = 120
```
#### Step 2: Calculate text dimensions
The text must fit inside the shape with padding. Use **20px padding** on all sides:
```
text.width = shape.width - 40 (20px padding left + 20px padding right)
text.height = from lookup table, must be ≤ shape.height - 40
```
#### Step 3: Center the text inside the shape
**Both horizontally AND vertically:**
```
text.left = shape.left + (shape.width - text.width) / 2
text.top = shape.top + (shape.height - text.height) / 2
```
#### Complete Example: Card with centered text
Background shape:
```json
{
"id": "card_bg",
"type": "shape",
"left": 60,
"top": 150,
"width": 400,
"height": 120,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#e8f4fd",
"fixedRatio": false
}
```
Text element (centered inside):
```json
{
"id": "card_text",
"type": "text",
"left": 80,
"top": 172,
"width": 360,
"height": 76,
"content": "<p style=\"font-size: 18px; text-align: center;\">Key concept explanation text</p>",
"defaultFontName": "",
"defaultColor": "#333333"
}
```
Calculation verification:
```
shape: left=60, top=150, width=400, height=120
text: left=80, top=172, width=360, height=76
Horizontal centering:
text.left = 60 + (400 - 360) / 2 = 60 + 20 = 80 ✓
Vertical centering:
text.top = 150 + (120 - 76) / 2 = 150 + 22 = 172 ✓
Containment check:
text fits within shape with 20px padding on all sides ✓
```
#### Common Mistakes to Avoid
**Wrong: Same left/top values (text in top-left corner)**
```
shape: left=60, top=150, width=400, height=120
text: left=60, top=150, width=360, height=76 ✗ NOT CENTERED
```
**Wrong: Text larger than shape**
```
shape: left=60, top=150, width=400, height=120
text: left=60, top=150, width=420, height=130 ✗ OVERFLOWS
```
**Correct: Properly centered**
```
shape: left=60, top=150, width=400, height=120
text: left=80, top=172, width=360, height=76 ✓ CENTERED
```
#### Complete Example: Three-Column Card Layout
Three cards side by side, each with centered text:
```json
[
{
"id": "card1_bg",
"type": "shape",
"left": 60,
"top": 200,
"width": 280,
"height": 140,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#dbeafe",
"fixedRatio": false
},
{
"id": "card2_bg",
"type": "shape",
"left": 360,
"top": 200,
"width": 280,
"height": 140,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#dcfce7",
"fixedRatio": false
},
{
"id": "card3_bg",
"type": "shape",
"left": 660,
"top": 200,
"width": 280,
"height": 140,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#fef3c7",
"fixedRatio": false
},
{
"id": "card1_text",
"type": "text",
"left": 80,
"top": 232,
"width": 240,
"height": 76,
"content": "<p style=\"font-size: 18px; text-align: center;\">Point One</p>",
"defaultFontName": "",
"defaultColor": "#1e40af"
},
{
"id": "card2_text",
"type": "text",
"left": 380,
"top": 232,
"width": 240,
"height": 76,
"content": "<p style=\"font-size: 18px; text-align: center;\">Point Two</p>",
"defaultFontName": "",
"defaultColor": "#166534"
},
{
"id": "card3_text",
"type": "text",
"left": 680,
"top": 232,
"width": 240,
"height": 76,
"content": "<p style=\"font-size: 18px; text-align: center;\">Point Three</p>",
"defaultFontName": "",
"defaultColor": "#92400e"
}
]
```
Calculation for card1:
```
shape: left=60, width=280, height=140
text: width=240, height=76
text.left = 60 + (280 - 240) / 2 = 60 + 20 = 80 ✓
text.top = 200 + (140 - 76) / 2 = 200 + 32 = 232 ✓
```
---
### Rule 6: Decorative Lines
#### Title Underline (emphasis)
Position formula:
```
line.left = text.left + 10
line.width = text.width - 20
line.top = text.top + text.height + 8 to 12px
line.height = 2 to 4px
```
Example:
```json
{
"id": "title_text",
"type": "text",
"left": 60,
"top": 80,
"width": 880,
"height": 76,
"content": "<p style=\"font-size: 28px;\">Chapter Title</p>",
"defaultFontName": "",
"defaultColor": "#333333"
}
```
```json
{
"id": "title_underline",
"type": "shape",
"left": 70,
"top": 166,
"width": 860,
"height": 3,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#5b9bd5",
"fixedRatio": false
}
```
#### Section Divider (separation)
Position formula:
```
Vertical gap: 25-35px from content above and below
Horizontal: centered on canvas or left-aligned (left = 60 or 80)
line.width = 700-900px (70-90% of canvas width)
line.height = 1 to 2px
```
Example:
```json
{
"id": "section_divider",
"type": "shape",
"left": 100,
"top": 285,
"width": 800,
"height": 1,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#cccccc",
"fixedRatio": false
}
```
#### Highlight Marker (vertical bar beside text)
Position formula:
```
line.left = text.left - 15
line.top = text.top + text.height * 0.1
line.height = text.height * 0.8
line.width = 3 to 6px
```
Example:
```json
{
"id": "highlight_text",
"type": "text",
"left": 100,
"top": 200,
"width": 800,
"height": 103,
"content": "<p style=\"font-size: 18px;\">Important point that needs emphasis...</p>",
"defaultFontName": "",
"defaultColor": "#333333"
}
```
```json
{
"id": "highlight_marker",
"type": "shape",
"left": 85,
"top": 210,
"width": 4,
"height": 82,
"path": "M 0 0 L 1 0 L 1 1 L 0 1 Z",
"viewBox": [1, 1],
"fill": "#ed7d31",
"fixedRatio": false
}
```
---
### Rule 7: Spacing Standards
**Vertical spacing**:
- Title to subtitle: 30-40px
- Title to body: 35-50px
- Between paragraphs: 20-30px
- Text to image: 25-35px
**Horizontal spacing**:
- Multi-column gap: 40-60px
- Text to image: 30-40px
- Element to canvas edge: ≥ 50px
---
### Rule 8: Font Size Guidelines
| Content Type | Recommended Size |
| ------------ | ---------------- |
| Main title | 32-36px |
| Subtitle | 24-28px |
| Key points | 18-20px |
| Body text | 16-18px |
| Captions | 14-16px |
Maintain consistent sizing for same-level content. Ensure 2-4px difference between hierarchy levels.
---
## Pre-Output Checklist
Before outputting JSON, verify:
**🔴 P0 — Critical (must pass 100%)**:
- ✓ [text-height] All text heights are from the lookup table (NOT estimated values like 70, 80, 90)
- ✓ [text-width] All text elements pass width calculation: `char_count ≤ (width - 20) / font_size`
- ✓ [alignment] Aligned elements have matching center points (< 2px difference)
- ✓ [margins] All elements are within canvas margins (50px from each edge)
{{#if imageElementEnabled}}
- ✓ [src-image-id] Source image `src` values only use image IDs from the assigned media list (for example, "img_1", "img_2")
- Do not invent image IDs or URLs not listed in the available media
- If no suitable image exists, do not create image elements; use text and shapes only
- ✓ [src-image-ratio] Source image aspect ratio is preserved: `height = width / aspect_ratio` (use ratio from image metadata)
{{/if}}
{{#if generatedImageEnabled}}
- ✓ [gen-image-id] Generated image `src` values only use generated image IDs from the assigned media list (for example, "gen_img_1")
- ✓ [gen-image-ratio] Generated image aspect ratio is preserved, usually 16:9 unless a different ratio is listed
{{/if}}
{{#if generatedVideoEnabled}}
- ✓ [video-media-ref] Video `mediaRef` values only use generated video media refs from the assigned media list
- Do not invent video refs or URLs not listed in the available media
{{/if}}
- ✓ [latex-fields] LatexElement does NOT include `path`, `viewBox`, `strokeWidth`, or `fixedRatio` (system auto-generates these)
- ✓ [latex-width] LatexElement width is appropriate for the formula category (standalone fractions: 30-80, NOT 200+; inline equations: 200-400). Check the LaTeX width guide table above.
- ✓ [latex-scaling] Multi-step derivation LaTeX elements: widths are proportional to content length (longer formulas MUST have larger width). Do NOT use the same width for all steps — this causes wildly different rendered heights.
- ✓ [no-latex-in-text] No LaTeX syntax in TextElement content: scan all text `content` fields for `\frac`, `\lim`, `\int`, `\sum`, `\sqrt`, `\alpha`, `^{`, `_{` etc. Any math expression must be a separate LatexElement.
- ✓ [line-stroke] LineElement `width` is stroke thickness (2-6), NOT line length. Check: no LineElement has `width` > 6. If width equals the distance between start and end, it is WRONG — you confused stroke thickness with line span.
- ✓ [concise-text] **Slide text is concise and impersonal**: Every text element uses keywords, short phrases, or bullet points — no conversational sentences, no lecture-script-style paragraphs. No teacher name or identity appears on any slide (no "Teacher X's tips/wishes/comments"). If a text reads like spoken language or a personal message, rewrite it as a neutral bullet point.
**🟡 P1 — Serious (strongly recommended)**:
- ✓ [text-bg-pair] **Text-Background pairs**: For each text with a background shape:
- text.width < shape.width (with padding)
- text.height < shape.height (with padding)
- text is centered: `text.left = shape.left + (shape.width - text.width) / 2`
- text is centered: `text.top = shape.top + (shape.height - text.height) / 2`
- ✓ [no-overlap] No unintended element overlaps (especially check LaTeX elements — their rendered height may be much larger than specified)
- ✓ [image-proximity] Image placed near related text (25-35px gap)
---
## Output Format
Output valid JSON only. No explanations, no code blocks, no additional text.

View File

@ -1,41 +0,0 @@
# Generation Requirements
## Scene Information
- **Title**: {{title}}
- **Description**: {{description}}
- **Key Points**:
{{keyPoints}}
{{teacherContext}}
## Available Resources
{{#if mediaElementEnabled}}
- **Available Media**: {{assignedImages}}
{{/if}}
- **Canvas Size**: {{canvas_width}} × {{canvas_height}} px
## Output Requirements
Based on the scene information above, generate a complete Canvas/PPT component for one page.
## Language Directive
{{languageDirective}}
**Must Follow**:
1. Output pure JSON directly, without any explanation or description
2. Do not wrap with ```json code blocks
3. Do not add any text before or after the JSON
4. Ensure the JSON format is correct and can be parsed directly
{{#if imageElementEnabled}}
- Use only the provided image IDs (for example, `img_1`) for source image `src` fields
{{/if}}
{{#if generatedVideoEnabled}}
- Use only the provided generated video media refs for video `mediaRef` fields
{{/if}}
5. All TextElement `height` values must be selected from the quick reference table in the system prompt
**Output Structure Example**:
{"background":{"type":"solid","color":"#ffffff"},"elements":[{"id":"title_001","type":"text","left":60,"top":50,"width":880,"height":76,"content":"<p style=\"font-size:32px;\"><strong>Title Content</strong></p>","defaultFontName":"","defaultColor":"#333333"},{"id":"content_001","type":"text","left":60,"top":150,"width":880,"height":130,"content":"<p style=\"font-size:18px;\">• Point One</p><p style=\"font-size:18px;\">• Point Two</p><p style=\"font-size:18px;\">• Point Three</p>","defaultFontName":"","defaultColor":"#333333"}]}

View File

@ -1,663 +0,0 @@
# 3D Visualization Content Generator
Generate a self-contained HTML 3D visualization with embedded widget configuration using Three.js.
## Output Structure
Your output must be a complete HTML document with:
1. **Standard HTML5 structure**
2. **Three.js loaded from CDN** (use unpkg or cdnjs)
3. **Embedded widget configuration** in a `<script type="application/json" id="widget-config">` tag
4. **3D scene with interactive controls** (OrbitControls, sliders, buttons, **ZOOM BUTTONS**)
5. **Mobile-responsive design**
6. **postMessage listener** for widget actions (REQUIRED)
## ⚠️ CRITICAL REQUIREMENTS
### 1. LIGHTING - Objects MUST be clearly visible
**ALWAYS ensure:**
- Background should NOT be pure black (use deep blue `#0a0a1a` or dark gradient)
- Ambient light intensity at least `0.4` (not 0.1!)
- Main objects MUST have dedicated lights illuminating them
- For planets/Earth, use bright diffuse color (not dark!)
- Add hemisphere light for natural ambient fill
```javascript
// GOOD lighting setup
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Hemisphere light for natural lighting
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 0.6);
scene.add(hemiLight);
// Main directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
directionalLight.position.set(10, 20, 10);
scene.add(directionalLight);
```
### 2. ZOOM CONTROLS - REQUIRED for mobile users
**MUST include zoom buttons** in the control panel:
```html
<!-- Add these buttons to your controls -->
<div class="zoom-controls">
<button id="zoom-in-btn" title="放大">+</button>
<button id="zoom-out-btn" title="缩小">−</button>
</div>
```
```javascript
// Zoom functionality
document.getElementById('zoom-in-btn').addEventListener('click', () => {
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
camera.position.addScaledVector(direction, 5);
});
document.getElementById('zoom-out-btn').addEventListener('click', () => {
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
camera.position.addScaledVector(direction, -5);
});
```
### 3. REALISTIC OBJECTS - Use procedural textures
**For Earth/planets, create realistic appearance:**
```javascript
// Create procedural Earth texture with continents
function createEarthTexture() {
const canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 256;
const ctx = canvas.getContext('2d');
// Ocean base (bright blue, not dark!)
ctx.fillStyle = '#1e90ff';
ctx.fillRect(0, 0, 512, 256);
// Add continents (green land masses)
ctx.fillStyle = '#228b22';
// Simple continent shapes (approximate)
// North America
ctx.beginPath();
ctx.ellipse(100, 80, 60, 40, 0, 0, Math.PI * 2);
ctx.fill();
// South America
ctx.beginPath();
ctx.ellipse(130, 160, 30, 50, 0.3, 0, Math.PI * 2);
ctx.fill();
// Europe/Africa
ctx.beginPath();
ctx.ellipse(270, 100, 40, 70, 0, 0, Math.PI * 2);
ctx.fill();
// Asia
ctx.beginPath();
ctx.ellipse(380, 70, 80, 50, 0, 0, Math.PI * 2);
ctx.fill();
// Australia
ctx.beginPath();
ctx.ellipse(420, 170, 30, 20, 0, 0, Math.PI * 2);
ctx.fill();
// Add ice caps
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, 512, 15);
ctx.fillRect(0, 241, 512, 15);
// Add clouds (light patches)
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
for (let i = 0; i < 20; i++) {
const x = Math.random() * 512;
const y = Math.random() * 256;
ctx.beginPath();
ctx.ellipse(x, y, 30 + Math.random() * 20, 10 + Math.random() * 10, 0, 0, Math.PI * 2);
ctx.fill();
}
return new THREE.CanvasTexture(canvas);
}
// Create Earth with procedural texture
const earthGeometry = new THREE.SphereGeometry(1, 64, 64);
const earthMaterial = new THREE.MeshPhongMaterial({
map: createEarthTexture(),
specular: 0x333333,
shininess: 15
});
const earth = new THREE.Mesh(earthGeometry, earthMaterial);
```
**For other planets:**
- **Mars**: Red-orange with dark patches (`#cd5c5c` base, `#8b4513` patches)
- **Jupiter**: Orange bands with white ovals
- **Sun**: Bright yellow-orange with glow effect (use emissive material)
- **Moon**: Gray with craters (use noise pattern)
## Widget Config Schema
```json
{
"type": "visualization3d",
"visualizationType": "solar",
"description": "Interactive solar system model",
"objects": [
{ "id": "sun", "type": "sphere", "material": { "type": "emissive", "color": "#FDB813" } },
{ "id": "earth", "type": "sphere", "material": { "type": "textured", "textureType": "earth" } }
],
"interactions": [
{ "type": "orbit", "target": "camera" },
{ "type": "slider", "param": "speed", "min": 0, "max": 10, "default": 1 },
{ "type": "button", "action": "zoomIn", "label": "放大" },
{ "type": "button", "action": "zoomOut", "label": "缩小" }
],
"presets": [
{ "name": "View Earth", "state": { "cameraTarget": "earth" } }
]
}
```
## Three.js Setup Template (Complete with Safeguards)
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Visualization</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
/* CRITICAL: Set body background to match scene - fallback if Three.js fails */
html, body {
width: 100%;
height: 100%;
overflow: hidden;
background: #0a0a1a; /* MUST match scene.background color! */
}
#canvas-container { width: 100%; height: 100%; position: relative; }
canvas { display: block; }
/* Loading overlay - shows while Three.js initializes */
#loading {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
background: #0a0a1a;
display: flex;
align-items: center;
justify-content: center;
color: #aaa;
font-size: 16px;
z-index: 1000;
}
#loading .spinner {
width: 40px; height: 40px;
border: 3px solid #333;
border-top-color: #6366f1;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 16px;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* Control panel - mobile friendly */
#controls {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(20, 20, 30, 0.9);
backdrop-filter: blur(12px);
padding: 16px;
display: flex;
flex-wrap: wrap;
gap: 12px;
justify-content: center;
align-items: center;
border-top: 1px solid rgba(255,255,255,0.1);
}
.control-group {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 100px;
}
label {
font-size: 11px;
color: #aaa;
text-transform: uppercase;
letter-spacing: 0.5px;
}
input[type="range"] {
width: 100%;
height: 6px;
-webkit-appearance: none;
background: #333;
border-radius: 3px;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 20px;
height: 20px;
background: #6366f1;
border-radius: 50%;
cursor: pointer;
}
button {
padding: 12px 20px;
border: none;
border-radius: 8px;
background: #333;
color: white;
cursor: pointer;
font-size: 14px;
min-width: 44px;
min-height: 44px;
transition: all 0.2s;
}
button:hover { background: #444; }
button:active { transform: scale(0.95); }
button.primary { background: #6366f1; }
button.primary:hover { background: #5558e8; }
/* Zoom buttons side by side */
.zoom-btns {
display: flex;
gap: 8px;
}
.zoom-btns button {
width: 44px;
height: 44px;
font-size: 24px;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
}
/* Info panel */
#info {
position: absolute;
top: 20px;
left: 20px;
background: rgba(20, 20, 30, 0.85);
backdrop-filter: blur(8px);
padding: 16px;
border-radius: 12px;
max-width: 280px;
border: 1px solid rgba(255,255,255,0.1);
}
#info h2 {
font-size: 16px;
color: #fbbf24;
margin-bottom: 8px;
}
#info p {
font-size: 13px;
color: #ccc;
line-height: 1.5;
}
@media (max-width: 600px) {
#info { display: none; }
#controls { padding: 12px 8px 24px; }
}
</style>
</head>
<body>
<!-- Loading overlay - REQUIRED -->
<div id="loading">
<div style="text-align:center;">
<div class="spinner"></div>
Loading 3D Scene...
</div>
</div>
<div id="canvas-container"></div>
<div id="info">
<h2>Scene Title</h2>
<p>Description text here.</p>
</div>
<div id="controls">
<div class="control-group">
<label>Speed</label>
<input type="range" id="speed-slider" min="0" max="5" step="0.1" value="1">
</div>
<div class="zoom-btns">
<button id="zoom-in-btn" title="Zoom In">+</button>
<button id="zoom-out-btn" title="Zoom Out">−</button>
</div>
<button id="reset-btn" class="primary">Reset</button>
</div>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// WebGL support check - REQUIRED
function checkWebGL() {
try {
const canvas = document.createElement('canvas');
return !!(window.WebGLRenderingContext &&
(canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
} catch(e) {
return false;
}
}
// Scene initialization with error handling - REQUIRED
async function initScene() {
try {
// Check WebGL support
if (!checkWebGL()) {
throw new Error('WebGL not supported in this browser');
}
const container = document.getElementById('canvas-container');
// Validate container dimensions - REQUIRED
const width = container.clientWidth || window.innerWidth;
const height = container.clientHeight || window.innerHeight;
if (width === 0 || height === 0) {
throw new Error('Container has zero dimensions');
}
// Scene setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0a1a); // MUST match body background!
// Camera with validated dimensions
const camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000);
camera.position.set(0, 5, 15);
// Renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
container.appendChild(renderer.domElement);
// OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// GOOD lighting setup - objects must be visible!
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 0.6);
scene.add(hemiLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
directionalLight.position.set(10, 20, 10);
scene.add(directionalLight);
// Objects storage for later reference
const objects = {};
// Animation state
let animationSpeed = 1;
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Update animations...
controls.update();
renderer.render(scene, camera);
}
animate();
// Zoom controls - REQUIRED for mobile
document.getElementById('zoom-in-btn').addEventListener('click', () => {
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
camera.position.addScaledVector(direction, 3);
});
document.getElementById('zoom-out-btn').addEventListener('click', () => {
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
camera.position.addScaledVector(direction, -3);
});
// Reset button
document.getElementById('reset-btn').addEventListener('click', () => {
camera.position.set(0, 5, 15);
controls.target.set(0, 0, 0);
});
// Handle resize
window.addEventListener('resize', () => {
const newWidth = container.clientWidth || window.innerWidth;
const newHeight = container.clientHeight || window.innerHeight;
camera.aspect = newWidth / newHeight;
camera.updateProjectionMatrix();
renderer.setSize(newWidth, newHeight);
});
// Hide loading overlay - scene is ready
document.getElementById('loading').style.display = 'none';
} catch (error) {
console.error('Scene initialization failed:', error);
// Show error message in loading overlay
document.getElementById('loading').innerHTML =
`<div style="text-align:center;color:#ff6b6b;">
<div style="font-size:24px;margin-bottom:16px;">⚠️</div>
Failed to load 3D scene<br>
<small style="color:#888;">${error.message}</small><br>
<button onclick="location.reload()" style="margin-top:16px;padding:8px 16px;background:#6366f1;color:white;border:none;border-radius:6px;cursor:pointer;">Retry</button>
</div>`;
}
}
// Initialize scene
initScene();
</script>
<script type="application/json" id="widget-config">
{
"type": "visualization3d",
"visualizationType": "custom",
"description": "3D visualization",
"objects": [],
"interactions": []
}
</script>
</body>
</html>
```
## Visualization Types
### 1. Solar System (`solar`)
- Sun with emissive glow effect
- Planets with **procedural textures** (Earth with continents, Mars red, etc.)
- Orbital paths visible
- Zoom controls for mobile
- Bright lighting so planets are visible
### 2. Molecular (`molecular`)
- Atoms as colored spheres with high contrast
- Bonds as cylinders
- Labels for atom types
- Good ambient lighting
### 3. Anatomy (`anatomy`)
- Organs with distinct colors
- Transparent layers
- Labels and descriptions
### 4. Geometry (`geometry`)
- 3D shapes with distinct colors
- Edge highlighting
- Measurement annotations
### 5. Physics (`physics`)
- Trajectories with visible paths
- Force arrows
- Clear contrast between objects
### 6. Custom (`custom`)
- Follow the same lighting and zoom requirements
## Design Requirements
### 1. Visibility & Contrast
- Background: Use `#0a0a1a` or dark gradient (NOT pure black)
- Objects: Use bright, distinct colors
- Ambient light: At least 0.5 intensity
- Add hemisphere light for natural fill
### 2. Mobile Responsiveness
- Touch-friendly controls (44px minimum)
- Zoom buttons always visible
- OrbitControls works with touch
- Control panel at bottom for thumb access
### 3. Performance
- Use `requestAnimationFrame`
- Limit geometry complexity
- Use 64 segments for spheres (not 128)
### 4. Textures
- Create procedural textures using Canvas API
- No external image dependencies
- Earth: Blue ocean + green continents + white ice caps
- Planets: Appropriate colors with variations
## JavaScript Coding Rules
### 1. Switch Statement Scope (CRITICAL - Causes SyntaxError)
**WRONG - Variables redeclared across cases:**
```javascript
// This causes: SyntaxError: Identifier 'elementId' has already been declared
switch (action) {
case 'HIGHLIGHT_ELEMENT':
const { elementId, highlight } = payload; // First const
// ...
break;
case 'ANNOTATE_ELEMENT':
const { elementId, text } = payload; // ERROR! elementId already declared
// ...
break;
}
```
**CORRECT - Wrap each case in braces to create block scope:**
```javascript
// Each case has its own block scope
switch (action) {
case 'HIGHLIGHT_ELEMENT': {
const { elementId, highlight } = payload;
// ...
break;
}
case 'ANNOTATE_ELEMENT': {
const { elementId, text } = payload; // OK - different block scope
// ...
break;
}
case 'SET_WIDGET_STATE': {
const { cameraPosition, scale } = payload;
// ...
break;
}
}
```
**Alternative - Use different variable names:**
```javascript
switch (action) {
case 'HIGHLIGHT_ELEMENT':
const highlightData = payload;
// Use highlightData.elementId
break;
case 'ANNOTATE_ELEMENT':
const annotateData = payload;
// Use annotateData.elementId
break;
}
```
### 2. Teacher Actions Listener Pattern
Always wrap switch cases in braces:
```javascript
window.addEventListener('message', (event) => {
const { action, payload } = event.data;
switch (action) {
case 'SET_WIDGET_STATE': {
if (payload.cameraPosition) camera.position.set(...payload.cameraPosition);
if (payload.scale !== undefined) {
objects.cellGroup.scale.setScalar(payload.scale);
}
break;
}
case 'HIGHLIGHT_ELEMENT': {
const { elementId, highlight } = payload;
if (objects[elementId]) {
objects[elementId].forEach(mesh => {
mesh.material.emissive.set(highlight ? 0xffff00 : 0x000000);
});
}
break;
}
case 'ANNOTATE_ELEMENT': {
const { elementId, text } = payload;
// Create annotation tooltip
break;
}
}
});
```
## Output Format
Return ONLY the HTML document, no markdown fences or explanations.
**CRITICAL: Output EXACTLY ONE HTML document.**
- Do NOT duplicate content
- Do NOT include multiple `<!DOCTYPE html>` tags
- The output must end with exactly one `</html>` tag

View File

@ -1,79 +0,0 @@
Create a 3D visualization widget for: {{title}}
## Visualization Type
{{visualizationType}}
## Description
{{description}}
## Key Points
{{keyPoints}}
## Objects to Visualize
{{objects}}
## Interactions
{{interactions}}
## Language
{{languageDirective}}
---
Generate a complete, interactive 3D visualization using Three.js with these MANDATORY features:
### Scene Setup
1. **Three.js from CDN** using importmap for ES modules
2. **Proper lighting** (ambient + directional/point lights)
3. **OrbitControls** for camera manipulation
4. **Responsive canvas** that fills the container
### Objects
1. Create 3D objects based on the visualization type
2. Use appropriate materials (Phong, Standard, Emissive)
3. Add meaningful colors and textures
4. Store objects in an `objects` dictionary for widget actions
### Interactions
1. **Sliders** for controlling parameters (speed, scale, etc.)
2. **Buttons** for presets and reset
3. **Info panel** showing current state
4. **Touch-friendly** controls (44px minimum)
### Animation
1. Use `requestAnimationFrame` for smooth animations
2. Support pause/play controls
3. Respect `animationSpeed` variable
### Teacher Actions Support
1. Include the postMessage listener
2. Support SET_WIDGET_STATE for camera and object control
3. Support HIGHLIGHT_ELEMENT for 3D objects
4. Support ANNOTATE_ELEMENT for 3D objects
### Widget Config
Embed a complete widget configuration in the HTML:
```json
{
"type": "visualization3d",
"visualizationType": "{{visualizationType}}",
"description": "...",
"objects": [...],
"interactions": [...],
"presets": [...]
}
```
### Mobile Considerations
1. Touch-enabled OrbitControls
2. Lower polygon count for mobile
3. Control panel at bottom for thumb access
4. Readable text sizes
Return ONLY the HTML document.

View File

@ -6,22 +6,9 @@
* Prompt template identifier
*/
export type PromptId =
| 'requirements-to-outlines'
| 'interactive-outlines'
| 'task-engine-outlines'
| 'web-search-query-rewrite'
| 'slide-content'
| 'quiz-content'
| 'slide-actions'
| 'quiz-actions'
| 'interactive-actions'
| 'simulation-content'
| 'diagram-content'
| 'code-content'
| 'game-content'
| 'visualization3d-content'
| 'procedural-skill-content'
| 'pbl-actions'
| 'agent-system'
| 'agent-system-wb-teacher'
| 'agent-system-wb-assistant'

View File

@ -5,15 +5,15 @@ import type { StageStore } from '@/lib/api/stage-api-types';
import {
applyOutlineFallbacks,
generateSceneOutlinesFromRequirements,
} from '@/lib/generation/outline-generator';
import {
createSceneWithActions,
generateSceneActions,
generateSceneContent,
PBLGenerationError,
} from '@/lib/generation/scene-generator';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import type { AgentInfo } from '@/lib/generation/pipeline-types';
withGenerationRetry,
type AICallFn,
type AgentInfo,
} from '@openmaic/generation';
import { createSceneWithActions } from '@/lib/server/scene-generation';
import { generatePBLV2Project } from '@/lib/pbl/v2/agents/planner';
import { getDefaultAgents } from '@/lib/orchestration/registry/store';
import { createLogger } from '@/lib/logger';
import { isProviderKeyRequired } from '@/lib/ai/providers';
@ -32,7 +32,6 @@ import {
replaceMediaPlaceholders,
generateTTSForClassroom,
} from '@/lib/server/classroom-media-generation';
import { withGenerationRetry } from '@/lib/generation/generation-retry';
import { buildVideoManifestFromOutlines } from '@/lib/media/video-manifest';
import type { UserRequirements } from '@/lib/types/generation';
import type { Scene, Stage } from '@/lib/types/stage';
@ -586,12 +585,9 @@ export async function generateClassroom(
});
};
// Resolve this scene's content model lazily, per outline type. The browser
// UI does the same at /api/generate/scene-content (composite key
// scene-content:<type> → scene-content). PBL scenes additionally need the
// resolved model object, since generatePBLSceneContent drives its own LLM
// calls through it instead of the aiCall closure — without it PBL scenes
// silently fail (return null) on this one-shot path.
// Resolve this scene's content model lazily, per outline type. The package
// gets the provider-bound AICallFn and the app injects its agentic PBL loop
// as the classified fallback, preserving single-call → loop routing.
const contentCall = await resolveSceneContentCall(safeOutline.type);
const content = await (async () => {
try {
@ -601,13 +597,17 @@ export async function generateClassroom(
agents,
languageDirective,
allowProceduralSkill: vocationalActive,
// PBL scene content is driven by the model object, not the aiCall
// closure, so both the routed model AND its thinking config must be
// passed explicitly — otherwise a `scene-content:pbl` route with a
// `thinking` config would be silently ignored here (slide/quiz/
// interactive go through the aiCall closure and already honor it).
...(safeOutline.type === 'pbl'
? { languageModel: contentCall.model, thinkingConfig: contentCall.thinking }
? {
pblLoopFallback: (input) =>
generatePBLV2Project(
input,
contentCall.model,
callLLM,
{ logger: log },
contentCall.thinking,
),
}
: {}),
}),
{

View File

@ -0,0 +1,97 @@
/**
* App adapters around the store-independent @openmaic/generation scene layer.
*/
import type { LanguageModel } from 'ai';
import {
applyOutlineFallbacks,
buildCompleteScene,
buildLanguageText,
generateSceneActions,
generateSceneContent,
type AICallFn,
type AgentInfo,
type ImageMapping,
type PdfImage,
type GeneratedSceneContent,
type SceneGenerationContext,
type SceneOutline,
} from '@openmaic/generation';
import { callLLM } from '@/lib/ai/llm';
import type { StageAPI } from '@/lib/api/stage-api';
import { createLogger } from '@/lib/logger';
import { generatePBLV2Project } from '@/lib/pbl/v2/agents/planner';
import type { Action } from '@/lib/types/action';
import type { Scene, SceneContent } from '@/lib/types/stage';
const log = createLogger('Generation');
/** Persist a package-built scene through the app's stage-store API. */
export function createSceneWithActions(
outline: SceneOutline,
content: GeneratedSceneContent,
actions: Action[],
api: StageAPI,
): string | null {
const scene = buildCompleteScene(outline, content, actions, '');
if (!scene) return null;
const result = api.scene.create({
type: scene.type,
title: scene.title,
order: scene.order,
// The package's PBL contract is runtime-compatible with the app overlay;
// the app type retains stronger learner-state field types.
content: scene.content as SceneContent,
actions: scene.actions,
outlineId: scene.outlineId,
});
return result.success ? (result.data ?? null) : null;
}
/** Generate both halves and assemble a store-independent app scene. */
export async function buildSceneFromOutline(
outline: SceneOutline,
aiCall: AICallFn,
stageId: string,
assignedImages?: PdfImage[],
imageMapping?: ImageMapping,
languageModel?: LanguageModel,
visionEnabled?: boolean,
ctx?: SceneGenerationContext,
agents?: AgentInfo[],
onPhaseChange?: (phase: 'content' | 'actions') => void,
userProfile?: string,
languageDirective?: string,
): Promise<Scene | null> {
const safeOutline = applyOutlineFallbacks(outline, !!languageModel, { logger: log });
const langText = buildLanguageText(languageDirective, safeOutline.languageNote);
onPhaseChange?.('content');
const content = await generateSceneContent(safeOutline, aiCall, {
assignedImages,
imageMapping,
visionEnabled,
agents,
languageDirective: langText,
logger: log,
...(languageModel
? {
pblLoopFallback: (input) =>
generatePBLV2Project(input, languageModel, callLLM, { logger: log }),
}
: {}),
});
if (!content) return null;
onPhaseChange?.('actions');
const actions = await generateSceneActions(safeOutline, content, aiCall, {
ctx,
agents,
userProfile,
languageDirective: langText,
logger: log,
});
return buildCompleteScene(safeOutline, content, actions, stageId) as Scene | null;
}

View File

@ -1,6 +1,6 @@
import { parseJsonResponse } from '@/lib/generation/json-repair';
import { parseJsonResponse } from '@openmaic/generation';
import { PROMPT_IDS, buildPrompt } from '@/lib/prompts';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import type { AICallFn } from '@openmaic/generation';
import { createLogger } from '@/lib/logger';
const log = createLogger('SearchQueryBuilder');

View File

@ -10,7 +10,11 @@ const nextConfig: NextConfig = {
// (the "Edit with AI" Pro-mode path), which broke the #619 keep-alive e2e.
// Mark them server-external so Next loads them natively and the dynamic
// import resolves as a real Node call.
serverExternalPackages: ['@earendil-works/pi-ai', '@earendil-works/pi-agent-core'],
serverExternalPackages: [
'@earendil-works/pi-ai',
'@earendil-works/pi-agent-core',
'@openmaic/generation',
],
experimental: {
proxyClientMaxBodySize: '200mb',
},

View File

@ -1,6 +1,6 @@
{
"name": "@openmaic/generation",
"version": "0.2.0",
"version": "0.3.0",
"description": "Pure generation pipeline contracts and packaged prompt assets for MAIC consumers.",
"type": "module",
"main": "./dist/index.js",

View File

@ -28,7 +28,32 @@ export { postProcessInteractiveHtml } from './interactive-post-processor.js';
export { generatePBLV2ProjectSingleCall } from './pbl/planner-single-call.js';
export type { PlannerSingleCallFn } from './pbl/planner-single-call.js';
export type { PBLPlannerV2Input, PriorQuizResult } from './pbl/types.js';
export {
MAX_SYNTHESIS_STAGES,
PlannerV2Error,
SCENARIO_SCHEMA_VERSION,
applyPlannerProficiency,
buildPlannerSystemPrompt,
buildScenarioDesignBlock,
emptyProject,
instructorProjectAnchor,
newId,
normalizeSynthesisChecks,
plannerCompletionGaps,
} from './pbl/planner-core.js';
export type { PlannerV2Callbacks, PlannerV2ProgressEvent } from './pbl/planner-core.js';
export { loadPBLV2Prompt } from './pbl/prompts/loader.js';
export {
MAX_ENGAGEMENT_EVENTS,
capEngagementEvents,
microtaskEngagement,
milestoneSynthesisSatisfied,
recordEvent,
} from './pbl/operations/kernel/engagement.js';
export * from './pbl/operations/kernel/proficiency.js';
export * from './pbl/operations/kernel/progress.js';
export * from './pbl/operations/kernel/runtime-events.js';
export * from './pbl/operations/kernel/task-completion.js';
export type {
CompleteScene,
CompleteSceneContent,
@ -59,6 +84,15 @@ export { parseJsonResponse } from './json-repair.js';
export type { JsonParsingOptions } from './json-repair.js';
export { noopGenerationLogger } from './logger.js';
export type { GenerationLogger } from './logger.js';
export {
buildCourseContext,
buildLanguageText,
buildVisionUserContent,
formatAgentsForPrompt,
formatImageDescription,
formatImagePlaceholder,
formatTeacherPersonaForPrompt,
} from './prompt-formatters.js';
export type {
ImageMapping,
MediaGenerationRequest,

View File

@ -11,14 +11,16 @@
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { interpolateVariables } from '../../prompts/loader.js';
const _cache = new Map<string, string>();
// `src/pbl/prompts` and `dist/pbl/prompts` have the same depth below the package root.
const PROMPTS_DIR = fileURLToPath(new URL('../../../prompts-pbl/', import.meta.url));
// Resolve from this module's URL via path operations so app bundlers do not
// mistake the Markdown directory for a statically imported module asset.
const PROMPTS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../../../prompts-pbl');
/** Read a markdown prompt by file name (without extension), cached. */
function readPromptFile(name: string): string {

View File

@ -3,12 +3,14 @@
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { LoadedPrompt, PromptId, PromptVariableDefaults, SnippetId } from './types.js';
// `src/prompts` and `dist/prompts` have the same depth below the package root.
const DEFAULT_PROMPTS_DIR = fileURLToPath(new URL('../../', import.meta.url));
// Resolve from this module's URL via path operations so app bundlers do not
// mistake the Markdown directory for a statically imported module asset.
const DEFAULT_PROMPTS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const PROMPT_VARIABLE_DEFAULTS = {
'pbl-actions': {

View File

@ -1,14 +1,13 @@
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'vitest';
import { loadSnippet } from '@openmaic/generation';
import type { SnippetId } from '@openmaic/generation';
const PACKAGE_ROOT = fileURLToPath(new URL('../', import.meta.url));
const APP_PROMPTS_DIR = resolve(PACKAGE_ROOT, '../../..', 'lib', 'prompts');
const APP_PBL_PROMPTS_DIR = resolve(PACKAGE_ROOT, '../../..', 'lib', 'pbl', 'v2', 'prompts');
const PBL_PROMPT_FILES = [
'planner-system.md',
'planner-scenario-single-call-system.md',
'planner-single-call-system.md',
] as const;
@ -78,17 +77,10 @@ describe('packaged prompt assets', () => {
expect(actualFiles).toEqual(expectedFiles);
});
test.each(expectedFiles)('%s is byte-identical to the app asset', (assetPath) => {
const packageBytes = readFileSync(join(PACKAGE_ROOT, assetPath));
const appBytes = readFileSync(join(APP_PROMPTS_DIR, assetPath));
expect(Buffer.compare(packageBytes, appBytes)).toBe(0);
});
test.each(PBL_PROMPT_FILES)('prompts-pbl/%s is byte-identical to the app asset', (filename) => {
const packageBytes = readFileSync(join(PACKAGE_ROOT, 'prompts-pbl', filename));
const appBytes = readFileSync(join(APP_PBL_PROMPTS_DIR, filename));
expect(Buffer.compare(packageBytes, appBytes)).toBe(0);
test.each(PBL_PROMPT_FILES)('ships prompts-pbl/%s', (filename) => {
expect(
readFileSync(join(PACKAGE_ROOT, 'prompts-pbl', filename), 'utf8').length,
).toBeGreaterThan(100);
});
test('every referenced snippet is packaged and represented by SnippetId', () => {

View File

@ -1,5 +1,4 @@
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { describe, expect, it, vi } from 'vitest';
import { generatePBLV2ProjectSingleCall, type AICallFn } from '@openmaic/generation';
import { pblPlannerInput, validPBLResponse } from './scene-fixtures.js';
@ -38,59 +37,21 @@ describe('re-seated PBL single-call planner', () => {
});
describe('PBL planner re-seat proof', () => {
it('produces the same normalized project through app and package call seams', () => {
const repositoryRoot = fileURLToPath(new URL('../../../../', import.meta.url));
it('keeps the app compatibility barrel on the package function', async () => {
const input = pblPlannerInput();
const response = validPBLResponse();
const program = `
import assert from 'node:assert/strict';
import { generatePBLV2ProjectSingleCall as packageGenerate } from './packages/@openmaic/generation/src/index.ts';
const appModule = await import('./lib/pbl/v2/agents/planner-single-call.ts');
const appGenerate = appModule.generatePBLV2ProjectSingleCall ?? appModule.default?.generatePBLV2ProjectSingleCall;
assert.equal(typeof appGenerate, 'function');
const input = ${JSON.stringify(input)};
const response = ${JSON.stringify(response)};
const appProject = await appGenerate(
input,
{ provider: 'proof', modelId: 'proof' },
async () => ({ text: response }),
);
const packageProject = await packageGenerate(input, async () => response);
function canonicalize(root) {
const ids = new Map();
let nextId = 1;
const visit = (value, key = '') => {
if (Array.isArray(value)) return value.map((entry) => visit(entry));
if (value && typeof value === 'object') {
return Object.fromEntries(Object.entries(value).map(([name, entry]) => [name, visit(entry, name)]));
}
if (typeof value === 'string') {
if (key === 'id' || key === 'agentId' || key.endsWith('Id')) {
if (!ids.has(value)) ids.set(value, '<id-' + nextId++ + '>');
return ids.get(value);
}
if (key === 'ts' || key.endsWith('At')) return '<timestamp>';
}
return value;
};
return visit(root);
}
assert.deepEqual(canonicalize(packageProject), canonicalize(appProject));
console.log(JSON.stringify({ equal: true, normalization: 'ids-and-timestamps' }));
`;
const output = execFileSync(
process.execPath,
['--import', 'tsx', '--input-type=module', '--eval', program],
{ cwd: repositoryRoot, encoding: 'utf8' },
const appBarrel = readFileSync(
new URL('../../../../lib/pbl/v2/agents/planner-single-call.ts', import.meta.url),
'utf8',
);
expect(JSON.parse(output.trim().split('\n').at(-1) ?? '{}')).toEqual({
equal: true,
normalization: 'ids-and-timestamps',
expect(appBarrel).toContain(
"export { generatePBLV2ProjectSingleCall } from '@openmaic/generation';",
);
await expect(
generatePBLV2ProjectSingleCall(input, async () => response),
).resolves.toMatchObject({
title: 'CSV Data Analyzer project',
status: 'active',
});
});
});

View File

@ -1,7 +1,6 @@
import { describe, expect, test } from 'vitest';
import { extractWidgetConfig, generateWidgetContent } from '@/lib/generation/scene-generator';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import { extractWidgetConfig, generateWidgetContent, type AICallFn } from '@openmaic/generation';
import type { SceneOutline } from '@/lib/types/generation';
const renderDiagramPrompt = async (widgetOutline: SceneOutline['widgetOutline']) => {

View File

@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';
import { extractInteractiveElements } from '@/lib/generation/scene-generator';
import { extractInteractiveElements } from '@openmaic/generation';
describe('extractInteractiveElements', () => {
test('returns empty string on empty input', () => {

View File

@ -7,8 +7,7 @@
*/
import { describe, expect, it } from 'vitest';
import { generateSceneActions } from '@/lib/generation/scene-generator';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import { generateSceneActions, type AICallFn } from '@openmaic/generation';
import type { GeneratedInteractiveContent, SceneOutline } from '@/lib/types/generation';
function baseOutline(): SceneOutline {

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { parseJsonResponse } from '@/lib/generation/json-repair';
import { parseJsonResponse } from '@openmaic/generation';
describe('json-repair targeted fixes', () => {
it('repairs quoted key-value fragments such as "height: 76"', () => {

View File

@ -1,8 +1,7 @@
import { describe, expect, test } from 'vitest';
import { generateSceneOutlinesFromRequirements } from '@/lib/generation/outline-generator';
import { generateSceneContent } from '@/lib/generation/scene-generator';
import { generateSceneContent, generateSceneOutlinesFromRequirements } from '@openmaic/generation';
import type { SceneOutline, UserRequirements } from '@/lib/types/generation';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import type { AICallFn } from '@openmaic/generation';
describe('media prompt condition wiring', () => {
test('outline generation passes media enable flags into conditional snippets', async () => {

View File

@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
import { changeOutlineType } from '@/lib/generation/outline-type';
import { applyOutlineFallbacks } from '@/lib/generation/outline-generator';
import { applyOutlineFallbacks, changeOutlineType } from '@openmaic/generation';
import type { SceneOutline } from '@/lib/types/generation';
const base: SceneOutline = {

View File

@ -1,79 +1,86 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { PBLGenerationError, generateSceneContent, type AICallFn } from '@openmaic/generation';
import { validateAppScene } from '@/lib/document-store/validators';
import { hasPBLProjectV2Containers, isRunnablePBLProjectV2 } from '@/lib/pbl/v2/types';
import type { GeneratedPBLContent, SceneOutline } from '@/lib/types/generation';
import type { AppScene } from '@/lib/types/stage';
const generatePBLV2ProjectSingleCallMock = vi.hoisted(() => vi.fn());
const generatePBLV2ProjectMock = vi.hoisted(() => vi.fn());
const loggerMock = vi.hoisted(() => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
}));
vi.mock('@/lib/pbl/v2/agents/planner-single-call', () => ({
generatePBLV2ProjectSingleCall: generatePBLV2ProjectSingleCallMock,
}));
vi.mock('@/lib/pbl/v2/agents/planner', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/pbl/v2/agents/planner')>()),
generatePBLV2Project: generatePBLV2ProjectMock,
}));
vi.mock('@/lib/logger', () => ({
createLogger: () => loggerMock,
}));
function pblOutline(): SceneOutline {
function pblOutline(scenarioRoleplay = false): SceneOutline {
return {
id: 'scene-pbl-1',
type: 'pbl',
title: 'CSV Data Analyzer',
title: scenarioRoleplay ? 'Difficult feedback conversation' : 'CSV Data Analyzer',
description: 'Build a small CSV analysis project.',
keyPoints: ['CSV', 'summary'],
order: 1,
pblConfig: {
projectTopic: 'CSV Data Analyzer',
projectTopic: scenarioRoleplay ? 'Difficult feedback conversation' : 'CSV Data Analyzer',
projectDescription: 'Build a small CSV analysis project.',
targetSkills: ['CSV parsing', 'summary writing'],
issueCount: 2,
scenarioRoleplay,
},
};
}
function scenarioPblOutline(): SceneOutline {
const outline = pblOutline();
function validSingleCallResponse(): string {
return JSON.stringify({
projectInfo: {
title: 'CSV Data Analyzer project',
description: 'Analyze a CSV and report findings.',
learningObjective: 'Practice end-to-end analysis.',
gains: ['Inspect tabular data', 'Summarize evidence', 'Communicate a finding'],
proficiency: 'beginner',
},
instructorRole: {
name: 'Data Coach',
description: 'I will guide your analysis.',
systemPrompt: 'Coach the learner through evidence-based analysis.',
},
milestones: [
{
title: 'Inspect the CSV',
description: 'Inspect columns and values.',
briefing: 'Start with the data.',
completionCriteria: 'The columns are understood.',
debrief: 'The data is ready.',
microtasks: [{ title: 'Inspect columns', description: 'List the columns.', hints: [] }],
},
{
title: 'Report a finding',
description: 'Write one supported finding.',
briefing: 'Turn data into evidence.',
completionCriteria: 'A supported finding is written.',
debrief: 'The analysis is complete.',
microtasks: [{ title: 'Write finding', description: 'Cite one value.', hints: [] }],
},
],
});
}
function fallbackProject() {
return {
...outline,
title: 'Difficult feedback conversation',
description: 'Practice giving feedback to a teammate.',
pblConfig: {
...outline.pblConfig!,
projectTopic: 'Difficult feedback conversation',
projectDescription: 'Practice giving feedback to a teammate.',
targetSkills: ['active listening', 'clear feedback'],
scenarioRoleplay: true,
scenarioBrief: 'The learner gives feedback to a teammate after a missed deadline.',
},
title: 'Recovered project',
description: 'Recovered by the app loop planner.',
tags: [],
language: 'en-US',
proficiency: 'beginner' as const,
status: 'active' as const,
uiPhase: 'hero' as const,
roles: [{ id: 'role-1', type: 'instructor' as const, name: 'Instructor' }],
milestones: [{ id: 'ms-1', microtasks: [{ id: 'mt-1', title: 'Recovered task' }] }],
submissions: [],
evaluations: [],
threads: [],
engagementEvents: [],
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
}
function mockModel() {
return { provider: 'test', modelId: 'test-model' } as never;
}
async function plannerError(message: string) {
const { PlannerV2Error } = await import('@/lib/pbl/v2/agents/planner-core');
return new PlannerV2Error(message, {} as never);
}
function expectPersistablePBLContent(content: GeneratedPBLContent | null): void {
expect(content).not.toBeNull();
if (!content) throw new Error('expected generated PBL content');
expect(hasPBLProjectV2Containers(content.projectV2)).toBe(true);
expect(isRunnablePBLProjectV2(content.projectV2)).toBe(true);
const scene = {
@ -88,211 +95,86 @@ function expectPersistablePBLContent(content: GeneratedPBLContent | null): void
}
describe('generateSceneContent — PBL v2 planner routing', () => {
beforeEach(() => {
vi.resetModules();
generatePBLV2ProjectSingleCallMock.mockReset();
generatePBLV2ProjectMock.mockReset();
loggerMock.info.mockReset();
loggerMock.warn.mockReset();
loggerMock.error.mockReset();
loggerMock.debug.mockReset();
});
it('always tries single-call first and returns only projectV2', async () => {
const projectV2 = {
title: 'CSV Data Analyzer project',
milestones: [{ microtasks: [{ id: 'task_1', title: 'Inspect the CSV' }] }],
roles: [{ id: 'role_1', type: 'instructor', name: 'Instructor' }],
submissions: [],
evaluations: [],
threads: [{ messages: [] }],
engagementEvents: [],
};
generatePBLV2ProjectSingleCallMock.mockResolvedValue(projectV2);
const { generateSceneContent } = await import('@/lib/generation/scene-generator');
const content = (await generateSceneContent(pblOutline(), vi.fn(), {
languageModel: mockModel(),
it('uses the package single-call path before the app loop fallback', async () => {
const aiCall = vi.fn<AICallFn>().mockResolvedValue(validSingleCallResponse());
const fallback = vi.fn();
const content = (await generateSceneContent(pblOutline(), aiCall, {
languageDirective: 'Reply in English.',
pblLoopFallback: fallback,
})) as GeneratedPBLContent | null;
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledWith(
expect.objectContaining({
courseContext: expect.objectContaining({ languageDirective: 'Reply in English.' }),
expect(aiCall).toHaveBeenCalledTimes(1);
expect(fallback).not.toHaveBeenCalled();
expect(content).toMatchObject({ projectV2: { title: 'CSV Data Analyzer project' } });
expectPersistablePBLContent(content);
});
it('runs the injected app loop after classified single-call validation failure', async () => {
const fallback = vi.fn().mockResolvedValue(fallbackProject());
const content = (await generateSceneContent(pblOutline(), async () => '{}', {
pblLoopFallback: fallback,
})) as GeneratedPBLContent | null;
expect(fallback).toHaveBeenCalledTimes(1);
expect(content).toEqual({ projectV2: fallbackProject() });
expectPersistablePBLContent(content);
});
it('preserves the loop planner failure as the terminal cause', async () => {
const loopError = Object.assign(new Error('loop rate limited'), { status: 429 });
await expect(
generateSceneContent(pblOutline(), async () => '{}', {
pblLoopFallback: vi.fn().mockRejectedValue(loopError),
}),
expect.anything(),
expect.any(Function),
expect.objectContaining({ onProgress: expect.any(Function) }),
undefined,
);
expect(generatePBLV2ProjectMock).not.toHaveBeenCalled();
expect(content).toEqual({ projectV2 });
expect(content).not.toHaveProperty('projectConfig');
expectPersistablePBLContent(content);
});
it('falls back to the loop when single-call validation fails', async () => {
const projectV2 = {
title: 'CSV Data Analyzer project',
milestones: [
{ microtasks: [{ id: 'task_1', title: 'Inspect the CSV' }] },
{ microtasks: [{ id: 'task_2', title: 'Summarize the data' }] },
],
roles: [{ id: 'role_1', type: 'instructor', name: 'Instructor' }],
submissions: [],
evaluations: [],
threads: [{ messages: [] }],
engagementEvents: [],
};
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(
await plannerError('single-call failed'),
);
generatePBLV2ProjectMock.mockResolvedValue(projectV2);
const { generateSceneContent } = await import('@/lib/generation/scene-generator');
const content = (await generateSceneContent(pblOutline(), vi.fn(), {
languageModel: mockModel(),
})) as GeneratedPBLContent | null;
expect(content).toEqual({ projectV2 });
expectPersistablePBLContent(content);
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectMock).toHaveBeenCalledTimes(1);
});
it('surfaces an error for ordinary PBL when both v2 attempts fail', async () => {
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(
await plannerError('single-call failed'),
);
generatePBLV2ProjectMock.mockRejectedValueOnce(new Error('loop failed'));
const { generateSceneContent, PBLGenerationError } =
await import('@/lib/generation/scene-generator');
await expect(
generateSceneContent(pblOutline(), vi.fn(), { languageModel: mockModel() }),
).rejects.toBeInstanceOf(PBLGenerationError);
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectMock).toHaveBeenCalledTimes(1);
});
it('preserves the last planner failure as cause and exposes its HTTP status', async () => {
const firstError = await plannerError('single-call validation failed');
const lastError = Object.assign(new Error('loop rate limited'), { status: 429 });
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(firstError);
generatePBLV2ProjectMock.mockRejectedValueOnce(lastError);
const { generateSceneContent, PBLGenerationError } =
await import('@/lib/generation/scene-generator');
try {
await generateSceneContent(pblOutline(), vi.fn(), { languageModel: mockModel() });
throw new Error('expected PBL generation to fail');
} catch (error) {
expect(error).toBeInstanceOf(PBLGenerationError);
expect(error).toMatchObject({
message: 'PBL v2 generation failed for "CSV Data Analyzer" after all planner attempts.',
statusCode: 429,
cause: lastError,
});
}
});
it('parses a numeric-string provider status and skips the loop fallback', async () => {
const firstError = Object.assign(new Error('single-call rate limited'), {
statusCode: '429',
).rejects.toMatchObject({
name: PBLGenerationError.name,
statusCode: 429,
cause: loopError,
});
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(firstError);
const { generateSceneContent, PBLGenerationError } =
await import('@/lib/generation/scene-generator');
try {
await generateSceneContent(pblOutline(), vi.fn(), { languageModel: mockModel() });
throw new Error('expected PBL generation to fail');
} catch (error) {
expect(error).toBeInstanceOf(PBLGenerationError);
expect(error).toMatchObject({ statusCode: 429, cause: firstError });
}
expect(generatePBLV2ProjectMock).not.toHaveBeenCalled();
});
it('continues to refuse degradation when scenario PBL v2 generation fails', async () => {
const firstError = await plannerError('single-call validation failed');
const lastError = Object.assign(new Error('loop rate limited'), { status: 429 });
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(firstError);
generatePBLV2ProjectMock.mockRejectedValueOnce(lastError);
const { generateSceneContent, PBLGenerationError } =
await import('@/lib/generation/scene-generator');
try {
await generateSceneContent(scenarioPblOutline(), vi.fn(), { languageModel: mockModel() });
throw new Error('expected scenario PBL generation to fail');
} catch (error) {
expect(error).toBeInstanceOf(PBLGenerationError);
expect(error).toMatchObject({
message:
'PBL v2 scenario generation failed for "Difficult feedback conversation" after all planner attempts.',
statusCode: 429,
cause: lastError,
});
}
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectMock).toHaveBeenCalledTimes(1);
});
it('does not run the loop planner after a single-call provider failure', async () => {
const unauthorized = Object.assign(new Error('provider key rejected'), { statusCode: 401 });
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(unauthorized);
const { generateSceneContent, PBLGenerationError } =
await import('@/lib/generation/scene-generator');
try {
await generateSceneContent(pblOutline(), vi.fn(), { languageModel: mockModel() });
throw new Error('expected PBL generation to fail');
} catch (error) {
expect(error).toBeInstanceOf(PBLGenerationError);
expect(error).toMatchObject({ statusCode: 401, cause: unauthorized });
}
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectMock).not.toHaveBeenCalled();
});
it('falls back to the loop planner after an unexpected runtime error', async () => {
const projectV2 = {
title: 'Recovered project',
roles: [{ id: 'role-i', type: 'instructor', name: 'Instructor' }],
milestones: [{ id: 'ms-1', microtasks: [{ id: 'mt-1', title: 'Recovered task' }] }],
submissions: [],
evaluations: [],
threads: [],
engagementEvents: [],
};
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(
new TypeError('unexpected runtime failure'),
);
generatePBLV2ProjectMock.mockResolvedValueOnce(projectV2);
const { generateSceneContent } = await import('@/lib/generation/scene-generator');
it('skips the loop fallback after a provider failure', async () => {
const fallback = vi.fn();
const providerError = Object.assign(new Error('provider key rejected'), { statusCode: 401 });
await expect(
generateSceneContent(pblOutline(), vi.fn(), { languageModel: mockModel() }),
).resolves.toEqual({ projectV2 });
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectMock).toHaveBeenCalledTimes(1);
generateSceneContent(
pblOutline(),
async () => {
throw providerError;
},
{ pblLoopFallback: fallback },
),
).rejects.toMatchObject({
name: PBLGenerationError.name,
statusCode: 401,
cause: providerError,
});
expect(fallback).not.toHaveBeenCalled();
});
it('does not run the loop planner after cancellation', async () => {
it('skips the loop fallback after cancellation', async () => {
const fallback = vi.fn();
const aborted = new DOMException('The operation was aborted', 'AbortError');
generatePBLV2ProjectSingleCallMock.mockRejectedValueOnce(aborted);
const { generateSceneContent, PBLGenerationError } =
await import('@/lib/generation/scene-generator');
await expect(
generateSceneContent(pblOutline(), vi.fn(), { languageModel: mockModel() }),
generateSceneContent(
pblOutline(),
async () => {
throw aborted;
},
{ pblLoopFallback: fallback },
),
).rejects.toMatchObject({ name: PBLGenerationError.name, cause: aborted });
expect(generatePBLV2ProjectSingleCallMock).toHaveBeenCalledTimes(1);
expect(generatePBLV2ProjectMock).not.toHaveBeenCalled();
expect(fallback).not.toHaveBeenCalled();
});
it('keeps scenario failures on the no-degradation error path', async () => {
await expect(
generateSceneContent(pblOutline(true), async () => '{}', {
pblLoopFallback: vi.fn().mockRejectedValue(new Error('loop failed')),
}),
).rejects.toMatchObject({
name: PBLGenerationError.name,
message: expect.stringContaining('generation failed'),
});
});
});

View File

@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';
import { applyOutlineFallbacks } from '@/lib/generation/outline-generator';
import { applyOutlineFallbacks } from '@openmaic/generation';
import type { SceneOutline } from '@/lib/types/generation';
describe('procedural-skill content gates', () => {

View File

@ -1,7 +1,6 @@
import { describe, expect, test } from 'vitest';
import { generateSceneContent, generateWidgetContent } from '@/lib/generation/scene-generator';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import { generateSceneContent, generateWidgetContent, type AICallFn } from '@openmaic/generation';
import type { GeneratedInteractiveContent, SceneOutline } from '@/lib/types/generation';
const DIRECTIVE = '<<PROCEDURAL-SKILL-LANGUAGE-DIRECTIVE>>';

View File

@ -25,7 +25,8 @@ vi.mock('@/lib/config/feature-flags', () => ({
resolveVocationalActive: mocks.resolveVocationalActive,
}));
vi.mock('@/lib/generation/generation-pipeline', () => ({
vi.mock('@openmaic/generation', async (importOriginal) => ({
...(await importOriginal<typeof import('@openmaic/generation')>()),
applyOutlineFallbacks: mocks.applyOutlineFallbacks,
generateSceneContent: mocks.generateSceneContent,
generateSceneActions: mocks.generateSceneActions,
@ -288,7 +289,7 @@ describe('scene API retry boundary', () => {
it('preserves the provider status carried by a PBLGenerationError', async () => {
vi.resetModules();
const providerError = Object.assign(new Error('provider rate limited'), { statusCode: 429 });
const { PBLGenerationError } = await import('@/lib/generation/scene-generator');
const { PBLGenerationError } = await import('@openmaic/generation');
mocks.generateSceneContent.mockRejectedValueOnce(
new PBLGenerationError('PBL planners failed', {
cause: providerError,

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { buildCompleteScene } from '@/lib/generation/scene-builder';
import { buildCompleteScene } from '@openmaic/generation';
import type { GeneratedPBLContent, SceneOutline } from '@/lib/types/generation';
import type { PBLProjectV2 } from '@/lib/pbl/v2/types';

View File

@ -10,9 +10,8 @@
*/
import { describe, expect, it } from 'vitest';
import { generateSceneContent, generateSceneActions } from '@/lib/generation/scene-generator';
import { buildSceneFromOutline } from '@/lib/generation/scene-builder';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import { generateSceneActions, generateSceneContent, type AICallFn } from '@openmaic/generation';
import { buildSceneFromOutline } from '@/lib/server/scene-generation';
import { normalizeLegacyPBLContent } from '@/lib/pbl/legacy/read';
import { legacyPBLSceneFixture } from '@/tests/fixtures/pbl-v1-scene';
import type {

View File

@ -10,8 +10,7 @@
*/
import { describe, expect, it } from 'vitest';
import { generateSceneContent } from '@/lib/generation/scene-generator';
import type { AICallFn } from '@/lib/generation/pipeline-types';
import { generateSceneContent, type AICallFn } from '@openmaic/generation';
import type { SceneOutline, GeneratedSlideContent } from '@/lib/types/generation';
const INSTRUCTION = '<<EDIT-INSTRUCTION-SENTINEL>> make it concise';

Some files were not shown because too many files have changed in this diff Show More