@eliceio/cdk-cli 1.6.0-entryqa.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@ Run `ecdk create --list` first: it prints each template with its own version (`q
9
9
  | Any other material | `ecdk create <folder> --template blank` (three screens with a small example to replace, "예측하고 확인하기", and the kit content editor on the edit screen: see 5) |
10
10
  | A material in several steps (intro → experiment → summary, slides) | `ecdk create <folder> --template steps` (kit stepper `app.useStepper` and a different content layout per step, example "진자의 주기", content editor on the edit screen: see [14](14-layouts.md)) |
11
11
  | One document to read (PDF or PPTX, completion on opening) | `ecdk create <folder> --template document` (the edit screen uploads a `.pdf` or `.pptx` and edits PPTX slide text in place; the student screen pages through it; `on_access` picked in LXP; `.ppt` · `.pps` · `.ppsx` must be saved as `.pptx` or `.pdf` first; in `ecdk dev` the file stays in `.ecdk/assets/`; for a page on LXP upload it with the MCP `create_asset_upload`, [12](12-upload-with-the-material-mcp.md) "Images and documents") |
12
+ | Block coding or Entry Python practice in Entry, AI blocks included | `ecdk create <folder> --template entry` (the Entry workspace in an iframe, so it works only where the server's content CSP allows the workspace; the person builds the start and answer projects on the edit screen; general or AI grading; then [17](17-using-the-entry-template.md)) |
12
13
  | A dark screen | Add `--theme dark` to the above |
13
14
  | A problem description | Create with blank, set `metadata.json` to `{ "kind": "description", "screens": { "learn": { "enabled": true, "entry": "index.html" } }, "commentary": "commentary.txt" }`, delete the other screen files |
14
15
  | An existing HTML page | [7. Move existing HTML](07-move-existing-html.md) |
@@ -0,0 +1,59 @@
1
+ # 17. Using the Entry template
2
+
3
+ - **When to use it**: block coding or Entry Python practice in Entry (엔트리), including the AI blocks (인공지능 › 모델 학습하기). Create it with `ecdk create <folder> --template entry`. It is not in the LXP material type list, so make it with `ecdk create` and upload the zip. It has a student screen and an edit screen, and **no instructor screen** (`screens.instructor.enabled: false`): instructors get the student screen.
4
+ - **It needs the server to allow the workspace.** The screens show the Entry workspace in an `<iframe>` from another origin (`https://entry-workspace.elice.io`). The content CSP blocks it unless the server's content CSP lists that origin in `frame-src`; where it does not, the workspace area shows "엔트리를 열 수 없습니다." and nothing else works. Tell the person this before you build. Object pictures in the AI criteria rows stay empty for the same reason (`img-src`).
5
+ - **The inside of the workspace is not yours.** Blocks, menus and the stage come from the workspace. The project can change only the screen around it (`ui/`, `styles.css`, `screens/`) and what it passes in (the projects and the language). Hiding blocks or adding a workspace option needs a change in the workspace itself: tell the person it is a feature request. Do not edit `core/` (Always).
6
+
7
+ **Who makes what**
8
+
9
+ - **The start project and the answer project are Entry project JSON. Never write or change them yourself**, not in code and not in `.ecdk/settings.json`. The person builds them with blocks and objects in the workspace on the edit screen (the content edit view in `ecdk dev`, or the LXP edit screen after the upload) and presses "초안으로 저장".
10
+ - **You draft the words around them**: `commentary.txt` (what to make, blocks that must be used, when it is done; no answers, learners can read it), AI grading criteria and scores, and the completion policy. Give the criteria to the person as text to type in: each row belongs to an object of the answer project, so it can be filled in only after that project exists. Write them as one check each, like the edit screen's examples ("시작하면 x좌표를 100 이동하는가?").
11
+ - The student screen shows only the workspace and its bottom bar; there is no text area for the task. If learners must read the task on screen, suggest a problem description page before this one ([3](03-create-the-project.md), `kind: description`), or that the person writes it into the start project (for example a text box object).
12
+
13
+ **The edit screen**
14
+
15
+ - **"언어 선택"** at the top: "블록 코딩" (`block`) or "엔트리파이썬" (`python`). Changing it reloads the workspace.
16
+ - **"시작 화면" tab**: the project learners open first.
17
+ - **"채점 설정" tab**: the answer project (it opens with the saved answer, otherwise a copy of the current start project, so object ids match), then "채점 방식":
18
+ - **"일반 채점"**: the server compares the learner's project with the answer project, 0 or 100. The answer project needs at least one block script or global list, or the save is blocked.
19
+ - **"AI 채점"**: rows of 오브젝트 · 채점 기준 · 부분 점수, and the AI gives a partial score per row. 1–10 rows, each criterion up to 1,000 characters, integer scores 1–100 that sum to exactly 100 (`core/grading.js` `RUBRIC_LIMITS`). "자동 배점" splits 100 evenly and gives the rest to the last row (3 → 33 · 33 · 34). Every row picks one object of the answer project; there is no whole-project criterion. AI grading also needs a start project.
20
+ - A new material whose "채점 설정" tab was never opened saves with no grading.
21
+ - The chip under the project shows the size of the whole settings. The limit is 64KB (`core/settings.js` `LIMITS`); a bigger project cannot be saved.
22
+ - In an AI-graded material, changing a saved start project shows a warning. If learners already started, tell the person: work equal to the new start project scores 0, and learners who started from the old one may be graded wrong.
23
+
24
+ **Settings** (written by the edit screen; never by hand, 2 ②). `settings.entry` goes to every viewer, learners included, so never put an answer there:
25
+
26
+ ```json
27
+ {
28
+ "startProject": { "enc": "gzip+base64", "data": "…" },
29
+ "preference": { "workspaceMode": "block" }
30
+ }
31
+ ```
32
+
33
+ `settings.grading` holds the answer project and the criteria. It never goes to learners and never goes in the zip, like every template. `"mode": "general"` has only `type`, `mode` and `answer_project`:
34
+
35
+ ```json
36
+ {
37
+ "type": "entry",
38
+ "mode": "ai",
39
+ "answer_project": { "enc": "gzip+base64", "data": "…" },
40
+ "rubrics": [{ "object": "ik8o", "criteria": "…", "score": 100 }]
41
+ }
42
+ ```
43
+
44
+ Other settings keys are kept when the edit screen saves.
45
+
46
+ **Completion policy** (12 "Completion policy"): graded → `on_graded` ("답안 확인 후 완료"), only with `settings.grading` saved; without it every submission scores 0 and never completes. Submit only, no grading → `on_submit`. This template has no default policy on the server, so propose one with the upload.
47
+
48
+ **The student screen**
49
+
50
+ - It opens the learner's saved work, otherwise the start project, otherwise Entry's default project. It saves by itself 2 seconds after a change ("저장됨 …", kvstore up to 512KB). The tutoring view only reads; the editor preview does not save.
51
+ - "제출하기" sends the project (up to 64KB) and the server grades it with `settings.grading`. The bar shows "최종 제출 : N점 (time)". General grading shows "올바르게 작성했어요" or "틀렸어요. 다시 해보세요."; AI grading shows "AI 채점", waits up to 45 seconds, then "AI 피드백 보기" with feedback per criterion.
52
+ - In Python mode a syntax error stops saving and submitting until the code is fixed.
53
+ - **AI training (모델 학습하기)**: the material saves the training data and models in the learner's files (kit `app.learnerFiles`, SDK `learnerFiles`, a temporary API) and kvstore (`entryMl.*`), only on the student screen. The editor preview keeps them in memory, so a saved model cannot be opened again there. The edit screen does not save AI training at all, so a start project cannot carry a trained model: learners train their own. There is no model file upload or download.
54
+
55
+ **Checking it in `ecdk dev`**
56
+
57
+ - It needs an Entry workspace running at `http://localhost:9000`; ecdk does not include one (the template README, "로컬에서 확인"). `ecdk dev` adds that origin to its CSP. Without it the workspace area shows "엔트리를 불러오지 못했습니다." after a wait.
58
+ - `ecdk dev --check` sees only the first state and cannot look inside the workspace. Ask the person to build the projects and try the screens in the browser.
59
+ - Grading in `ecdk dev` is a mock: general gives 100 only when the project is exactly the answer project, and AI gives a size-based score with sample feedback. Real grading happens only on LXP.
@@ -17,6 +17,7 @@ Reference files are in `references/` in this skill's folder (see Always). For th
17
17
  - Stays on "Loading" or shows nothing: rebuild with the current `ecdk build` (it adapts the pages to the LXP sandbox) and check the built zip with `ecdk validate dist/content.zip`. Ask the person for the browser console error.
18
18
  - Upload rejected: check `ecdk validate dist/content.zip`; a material needs `commentary.txt` and every file named in `metadata.json`.
19
19
  - Screens show "학습 자료를 준비하고 있어요": nothing is saved yet; create the content in the edit screen (there is no default content file), and in LXP press '수업 자료에 반영' at the top of the edit page after saving the edit screen (`references/12-upload-with-the-material-mcp.md`, "Fallback").
20
+ - The Entry template shows "엔트리를 열 수 없습니다.": the server's content CSP does not allow the Entry workspace in `frame-src`; the project cannot fix it (`references/17-using-the-entry-template.md`).
20
21
  - Answers or grading wrong: check the answers on the edit screen (saving in the `ecdk dev` content edit view writes `.ecdk/settings.json`) and that the submitted answer string matches the regex (`references/02-design-the-material.md`, `references/06-using-the-quiz-template.md`). In `ecdk dev` a submission is graded only when grading is saved; otherwise it is only accepted. Completing at the wrong time is the completion policy, an LXP setting (Always).
21
22
  4. **Confirm.** `ecdk validate` has no errors, `ecdk dev --check` passes (or the person checked the dev URL), and `ecdk build --json` returns `ok: true`. Tell the person what caused it and what you changed.
22
23
 
@@ -15,7 +15,7 @@ Write the progress line `[n/N] …` before and after every step below (Always
15
15
 
16
16
  1. **Design before code.** Read `references/00-what-the-person-decides.md` and `references/02-design-the-material.md`. Decide ① what the student does, ② whether the student submits and the grading (`type` `pattern` or `rubric`, set on the edit screen; the quiz template uses `pattern`, so do not ask for a quiz; AI grading is `rubric` saved by the edit screen's `getGrading` and the student submits only the answer, never a score computed with `mlapi`, `references/05-screen-code.md` "AI grading") and which completion policy fits (the publish skill sets it after the person agrees; only `on_graded` grades, `on_submit` completes on any submission without grading), ③ the instructor screen (seen only in the LXP editor preview; instructors on the learning page see the student screen), ④ the content edit screen, ⑤ the purpose. Decide what the request leaves out and tell the person briefly; ask only when the learning goal is unclear. Then show the numbered plan.
17
17
  2. **Environment and project.** `ecdk --version && ecdk doctor --json` (`references/01-check-the-environment.md`, also for `cli.latest`), then `ecdk create --list` to pick a template and `ecdk create <folder> --template <name>` (`references/03-create-the-project.md`; it runs `npm install` for the SDK, so when that fails run `npm install` in the project). Start `ecdk dev <folder>` in the background now and give the person the URL.
18
- 3. **Write the screens.** Start from the template's example code and the kit API table at the top of `references/05-screen-code.md`; do not open `lib/` to learn the API (the table is the API). Follow its UI patterns (kit icon buttons, list rows, drop zones; the quiz template: `references/06-using-the-quiz-template.md`; a survey (opinions, feedback, self-assessment, no right answers): the survey template and `references/16-using-the-survey-template.md` for the settings shape, question-writing rules, personal data and where the answers are); an edit screen you write by hand follows `references/13-edit-screen-design.md` (kit classes, layout, microcopy); when a student or instructor screen has nothing to show, always use `app.emptyState()`, never your own empty-state markup, illustration or text (`references/05-screen-code.md`, "Nothing to show"), and write `commentary.txt` (key concepts and intent, no answers). There is no default content file: the content and answers are what the edit screen saves (`ecdk dev` writes `.ecdk/settings.json`, local by default; the elice-content-publish skill can send it with the upload after the person agrees, otherwise the person enters it in the LXP edit screen).
18
+ 3. **Write the screens.** Start from the template's example code and the kit API table at the top of `references/05-screen-code.md`; do not open `lib/` to learn the API (the table is the API). Follow its UI patterns (kit icon buttons, list rows, drop zones; the quiz template: `references/06-using-the-quiz-template.md`; a survey (opinions, feedback, self-assessment, no right answers): the survey template and `references/16-using-the-survey-template.md` for the settings shape, question-writing rules, personal data and where the answers are; block coding in Entry: the Entry template and `references/17-using-the-entry-template.md`, where the person builds the start and answer projects on the edit screen and you never write project JSON); an edit screen you write by hand follows `references/13-edit-screen-design.md` (kit classes, layout, microcopy); when a student or instructor screen has nothing to show, always use `app.emptyState()`, never your own empty-state markup, illustration or text (`references/05-screen-code.md`, "Nothing to show"), and write `commentary.txt` (key concepts and intent, no answers). There is no default content file: the content and answers are what the edit screen saves (`ecdk dev` writes `.ecdk/settings.json`, local by default; the elice-content-publish skill can send it with the upload after the person agrees, otherwise the person enters it in the LXP edit screen).
19
19
  - For a material that is not a quiz or a survey, start from the blank template and its content editor: design the content JSON shape and its schema first (`references/02-design-the-material.md` ④-1), put them in `screens/edit.js` (`useContentEditor(app, { initial, schema })`), then write the student screen against that shape. Replace the template's example everywhere it says `이 자료에 맞게 바꿀 곳`.
20
20
  - If the person describes the content (for example "5 questions about perceptrons"), fill it in so the upload can carry it: write `.ecdk/settings.json` in the shape `references/09-check.md` describes (the edit screen's content object at the top level, `grading` when graded), then have the person open the edit view in `ecdk dev`, check it and save with the edit screen's button, so the edit screen's own validation runs. Draft the answers, but the person confirms them before any upload (Always). One quiz material holds up to 20 questions (`references/06-using-the-quiz-template.md`): put them all in one material; only more than 20 means several quiz materials (pages). If the person prefers, give the content as draft text (the content editor: one JSON block for 코드 보기) to enter in the LXP edit screen instead.
21
21
  4. **Check each screen** with `ecdk dev <folder> --check --screens <screen>` after you write it (`references/09-check.md`), fix what it reports (error ids: `references/08-fix-check-errors.md`). The person looks at the screens too.
@@ -5,7 +5,7 @@ description: Change an existing Elice Custom HTML learning material made with ec
5
5
 
6
6
  # Change an existing Elice learning material
7
7
 
8
- Reference files are in `references/` in this skill's folder (see Always). For this skill: `references/15-edit-settings-by-hand.md` (what each settings key means, building answer regexes with `core/model.js`, example diffs), `references/00-what-the-person-decides.md`, for a quiz `references/06-using-the-quiz-template.md`, and for a survey `references/16-using-the-survey-template.md` (keep question and option ids, no `grading`, its writing rules and checklist).
8
+ Reference files are in `references/` in this skill's folder (see Always). For this skill: `references/15-edit-settings-by-hand.md` (what each settings key means, building answer regexes with `core/model.js`, example diffs), `references/00-what-the-person-decides.md`, for a quiz `references/06-using-the-quiz-template.md`, and for a survey `references/16-using-the-survey-template.md` (keep question and option ids, no `grading`, its writing rules and checklist), and for the Entry template `references/17-using-the-entry-template.md` (its projects and grading are changed only on its edit screen, never by hand).
9
9
 
10
10
  {{always}}
11
11
 
@@ -127,6 +127,23 @@ interface Kvstore {
127
127
  delete(key: string, init?: RequestInit): Promise<void>;
128
128
  }
129
129
 
130
+ /** Learner files (provisional SDK API, waits for the SDK owners' agreement) */
131
+ interface LearnerFiles {
132
+ post(
133
+ file: Blob,
134
+ options: {
135
+ folder: string;
136
+ name: string;
137
+ contentType?: string;
138
+ onProgress?: (progress: { loaded: number; total: number }) => void;
139
+ signal?: AbortSignal;
140
+ }
141
+ ): Promise<{ key: string; folder: string; name: string; size: number }>;
142
+ /** The mock has no signed folder: null */
143
+ baseUrl(): Promise<{ url: string; expiresAt: number } | null>;
144
+ url(path: string): Promise<string | null>;
145
+ }
146
+
130
147
  interface Mlapi {
131
148
  /** Same as `fetch`. The mock answers 503 SERVICE_UNAVAILABLE (reason ai_not_configured) */
132
149
  fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
@@ -159,6 +176,7 @@ export declare class MockEliceCDK {
159
176
  /** 자료 파일. ecdk dev 콘텐츠 주소를 직접 열면 흉내 서버에, 아니면 이 페이지 메모리에만 (blob:) */
160
177
  readonly assets: Assets;
161
178
  readonly kvstore: Kvstore;
179
+ readonly learnerFiles: LearnerFiles;
162
180
  readonly mlapi: Mlapi;
163
181
  readonly accessToken: string | null;
164
182
  readonly videoPlayerUrl: string | null;
@@ -546,6 +546,7 @@ export class MockEliceCDK {
546
546
  #navigation;
547
547
  #assets;
548
548
  #kvstore;
549
+ #learnerFiles;
549
550
  #mlapi;
550
551
 
551
552
  /** @param {MockOptions} [options] */
@@ -648,6 +649,46 @@ export class MockEliceCDK {
648
649
  },
649
650
  });
650
651
 
652
+ // Learner files (provisional SDK API): kept in memory with object URLs, like the SDK's editor preview.
653
+ // baseUrl is null (no signed folder locally), url(path) gives the object URL of a saved file
654
+ const learnerFiles = new Map();
655
+ const LEARNER_NAME = '[A-Za-z0-9_-]+';
656
+ const LEARNER_FOLDER = new RegExp(`^${LEARNER_NAME}(/${LEARNER_NAME}){0,3}$`);
657
+ const LEARNER_FILE = new RegExp(`^${LEARNER_NAME}(\\.${LEARNER_NAME})+$`);
658
+ const LEARNER_MAX_MB = { json: 20, bin: 50, wav: 10, mp3: 10, png: 10, jpg: 10, jpeg: 10 };
659
+ this.#learnerFiles = Object.freeze({
660
+ post: async (file, { folder, name, onProgress, signal } = {}) => {
661
+ this.#assertReady();
662
+ if (this.#screen === 'edit')
663
+ throw new EliceCDKError(ErrorCode.ScreenNotSupported, 'Learner files cannot be saved on the edit screen (mock).');
664
+ if (this.#viewer === 'tutor')
665
+ throw new EliceCDKError(ErrorCode.ReadOnlyMode, 'A tutor cannot save files (mock).');
666
+ if (!LEARNER_FOLDER.test(String(folder)) || !LEARNER_FILE.test(String(name)))
667
+ throw new EliceCDKError(ErrorCode.InvalidParam, 'Invalid folder or name (mock).');
668
+ const maxMb = LEARNER_MAX_MB[String(name).split('.').pop().toLowerCase()];
669
+ if (maxMb == null)
670
+ throw new EliceCDKError(ErrorCode.FileInvalidType, 'Only JSON, BIN, WAV, MP3, PNG and JPEG files can be saved (mock).');
671
+ if (!(file.size >= 1) || file.size > maxMb * MB)
672
+ throw new EliceCDKError(ErrorCode.FileInvalidSize, `The file must be between 1 byte and ${maxMb}MB (mock).`);
673
+ if (signal?.aborted) throw signal.reason;
674
+ await this.#delay();
675
+ const path = `${folder}/${name}`;
676
+ const previous = learnerFiles.get(path);
677
+ if (previous) URL.revokeObjectURL(previous);
678
+ learnerFiles.set(path, URL.createObjectURL(file));
679
+ onProgress?.({ loaded: file.size, total: file.size });
680
+ return { key: `learners/mock/mock/${path}`, folder, name, size: file.size };
681
+ },
682
+ baseUrl: async () => {
683
+ this.#assertReady();
684
+ return null;
685
+ },
686
+ url: async (path) => {
687
+ this.#assertReady();
688
+ return learnerFiles.get(path) ?? null;
689
+ },
690
+ });
691
+
651
692
  this.#mlapi = Object.freeze({
652
693
  // There is no mlapi locally: answer like a server without AI (503 ai_not_configured).
653
694
  fetch: async (_input, _init) => {
@@ -706,6 +747,10 @@ export class MockEliceCDK {
706
747
  get kvstore() {
707
748
  return this.#kvstore;
708
749
  }
750
+ /** Learner files (provisional): in memory with object URLs, baseUrl null */
751
+ get learnerFiles() {
752
+ return this.#learnerFiles;
753
+ }
709
754
  /** Calls mlapi. The mock calls nothing and answers 503 ai_not_configured. */
710
755
  get mlapi() {
711
756
  return this.#mlapi;
@@ -387,6 +387,28 @@ export interface ContentApp<C = Record<string, unknown>> {
387
387
  post(params: { key: string; value: unknown }): Promise<void>;
388
388
  delete(key: string): Promise<void>;
389
389
  };
390
+ /**
391
+ * 보는 사람의 이 자료 파일 폴더 (SDK learnerFiles, 임시 API · 3인 합의 전). { folder, name }을 kvstore에 두고 url로 다시 연다.
392
+ * SDK에 없으면 ContentError learner_files_unavailable, 튜터링 post는 read_only_mode
393
+ */
394
+ readonly learnerFiles: {
395
+ /** SDK에 learnerFiles가 있는지 */
396
+ readonly available: boolean;
397
+ post(
398
+ file: Blob,
399
+ options: {
400
+ folder: string;
401
+ name: string;
402
+ contentType?: string;
403
+ onProgress?: (progress: { loaded: number; total: number }) => void;
404
+ signal?: AbortSignal;
405
+ }
406
+ ): Promise<{ key: string; folder: string; name: string; size: number }>;
407
+ /** 폴더 서명 주소 (끝 /), 편집 화면 · 편집기 미리보기는 null */
408
+ baseUrl(): Promise<{ url: string; expiresAt: number } | null>;
409
+ /** '{folder}/{name}'의 주소, 모르면 null */
410
+ url(path: string): Promise<string | null>;
411
+ };
390
412
  /** 편집 화면 저장 영역 */
391
413
  useSave(options: SaveOptions<C>): {
392
414
  element: Element;
@@ -115,6 +115,9 @@ const MESSAGES = {
115
115
  image_bad_type: 'PNG · JPEG · WebP · GIF 이미지만 올릴 수 있어요.',
116
116
  image_bad_file: '이미지가 비어 있거나 10MB를 넘어 올릴 수 없어요.',
117
117
  image_unreadable: '이미지를 읽지 못했어요. 다른 파일로 다시 시도해 주세요.',
118
+ // 키트만의 코드: 학생 파일 (app.learnerFiles). SDK에 learnerFiles가 없음 (임시 API 전 SDK)
119
+ learner_files_unavailable:
120
+ '이 SDK에는 학생 파일 저장이 없어요 (@eliceio/cdk를 올려 주세요).',
118
121
  request_failed: '서버와 연결하지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
119
122
  // 키트만의 코드: 자료 주소인데 접속 토큰이 없음 (새로고침 · 다른 HTML로 이동하면 SDK가 지운 토큰이 남지 않는다)
120
123
  reopen_required:
@@ -208,6 +211,13 @@ function toContentError(err, action) {
208
211
  return new ContentError(code, MESSAGES[code] ?? MESSAGES.request_failed, err);
209
212
  }
210
213
 
214
+ /** SDK learnerFiles (없으면 ContentError learner_files_unavailable) */
215
+ function learnerFilesOf(sdk) {
216
+ if (typeof sdk.learnerFiles?.post !== 'function')
217
+ throw new ContentError('learner_files_unavailable', MESSAGES.learner_files_unavailable);
218
+ return sdk.learnerFiles;
219
+ }
220
+
211
221
  /**
212
222
  * 점수를 숫자로: 서버가 "70" · "70.00"처럼 글자로 줄 때가 있다 (SDK는 그대로 넘김). null · undefined는 그대로,
213
223
  * 숫자로 읽지 못하는 값도 그대로 둔다
@@ -637,6 +647,46 @@ export async function start(options) {
637
647
  },
638
648
  }),
639
649
 
650
+ /**
651
+ * 보는 사람의 이 자료 파일 폴더 (SDK learnerFiles, 임시 API · 3인 합의 전). 엔트리 AI 학습 데이터 · 모델처럼 kvstore에
652
+ * 넣기 큰 것. 저장 키는 서버가 정한다(learners/{자료}/{계정}/{folder}/{name}), 화면은 { folder, name }(폴더 안 상대 경로)을
653
+ * kvstore에 둔다.
654
+ * - available: SDK에 learnerFiles가 있는지. 없으면(옛 SDK) post · baseUrl · url이 ContentError learner_files_unavailable
655
+ * - post(file, { folder, name, contentType?, onProgress?, signal? }): 같은 경로면 덮어씀. 튜터링은 read_only_mode,
656
+ * 편집 화면은 screen_not_supported, 편집기 미리보기는 SDK가 메모리에만 둔다
657
+ * - baseUrl(): 폴더 서명 주소 { url(끝 /), expiresAt(epoch ms) }. 편집 화면 · 편집기 미리보기는 null
658
+ * - url(path): baseUrl + path ('{folder}/{name}'), 미리보기는 object URL. 모르는 경로는 null
659
+ */
660
+ learnerFiles: Object.freeze({
661
+ get available() {
662
+ return typeof sdk.learnerFiles?.post === 'function';
663
+ },
664
+ async post(file, options) {
665
+ if (readOnly) throw new ContentError('read_only_mode', MESSAGES.read_only_mode);
666
+ try {
667
+ return await learnerFilesOf(sdk).post(file, options);
668
+ } catch (err) {
669
+ if (err?.name === 'AbortError' || (options?.signal?.aborted && err === options.signal.reason))
670
+ throw err;
671
+ throw toContentError(err);
672
+ }
673
+ },
674
+ async baseUrl() {
675
+ try {
676
+ return (await learnerFilesOf(sdk).baseUrl()) ?? null;
677
+ } catch (err) {
678
+ throw toContentError(err);
679
+ }
680
+ },
681
+ async url(path) {
682
+ try {
683
+ return (await learnerFilesOf(sdk).url(path)) ?? null;
684
+ } catch (err) {
685
+ throw toContentError(err);
686
+ }
687
+ },
688
+ }),
689
+
640
690
  /**
641
691
  * 학생 화면의 제출 영역. 화면은 답을 모으고 채우는 방법만 알려 주면, 보는 사람별 처리는 키트가 한다.
642
692
  * - 튜터링: 화면을 읽기 전용으로 잠그고 학생 답을 채움, 제출 버튼 없음
@@ -17,6 +17,7 @@ Elice Custom HTML 학습자료 프로젝트입니다 (엔트리 템플릿). 엔
17
17
  | `ui/` | 모양: 크기와 색(`theme.css`), 문구(`texts.js`), 마크업(`templates/`) |
18
18
  | `styles.css` | 배치 |
19
19
  | `core/workspace.js` | 엔트리 어댑터: 워크스페이스와 나누는 메시지를 모두 여기서 (고치지 않음) |
20
+ | `core/ml-data.js` | AI 학습(모델 학습하기) 데이터 · 모델 저장: 워크스페이스의 `ML_DATA_API` 물음에 학생 파일 · kvstore로 답함 (고치지 않음) |
20
21
  | `core/settings.js`, `core/grading.js`, `core/pack.js`, `core/autosave.js` | 저장 모양, 채점 설정 모양, 작품 줄이기, 자동 저장 (고치지 않음) |
21
22
  | `docs/storage.md` | 무엇을 어디에 저장하는지 표 |
22
23
  | `metadata.json` | 화면 구성(`screens`), 학습 참고 내용(`commentary`). `ecdk build`가 `build`만 채움 |
@@ -40,7 +41,18 @@ ws.onChange(() => autosave.schedule()); // 블록이 바뀔 때마다
40
41
  - 워크스페이스는 물음마다 답을 받을 때까지 시간 제한 없이 기다립니다. 어댑터는 모든 물음에 답하고, 모르는 물음에는 빈 답을 줍니다.
41
42
  - 받은 메시지는 그 iframe에서 워크스페이스 주소로 온 것만 처리하고, 보낼 때도 받는 주소를 정해서 보냅니다.
42
43
  - 워크스페이스 주소는 `WORKSPACE_ORIGINS` 한곳에서 정합니다. 운영은 `https://entry-workspace.elice.io`, 로컬(화면 주소가 localhost, 127.0.0.1)은 `http://localhost:9000`입니다. 로컬에서는 주소에 `?entryWorkspace=<주소>`를 붙여 다른 워크스페이스를 쓸 수 있습니다. 다른 환경의 워크스페이스로 시험하려면 `production` 값을 바꿔 빌드합니다 (SDK가 환경을 알려 주지 않아 자동으로 고르지 못함).
43
- - AI 학습 블록의 데이터 저장은 엘리스 계정 토큰이 필요한데, 학습자료에는 그 토큰이 없어 지금은 쓸 수 없습니다 (토큰 없음으로 답함).
44
+ - AI 학습(인공지능 › 모델 학습하기)의 데이터 · 모델은 학습자료가 저장합니다. 아래 "AI 학습 저장"을 보세요.
45
+
46
+ ## AI 학습 저장 (`core/ml-data.js`, 임시)
47
+
48
+ 학생 화면은 워크스페이스를 `?mlData=parent`로 띄웁니다. 그러면 워크스페이스가 AI 학습 데이터 · 모델을 작업공간 서버에 두지 않고 이 화면에 `ML_DATA_API { method, args }`로 묻고, `core/ml-data.js`가 키트 `app.learnerFiles`(학생 파일, SDK `learnerFiles`) · `app.kvstore`로 저장해 답합니다. 실패도 `{ error: { message } }`로 꼭 답합니다(워크스페이스는 시간 제한 없이 기다림).
49
+
50
+ - 파일: 모델 `models/{모델 id}/{n}/model.json` · `model.weights.bin`(학습할 때마다 `n`이 1씩 올라감), 이미지 · 소리 데이터 `data/{모델 id}/{반 id}/{데이터 id}.png|jpg|wav|mp3`, 1KB를 넘는 글 · 표 데이터 `…/{데이터 id}.json`(kvstore 512KB는 학생 작품과 나눠 써서)
51
+ - kvstore: `entryMl.models.{모델 id}`(모델 정보 + `basePath`), `entryMl.data.{모델 id}.{반 id}`(데이터 목록, 짧은 글 · 표는 원문)
52
+ - 튜터링은 학생 것을 읽기만 합니다(저장 · 지우기는 오류로 답함). 편집 화면은 붙이지 않습니다(학생 파일 폴더가 없음). 편집기 미리보기는 SDK가 메모리에만 두고 서명 주소가 없어 저장한 모델을 다시 불러오지 못합니다.
53
+ - 서버에 파일을 지우는 길이 없어 모델 · 데이터를 지우면 kvstore 참조만 지웁니다.
54
+ - 서버는 학생 × 자료마다 파일 업로드를 1분에 30번까지 받습니다. 이미지를 한꺼번에 많이 넣으면 이 화면이 1분에 30장씩 차례로 올리고(나머지는 기다림), 그래도 너무 잦다고 하면 2초부터 늘려 가며 다시 시도합니다. kvstore가 512KB를 넘으면 워크스페이스에 "저장 한도를 넘어…" 문구로 답합니다.
55
+ - SDK `learnerFiles`는 임시(3인 합의 전)입니다. 저장 위치 표: [`docs/storage.md`](docs/storage.md)
44
56
 
45
57
  ## 자동 저장과 제출
46
58
 
@@ -0,0 +1,51 @@
1
+ // core/ml-data.js 타입 (편집기 자동완성 · 테스트용)
2
+ export declare const ML_KV_ROOT: 'entryMl';
3
+ export declare const INLINE_DATA_MAX: number;
4
+ export declare const ML_WRITE_METHODS: readonly string[];
5
+ export declare const ML_MESSAGES: Readonly<Record<string, string | ((value: unknown) => string)>>;
6
+
7
+ export declare function newObjectId(): string;
8
+ export declare function dataUrlToBlob(url: string): Blob;
9
+
10
+ /** 처리기가 쓰는 키트 app의 일부 */
11
+ export interface MlDataApp {
12
+ readOnly: boolean;
13
+ kvstore: {
14
+ get(params: { key: string }): Promise<unknown>;
15
+ post(params: { key: string; value: unknown }): Promise<void>;
16
+ delete(key: string): Promise<void>;
17
+ };
18
+ learnerFiles?: {
19
+ readonly available?: boolean;
20
+ post(file: Blob, options: { folder: string; name: string }): Promise<unknown>;
21
+ baseUrl(): Promise<{ url: string; expiresAt: number } | null>;
22
+ url(path: string): Promise<string | null>;
23
+ };
24
+ }
25
+
26
+ export interface MlData {
27
+ /** ML_DATA_API 물음 하나 → 결과. 실패는 throw (workspace.js가 { error: { message } }로 답함) */
28
+ handle(method: string, args: unknown[]): Promise<unknown>;
29
+ }
30
+
31
+ export declare function createMlData(
32
+ app: MlDataApp,
33
+ options?: {
34
+ fetch?: typeof fetch;
35
+ now?: () => Date;
36
+ newId?: () => string;
37
+ rateWaitMs?: number;
38
+ /** 학생 파일 업로드 차례 · RateLimited 다시 시도 (기본 1분 1초에 30번, 2초부터 두 배 · 30초까지 6번) */
39
+ upload?: {
40
+ perWindow?: number;
41
+ windowMs?: number;
42
+ retries?: number;
43
+ retryBaseMs?: number;
44
+ retryMaxMs?: number;
45
+ };
46
+ /** 업로드 차례를 셀 시계 (ms) */
47
+ clock?: () => number;
48
+ /** 다시 시도 간격을 흩뜨릴 난수 (0 이상 1 미만) */
49
+ random?: () => number;
50
+ }
51
+ ): MlData;