seance-cli 0.0.0-stage → 0.1.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.
Files changed (190) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/dist/commands/init.d.ts +29 -0
  4. package/dist/commands/init.js +310 -0
  5. package/dist/commands/init.js.map +1 -0
  6. package/dist/commands/mcp.d.ts +19 -0
  7. package/dist/commands/mcp.js +38 -0
  8. package/dist/commands/mcp.js.map +1 -0
  9. package/dist/commands/quiz.d.ts +23 -0
  10. package/dist/commands/quiz.js +187 -0
  11. package/dist/commands/quiz.js.map +1 -0
  12. package/dist/commands/review.d.ts +4 -0
  13. package/dist/commands/review.js +115 -0
  14. package/dist/commands/review.js.map +1 -0
  15. package/dist/commands/sync.d.ts +17 -0
  16. package/dist/commands/sync.js +367 -0
  17. package/dist/commands/sync.js.map +1 -0
  18. package/dist/git.d.ts +33 -0
  19. package/dist/git.js +103 -0
  20. package/dist/git.js.map +1 -0
  21. package/dist/hosted-api.d.ts +24 -0
  22. package/dist/hosted-api.js +85 -0
  23. package/dist/hosted-api.js.map +1 -0
  24. package/dist/hosted-consent.d.ts +8 -0
  25. package/dist/hosted-consent.js +37 -0
  26. package/dist/hosted-consent.js.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +108 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/init-fs.d.ts +51 -0
  31. package/dist/init-fs.js +220 -0
  32. package/dist/init-fs.js.map +1 -0
  33. package/dist/init-questions.d.ts +21 -0
  34. package/dist/init-questions.js +161 -0
  35. package/dist/init-questions.js.map +1 -0
  36. package/dist/mcp-handlers.d.ts +22 -0
  37. package/dist/mcp-handlers.js +185 -0
  38. package/dist/mcp-handlers.js.map +1 -0
  39. package/dist/mcp-server.d.ts +4 -0
  40. package/dist/mcp-server.js +39 -0
  41. package/dist/mcp-server.js.map +1 -0
  42. package/dist/prompter.d.ts +29 -0
  43. package/dist/prompter.js +42 -0
  44. package/dist/prompter.js.map +1 -0
  45. package/dist/quiz-backend.d.ts +40 -0
  46. package/dist/quiz-backend.js +116 -0
  47. package/dist/quiz-backend.js.map +1 -0
  48. package/dist/quiz-input.d.ts +12 -0
  49. package/dist/quiz-input.js +52 -0
  50. package/dist/quiz-input.js.map +1 -0
  51. package/dist/quiz-io.d.ts +30 -0
  52. package/dist/quiz-io.js +83 -0
  53. package/dist/quiz-io.js.map +1 -0
  54. package/dist/quiz-ui.d.ts +18 -0
  55. package/dist/quiz-ui.js +51 -0
  56. package/dist/quiz-ui.js.map +1 -0
  57. package/node_modules/@seance/ai/LICENSE +21 -0
  58. package/node_modules/@seance/ai/dist/chain.d.ts +31 -0
  59. package/node_modules/@seance/ai/dist/chain.js +114 -0
  60. package/node_modules/@seance/ai/dist/chain.js.map +1 -0
  61. package/node_modules/@seance/ai/dist/grade.d.ts +14 -0
  62. package/node_modules/@seance/ai/dist/grade.js +44 -0
  63. package/node_modules/@seance/ai/dist/grade.js.map +1 -0
  64. package/node_modules/@seance/ai/dist/hosted-config.d.ts +9 -0
  65. package/node_modules/@seance/ai/dist/hosted-config.js +27 -0
  66. package/node_modules/@seance/ai/dist/hosted-config.js.map +1 -0
  67. package/node_modules/@seance/ai/dist/index.d.ts +9 -0
  68. package/node_modules/@seance/ai/dist/index.js +9 -0
  69. package/node_modules/@seance/ai/dist/index.js.map +1 -0
  70. package/node_modules/@seance/ai/dist/providers.d.ts +54 -0
  71. package/node_modules/@seance/ai/dist/providers.js +149 -0
  72. package/node_modules/@seance/ai/dist/providers.js.map +1 -0
  73. package/node_modules/@seance/ai/dist/quiz.d.ts +26 -0
  74. package/node_modules/@seance/ai/dist/quiz.js +41 -0
  75. package/node_modules/@seance/ai/dist/quiz.js.map +1 -0
  76. package/node_modules/@seance/ai/package.json +25 -0
  77. package/node_modules/@seance/core/LICENSE +21 -0
  78. package/node_modules/@seance/core/dist/ai-check.d.ts +58 -0
  79. package/node_modules/@seance/core/dist/ai-check.js +460 -0
  80. package/node_modules/@seance/core/dist/ai-check.js.map +1 -0
  81. package/node_modules/@seance/core/dist/ai-prompts.d.ts +29 -0
  82. package/node_modules/@seance/core/dist/ai-prompts.js +221 -0
  83. package/node_modules/@seance/core/dist/ai-prompts.js.map +1 -0
  84. package/node_modules/@seance/core/dist/ai-schemas.d.ts +155 -0
  85. package/node_modules/@seance/core/dist/ai-schemas.js +92 -0
  86. package/node_modules/@seance/core/dist/ai-schemas.js.map +1 -0
  87. package/node_modules/@seance/core/dist/api-client.d.ts +26 -0
  88. package/node_modules/@seance/core/dist/api-client.js +71 -0
  89. package/node_modules/@seance/core/dist/api-client.js.map +1 -0
  90. package/node_modules/@seance/core/dist/api-errors.d.ts +37 -0
  91. package/node_modules/@seance/core/dist/api-errors.js +66 -0
  92. package/node_modules/@seance/core/dist/api-errors.js.map +1 -0
  93. package/node_modules/@seance/core/dist/api-schemas.d.ts +284 -0
  94. package/node_modules/@seance/core/dist/api-schemas.js +67 -0
  95. package/node_modules/@seance/core/dist/api-schemas.js.map +1 -0
  96. package/node_modules/@seance/core/dist/decision-log.d.ts +73 -0
  97. package/node_modules/@seance/core/dist/decision-log.js +239 -0
  98. package/node_modules/@seance/core/dist/decision-log.js.map +1 -0
  99. package/node_modules/@seance/core/dist/dependency-guard.d.ts +20 -0
  100. package/node_modules/@seance/core/dist/dependency-guard.js +732 -0
  101. package/node_modules/@seance/core/dist/dependency-guard.js.map +1 -0
  102. package/node_modules/@seance/core/dist/gate.d.ts +11 -0
  103. package/node_modules/@seance/core/dist/gate.js +26 -0
  104. package/node_modules/@seance/core/dist/gate.js.map +1 -0
  105. package/node_modules/@seance/core/dist/git-parse.d.ts +11 -0
  106. package/node_modules/@seance/core/dist/git-parse.js +23 -0
  107. package/node_modules/@seance/core/dist/git-parse.js.map +1 -0
  108. package/node_modules/@seance/core/dist/index.d.ts +65 -0
  109. package/node_modules/@seance/core/dist/index.js +47 -0
  110. package/node_modules/@seance/core/dist/index.js.map +1 -0
  111. package/node_modules/@seance/core/dist/init-checklist.d.ts +153 -0
  112. package/node_modules/@seance/core/dist/init-checklist.js +200 -0
  113. package/node_modules/@seance/core/dist/init-checklist.js.map +1 -0
  114. package/node_modules/@seance/core/dist/init-detect.d.ts +9 -0
  115. package/node_modules/@seance/core/dist/init-detect.js +84 -0
  116. package/node_modules/@seance/core/dist/init-detect.js.map +1 -0
  117. package/node_modules/@seance/core/dist/init-templates.d.ts +36 -0
  118. package/node_modules/@seance/core/dist/init-templates.js +257 -0
  119. package/node_modules/@seance/core/dist/init-templates.js.map +1 -0
  120. package/node_modules/@seance/core/dist/map-basics.d.ts +13 -0
  121. package/node_modules/@seance/core/dist/map-basics.js +19 -0
  122. package/node_modules/@seance/core/dist/map-basics.js.map +1 -0
  123. package/node_modules/@seance/core/dist/map-summary.d.ts +5 -0
  124. package/node_modules/@seance/core/dist/map-summary.js +50 -0
  125. package/node_modules/@seance/core/dist/map-summary.js.map +1 -0
  126. package/node_modules/@seance/core/dist/markers.d.ts +51 -0
  127. package/node_modules/@seance/core/dist/markers.js +84 -0
  128. package/node_modules/@seance/core/dist/markers.js.map +1 -0
  129. package/node_modules/@seance/core/dist/mcp-quiz.d.ts +94 -0
  130. package/node_modules/@seance/core/dist/mcp-quiz.js +130 -0
  131. package/node_modules/@seance/core/dist/mcp-quiz.js.map +1 -0
  132. package/node_modules/@seance/core/dist/mcp-tools.d.ts +82 -0
  133. package/node_modules/@seance/core/dist/mcp-tools.js +136 -0
  134. package/node_modules/@seance/core/dist/mcp-tools.js.map +1 -0
  135. package/node_modules/@seance/core/dist/mcp-views.d.ts +21 -0
  136. package/node_modules/@seance/core/dist/mcp-views.js +83 -0
  137. package/node_modules/@seance/core/dist/mcp-views.js.map +1 -0
  138. package/node_modules/@seance/core/dist/quiz-assembly.d.ts +21 -0
  139. package/node_modules/@seance/core/dist/quiz-assembly.js +43 -0
  140. package/node_modules/@seance/core/dist/quiz-assembly.js.map +1 -0
  141. package/node_modules/@seance/core/dist/quiz-cards.d.ts +183 -0
  142. package/node_modules/@seance/core/dist/quiz-cards.js +215 -0
  143. package/node_modules/@seance/core/dist/quiz-cards.js.map +1 -0
  144. package/node_modules/@seance/core/dist/quiz-session.d.ts +67 -0
  145. package/node_modules/@seance/core/dist/quiz-session.js +141 -0
  146. package/node_modules/@seance/core/dist/quiz-session.js.map +1 -0
  147. package/node_modules/@seance/core/dist/quiz-subjects.d.ts +13 -0
  148. package/node_modules/@seance/core/dist/quiz-subjects.js +63 -0
  149. package/node_modules/@seance/core/dist/quiz-subjects.js.map +1 -0
  150. package/node_modules/@seance/core/dist/rate-limit.d.ts +33 -0
  151. package/node_modules/@seance/core/dist/rate-limit.js +114 -0
  152. package/node_modules/@seance/core/dist/rate-limit.js.map +1 -0
  153. package/node_modules/@seance/core/dist/scoring.d.ts +48 -0
  154. package/node_modules/@seance/core/dist/scoring.js +95 -0
  155. package/node_modules/@seance/core/dist/scoring.js.map +1 -0
  156. package/node_modules/@seance/core/dist/seance-config.d.ts +177 -0
  157. package/node_modules/@seance/core/dist/seance-config.js +43 -0
  158. package/node_modules/@seance/core/dist/seance-config.js.map +1 -0
  159. package/node_modules/@seance/core/dist/seance-state.d.ts +125 -0
  160. package/node_modules/@seance/core/dist/seance-state.js +61 -0
  161. package/node_modules/@seance/core/dist/seance-state.js.map +1 -0
  162. package/node_modules/@seance/core/dist/sm2.d.ts +18 -0
  163. package/node_modules/@seance/core/dist/sm2.js +87 -0
  164. package/node_modules/@seance/core/dist/sm2.js.map +1 -0
  165. package/node_modules/@seance/core/dist/stored-schemas.d.ts +29 -0
  166. package/node_modules/@seance/core/dist/stored-schemas.js +29 -0
  167. package/node_modules/@seance/core/dist/stored-schemas.js.map +1 -0
  168. package/node_modules/@seance/core/dist/structural-questions.d.ts +31 -0
  169. package/node_modules/@seance/core/dist/structural-questions.js +575 -0
  170. package/node_modules/@seance/core/dist/structural-questions.js.map +1 -0
  171. package/node_modules/@seance/core/dist/structure-map-schema.d.ts +84 -0
  172. package/node_modules/@seance/core/dist/structure-map-schema.js +73 -0
  173. package/node_modules/@seance/core/dist/structure-map-schema.js.map +1 -0
  174. package/node_modules/@seance/core/dist/structure-map.d.ts +78 -0
  175. package/node_modules/@seance/core/dist/structure-map.js +750 -0
  176. package/node_modules/@seance/core/dist/structure-map.js.map +1 -0
  177. package/node_modules/@seance/core/dist/sync-changes.d.ts +38 -0
  178. package/node_modules/@seance/core/dist/sync-changes.js +89 -0
  179. package/node_modules/@seance/core/dist/sync-changes.js.map +1 -0
  180. package/node_modules/@seance/core/dist/sync-render.d.ts +28 -0
  181. package/node_modules/@seance/core/dist/sync-render.js +113 -0
  182. package/node_modules/@seance/core/dist/sync-render.js.map +1 -0
  183. package/node_modules/@seance/core/dist/terminal-text.d.ts +8 -0
  184. package/node_modules/@seance/core/dist/terminal-text.js +33 -0
  185. package/node_modules/@seance/core/dist/terminal-text.js.map +1 -0
  186. package/node_modules/@seance/core/dist/write-plan.d.ts +51 -0
  187. package/node_modules/@seance/core/dist/write-plan.js +173 -0
  188. package/node_modules/@seance/core/dist/write-plan.js.map +1 -0
  189. package/node_modules/@seance/core/package.json +26 -0
  190. package/package.json +42 -6
@@ -0,0 +1,44 @@
1
+ // gradeExplanation: scores a student's written explanation against the question's rubric.
2
+ // The AI only says which key points the answer covers; we compute the score. With no AI, a keyword match is used.
3
+ import { AI_LIMITS, BLANK_ANSWER_FEEDBACK, buildGradeMessages, checkGrade, isBlankAnswer, keywordGrade } from "@seance/core";
4
+ import { runChain } from "./chain.js";
5
+ // Larger than the reply needs: reasoning tokens of a reasoning model count against max_tokens.
6
+ const GRADE_MAX_TOKENS = 1_500;
7
+ /** Throws a RangeError unless the question is an explain question with a rubric and the answer is short enough. */
8
+ function checkInput(question, answerText) {
9
+ if (typeof answerText !== "string")
10
+ throw new RangeError("the answer must be a string");
11
+ if (answerText.length > AI_LIMITS.maxAnswerChars) {
12
+ throw new RangeError(`the answer has ${answerText.length} characters, the limit is ${AI_LIMITS.maxAnswerChars}`);
13
+ }
14
+ if (question?.kind !== "explain" || !question.rubric) {
15
+ throw new RangeError("gradeExplanation needs an explain question with a rubric");
16
+ }
17
+ return question.rubric;
18
+ }
19
+ function keywordFeedback(rubric, covered) {
20
+ const missing = rubric.keyPoints.filter((_, i) => !covered.includes(i));
21
+ const head = `Matched ${covered.length} of ${rubric.keyPoints.length} key points by keywords (no AI was available).`;
22
+ const tail = missing.length > 0 ? ` Not found: ${missing.join("; ")}.` : "";
23
+ return `${head}${tail}`.slice(0, AI_LIMITS.maxFeedbackChars);
24
+ }
25
+ /** Grades with keywords only: no provider is called. */
26
+ function gradeByKeywords(rubric, answer, attempts) {
27
+ const { score, covered } = keywordGrade(rubric, answer);
28
+ return { score, feedback: keywordFeedback(rubric, covered), servedBy: "keyword", rough: true, attempts };
29
+ }
30
+ export async function gradeExplanation(question, answerText, deps) {
31
+ const rubric = checkInput(question, answerText);
32
+ // A blank answer is a sure 0, so no provider is asked.
33
+ if (isBlankAnswer(answerText)) {
34
+ return { score: 0, feedback: BLANK_ANSWER_FEEDBACK, servedBy: "keyword", rough: false, attempts: [] };
35
+ }
36
+ const request = { messages: buildGradeMessages(question, answerText), maxTokens: GRADE_MAX_TOKENS };
37
+ const chain = await runChain(request, (json) => checkGrade(json, rubric, answerText), deps);
38
+ if (chain.ok) {
39
+ const { score, feedback } = chain.value;
40
+ return { score, feedback, servedBy: chain.servedBy, model: chain.model, rough: false, attempts: chain.attempts };
41
+ }
42
+ return gradeByKeywords(rubric, answerText, chain.attempts);
43
+ }
44
+ //# sourceMappingURL=grade.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grade.js","sourceRoot":"","sources":["../src/grade.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,kHAAkH;AAClH,OAAO,EAAE,SAAS,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,UAAU,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE7H,OAAO,EAAE,QAAQ,EAAE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O,eAAe,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { ChainConfig, Env } from "./providers.js";
2
+ export declare const HOSTED_TIMEOUTS: {
3
+ readonly providerDefault: 10000;
4
+ readonly providerMax: 15000;
5
+ readonly chainDefault: 20000;
6
+ readonly chainMax: 24000;
7
+ };
8
+ /** Provider settings from `readChainConfig(env)` with hosted time limits. Never throws. */
9
+ export declare function hostedChainConfig(env: Env): ChainConfig;
@@ -0,0 +1,27 @@
1
+ // The chain config of the hosted API (Task 8, D3 decided by Vedant Nov 30): the same providers as `readChainConfig`,
2
+ // but with shorter default time limits (10 s per provider, 20 s per chain) so a request fits the Netlify function time limit. Env can change them, capped at 15 s and 24 s.
3
+ import { readChainConfig } from "./providers.js";
4
+ export const HOSTED_TIMEOUTS = { providerDefault: 10_000, providerMax: 15_000, chainDefault: 20_000, chainMax: 24_000 };
5
+ // The same digit-and-range test as `readTimeout` in providers.ts (it cannot tell "unset" from "set to the CLI default").
6
+ const PROVIDER_RANGE = { min: 1_000, max: 60_000 };
7
+ const CHAIN_RANGE = { min: 1_000, max: 120_000 };
8
+ /** A whole number written in digits inside the range gives `min(value, max)`; anything else gives the default. */
9
+ function hostedTimeout(value, range, fallback, ceiling) {
10
+ const text = value?.trim();
11
+ if (text === undefined || !/^\d+$/.test(text))
12
+ return fallback;
13
+ const n = Number(text);
14
+ if (!Number.isSafeInteger(n) || n < range.min || n > range.max)
15
+ return fallback;
16
+ return Math.min(n, ceiling);
17
+ }
18
+ /** Provider settings from `readChainConfig(env)` with hosted time limits. Never throws. */
19
+ export function hostedChainConfig(env) {
20
+ const config = readChainConfig(env);
21
+ return {
22
+ ...config,
23
+ providerTimeoutMs: hostedTimeout(env.AI_PROVIDER_TIMEOUT_MS, PROVIDER_RANGE, HOSTED_TIMEOUTS.providerDefault, HOSTED_TIMEOUTS.providerMax),
24
+ chainTimeoutMs: hostedTimeout(env.AI_CHAIN_TIMEOUT_MS, CHAIN_RANGE, HOSTED_TIMEOUTS.chainDefault, HOSTED_TIMEOUTS.chainMax),
25
+ };
26
+ }
27
+ //# sourceMappingURL=hosted-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted-config.js","sourceRoot":"","sources":["../src/hosted-config.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,4KAA4K;AAC5K,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAGjD,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAW,CAAC;AAEjI,yHAAyH;AACzH,MAAM,cAAc,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAW,CAAC;AAC5D,MAAM,WAAW,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAW,CAAC;AAE1D,kHAAkH;AAClH,SAAS,aAAa,CAAC,KAAyB,EAAE,KAAmC,EAAE,QAAgB,EAAE,OAAe;IACtH,MAAM,IAAI,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IAC3B,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,QAAQ,CAAC;IAC/D,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,GAAG,KAAK,CAAC,GAAG;QAAE,OAAO,QAAQ,CAAC;IAChF,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AAC9B,CAAC;AAED,2FAA2F;AAC3F,MAAM,UAAU,iBAAiB,CAAC,GAAQ;IACxC,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO;QACL,GAAG,MAAM;QACT,iBAAiB,EAAE,aAAa,CAAC,GAAG,CAAC,sBAAsB,EAAE,cAAc,EAAE,eAAe,CAAC,eAAe,EAAE,eAAe,CAAC,WAAW,CAAC;QAC1I,cAAc,EAAE,aAAa,CAAC,GAAG,CAAC,mBAAmB,EAAE,WAAW,EAAE,eAAe,CAAC,YAAY,EAAE,eAAe,CAAC,QAAQ,CAAC;KAC5H,CAAC;AACJ,CAAC"}
@@ -0,0 +1,9 @@
1
+ export { runChain } from "./chain.js";
2
+ export type { Attempt, ChainDeps, ChainResult, Outcome } from "./chain.js";
3
+ export { createOpenAiClientFactory, MAX_MODELS_PER_PROVIDER, parseModelList, PROVIDER_NAMES, ProviderCallError, readChainConfig, } from "./providers.js";
4
+ export type { ChainConfig, ChatClient, ChatRequest, ClientFactory, Env, ProviderConfig, ProviderName, } from "./providers.js";
5
+ export { generateQuiz } from "./quiz.js";
6
+ export type { Quiz, QuizInput } from "./quiz.js";
7
+ export { gradeExplanation } from "./grade.js";
8
+ export type { Grade } from "./grade.js";
9
+ export { HOSTED_TIMEOUTS, hostedChainConfig } from "./hosted-config.js";
@@ -0,0 +1,9 @@
1
+ // Public entry point for @seance/ai: the AI provider chain, generateQuiz and gradeExplanation.
2
+ // Network I/O lives here; the schemas, prompts and checks it uses live in @seance/core.
3
+ export { runChain } from "./chain.js";
4
+ export { createOpenAiClientFactory, MAX_MODELS_PER_PROVIDER, parseModelList, PROVIDER_NAMES, ProviderCallError, readChainConfig, } from "./providers.js";
5
+ export { generateQuiz } from "./quiz.js";
6
+ export { gradeExplanation } from "./grade.js";
7
+ // Task 8: the chain config of the hosted API (shorter time limits).
8
+ export { HOSTED_TIMEOUTS, hostedChainConfig } from "./hosted-config.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,wFAAwF;AACxF,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,cAAc,EACd,cAAc,EACd,iBAAiB,EACjB,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAUxB,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,oEAAoE;AACpE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,54 @@
1
+ import type { ChatMessage } from "@seance/core";
2
+ export type ProviderName = "gemini" | "nvidia" | "openrouter";
3
+ /** The chain order: Gemini first, then NVIDIA, then OpenRouter (changed Nov 29 after live test). */
4
+ export declare const PROVIDER_NAMES: readonly ProviderName[];
5
+ /** One (provider, model) pair. A provider with 3 models is 3 entries that share the key and base URL. */
6
+ export interface ProviderConfig {
7
+ name: ProviderName;
8
+ baseURL: string;
9
+ apiKey: string;
10
+ model: string;
11
+ }
12
+ export interface ChainConfig {
13
+ providers: ProviderConfig[];
14
+ unconfigured: ProviderName[];
15
+ providerTimeoutMs: number;
16
+ chainTimeoutMs: number;
17
+ }
18
+ export type Env = Readonly<Record<string, string | undefined>>;
19
+ export declare const DEFAULT_PROVIDER_TIMEOUT_MS = 15000;
20
+ export declare const DEFAULT_CHAIN_TIMEOUT_MS = 30000;
21
+ /** At most this many models are used per provider (added Nov 29: multiple models). */
22
+ export declare const MAX_MODELS_PER_PROVIDER = 5;
23
+ /**
24
+ * Reads a comma-separated model list, e.g. "gemini-a, gemini-b". Each entry is trimmed; empty, invalid and
25
+ * duplicate entries are dropped; the order is kept; at most 5 are returned (added Nov 29: multiple models).
26
+ */
27
+ export declare function parseModelList(text: string | undefined): string[];
28
+ /** Reads the chain config from the env object that is passed in. Never throws. */
29
+ export declare function readChainConfig(env: Env): ChainConfig;
30
+ export interface ChatRequest {
31
+ messages: ChatMessage[];
32
+ maxTokens: number;
33
+ }
34
+ /** What the chain needs from a provider: send messages, get the reply text (or null). */
35
+ export interface ChatClient {
36
+ complete(req: ChatRequest, signal: AbortSignal): Promise<string | null>;
37
+ }
38
+ export type ClientFactory = (cfg: ProviderConfig, timeoutMs: number) => ChatClient;
39
+ /**
40
+ * The only error a client may throw. Its message is fixed text: SDK messages can contain
41
+ * response bodies or request details, so they are dropped (req 2.8).
42
+ */
43
+ export declare class ProviderCallError extends Error {
44
+ readonly kind: "timeout" | "network" | "http";
45
+ readonly status?: number;
46
+ constructor(kind: "timeout" | "network" | "http", status?: number);
47
+ }
48
+ /**
49
+ * Makes clients that use the `openai` SDK. `fetch` is only for tests. The SDK never retries (the next
50
+ * provider is the retry), never logs, and never falls back to OPENAI_* env vars because key and URL are always passed.
51
+ */
52
+ export declare function createOpenAiClientFactory(opts?: {
53
+ fetch?: typeof fetch;
54
+ }): ClientFactory;
@@ -0,0 +1,149 @@
1
+ // Provider config and the OpenAI-compatible chat client. Gemini, NVIDIA and OpenRouter are all called
2
+ // through the `openai` SDK with their own base URL. Env is passed in; this file never reads process.env.
3
+ import OpenAI, { APIConnectionError, APIConnectionTimeoutError, APIError, APIUserAbortError } from "openai";
4
+ /** The chain order: Gemini first, then NVIDIA, then OpenRouter (changed Nov 29 after live test). */
5
+ export const PROVIDER_NAMES = ["gemini", "nvidia", "openrouter"];
6
+ // Same defaults as .env.example.
7
+ const DEFAULT_BASE_URLS = {
8
+ gemini: "https://generativelanguage.googleapis.com/v1beta/openai/",
9
+ nvidia: "https://integrate.api.nvidia.com/v1",
10
+ openrouter: "https://openrouter.ai/api/v1",
11
+ };
12
+ // Raised from 8 s / 20 s after the first live test (a real quiz prompt took more than 8 s on Gemini and 11-15 s on a
13
+ // reasoning model). The hosted API (Task 8) sets its own lower limits to fit the Netlify function time limit; the CLI uses these.
14
+ export const DEFAULT_PROVIDER_TIMEOUT_MS = 15_000;
15
+ export const DEFAULT_CHAIN_TIMEOUT_MS = 30_000;
16
+ function nonBlank(value) {
17
+ const trimmed = value?.trim();
18
+ return trimmed ? trimmed : undefined;
19
+ }
20
+ /** An https URL without a username or password (those would end up in logs and error texts). */
21
+ function isHttpsUrl(text) {
22
+ try {
23
+ const url = new URL(text);
24
+ return url.protocol === "https:" && url.username === "" && url.password === "";
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ /** A whole number written in digits inside min..max, else the default (req 1.4, so a typo never breaks a quiz). */
31
+ function readTimeout(value, fallback, min, max) {
32
+ const text = nonBlank(value);
33
+ if (text === undefined || !/^\d+$/.test(text))
34
+ return fallback;
35
+ const n = Number(text);
36
+ return Number.isSafeInteger(n) && n >= min && n <= max ? n : fallback;
37
+ }
38
+ /** At most this many models are used per provider (added Nov 29: multiple models). */
39
+ export const MAX_MODELS_PER_PROVIDER = 5;
40
+ /** A model name is 1-200 printable ASCII characters with no whitespace (0x21-0x7e). */
41
+ const MODEL_NAME = /^[\x21-\x7e]{1,200}$/;
42
+ /**
43
+ * Reads a comma-separated model list, e.g. "gemini-a, gemini-b". Each entry is trimmed; empty, invalid and
44
+ * duplicate entries are dropped; the order is kept; at most 5 are returned (added Nov 29: multiple models).
45
+ */
46
+ export function parseModelList(text) {
47
+ const models = [];
48
+ for (const entry of (text ?? "").split(",")) {
49
+ const model = entry.trim();
50
+ if (!MODEL_NAME.test(model) || models.includes(model))
51
+ continue;
52
+ models.push(model);
53
+ if (models.length === MAX_MODELS_PER_PROVIDER)
54
+ break;
55
+ }
56
+ return models;
57
+ }
58
+ /** One entry per model of one provider; an empty list when the key or all models are missing or the base URL is not a plain https URL. */
59
+ function readProvider(name, env) {
60
+ const prefix = name.toUpperCase();
61
+ const apiKey = nonBlank(env[`${prefix}_API_KEY`]);
62
+ const models = parseModelList(env[`${prefix}_MODEL`]);
63
+ const baseURL = nonBlank(env[`${prefix}_BASE_URL`]) ?? DEFAULT_BASE_URLS[name];
64
+ if (apiKey === undefined || models.length === 0 || !isHttpsUrl(baseURL))
65
+ return [];
66
+ return models.map((model) => ({ name, baseURL, apiKey, model }));
67
+ }
68
+ /** Reads the chain config from the env object that is passed in. Never throws. */
69
+ export function readChainConfig(env) {
70
+ const providers = [];
71
+ const unconfigured = [];
72
+ for (const name of PROVIDER_NAMES) {
73
+ const entries = readProvider(name, env);
74
+ if (entries.length > 0)
75
+ providers.push(...entries);
76
+ else
77
+ unconfigured.push(name);
78
+ }
79
+ return {
80
+ providers,
81
+ unconfigured,
82
+ providerTimeoutMs: readTimeout(env.AI_PROVIDER_TIMEOUT_MS, DEFAULT_PROVIDER_TIMEOUT_MS, 1_000, 60_000),
83
+ chainTimeoutMs: readTimeout(env.AI_CHAIN_TIMEOUT_MS, DEFAULT_CHAIN_TIMEOUT_MS, 1_000, 120_000),
84
+ };
85
+ }
86
+ /**
87
+ * The only error a client may throw. Its message is fixed text: SDK messages can contain
88
+ * response bodies or request details, so they are dropped (req 2.8).
89
+ */
90
+ export class ProviderCallError extends Error {
91
+ kind;
92
+ status;
93
+ constructor(kind, status) {
94
+ super(status === undefined ? `provider call failed: ${kind}` : `provider call failed: ${kind} ${status}`);
95
+ this.name = "ProviderCallError";
96
+ this.kind = kind;
97
+ if (status !== undefined)
98
+ this.status = status;
99
+ }
100
+ }
101
+ /** Sorts an SDK error into timeout, http (with status) or network. Everything else is `network`. */
102
+ function toProviderError(error) {
103
+ if (error instanceof APIUserAbortError || error instanceof APIConnectionTimeoutError)
104
+ return new ProviderCallError("timeout");
105
+ if (error instanceof APIConnectionError)
106
+ return new ProviderCallError("network");
107
+ if (error instanceof APIError && typeof error.status === "number")
108
+ return new ProviderCallError("http", error.status);
109
+ return new ProviderCallError("network");
110
+ }
111
+ /**
112
+ * Makes clients that use the `openai` SDK. `fetch` is only for tests. The SDK never retries (the next
113
+ * provider is the retry), never logs, and never falls back to OPENAI_* env vars because key and URL are always passed.
114
+ */
115
+ export function createOpenAiClientFactory(opts = {}) {
116
+ return (cfg, timeoutMs) => {
117
+ const client = new OpenAI({
118
+ apiKey: cfg.apiKey,
119
+ baseURL: cfg.baseURL,
120
+ timeout: timeoutMs,
121
+ maxRetries: 0,
122
+ logLevel: "off",
123
+ organization: null, // null stops the SDK from reading OPENAI_ORG_ID, OPENAI_PROJECT_ID,
124
+ project: null, // OPENAI_WEBHOOK_SECRET and OPENAI_ADMIN_KEY from the environment
125
+ webhookSecret: null,
126
+ adminAPIKey: null,
127
+ ...(opts.fetch ? { fetch: opts.fetch } : {}),
128
+ });
129
+ return {
130
+ async complete(req, signal) {
131
+ try {
132
+ const completion = await client.chat.completions.create({
133
+ model: cfg.model,
134
+ messages: req.messages,
135
+ response_format: { type: "json_object" },
136
+ temperature: 0.2,
137
+ max_tokens: req.maxTokens,
138
+ }, { signal });
139
+ const content = completion?.choices?.[0]?.message?.content;
140
+ return typeof content === "string" ? content : null;
141
+ }
142
+ catch (error) {
143
+ throw toProviderError(error);
144
+ }
145
+ },
146
+ };
147
+ };
148
+ }
149
+ //# sourceMappingURL=providers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.js","sourceRoot":"","sources":["../src/providers.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,yGAAyG;AACzG,OAAO,MAAM,EAAE,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAK5G,oGAAoG;AACpG,MAAM,CAAC,MAAM,cAAc,GAA4B,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;AAmB1F,iCAAiC;AACjC,MAAM,iBAAiB,GAAiC;IACtD,MAAM,EAAE,0DAA0D;IAClE,MAAM,EAAE,qCAAqC;IAC7C,UAAU,EAAE,8BAA8B;CAC3C,CAAC;AAEF,qHAAqH;AACrH,kIAAkI;AAClI,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAClD,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,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,CAAC,CAAC,CAAC,IAAI,CAAC;gBACtD,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,MAAM,eAAe,CAAC,KAAK,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { DecisionEntry, QuizItem, SourceFile, StructureMap } from "@seance/core";
2
+ import type { Attempt, ChainDeps } from "./chain.js";
3
+ import type { ProviderName } from "./providers.js";
4
+ export interface QuizInput {
5
+ map: StructureMap;
6
+ files: SourceFile[];
7
+ /** Picks which structural questions appear. Default 0. */
8
+ seed?: number;
9
+ /** Changes only the order of the choices on a retake. Default 0. */
10
+ attempt?: number;
11
+ /** The latest DECISIONS.md entry. Used only when it has Chose and Why; otherwise ignored. */
12
+ decision?: DecisionEntry;
13
+ }
14
+ export interface Quiz {
15
+ questions: QuizItem[];
16
+ servedBy: ProviderName | "structural";
17
+ /** The model that answered; left out when `servedBy` is `structural`. */
18
+ model?: string;
19
+ attempts: Attempt[];
20
+ unconfigured: ProviderName[];
21
+ }
22
+ /**
23
+ * Makes a quiz of up to 5 questions. Throws a RangeError for a map that is not `schemaVersion: 1`
24
+ * (or a bad seed or attempt) before any provider is called. Everything else is handled: the result says who served it.
25
+ */
26
+ export declare function generateQuiz(input: QuizInput, deps: ChainDeps): Promise<Quiz>;
@@ -0,0 +1,41 @@
1
+ // generateQuiz: asks the provider chain for a quiz about a structure map. If no provider gives a good
2
+ // answer, it returns the structural (no-AI) questions instead. It never fails because of a provider.
3
+ import { buildQuizMessages, checkAiQuiz, fillQuiz, generateStructuralQuestions, hasChoice, QuizItemSchema } from "@seance/core";
4
+ import { runChain } from "./chain.js";
5
+ const QUIZ_SIZE = 5;
6
+ // Reasoning tokens of a reasoning model count against max_tokens (1 300-1 600 measured), so leave room for the answer.
7
+ const QUIZ_MAX_TOKENS = 6_000;
8
+ /** Keeps only questions that fit the output schema (the structural ones can have very long names). */
9
+ function onlyValid(questions) {
10
+ return questions.filter((q) => QuizItemSchema.safeParse(q).success);
11
+ }
12
+ function structuralItems(questions) {
13
+ return questions.map((q) => ({ ...q, origin: "structural" }));
14
+ }
15
+ /**
16
+ * Makes a quiz of up to 5 questions. Throws a RangeError for a map that is not `schemaVersion: 1`
17
+ * (or a bad seed or attempt) before any provider is called. Everything else is handled: the result says who served it.
18
+ */
19
+ export async function generateQuiz(input, deps) {
20
+ const { map, files, seed = 0, attempt = 0 } = input;
21
+ const decision = input.decision !== undefined && hasChoice(input.decision) ? input.decision : undefined;
22
+ if (map?.schemaVersion !== 1)
23
+ throw new RangeError("the structure map must have schemaVersion 1");
24
+ // The structural questions are made first: they validate seed and attempt, and they are the fallback.
25
+ // Ten, not five: `fillQuiz` skips structural questions about a subject the AI questions already cover (changed Dec 2 after manual test).
26
+ const structural = generateStructuralQuestions(map, { count: QUIZ_SIZE * 2, seed, attempt });
27
+ const unconfigured = deps.config.unconfigured;
28
+ const request = { messages: buildQuizMessages(map, files, decision), maxTokens: QUIZ_MAX_TOKENS };
29
+ const chain = await runChain(request, (json) => checkAiQuiz(json, map, { seed, attempt, ...(decision === undefined ? {} : { decision }) }), deps);
30
+ // Questions that do not fit the output schema are dropped first, on both sides. Then `fillQuiz` tops the AI quiz up
31
+ // from the valid structural questions, so a dropped question is replaced and the quiz still has 5 where possible.
32
+ const validStructural = structural.filter((q) => QuizItemSchema.safeParse({ ...q, origin: "structural" }).success);
33
+ if (chain.ok) {
34
+ // 3 or 4 AI questions are topped up with structural ones; 5 are used as they are.
35
+ const questions = fillQuiz(onlyValid(chain.value), validStructural);
36
+ return { questions, servedBy: chain.servedBy, model: chain.model, attempts: chain.attempts, unconfigured };
37
+ }
38
+ // Valid first, then the first 5 (changed Dec 2 after review): cutting to 5 first lost a slot for every invalid question.
39
+ return { questions: structuralItems(validStructural.slice(0, QUIZ_SIZE)), servedBy: "structural", attempts: chain.attempts, unconfigured };
40
+ }
41
+ //# sourceMappingURL=quiz.js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AAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,YAAY,EAAE,CAAC;AAC7I,CAAC"}
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@seance/ai",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "description": "AI provider chain for Seance (Gemini -> NVIDIA -> OpenRouter -> structural fallback). Does network I/O; pure logic stays in @seance/core.",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.json",
18
+ "test": "vitest run"
19
+ },
20
+ "dependencies": {
21
+ "@seance/core": "0.0.0",
22
+ "openai": "7.62.0",
23
+ "zod": "4.6.7"
24
+ }
25
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vedant Hande
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,58 @@
1
+ import type { QuizItem } from "./ai-schemas.js";
2
+ import type { DecisionEntry } from "./decision-log.js";
3
+ import type { Rubric } from "./scoring.js";
4
+ import type { StructuralQuestion } from "./structural-questions.js";
5
+ import type { StructureMap } from "./structure-map.js";
6
+ export type CheckFailure = "not-json" | "invalid" | "semantic";
7
+ export type Checked<T> = {
8
+ ok: true;
9
+ value: T;
10
+ } | {
11
+ ok: false;
12
+ reason: CheckFailure;
13
+ };
14
+ /** Trims, removes one surrounding code fence, then parses. A parse failure or a non-object is `not-json`. */
15
+ export declare function extractJson(content: string): Checked<unknown>;
16
+ /** Paths, function, class and method names, export names and imported names of the parsed files. Never `default` or `*`. */
17
+ export declare function mapNames(map: StructureMap): Set<string>;
18
+ /**
19
+ * Turns the model's JSON into quiz items. Bad questions are dropped one by one; if fewer than 3 are left
20
+ * the whole reply is `semantic` (product decision 1). The model gives answer text, we compute the index.
21
+ */
22
+ export declare function checkAiQuiz(json: unknown, map: StructureMap, opts: {
23
+ seed: number;
24
+ attempt: number;
25
+ decision?: DecisionEntry;
26
+ }): Checked<QuizItem[]>;
27
+ /**
28
+ * Fills a 3-4 question AI quiz up to 5 with structural questions (req 3.7).
29
+ * Order: AI choice questions, then structural ones, then the AI explain question last.
30
+ * A structural question about a (concept, subject) that the quiz already has is skipped (changed Dec 2 after manual test),
31
+ * so pass more structural questions than there is room for.
32
+ */
33
+ export declare function fillQuiz(ai: QuizItem[], structural: StructuralQuestion[]): QuizItem[];
34
+ /** Lower-cased words of 4+ characters without stop words; one trailing `s` is dropped from words of 5+ characters. */
35
+ export declare function keyTerms(text: string): Set<string>;
36
+ /** The feedback for a blank explain answer (changed Dec 2 after manual test). */
37
+ export declare const BLANK_ANSWER_FEEDBACK = "No answer was given.";
38
+ /** True for an answer with nothing visible in it: empty, whitespace or only invisible characters. */
39
+ export declare function isBlankAnswer(answer: string): boolean;
40
+ /**
41
+ * Grades without AI: a key point is covered when the answer passes the evidence test for it.
42
+ * Rough, and a pasted list of names can game it (product decision 2).
43
+ */
44
+ export declare function keywordGrade(rubric: Rubric, answer: string): {
45
+ score: number;
46
+ covered: number[];
47
+ };
48
+ /**
49
+ * Turns the model's `{ covered, feedback }` into a score. The model only names key points; we count them.
50
+ * A key point counts only if the model lists it AND the answer passes the same evidence test as `keywordGrade`
51
+ * (product decision 3). So the AI score is never above the keyword score: the model cannot give credit for a
52
+ * key point the answer has no evidence for. The AI can only confirm or lower the keyword result.
53
+ * The feedback is untrusted text from the model; it is only trimmed and cut here, and a UI must show it as plain text.
54
+ */
55
+ export declare function checkGrade(json: unknown, rubric: Rubric, answer: string): Checked<{
56
+ score: number;
57
+ feedback: string;
58
+ }>;