@tora-editor/tora 0.1.0 → 0.3.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 (131) hide show
  1. package/README.md +107 -58
  2. package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
  3. package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
  4. package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
  5. package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
  6. package/assets/kenney-food-starter/License.txt +28 -0
  7. package/assets/kenney-food-starter/burger.glb +0 -0
  8. package/assets/kenney-food-starter/frying-pan.glb +0 -0
  9. package/assets/kenney-food-starter/plan.json +61 -0
  10. package/assets/kenney-food-starter/plate.glb +0 -0
  11. package/assets/kenney-food-starter/pot.glb +0 -0
  12. package/assets/kenney-harvest/audio/victory.wav +0 -0
  13. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
  14. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
  15. package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
  16. package/bin/tora.mjs +322 -28
  17. package/crates/packer/trusted/native-3d-meta.json +4 -3
  18. package/crates/packer/trusted/native-3d.js +181 -181
  19. package/crates/packer/trusted/native-meta.json +3 -3
  20. package/crates/packer/trusted/native.js +5 -5
  21. package/crates/packer/trusted/release-manifest.json +17 -17
  22. package/crates/packer/trusted/review-runtime-meta.json +4 -3
  23. package/crates/packer/trusted/review-runtime.js +182 -182
  24. package/docs/MIGRATION_0_3.md +39 -0
  25. package/docs/NATIVE_AGENT_TOOLS.md +12 -363
  26. package/docs/TORA_AGENT_SETUP.md +24 -95
  27. package/docs/TORA_CREATION_API.md +63 -348
  28. package/docs/reference/CORE_AUTHORING.md +10 -3
  29. package/docs/reference/PLAYABLE_STARTERS.md +20 -0
  30. package/docs/reference/packs/3d.md +11 -3
  31. package/network-rules/mintegral-appgrowth-single-html.json +10 -10
  32. package/package.json +6 -6
  33. package/packages/creative-project/project-v21.schema.json +372 -9
  34. package/scripts/lean/editor/entry.js +11 -6
  35. package/scripts/lean/editor/project-launcher.js +116 -0
  36. package/scripts/lean/editor/quick-edit-panel.js +479 -0
  37. package/scripts/lean/editor/review-editor.css +256 -68
  38. package/scripts/lean/editor/review-editor.js +1834 -1086
  39. package/scripts/lean/editor-state.mjs +6 -0
  40. package/scripts/lean/editor.mjs +6 -3
  41. package/scripts/lean/matrix.mjs +5 -0
  42. package/scripts/lean/native/agent-tools.mjs +39 -62
  43. package/scripts/lean/native/api.mjs +161 -136
  44. package/scripts/lean/native/asset-catalog.mjs +7 -6
  45. package/scripts/lean/native/asset-lineage.mjs +54 -0
  46. package/scripts/lean/native/asset-prep.mjs +173 -40
  47. package/scripts/lean/native/assets.mjs +107 -11
  48. package/scripts/lean/native/audio-assets.mjs +30 -0
  49. package/scripts/lean/native/browser-pool.mjs +34 -0
  50. package/scripts/lean/native/build-cache.mjs +38 -7
  51. package/scripts/lean/native/cc0-inputs.mjs +24 -0
  52. package/scripts/lean/native/cc0-staging.mjs +28 -8
  53. package/scripts/lean/native/compiler.mjs +9 -3
  54. package/scripts/lean/native/contracts.mjs +16 -11
  55. package/scripts/lean/native/creative-qa.mjs +365 -128
  56. package/scripts/lean/native/demos.mjs +53 -18
  57. package/scripts/lean/native/document.mjs +50 -12
  58. package/scripts/lean/native/export-budget.mjs +75 -0
  59. package/scripts/lean/native/local-bundle.mjs +7 -3
  60. package/scripts/lean/native/mcp-server.mjs +42 -74
  61. package/scripts/lean/native/media-validate.mjs +124 -0
  62. package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
  63. package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
  64. package/scripts/lean/native/modules/star-salvage.mjs +3 -368
  65. package/scripts/lean/native/native-bin.mjs +3 -3
  66. package/scripts/lean/native/outcome-playthrough.mjs +97 -0
  67. package/scripts/lean/native/project-bundle.mjs +6 -5
  68. package/scripts/lean/native/project-index.mjs +0 -2
  69. package/scripts/lean/native/qa-adapters.mjs +10 -0
  70. package/scripts/lean/native/quick-edit.mjs +328 -0
  71. package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
  72. package/scripts/lean/native/review.mjs +205 -571
  73. package/scripts/lean/native/schema-vocabulary.mjs +10 -0
  74. package/scripts/lean/native/schema.mjs +7 -5
  75. package/scripts/lean/native/scope.mjs +45 -0
  76. package/scripts/lean/native/service.mjs +378 -79
  77. package/scripts/lean/native/starters.mjs +563 -0
  78. package/scripts/lean/native/variant-adapters.mjs +8 -0
  79. package/scripts/lean/native/variants-core.mjs +186 -0
  80. package/scripts/lean/native/variants.mjs +63 -0
  81. package/scripts/lean/native/win-cues.mjs +96 -0
  82. package/skills/tora-playables/SKILL.md +1 -1
  83. package/scripts/lean/editor/review-intake.js +0 -837
  84. package/scripts/lean/model-client.mjs +0 -119
  85. package/scripts/lean/native/author-expansion-proofs.mjs +0 -240
  86. package/scripts/lean/native/author-games.mjs +0 -160
  87. package/scripts/lean/native/author-harvest.mjs +0 -74
  88. package/scripts/lean/native/author-primitive-proofs.mjs +0 -874
  89. package/scripts/lean/native/author-salvage.mjs +0 -71
  90. package/scripts/lean/native/chat-compose.mjs +0 -287
  91. package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -191
  92. package/scripts/lean/native/check-salvage.mjs +0 -197
  93. package/scripts/lean/native/compatibility.mjs +0 -34
  94. package/scripts/lean/native/concept.mjs +0 -633
  95. package/scripts/lean/native/draw-stroke.mjs +0 -26
  96. package/scripts/lean/native/erase-mask.mjs +0 -18
  97. package/scripts/lean/native/harvest-recipe.mjs +0 -21
  98. package/scripts/lean/native/instance-steering.mjs +0 -24
  99. package/scripts/lean/native/intake-creator-agent.mjs +0 -98
  100. package/scripts/lean/native/intake-creator-tools.mjs +0 -165
  101. package/scripts/lean/native/interaction-gestures.mjs +0 -45
  102. package/scripts/lean/native/match-board.mjs +0 -138
  103. package/scripts/lean/native/modules/index.mjs +0 -54
  104. package/scripts/lean/native/modules/tap-collect.mjs +0 -54
  105. package/scripts/lean/native/path-network.mjs +0 -132
  106. package/scripts/lean/native/physics-2d.mjs +0 -154
  107. package/scripts/lean/native/physics-3d.mjs +0 -259
  108. package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
  109. package/scripts/lean/native/prepare-game-audio.mjs +0 -372
  110. package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
  111. package/scripts/lean/native/prepare-golf-assets.py +0 -211
  112. package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
  113. package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
  114. package/scripts/lean/native/prepare-primitive-images.py +0 -25
  115. package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
  116. package/scripts/lean/native/prepare-traffic-assets.py +0 -329
  117. package/scripts/lean/native/presentation.mjs +0 -335
  118. package/scripts/lean/native/review-agent-tools.mjs +0 -561
  119. package/scripts/lean/native/review-connection.mjs +0 -303
  120. package/scripts/lean/native/review-fields.mjs +0 -24
  121. package/scripts/lean/native/review-intake.mjs +0 -385
  122. package/scripts/lean/native/review-intents.mjs +0 -217
  123. package/scripts/lean/native/review-provider.mjs +0 -580
  124. package/scripts/lean/native/review-receipts.mjs +0 -76
  125. package/scripts/lean/native/review-resolver.mjs +0 -429
  126. package/scripts/lean/native/review-targets.mjs +0 -35
  127. package/scripts/lean/native/runtime.mjs +0 -1623
  128. package/scripts/lean/native/salvage-recipe.mjs +0 -20
  129. package/scripts/lean/native/stage-3d.mjs +0 -818
  130. package/scripts/lean/native/verify.mjs +0 -4
  131. package/scripts/lean/scene-document.mjs +0 -48
@@ -1,580 +0,0 @@
1
- import process from 'node:process';
2
- import {Buffer} from 'node:buffer';
3
- import {URL} from 'node:url';
4
- import {PlanError,requestChatCompletion} from '../model-client.mjs';
5
-
6
- const providers=new Set(['orca','openai','anthropic','gemini','openai-compatible']);
7
- const imageTypes=new Set(['image/png','image/jpeg','image/webp']);
8
- const clean=value=>typeof value==='string'?value.trim():'';
9
-
10
- const MODEL_ID_RE=/^[a-zA-Z0-9][a-zA-Z0-9._:-]{1,95}$/;
11
- const COMPAT_MODEL_ID_RE=/^[a-zA-Z0-9][a-zA-Z0-9._:/-]{1,127}$/;
12
- const DISALLOWED_MODEL_FRAGMENT=/(?:embed|embedding|whisper|tts|transcribe|realtime|audio-preview|native-audio|moderation|dall-e|imagen|veo|sora|lyria|aqa|bison|gecko|instruct|davinci|babbage|curie|ada|-image(?:$|-)|-search(?:$|-)|-live(?:$|-)|robotics|computer-use)/i;
13
-
14
- const GEMINI_CAPABILITIES=Object.freeze({tools:true,json:true,vision:true,audio:'native',video:'native-and-keyframes'});
15
- const MULTIMODAL_QA_CAPABILITIES=Object.freeze({tools:true,json:true,vision:true,audio:'tora-analyzed',video:'keyframes'});
16
- const TEXT_ONLY_QA_CAPABILITIES=Object.freeze({tools:true,json:true,vision:false,audio:'tora-analyzed',video:'none'});
17
-
18
- export const OPENAI_COMPATIBLE_PRESETS=Object.freeze([
19
- Object.freeze({
20
- id:'openrouter',
21
- label:'OpenRouter',
22
- endpoint:'https://openrouter.ai/api/v1',
23
- keyUrl:'https://openrouter.ai/keys',
24
- keyPlaceholder:'sk-or-v1-...',
25
- defaultModel:'qwen/qwen3.8-max',
26
- vision:true,
27
- models:Object.freeze([
28
- Object.freeze({id:'qwen/qwen3.8-max',label:'Qwen 3.8 Max (OpenRouter)',badge:'Recommended',contextTokens:1_000_000,vision:true}),
29
- Object.freeze({id:'moonshotai/kimi-k3.1-pro',label:'Kimi K3.1 Pro (OpenRouter)',badge:'Flagship',contextTokens:1_000_000,vision:true}),
30
- Object.freeze({id:'z-ai/glm-5.3-flash',label:'GLM-5.3 Flash (OpenRouter)',badge:'Fast',contextTokens:1_000_000,vision:true}),
31
- Object.freeze({id:'deepseek/deepseek-v4-pro',label:'DeepSeek V4 Pro (OpenRouter)',badge:'Coding',contextTokens:128_000,vision:false}),
32
- ]),
33
- }),
34
- Object.freeze({
35
- id:'deepseek',
36
- label:'DeepSeek',
37
- endpoint:'https://api.deepseek.com/v1',
38
- keyUrl:'https://platform.deepseek.com/api_keys',
39
- keyPlaceholder:'sk-...',
40
- defaultModel:'deepseek-chat',
41
- vision:false,
42
- models:Object.freeze([
43
- Object.freeze({id:'deepseek-chat',label:'DeepSeek Chat',badge:'Recommended',contextTokens:128_000,vision:false}),
44
- Object.freeze({id:'deepseek-reasoner',label:'DeepSeek Reasoner',badge:'Reasoning',contextTokens:128_000,vision:false}),
45
- ]),
46
- }),
47
- Object.freeze({
48
- id:'kimi',
49
- label:'Kimi (Moonshot)',
50
- endpoint:'https://api.moonshot.ai/v1',
51
- keyUrl:'https://platform.moonshot.ai/console/api-keys',
52
- keyPlaceholder:'sk-...',
53
- defaultModel:'kimi-k3.1-pro',
54
- vision:true,
55
- models:Object.freeze([
56
- Object.freeze({id:'kimi-k3.1-pro',label:'Kimi K3.1 Pro',badge:'Recommended',contextTokens:1_000_000,vision:true}),
57
- Object.freeze({id:'kimi-k3',label:'Kimi K3',badge:'Balanced',contextTokens:1_000_000,vision:true}),
58
- Object.freeze({id:'kimi-k2.7-code',label:'Kimi K2.7 Code',badge:'Coding',contextTokens:256_000,vision:true}),
59
- Object.freeze({id:'kimi-k2-turbo-preview',label:'Kimi K2 Turbo',badge:'Fast',contextTokens:256_000,vision:true}),
60
- ]),
61
- }),
62
- Object.freeze({
63
- id:'qwen',
64
- label:'Qwen (Alibaba)',
65
- endpoint:'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
66
- keyUrl:'https://modelstudio.console.alibabacloud.com/',
67
- keyPlaceholder:'sk-...',
68
- defaultModel:'qwen3.8-max',
69
- vision:true,
70
- models:Object.freeze([
71
- Object.freeze({id:'qwen3.8-max',label:'Qwen 3.8 Max',badge:'Recommended',contextTokens:1_000_000,vision:true}),
72
- Object.freeze({id:'qwen3.7-plus',label:'Qwen 3.7 Plus',badge:'Balanced',contextTokens:1_000_000,vision:true}),
73
- Object.freeze({id:'qwen3.8-flash',label:'Qwen 3.8 Flash',badge:'Fast',contextTokens:1_000_000,vision:true}),
74
- Object.freeze({id:'qwen-vl-max-latest',label:'Qwen VL Max',badge:'Vision',contextTokens:128_000,vision:true}),
75
- ]),
76
- }),
77
- Object.freeze({
78
- id:'glm',
79
- label:'GLM (Z.ai)',
80
- endpoint:'https://api.z.ai/api/paas/v4',
81
- keyUrl:'https://z.ai/manage-apikey/apikey-list',
82
- keyPlaceholder:'Paste Z.ai / BigModel key',
83
- defaultModel:'glm-5.3-flash',
84
- vision:true,
85
- models:Object.freeze([
86
- Object.freeze({id:'glm-5.3-flash',label:'GLM-5.3 Flash',badge:'Recommended',contextTokens:1_000_000,vision:true}),
87
- Object.freeze({id:'glm-5.3',label:'GLM-5.3',badge:'Flagship',contextTokens:1_000_000,vision:false}),
88
- Object.freeze({id:'glm-5v-turbo',label:'GLM-5V Turbo',badge:'Vision',contextTokens:256_000,vision:true}),
89
- Object.freeze({id:'glm-5.4',label:'GLM-5.4',badge:'Coding',contextTokens:1_000_000,vision:false}),
90
- ]),
91
- }),
92
- Object.freeze({
93
- id:'custom',
94
- label:'Custom / Local',
95
- endpoint:'',
96
- keyUrl:'',
97
- keyPlaceholder:'API key (or "local" for Ollama/vLLM)',
98
- defaultModel:'',
99
- vision:true,
100
- models:Object.freeze([]),
101
- }),
102
- ]);
103
-
104
- export function normalizeOpenAiCompatibleEndpoint(raw){
105
- const value=clean(raw);
106
- if(!value||value.length>512)return null;
107
- let parsed;
108
- try{parsed=new URL(value);}catch{return null;}
109
- if(parsed.username||parsed.password||parsed.search||parsed.hash)return null;
110
- const host=parsed.hostname.toLowerCase();
111
- const isLocal=host==='localhost'||host==='127.0.0.1'||host==='[::1]';
112
- if(parsed.protocol!=='https:'&&!(parsed.protocol==='http:'&&isLocal))return null;
113
- const path=parsed.pathname.replace(/\/+$/,'').replace(/\/chat\/completions$/i,'');
114
- return parsed.origin+path;
115
- }
116
-
117
- export function openAiCompatiblePreset(presetId,endpoint){
118
- const byId=OPENAI_COMPATIBLE_PRESETS.find(item=>item.id===clean(presetId));
119
- if(byId&&byId.id!=='custom')return byId;
120
- const normalized=normalizeOpenAiCompatibleEndpoint(endpoint);
121
- if(normalized){
122
- const byEndpoint=OPENAI_COMPATIBLE_PRESETS.find(item=>item.endpoint&&normalized.startsWith(item.endpoint));
123
- if(byEndpoint)return byEndpoint;
124
- }
125
- return OPENAI_COMPATIBLE_PRESETS.find(item=>item.id==='custom');
126
- }
127
-
128
- export const VERIFIED_PLAYABLE_PROVIDERS=Object.freeze([
129
- Object.freeze({
130
- id:'gemini',
131
- label:'Google Gemini',
132
- keyUrl:'https://aistudio.google.com/apikey',
133
- keyPlaceholder:'AIza...',
134
- defaultModel:'gemini-4-hydrogen',
135
- audioSummary:'Native audio + Tora acoustic QA',
136
- videoSummary:'Native video + keyframes',
137
- summary:'Handles everything natively: vision, audio, video frames, and multi-turn playable tools.',
138
- defaultCapabilities:GEMINI_CAPABILITIES,
139
- models:Object.freeze([
140
- Object.freeze({
141
- id:'gemini-4-hydrogen',
142
- label:'Gemini 4 Hydrogen',
143
- badge:'Recommended',
144
- contextTokens:1_000_000,
145
- capabilities:GEMINI_CAPABILITIES,
146
- }),
147
- Object.freeze({
148
- id:'gemini-4-carbon',
149
- label:'Gemini 4 Carbon',
150
- badge:'Flagship',
151
- contextTokens:1_000_000,
152
- capabilities:GEMINI_CAPABILITIES,
153
- }),
154
- Object.freeze({
155
- id:'gemini-4-neon',
156
- label:'Gemini 4 Neon',
157
- badge:'Frontier',
158
- contextTokens:1_000_000,
159
- capabilities:GEMINI_CAPABILITIES,
160
- }),
161
- Object.freeze({
162
- id:'gemini-3.8-flash',
163
- label:'Gemini 3.8 Flash',
164
- badge:'Fast',
165
- contextTokens:1_000_000,
166
- capabilities:GEMINI_CAPABILITIES,
167
- }),
168
- ]),
169
- }),
170
- Object.freeze({
171
- id:'openai',
172
- label:'OpenAI',
173
- keyUrl:'https://platform.openai.com/api-keys',
174
- keyPlaceholder:'sk-...',
175
- defaultModel:'gpt-6.2-sol',
176
- audioSummary:'Tora acoustic QA + WAV catalog',
177
- videoSummary:'Extracted video keyframes',
178
- summary:'Strong tool calling and vision for scenes and video frames; sounds verified via Tora acoustic analysis.',
179
- defaultCapabilities:MULTIMODAL_QA_CAPABILITIES,
180
- models:Object.freeze([
181
- Object.freeze({
182
- id:'gpt-6.2-sol',
183
- label:'GPT-6.2 Sol',
184
- badge:'Recommended',
185
- contextTokens:1_000_000,
186
- capabilities:MULTIMODAL_QA_CAPABILITIES,
187
- }),
188
- Object.freeze({
189
- id:'gpt-6.2-astra',
190
- label:'GPT-6.2 Astra',
191
- badge:'Flagship',
192
- contextTokens:1_050_000,
193
- capabilities:MULTIMODAL_QA_CAPABILITIES,
194
- }),
195
- Object.freeze({
196
- id:'gpt-6.1-terra',
197
- label:'GPT-6.1 Terra',
198
- badge:'Fast',
199
- contextTokens:1_000_000,
200
- capabilities:MULTIMODAL_QA_CAPABILITIES,
201
- }),
202
- ]),
203
- }),
204
- Object.freeze({
205
- id:'anthropic',
206
- label:'Anthropic Claude',
207
- keyUrl:'https://console.anthropic.com/settings/keys',
208
- keyPlaceholder:'sk-ant-...',
209
- defaultModel:'claude-opus-5-5',
210
- audioSummary:'Tora acoustic QA + WAV catalog',
211
- videoSummary:'Extracted video keyframes',
212
- summary:'Precise multi-turn scene editing and vision for visuals and video frames; sounds verified via Tora acoustic analysis.',
213
- defaultCapabilities:MULTIMODAL_QA_CAPABILITIES,
214
- models:Object.freeze([
215
- Object.freeze({
216
- id:'claude-opus-5-5',
217
- label:'Claude Opus 5.5',
218
- badge:'Recommended',
219
- contextTokens:1_000_000,
220
- capabilities:MULTIMODAL_QA_CAPABILITIES,
221
- }),
222
- Object.freeze({
223
- id:'claude-sonnet-5-5',
224
- label:'Claude Sonnet 5.5',
225
- badge:'Fast',
226
- contextTokens:1_000_000,
227
- capabilities:MULTIMODAL_QA_CAPABILITIES,
228
- }),
229
- Object.freeze({
230
- id:'claude-fable-5-2',
231
- label:'Claude Fable 5.2',
232
- badge:'Deep reasoning',
233
- contextTokens:1_000_000,
234
- capabilities:MULTIMODAL_QA_CAPABILITIES,
235
- }),
236
- ]),
237
- }),
238
- Object.freeze({
239
- id:'openai-compatible',
240
- label:'Custom / OpenRouter',
241
- keyUrl:'https://openrouter.ai/keys',
242
- keyPlaceholder:'sk-or-v1-...',
243
- defaultModel:'qwen/qwen3.8-max',
244
- audioSummary:'Tora acoustic QA + WAV catalog',
245
- videoSummary:'Extracted video keyframes (when vision enabled)',
246
- summary:'Connect OpenRouter, DeepSeek, Kimi, Qwen, GLM, or any custom/local OpenAI-compatible API.',
247
- defaultCapabilities:MULTIMODAL_QA_CAPABILITIES,
248
- customEndpoint:true,
249
- presets:OPENAI_COMPATIBLE_PRESETS,
250
- models:OPENAI_COMPATIBLE_PRESETS[0].models,
251
- }),
252
- ]);
253
-
254
- function humanizeModelId(providerId,modelId){
255
- if(providerId==='openai'){
256
- return modelId.replace(/^gpt-/i,'GPT-').replace(/-([a-z])/g,(_m,ch)=>' '+ch.toUpperCase());
257
- }
258
- if(providerId==='anthropic'){
259
- return modelId.replace(/^claude-/i,'Claude ').replace(/-(\d+)-(\d+)(?!\d)/,' $1.$2').replace(/-([a-z])/g,(_m,ch)=>' '+ch.toUpperCase());
260
- }
261
- return modelId.replace(/^gemini-/i,'Gemini ').replace(/-([a-z])/g,(_m,ch)=>' '+ch.toUpperCase());
262
- }
263
-
264
- export function isPlayableCapableModel(providerId,modelId){
265
- const id=clean(modelId);
266
- if(providerId==='openai-compatible'){
267
- return Boolean(COMPAT_MODEL_ID_RE.test(id)&&!id.includes('..')&&!DISALLOWED_MODEL_FRAGMENT.test(id));
268
- }
269
- if(!MODEL_ID_RE.test(id)||DISALLOWED_MODEL_FRAGMENT.test(id))return false;
270
- if(providerId==='gemini'){
271
- const match=/^gemini-(\d+(?:\.\d+)?)-/.exec(id);
272
- if(!match)return false;
273
- return Number.parseFloat(match[1])>=2.5;
274
- }
275
- if(providerId==='openai'){
276
- if(/^(?:gpt-3\.5|gpt-4(?:$|-0|-32|-turbo|-vision)|o1-)/i.test(id))return false;
277
- return /^(?:gpt-(?:4o|4\.1|[5-9](?:\.\d+)?)(?:$|-)|o[3-9](?:$|-))/.test(id);
278
- }
279
- if(providerId==='anthropic'){
280
- return /^claude-(?:(?:opus|sonnet|fable)-(?:4(?:-\d+)?|[5-9](?:-\d+)?)|haiku-(?:[5-9](?:-\d+)?))(?:$|-)/.test(id);
281
- }
282
- return false;
283
- }
284
-
285
- export function verifiedPlayableModel(providerId,modelId,displayNameOrOptions){
286
- const options=typeof displayNameOrOptions==='string'?{displayName:displayNameOrOptions}:(displayNameOrOptions??{});
287
- const provider=VERIFIED_PLAYABLE_PROVIDERS.find(item=>item.id===clean(providerId));
288
- if(!provider)return null;
289
- if(provider.id==='openai-compatible'){
290
- const endpoint=normalizeOpenAiCompatibleEndpoint(options.endpoint);
291
- if(!endpoint)return null;
292
- const preset=openAiCompatiblePreset(options.preset,endpoint);
293
- const selected=clean(modelId)||preset?.defaultModel||'';
294
- if(!isPlayableCapableModel('openai-compatible',selected))return null;
295
- const curated=preset?.models?.find(item=>item.id===selected);
296
- const vision=typeof options.vision==='boolean'?options.vision:(curated?.vision??preset?.vision??true);
297
- const caps=vision?MULTIMODAL_QA_CAPABILITIES:TEXT_ONLY_QA_CAPABILITIES;
298
- const providerLabel=preset&&preset.id!=='custom'?preset.label:'OpenAI-Compatible';
299
- return {
300
- provider:{
301
- ...provider,
302
- label:providerLabel,
303
- preset:preset?.id??'custom',
304
- endpoint,
305
- videoSummary:vision?'Extracted video keyframes':'Text-only (no screenshot review)',
306
- },
307
- model:{
308
- id:selected,
309
- label:clean(options.displayName)||curated?.label||selected,
310
- badge:curated?.badge??'Custom',
311
- contextTokens:curated?.contextTokens??null,
312
- vision,
313
- capabilities:caps,
314
- },
315
- };
316
- }
317
- const selected=clean(modelId)||provider.defaultModel;
318
- const curated=provider.models.find(item=>item.id===selected);
319
- if(curated)return {provider,model:curated};
320
- if(!isPlayableCapableModel(provider.id,selected))return null;
321
- return {
322
- provider,
323
- model:{
324
- id:selected,
325
- label:clean(options.displayName)||humanizeModelId(provider.id,selected),
326
- badge:'Verified',
327
- contextTokens:null,
328
- capabilities:provider.defaultCapabilities,
329
- },
330
- };
331
- }
332
-
333
- export function publicPlayableProviders(){
334
- return VERIFIED_PLAYABLE_PROVIDERS.map(provider=>({
335
- id:provider.id,
336
- label:provider.label,
337
- keyUrl:provider.keyUrl,
338
- keyPlaceholder:provider.keyPlaceholder,
339
- defaultModel:provider.defaultModel,
340
- audioSummary:provider.audioSummary,
341
- videoSummary:provider.videoSummary,
342
- summary:provider.summary,
343
- ...(provider.customEndpoint?{
344
- customEndpoint:true,
345
- presets:provider.presets.map(preset=>({
346
- id:preset.id,
347
- label:preset.label,
348
- endpoint:preset.endpoint,
349
- keyUrl:preset.keyUrl,
350
- keyPlaceholder:preset.keyPlaceholder,
351
- defaultModel:preset.defaultModel,
352
- vision:preset.vision,
353
- models:preset.models.map(model=>({...model})),
354
- })),
355
- }:{}),
356
- models:provider.models.map(model=>({
357
- id:model.id,
358
- label:model.label,
359
- badge:model.badge,
360
- contextTokens:model.contextTokens,
361
- ...(typeof model.vision==='boolean'?{vision:model.vision}:{}),
362
- capabilities:{...(model.capabilities??provider.defaultCapabilities)},
363
- })),
364
- }));
365
- }
366
-
367
- export function modelListRequest(providerId,apiKey,options={}){
368
- const provider=VERIFIED_PLAYABLE_PROVIDERS.find(item=>item.id===clean(providerId));
369
- if(!provider)throw new PlanError('E_MODEL_UNSUPPORTED_CAPABILITY');
370
- if(provider.id==='openai-compatible'){
371
- const base=normalizeOpenAiCompatibleEndpoint(options.endpoint);
372
- if(!base)throw new PlanError('E_MODEL_UNSUPPORTED_CAPABILITY');
373
- return {
374
- url:`${base}/models`,
375
- headers:{Authorization:'Bearer '+apiKey},
376
- };
377
- }
378
- if(provider.id==='gemini'){
379
- return {
380
- url:'https://generativelanguage.googleapis.com/v1beta/models?pageSize=200',
381
- headers:{'x-goog-api-key':apiKey},
382
- };
383
- }
384
- if(provider.id==='openai'){
385
- return {
386
- url:'https://api.openai.com/v1/models',
387
- headers:{Authorization:'Bearer '+apiKey},
388
- };
389
- }
390
- return {
391
- url:'https://api.anthropic.com/v1/models?limit=100',
392
- headers:{'x-api-key':apiKey,'anthropic-version':'2023-06-01'},
393
- };
394
- }
395
-
396
- export function modelVerificationRequest(providerId,modelId,apiKey,options={}){
397
- const verified=verifiedPlayableModel(providerId,modelId,options);
398
- if(!verified)throw new PlanError('E_MODEL_UNSUPPORTED_CAPABILITY');
399
- const {provider,model}=verified;
400
- const encoded=encodeURIComponent(model.id);
401
- if(provider.id==='openai-compatible'){
402
- return {
403
- url:`${provider.endpoint}/models/${encoded}`,
404
- listUrl:`${provider.endpoint}/models`,
405
- headers:{Authorization:'Bearer '+apiKey},
406
- };
407
- }
408
- if(provider.id==='gemini'){
409
- return {
410
- url:`https://generativelanguage.googleapis.com/v1beta/models/${encoded}`,
411
- headers:{'x-goog-api-key':apiKey},
412
- };
413
- }
414
- if(provider.id==='openai'){
415
- return {
416
- url:`https://api.openai.com/v1/models/${encoded}`,
417
- headers:{Authorization:'Bearer '+apiKey},
418
- };
419
- }
420
- return {
421
- url:`https://api.anthropic.com/v1/models/${encoded}`,
422
- headers:{'x-api-key':apiKey,'anthropic-version':'2023-06-01'},
423
- };
424
- }
425
-
426
- export function orcaProviderConfig(apiKey=process.env.ORCAROUTER_API_KEY){
427
- const key=clean(apiKey);if(!key)return undefined;
428
- return {provider:'orca',endpoint:'https://api.orcarouter.ai/v1/chat/completions',apiKey:key,
429
- model:'deepseek/deepseek-v4-flash-free',paidModel:'deepseek/deepseek-v4-pro',vision:false,orcaFreeTier:true};
430
- }
431
-
432
- export function reviewProviderConfig(options={}){
433
- const provider=options.provider??process.env.TORA_REVIEW_PROVIDER??'orca';
434
- if(!providers.has(provider))throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
435
- if(provider==='orca'){
436
- const config=orcaProviderConfig(options.apiKey);
437
- return config?{...config,vision:options.vision===true||process.env.TORA_REVIEW_VISION==='1'}:undefined;
438
- }
439
- const names={openai:'OPENAI_API_KEY',anthropic:'ANTHROPIC_API_KEY',gemini:'GEMINI_API_KEY','openai-compatible':'TORA_REVIEW_API_KEY'};
440
- const apiKey=clean(options.apiKey??process.env[names[provider]]);if(!apiKey)return undefined;
441
- const model=clean(options.model??process.env.TORA_REVIEW_MODEL);
442
- const rawEndpoint=clean(options.endpoint??process.env.TORA_REVIEW_ENDPOINT??({
443
- openai:'https://api.openai.com/v1/chat/completions',anthropic:'https://api.anthropic.com/v1/messages',gemini:'https://generativelanguage.googleapis.com/v1beta/models',
444
- })[provider]);
445
- if(!model||!rawEndpoint)throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
446
- let endpoint=rawEndpoint;
447
- if(provider==='openai-compatible'){
448
- const base=normalizeOpenAiCompatibleEndpoint(rawEndpoint);
449
- if(!base)throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
450
- endpoint=`${base}/chat/completions`;
451
- }else{
452
- if(!/^https:\/\//.test(rawEndpoint))throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
453
- let parsed;try{parsed=new URL(rawEndpoint);}catch{throw new PlanError('E_REVIEW_PROVIDER_CONFIG');}
454
- if(parsed.username||parsed.password||parsed.search||parsed.hash)throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
455
- }
456
- return {provider,endpoint,apiKey,model,paidModel:clean(options.paidModel??process.env.TORA_REVIEW_PAID_MODEL)||model,
457
- vision:options.vision===true||process.env.TORA_REVIEW_VISION==='1',orcaFreeTier:false};
458
- }
459
-
460
- function orcaRequest(config,request){return {endpoint:config.endpoint,headers:{'Content-Type':'application/json',Authorization:'Bearer '+config.apiKey},body:request};}
461
- function openAiRequest(config,request){
462
- const body={...request};delete body.thinking;delete body.include_reasoning;
463
- if(config.provider==='openai'&&/^(?:gpt-[5-9]|o[1-9])(?:$|[.-])/.test(String(body.model??''))&&body.max_tokens!==undefined){
464
- body.max_completion_tokens=body.max_tokens;
465
- delete body.max_tokens;
466
- }
467
- return {endpoint:config.endpoint,headers:{'Content-Type':'application/json',Authorization:'Bearer '+config.apiKey},body};
468
- }
469
- function safeToolArgs(raw){
470
- if(raw&&typeof raw==='object'&&!Array.isArray(raw))return raw;
471
- try{const parsed=JSON.parse(String(raw??'{}'));return parsed&&typeof parsed==='object'&&!Array.isArray(parsed)?parsed:{};}catch{return {};}
472
- }
473
- function geminiSchema(schema){
474
- if(!schema||typeof schema!=='object')return schema;
475
- const out={};
476
- for(const key of ['type','description','enum','required','nullable']){
477
- if(Object.hasOwn(schema,key))out[key]=schema[key];
478
- }
479
- if(schema.properties&&typeof schema.properties==='object'){
480
- out.properties=Object.fromEntries(Object.entries(schema.properties).map(([k,v])=>[k,geminiSchema(v)]));
481
- }
482
- if(schema.items&&typeof schema.items==='object')out.items=geminiSchema(schema.items);
483
- return out;
484
- }
485
- function anthropicContent(content,toolCalls){
486
- if(typeof content==='string'||content==null)return [...(content?[{type:'text',text:content}]:[]),...(toolCalls??[]).map(call=>({type:'tool_use',id:call.id,name:call.function.name,input:safeToolArgs(call.function.arguments)}))];
487
- return content.map(part=>{
488
- if(part.type==='text')return {type:'text',text:part.text};
489
- if(part.type==='image_url'){
490
- const match=/^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/.exec(part.image_url?.url??'');
491
- if(!match)throw new PlanError('E_REVIEW_VISION_INPUT');
492
- return {type:'image',source:{type:'base64',media_type:match[1],data:match[2]}};
493
- }
494
- throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
495
- });
496
- }
497
- function anthropicRequest(config,request){
498
- const system=request.messages.filter(message=>message.role==='system').map(message=>message.content).join('\n');
499
- const messages=[];
500
- for(const message of request.messages){
501
- if(message.role==='system')continue;
502
- const role=message.role==='assistant'?'assistant':'user';
503
- const content=message.role==='tool'?[{type:'tool_result',tool_use_id:message.tool_call_id,content:message.content}]:anthropicContent(message.content,message.tool_calls);
504
- const previous=messages.at(-1);
505
- if(previous?.role===role){const parts=Array.isArray(previous.content)?previous.content:[{type:'text',text:previous.content}];previous.content=[...parts,...content];}
506
- else messages.push({role,content});
507
- }
508
- return {endpoint:config.endpoint,headers:{'Content-Type':'application/json','x-api-key':config.apiKey,'anthropic-version':'2023-06-01'},body:{
509
- model:request.model,max_tokens:request.max_tokens,...(system?{system}:{}),messages,
510
- ...(request.tools?{tools:request.tools.map(tool=>({name:tool.function.name,description:tool.function.description,input_schema:tool.function.parameters}))}:{}),
511
- }};
512
- }
513
- function geminiParts(content,toolCalls){
514
- if(typeof content==='string'||content==null)return [...(content?[{text:content}]:[]),...(toolCalls??[]).map(call=>({functionCall:{name:call.function.name,args:safeToolArgs(call.function.arguments)}}))];
515
- return content.map(part=>{
516
- if(part.type==='text')return {text:part.text};
517
- if(part.type==='image_url'){
518
- const match=/^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/.exec(part.image_url?.url??'');
519
- if(!match)throw new PlanError('E_REVIEW_VISION_INPUT');
520
- return {inlineData:{mimeType:match[1],data:match[2]}};
521
- }
522
- throw new PlanError('E_REVIEW_PROVIDER_CONFIG');
523
- });
524
- }
525
- function geminiRequest(config,request){
526
- const contents=[],toolNames=new Map();
527
- for(const message of request.messages){
528
- if(message.role==='system')continue;
529
- for(const call of message.tool_calls??[])toolNames.set(call.id,call.function.name);
530
- const role=message.role==='assistant'?'model':'user';
531
- let parts;
532
- if(message.role==='tool'){
533
- let response;try{response=JSON.parse(message.content);}catch{response={content:message.content};}
534
- const name=toolNames.get(message.tool_call_id);if(!name)throw new PlanError('E_MODEL_TOOLS');
535
- parts=[{functionResponse:{name,response:typeof response==='object'&&response&&!Array.isArray(response)?response:{result:response}}}];
536
- }else parts=geminiParts(message.content,message.tool_calls);
537
- const previous=contents.at(-1);if(previous?.role===role)previous.parts.push(...parts);else contents.push({role,parts});
538
- }
539
- const declarations=request.tools?.map(tool=>({name:tool.function.name,description:tool.function.description,parameters:geminiSchema(tool.function.parameters)}));
540
- const system=request.messages.filter(message=>message.role==='system').map(message=>message.content).join('\n');
541
- const base=endpointForGemini(config.endpoint,request.model);
542
- return {endpoint:base,headers:{'Content-Type':'application/json','x-goog-api-key':config.apiKey},body:{
543
- ...(system?{systemInstruction:{parts:[{text:system}]}}:{}),contents,
544
- ...(declarations?.length?{tools:[{functionDeclarations:declarations}]}:{}),
545
- generationConfig:{maxOutputTokens:request.max_tokens,...(declarations?.length?{}:{responseMimeType:'application/json'})},
546
- }};
547
- }
548
- function endpointForGemini(endpoint,model){
549
- if(endpoint.endsWith(':generateContent'))return endpoint;
550
- return endpoint.replace(/\/$/,'')+'/'+encodeURIComponent(model)+':generateContent';
551
- }
552
- function normalizeResponse(provider,envelope){
553
- if(provider!=='anthropic'&&provider!=='gemini')return envelope;
554
- if(provider==='anthropic'){
555
- const text=(envelope.content??[]).filter(part=>part.type==='text').map(part=>part.text).join('');
556
- const calls=(envelope.content??[]).filter(part=>part.type==='tool_use').map(part=>({id:part.id,type:'function',function:{name:part.name,arguments:JSON.stringify(part.input??{})}}));
557
- return {id:envelope.id,model:envelope.model,choices:[{finish_reason:envelope.stop_reason==='tool_use'?'tool_calls':envelope.stop_reason==='end_turn'?'stop':envelope.stop_reason==='max_tokens'?'length':'stop',message:{content:text||null,...(calls.length?{tool_calls:calls}:{})}}],usage:{prompt_tokens:envelope.usage?.input_tokens,completion_tokens:envelope.usage?.output_tokens}};
558
- }
559
- const candidate=envelope.candidates?.[0],parts=candidate?.content?.parts??[],text=parts.filter(part=>typeof part.text==='string').map(part=>part.text).join('');
560
- const calls=parts.filter(part=>part.functionCall).map((part,index)=>({id:part.functionCall.id??`gemini-${index}`,type:'function',function:{name:part.functionCall.name,arguments:JSON.stringify(part.functionCall.args??{})}}));
561
- return {model:envelope.modelVersion,choices:[{finish_reason:calls.length?'tool_calls':candidate?.finishReason==='STOP'?'stop':candidate?.finishReason==='MAX_TOKENS'?'length':'stop',message:{content:text||null,...(calls.length?{tool_calls:calls}:{})}}],usage:{prompt_tokens:envelope.usageMetadata?.promptTokenCount,completion_tokens:envelope.usageMetadata?.candidatesTokenCount}};
562
- }
563
- export async function requestReviewCompletion({config,request,fetchImpl=globalThis.fetch,call={}}){
564
- const adapted=config.provider==='anthropic'?anthropicRequest(config,request):config.provider==='gemini'?geminiRequest(config,request):config.provider==='orca'?orcaRequest(config,request):openAiRequest(config,request);
565
- const envelope=await requestChatCompletion({config:{...config,endpoint:adapted.endpoint,maximumResponseBytes:config.maximumResponseBytes??192000,timeoutMs:config.timeoutMs??45000},request:adapted.body,call,
566
- fetchImpl:async(_url,init)=>fetchImpl(adapted.endpoint,{...init,headers:adapted.headers,body:JSON.stringify(adapted.body)})});
567
- return normalizeResponse(config.provider,envelope);
568
- }
569
-
570
- export function reviewUserMessage(input,config){
571
- const screenshots=input?.screenshots??[],copy={...input};delete copy.screenshots;
572
- if(!Array.isArray(screenshots)||screenshots.length>4)throw new PlanError('E_REVIEW_VISION_INPUT');
573
- if(!config.vision){if(screenshots.length)copy.screenshotsOmitted=screenshots.length;return {role:'user',content:JSON.stringify(copy)};}
574
- let bytes=0;const images=screenshots.map(screenshot=>{
575
- if(!screenshot||!imageTypes.has(screenshot.mimeType)||typeof screenshot.data!=='string'||!/^[A-Za-z0-9+/=]+$/.test(screenshot.data))throw new PlanError('E_REVIEW_VISION_INPUT');
576
- const size=Buffer.byteLength(screenshot.data,'base64');bytes+=size;if(size>2_500_000||bytes>8_000_000||!size)throw new PlanError('E_REVIEW_VISION_INPUT');
577
- return {type:'image_url',image_url:{url:`data:${screenshot.mimeType};base64,${screenshot.data}`}};
578
- });
579
- return {role:'user',content:[{type:'text',text:JSON.stringify(copy)},...images]};
580
- }
@@ -1,76 +0,0 @@
1
- const safeInteger=value=>Number.isSafeInteger(value)&&value>=0;
2
-
3
- export function createReviewReceipt(requestId,expected,now=Date.now()){
4
- return {
5
- format:'tora-review-receipt-1',requestId,baseline:expected,route:'unresolved',submittedAt:now,
6
- candidateId:null,disposition:'submitted',providerCalls:[],providerUsage:{inputTokens:0,outputTokens:0,cachedInputTokens:0},
7
- tools:[],repairs:0,clarifications:0,verificationRuns:[],cache:{buildHits:0,buildMisses:0,verifyHits:0,verifyMisses:0},
8
- timing:{queueMs:null,providerMs:0,previewMs:0,compilationMs:0,playbackMs:0,endToEndMs:null},rateLimitWaitMs:0,
9
- };
10
- }
11
-
12
- function usageTotals(receipt){
13
- const reported=receipt.providerCalls.map(call=>call.usage).filter(Boolean);
14
- for(const key of ['inputTokens','outputTokens','cachedInputTokens']){
15
- receipt.providerUsage[key]=reported.length===receipt.providerCalls.length&&reported.every(usage=>safeInteger(usage[key]))
16
- ?reported.reduce((sum,usage)=>sum+usage[key],0):null;
17
- }
18
- }
19
-
20
- export function applyReviewReceiptEvent(receipt,event,now=Date.now()){
21
- if(!receipt)return;
22
- const duration=safeInteger(event.durationMs)?event.durationMs:0;
23
- switch(event.type){
24
- case 'route':
25
- receipt.route=event.route;
26
- receipt.timing.queueMs??=Math.max(0,now-receipt.submittedAt);
27
- break;
28
- case 'provider-start':
29
- receipt.providerCalls.push({model:event.model,status:'attempted',durationMs:0,usage:null,
30
- ...(event.phase?{phase:event.phase}:{})});
31
- usageTotals(receipt);
32
- break;
33
- case 'provider-success':{
34
- const call=receipt.providerCalls.at(-1);
35
- if(call)Object.assign(call,{status:'completed',durationMs:duration,usage:event.usage??null});
36
- receipt.timing.providerMs+=duration;
37
- usageTotals(receipt);
38
- break;
39
- }
40
- case 'provider-error':{
41
- const call=receipt.providerCalls.at(-1);
42
- if(call)Object.assign(call,{status:'failed',durationMs:duration,error:event.code,usage:null});
43
- receipt.timing.providerMs+=duration;
44
- if(safeInteger(event.retryAfterSeconds))receipt.rateLimitWaitMs+=event.retryAfterSeconds*1000;
45
- usageTotals(receipt);
46
- break;
47
- }
48
- case 'tool':
49
- receipt.tools.push({name:event.name,status:event.status,responseBytes:event.responseBytes??null,durationMs:duration});
50
- if(event.name==='preview'&&event.status==='completed')receipt.timing.previewMs+=duration;
51
- break;
52
- case 'compilation':
53
- receipt.timing.compilationMs+=duration;
54
- break;
55
- case 'playback':
56
- receipt.timing.playbackMs+=duration;
57
- receipt.verificationRuns.push({kind:event.kind,outcomes:event.outcomes??[],status:event.status,durationMs:duration});
58
- break;
59
- case 'cache':
60
- receipt.cache??={buildHits:0,buildMisses:0,verifyHits:0,verifyMisses:0};
61
- if(event.stage==='build')receipt.cache[event.hit?'buildHits':'buildMisses']++;
62
- else receipt.cache[event.hit?'verifyHits':'verifyMisses']++;
63
- break;
64
- case 'repair':receipt.repairs++;break;
65
- case 'clarification':receipt.clarifications++;break;
66
- case 'final':{
67
- const candidateAlreadyTimed=receipt.candidateId!==null&&receipt.timing.endToEndMs!==null;
68
- receipt.disposition=event.disposition;
69
- receipt.candidateId=event.candidateId??receipt.candidateId;
70
- if(!candidateAlreadyTimed||!['promoted','discarded'].includes(event.disposition))
71
- receipt.timing.endToEndMs=Math.max(0,now-receipt.submittedAt);
72
- break;
73
- }
74
- }
75
- return receipt;
76
- }