ravensight-playtest 0.7.2 → 0.8.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.
@@ -1,10 +1,11 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { mkdir, open } from 'node:fs/promises';
2
+ import { mkdir, open, rm } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { Readable } from 'node:stream';
5
5
  import { CliError } from '../errors.js';
6
6
  import { ApiError } from '../api/errors.js';
7
7
  import { writeJson } from '../fsutil.js';
8
+ import { printable } from '../ui/index.js';
8
9
  import { openBuildArchive, inspectBuildArchive, buildLimits, limitsFromProfile } from './archivePreflight.js';
9
10
 
10
11
  const fail = message => { throw new CliError(message); };
@@ -42,6 +43,31 @@ export async function putArchive(archive, transfer, { fetchImpl = globalThis.fet
42
43
  } finally { stream.destroy(); }
43
44
  }
44
45
 
46
+ // Server text is one plain sentence; still print it as one bounded line.
47
+ const serverSentence = text => printable(String(text || '')).replace(/\s+/g, ' ').trim().slice(0, 300);
48
+
49
+ /**
50
+ * The profile to upload under: the one named, or the only one advertised. With
51
+ * several and none named, the error lists them so the person can pick one.
52
+ */
53
+ export function chooseProfile(profiles, requested) {
54
+ const advertised = profiles.filter(profile => typeof profile?.profileVersion === 'string' && profile.profileVersion);
55
+ const names = [...new Set(advertised.map(profile => profile.profileVersion))];
56
+ const list = names.map(name => {
57
+ const format = advertised.find(profile => profile.profileVersion === name).format;
58
+ return format ? `${name} (${format})` : name;
59
+ }).join(', ');
60
+ if (!names.length) fail('No build profile is advertised for this game right now. Nothing was charged.');
61
+ if (!requested) {
62
+ if (names.length === 1) return names[0];
63
+ fail(`Several build profiles are available. Choose one with --profile: ${list}. Nothing was charged.`);
64
+ }
65
+ if (advertised.filter(profile => profile.profileVersion === requested).length !== 1) {
66
+ fail(`"${requested}" is not an advertised build profile. Choose one with --profile: ${list}. Nothing was charged.`);
67
+ }
68
+ return requested;
69
+ }
70
+
45
71
  async function journalOnce(filename, value) {
46
72
  await mkdir(path.dirname(filename), { recursive: true, mode: 0o700 });
47
73
  let handle;
@@ -58,18 +84,21 @@ async function journalOnce(filename, value) {
58
84
  // the only wallet-mutating POST. No model or gameplay API is called here.
59
85
  export async function uploadHostedBuild({ filename, gameId, profileVersion, entrypoint, repoRoot, api,
60
86
  apiUrl, journalPath, dryRun = false, confirm, onPrepared = () => {}, onProgress = () => {}, fetchImpl, signal } = {}) {
61
- if (!gameId || !profileVersion || typeof confirm !== 'function') fail('Choose a game, ready profile and upload confirmation.');
87
+ if (!gameId || typeof confirm !== 'function') fail('Choose a game and upload confirmation.');
62
88
  onProgress({ phase: 'capabilities' });
63
89
  const caps = body(await api.request('GET', `${base(gameId)}/capabilities`, { idempotent: true }));
64
90
  const profiles = caps?.recorded?.profiles;
65
91
  if (!caps?.recorded?.available || !Array.isArray(profiles)) fail('Recorded game uploads are not available for this game.');
92
+ profileVersion = chooseProfile(profiles, profileVersion);
66
93
  const matching = profiles.filter(profile => profile.profileVersion === profileVersion);
67
- if (matching.length !== 1) fail('Choose exactly one currently advertised ready profile.');
68
94
  const profile = matching[0], limits = profile.capacity ? limitsFromProfile(profile) : buildLimits(caps.limits);
69
95
  const offer = profile.reservationOffer;
70
96
  if (!offer || offer.amountCents !== 49 || offer.currency !== 'USD' || offer.purpose !== 'validation_hold'
71
97
  || offer.refund !== 'after_cleanup' || !/^[a-f0-9]{64}$/.test(offer.version || '')) fail('The server did not provide the supported validation-hold offer.');
72
98
  if (caps.funding?.eligible === false) fail('The server reports insufficient prepaid funding. No reservation or top-up was requested.');
99
+ // Today's build checks are used up: the server would refuse the upload, so
100
+ // say why and when before any archive work or hold.
101
+ if (caps.validationLimit?.available === false) fail(`${serverSentence(caps.validationLimit.message) || 'Your studio has used today\'s build checks. The next one is available at 00:00 UTC.'} No reservation was requested.`);
73
102
  const archive = await openBuildArchive(filename, { signal });
74
103
  try {
75
104
  onProgress({ phase: 'preflight' });
@@ -108,6 +137,13 @@ export async function uploadHostedBuild({ filename, gameId, profileVersion, entr
108
137
  return { state: state.phase, buildId: state.buildId, journal, walletMutationRequested: true, validationHoldCents: offer.amountCents,
109
138
  multipartSupported: false, uploadResumeSupported: false, gameplayStarted: false };
110
139
  } catch (error) {
140
+ // A definite refusal before any hold (the server checks the daily build
141
+ // check limit inside the same transaction): nothing to reconcile, so
142
+ // the journal goes and the same upload can be tried after the reset.
143
+ if (error instanceof ApiError && error.code === 'hosted_validation_limit' && state.phase === 'reservation_unknown') {
144
+ await rm(journal, { force: true });
145
+ fail(serverSentence(error.message === error.code ? '' : error.message) || 'Your studio has used today\'s build checks. The next one is available at 00:00 UTC. Nothing was charged.');
146
+ }
111
147
  if (error instanceof ApiError && [401, 403].includes(error.status)) {
112
148
  error.message += ` Original upload journal: ${journal}; no replacement reservation was requested.`;
113
149
  throw error;
@@ -4,11 +4,18 @@ import path from 'node:path';
4
4
  import { CliError, ExitCode } from '../errors.js';
5
5
  import { ApiError } from '../api/errors.js';
6
6
  import { stableStringify } from '../fsutil.js';
7
+ import { printable } from '../ui/index.js';
8
+ import { chooseProfile } from './buildUpload.js';
9
+ import { displayName } from '../run/controllers.js';
7
10
 
8
11
  const MAX_QUOTE_BYTES = 1024 * 1024;
9
12
  const CONSENT_KEYS = ['quoteId', 'planHash', 'profileVersion', 'controllers', 'includeVideo', 'includeTranscript',
10
13
  'totalPriceCents', 'dueNowCents', 'priceVersion', 'policyVersion'];
11
14
  const PROVIDERS = ['anthropic', 'openai'];
15
+ // Customers choose Geri's model provider by role, never by vendor name. The
16
+ // server's wire values stay; ravensight.io/legal/subprocessors names both.
17
+ export const GERI_PROVIDERS = Object.freeze({ primary: 'anthropic', alternate: 'openai' });
18
+ const providerLabel = wire => ({ anthropic: 'primary model provider', openai: 'alternate model provider' }[wire] || 'model provider');
12
19
  const base = game => `/api/v1/games/${encodeURIComponent(game)}/playtest/hosted`;
13
20
  const digest = value => createHash('sha256').update(stableStringify(value)).digest('hex');
14
21
  const fail = message => { throw new CliError(message); };
@@ -57,7 +64,7 @@ export async function readHostedQuote(filename) {
57
64
  function requestFor({ buildId, profileVersion, persona, standardProvider, includeVideo = false, includeTranscript = false }, profile) {
58
65
  if (!id(buildId) || !id(profileVersion) || typeof persona !== 'string' || persona.length > 48
59
66
  || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(persona)) fail('Choose a validated build, ready profile and one persona.');
60
- if (standardProvider !== undefined && !PROVIDERS.includes(standardProvider)) fail('Choose anthropic or openai for Standard.');
67
+ if (standardProvider !== undefined && !PROVIDERS.includes(standardProvider)) fail('Choose primary or alternate for the Geri model provider.');
61
68
  if (typeof includeVideo !== 'boolean' || typeof includeTranscript !== 'boolean') fail('Choose explicit video and transcript options.');
62
69
  return { kind: 'recorded_graphical', buildId, personas: [persona], controllers: ['standard', 'jev'],
63
70
  driver: profile.driver, runLength: 'standard', profileVersion, includeVideo, includeTranscript,
@@ -69,13 +76,16 @@ async function available(api, gameId, profileVersion, standardProvider) {
69
76
  const caps = answer.body, recorded = caps?.recorded;
70
77
  if (!recorded?.available || recorded.intakeEnabled !== true || !Array.isArray(recorded.profiles)
71
78
  || !Array.isArray(recorded.controllers) || !['standard', 'jev'].every(value => recorded.controllers.includes(value))) {
72
- fail('This server does not currently advertise ready recorded Standard/Jev runs. Nothing was charged.');
79
+ fail('This server does not currently advertise ready hosted Geri and Freki runs. Nothing was charged.');
73
80
  }
74
- const matches = recorded.profiles.filter(value => value.profileVersion === profileVersion);
81
+ // The same rule as "build upload": the one named, or the only one
82
+ // advertised; with several and none named, the error lists them.
83
+ const chosen = chooseProfile(recorded.profiles, profileVersion);
84
+ const matches = recorded.profiles.filter(value => value.profileVersion === chosen);
75
85
  if (matches.length !== 1 || !['playwright_web', 'godot_driver'].includes(matches[0].driver)) fail('Choose exactly one currently advertised ready hosted profile. Nothing was charged.');
76
86
  if (standardProvider !== undefined && (!PROVIDERS.includes(standardProvider)
77
87
  || !Array.isArray(recorded.standardProviders) || !recorded.standardProviders.includes(standardProvider))) {
78
- fail(`This server does not advertise ready Standard ${standardProvider}. No provider fallback or charge was requested.`);
88
+ fail(`This server does not advertise Geri on the ${providerLabel(standardProvider)} as ready. No provider fallback or charge was requested.`);
79
89
  }
80
90
  return { profile: matches[0], funding: caps.funding };
81
91
  }
@@ -100,11 +110,11 @@ export function hostedConsent(quote, request, now = Date.now()) {
100
110
  || sum(quote.localBreakdown, row => BigInt(row.count) * BigInt(row.unitCents)) !== quote.localPriceCents
101
111
  || !Array.isArray(quote.computeBreakdown) || quote.computeBreakdown.length !== 2
102
112
  || !quote.computeBreakdown.every((row, index) => row.controller === request.controllers[index] && row.profileVersion === request.profileVersion && cents(row.priceCents))
103
- || sum(quote.computeBreakdown, row => BigInt(row.priceCents)) !== quote.computePriceCents) fail('The server did not quote every Standard/Jev price. Nothing was charged.');
113
+ || sum(quote.computeBreakdown, row => BigInt(row.priceCents)) !== quote.computePriceCents) fail('The server did not quote every Geri and Freki price. Nothing was charged.');
104
114
  const explicit = request.standardProvider !== undefined;
105
115
  if (explicit ? quote.standardProvider !== request.standardProvider || !hex(quote.standardProviderPolicyHash)
106
116
  : Object.hasOwn(quote, 'standardProvider') || Object.hasOwn(quote, 'standardProviderPolicyHash')) {
107
- fail('The quoted Standard provider policy does not match the requested choice. Nothing was charged.');
117
+ fail('The quoted Geri provider policy does not match the requested choice. Nothing was charged.');
108
118
  }
109
119
  return Object.fromEntries([...CONSENT_KEYS, ...(explicit ? ['standardProvider', 'standardProviderPolicyHash'] : [])].map(key => [key, quote[key]]));
110
120
  }
@@ -122,7 +132,7 @@ export async function quoteHostedRun({ api, apiUrl, gameId, output, now = Date.n
122
132
  try { await access(output); fail('That saved quote already exists. Choose a new output path; the original was preserved.'); }
123
133
  catch (error) { if (error.code !== 'ENOENT') throw error; }
124
134
  const { profile } = await available(api, gameId, options.profileVersion, options.standardProvider);
125
- const request = requestFor(options, profile);
135
+ const request = requestFor({ ...options, profileVersion: profile.profileVersion }, profile);
126
136
  const response = await api.request('POST', `${base(gameId)}/quotes`, { body: request, idempotent: false });
127
137
  if (response.status !== 200) fail('The server did not return a hosted quote. No admission was requested.');
128
138
  const quote = response.body, consent = hostedConsent(quote, request, now());
@@ -135,10 +145,10 @@ export async function quoteHostedRun({ api, apiUrl, gameId, output, now = Date.n
135
145
  export function hostedQuoteLines(offer) {
136
146
  const { quote: q, request: r } = offer;
137
147
  return [`Game ${offer.gameId}; build ${r.buildId}; persona ${r.personas[0]}; profile ${r.profileVersion}.`,
138
- `Two separate playthroughs: Standard (${r.standardProvider || 'server default Anthropic'}) then Jev.`,
139
- ...(r.standardProvider ? [`Standard provider policy: ${q.standardProviderPolicyHash}.`] : []),
148
+ `Two separate playthroughs: Geri (${r.standardProvider ? providerLabel(r.standardProvider) : 'server default model provider'}) then Freki.`,
149
+ ...(r.standardProvider ? [`Geri provider policy: ${q.standardProviderPolicyHash}.`] : []),
140
150
  ...q.localBreakdown.map(row => `${row.count} ${row.unit} at ${money(row.unitCents)} each: ${money(row.count * row.unitCents)}.`),
141
- ...q.computeBreakdown.map(row => `${row.controller} hosted compute: ${money(row.priceCents)}.`),
151
+ ...q.computeBreakdown.map(row => `${displayName(row.controller)} hosted compute: ${money(row.priceCents)}.`),
142
152
  `Total ${money(q.totalPriceCents)}; already reserved ${money(q.alreadyReservedCents)}; due now ${money(q.dueNowCents)} from prepaid funds. No top-up is performed.`,
143
153
  `Video: ${r.includeVideo ? 'included' : 'off'}. Hosted runs save no transcript.`,
144
154
  `Customer failure: ${q.customerFailure}; cancellation after start: ${q.cancelAfterStart}. Price ${q.priceVersion}; refund policy ${q.policyVersion}.`,
@@ -161,7 +171,7 @@ export async function runHostedQuote({ filename, api, apiUrl, repoRoot, confirm,
161
171
  return admitHostedOffer({ offer, api, apiUrl, repoRoot, now });
162
172
  }
163
173
 
164
- export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Standard then Jev runs and the evidence options shown?`;
174
+ export const confirmQuestion = offer => `Pay ${money(offer.quote.dueNowCents)} now (${money(offer.quote.totalPriceCents)} total) for the quoted Geri then Freki runs and the evidence options shown?`;
165
175
 
166
176
  // Refusals the server makes before any charge: the quote or consent was not
167
177
  // accepted, funding or capacity said no, or the quote is gone. The original
@@ -259,6 +269,8 @@ export async function prepareHostedRun({ api, apiUrl, gameId, buildId, persona,
259
269
  let build;
260
270
  if (buildId) {
261
271
  build = eligible.find(row => row.buildId === buildId);
272
+ const refused = (Array.isArray(listed.body?.builds) ? listed.body.builds : []).find(row => row?.buildId === buildId && row.rejection?.message);
273
+ if (!build && refused) fail(`Build ${buildId} was not accepted: ${printable(String(refused.rejection.message)).replace(/\s+/g, ' ').slice(0, 300)} Nothing was charged.`);
262
274
  if (!build) fail(`Build ${buildId} is not ready for a hosted run: it has to pass its static archive check on a ready profile and not have expired. Nothing was charged.`);
263
275
  } else {
264
276
  build = eligible[0];
@@ -285,7 +297,7 @@ export function fundingShortfall(quote, funding) {
285
297
  export function hostedConsentLines(offer) {
286
298
  const q = offer.quote;
287
299
  return [
288
- 'One persona plays the same build twice, once with Standard and once with Jev, on isolated hosted machines. These are AI playtests, not human feedback.',
300
+ 'One persona plays the same build twice, once with Geri and once with Freki, on isolated hosted machines. These are AI playtests, not human feedback.',
289
301
  'The game runs without network access. Shared capacity, daily limits and the quoted runtime bounds still apply; funding does not guarantee an immediate start.',
290
302
  `If the build fails, hosted compute is ${q.customerFailure === 'refund' ? 'refunded' : 'kept'}. Canceling after a confirmed start ${q.cancelAfterStart === 'refund' ? 'refunds' : 'keeps'} that run's compute charge. Unstarted work is refunded during settlement.`,
291
303
  'The build\'s validation hold is separate and is returned after safe cleanup. It does not reduce this price.',
@@ -5,6 +5,8 @@
5
5
  // words. Change both together. The admission owns the provider and payment
6
6
  // lifecycle; the job and its runs own gameplay, report capture and aggregation.
7
7
 
8
+ import { DISPLAY_NAMES } from '../run/controllers.js';
9
+
8
10
  const FAILED = new Set(['failed', 'budget_exceeded', 'interrupted', 'stalled', 'refused']);
9
11
  const CANCELED = new Set(['canceled']);
10
12
  const boundedReason = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 240);
@@ -70,10 +72,9 @@ export function hostedPlaytestStatus(admission, job = null, runs = [], now = Dat
70
72
  };
71
73
  }
72
74
 
73
- const MODE_NAMES = Object.freeze({ standard: 'Standard', jev: 'Jev' });
74
75
 
75
76
  /**
76
- * One row per hosted mode (Standard, Jev), from the job's persona runs. A mode
77
+ * One row per hosted mode (Geri, Freki), from the job's persona runs. A mode
77
78
  * whose run the server has not created yet reads as not started.
78
79
  * @param {Array<object>} runs
79
80
  * @param {Array<string>} [controllers]
@@ -85,7 +86,7 @@ export function modeOutcomes(runs = [], controllers = ['standard', 'jev']) {
85
86
  const report = run?.report || null;
86
87
  return {
87
88
  mode: controller,
88
- name: MODE_NAMES[controller] || controller,
89
+ name: DISPLAY_NAMES[controller] || 'Playtester',
89
90
  runId: run?.run_id || null,
90
91
  state: run?.state || 'not_started',
91
92
  reason: run?.state_reason ? boundedReason(run.state_reason) : null,
@@ -97,7 +98,7 @@ export function modeOutcomes(runs = [], controllers = ['standard', 'jev']) {
97
98
  });
98
99
  }
99
100
 
100
- /** "Standard: completed, 4 findings, video saved." */
101
+ /** "Geri: completed, 4 findings, video saved." */
101
102
  export function modeLine(row) {
102
103
  const parts = [row.state.replace(/_/g, ' ')];
103
104
  if (row.findings !== null) parts.push(`${row.findings} finding${row.findings === 1 ? '' : 's'}`);
@@ -1,4 +1,6 @@
1
1
  // Deterministic comparison of the reports already paid for. No new model call.
2
+ // The JSON keeps the wire ids; the markdown a person reads names the playtesters.
3
+ import { displayName } from './controllers.js';
2
4
  export function compareControllers(runs) {
3
5
  const planned = runs.filter(run => run.controller);
4
6
  const controllers = [...new Set(planned.map(run => run.controller))];
@@ -19,14 +21,14 @@ export function compareControllers(runs) {
19
21
  const findings = [...groups.values()].map(group => ({ ...group,
20
22
  match: new Set(group.occurrences.map(row => row.controller)).size > 1 ? 'reported_by_multiple_controllers' : 'reported_by_one_controller' }));
21
23
  return { schema_version: '1.0', controllers, status: rows.some(row => row.partial) ? 'inconclusive' : 'reports_complete',
22
- limits: ['Controllers use separate game sessions. Server saves and random state are not proven identical.', 'Matches use the same persona, category and exact normalized title. Agreement does not verify a bug; absence does not prove a pass.'], runs: rows, findings };
24
+ limits: ['Playtesters use separate game sessions. Server saves and random state are not proven identical.', 'Matches use the same persona, category and exact normalized title. Agreement does not verify a bug; absence does not prove a pass.'], runs: rows, findings };
23
25
  }
24
26
  export function comparisonMarkdown(comparison) {
25
27
  if (!comparison) return '';
26
28
  const safe = value => String(value ?? '').replace(/[\r\n|]/g, ' ');
27
- return '\n\n## Controller comparison\n\n' + comparison.limits.join(' ') + '\n\n' +
29
+ return '\n\n## Playtester comparison\n\n' + comparison.limits.join(' ') + '\n\n' +
28
30
  (comparison.status === 'inconclusive' ? 'At least one playthrough is missing or partial. This comparison is inconclusive.\n\n' : '') +
29
- '| Controller | Persona | Run | Report |\n| --- | --- | --- | --- |\n' +
30
- comparison.runs.map(row => `| ${safe(row.controller)} | ${safe(row.persona)} | ${safe(row.run_id)} | ${row.partial ? 'Incomplete' : 'Complete'} |`).join('\n') +
31
- '\n\n' + comparison.findings.map(group => `- ${safe(group.title)}: ${[...new Set(group.occurrences.map(row => row.controller))].join(', ')} (${group.occurrences.map(row => safe(row.run_id)).join(', ')}).`).join('\n');
31
+ '| Playtester | Persona | Run | Report |\n| --- | --- | --- | --- |\n' +
32
+ comparison.runs.map(row => `| ${safe(displayName(row.controller))} | ${safe(row.persona)} | ${safe(row.run_id)} | ${row.partial ? 'Incomplete' : 'Complete'} |`).join('\n') +
33
+ '\n\n' + comparison.findings.map(group => `- ${safe(group.title)}: ${[...new Set(group.occurrences.map(row => displayName(row.controller)))].join(', ')} (${group.occurrences.map(row => safe(row.run_id)).join(', ')}).`).join('\n');
32
34
  }
@@ -165,17 +165,136 @@ export function pruneObservations(messages, keep = KEEP_OBSERVATIONS) {
165
165
  return out;
166
166
  }
167
167
 
168
+ /** What a tool_result with nothing in it is sent as. */
169
+ export const EMPTY_TOOL_RESULT_TEXT = '(no output)';
170
+
171
+ /** The tool_result for a tool_use the runner never answered. */
172
+ export const MISSING_TOOL_RESULT_TEXT = 'Not run: the runner did not play this call.';
173
+
174
+ /**
175
+ * Make every tool_result in the conversation one the Messages API accepts.
176
+ *
177
+ * The rules the API enforces, and what each repair is:
178
+ *
179
+ * - **An `is_error` result is text only.** A result flagged `is_error` that
180
+ * also carries an image block is refused with a 400. That is the 0.7.2
181
+ * failure: a refused off-site `navigate` on a canvas build came back as
182
+ * "That did not work: ..." plus the screenshot, flagged as an error, and
183
+ * every persona of the job died on its next turn. The screenshot is the
184
+ * persona's only view of a canvas game, so the image stays and the flag
185
+ * goes: the text already says the action did not work.
186
+ * - **Content is never empty.** An empty string, an empty array or a text
187
+ * block with no text becomes {@link EMPTY_TOOL_RESULT_TEXT}; a non-string,
188
+ * non-array content becomes its string form.
189
+ * - **Exactly one result per tool_use, in the very next user message.** A
190
+ * missing result is added ({@link MISSING_TOOL_RESULT_TEXT}); a second
191
+ * result for one id, and a result whose id the assistant turn before it
192
+ * never used, are dropped. A user message left with nothing gets the empty
193
+ * text, because an empty message is refused too.
194
+ *
195
+ * A new array; the input is not mutated.
196
+ *
197
+ * @param {Array} messages
198
+ * @returns {Array}
199
+ */
200
+ export function validToolResults(messages) {
201
+ const out = messages.map(message => message);
202
+ for (let i = 0; i < out.length; i += 1) {
203
+ const message = out[i];
204
+ if (!message || message.role !== 'user' || !Array.isArray(message.content)) continue;
205
+ const previous = i > 0 ? out[i - 1] : null;
206
+ const expected = previous && previous.role === 'assistant' && Array.isArray(previous.content)
207
+ ? previous.content.filter(block => block && block.type === 'tool_use').map(block => block.id)
208
+ : [];
209
+ const seen = new Set();
210
+ const content = [];
211
+ for (const block of message.content) {
212
+ if (!block || block.type !== 'tool_result') {
213
+ content.push(block);
214
+ continue;
215
+ }
216
+ if (!expected.includes(block.tool_use_id) || seen.has(block.tool_use_id)) continue;
217
+ seen.add(block.tool_use_id);
218
+ content.push(validToolResult(block));
219
+ }
220
+ const missing = expected.filter(id => !seen.has(id))
221
+ .map(id => ({ type: 'tool_result', tool_use_id: id, content: [{ type: 'text', text: MISSING_TOOL_RESULT_TEXT }] }));
222
+ // Results go first in the message: the API wants them before any text.
223
+ const results = [...content.filter(block => block && block.type === 'tool_result'), ...missing];
224
+ const rest = content.filter(block => !(block && block.type === 'tool_result'));
225
+ const next = [...results, ...rest];
226
+ out[i] = { ...message, content: next.length > 0 ? next : [{ type: 'text', text: EMPTY_TOOL_RESULT_TEXT }] };
227
+ }
228
+ return out;
229
+ }
230
+
231
+ /**
232
+ * One tool_result made valid. See {@link validToolResults}.
233
+ *
234
+ * @param {Object} block
235
+ * @returns {Object}
236
+ */
237
+ export function validToolResult(block) {
238
+ let content = block.content;
239
+ if (typeof content === 'string') {
240
+ content = content.trim() ? content : EMPTY_TOOL_RESULT_TEXT;
241
+ } else if (Array.isArray(content)) {
242
+ content = content
243
+ .filter(child => child && (child.type !== 'text' || (typeof child.text === 'string' && child.text.trim())))
244
+ .map(child => child);
245
+ if (content.length === 0) content = [{ type: 'text', text: EMPTY_TOOL_RESULT_TEXT }];
246
+ } else {
247
+ content = content === undefined || content === null || String(content).trim() === '' ? EMPTY_TOOL_RESULT_TEXT : String(content);
248
+ }
249
+ const result = { ...block, content };
250
+ if (result.is_error && Array.isArray(content) && content.some(child => child.type !== 'text')) delete result.is_error;
251
+ return result;
252
+ }
253
+
254
+ /**
255
+ * Every tool_result in the newest user message rewritten as plain text with
256
+ * no `is_error` flag and no image: the one repair the persona loop makes
257
+ * when the provider refuses a turn it cannot otherwise explain, before it
258
+ * gives up on the conversation. The text keeps what the persona was told.
259
+ *
260
+ * @param {Array} messages
261
+ * @returns {Array} a new array; the input is not mutated
262
+ */
263
+ export function repairLastTurn(messages) {
264
+ const out = validToolResults(messages);
265
+ for (let i = out.length - 1; i >= 0; i -= 1) {
266
+ const message = out[i];
267
+ if (!message || message.role !== 'user' || !Array.isArray(message.content)) continue;
268
+ out[i] = {
269
+ ...message,
270
+ content: message.content.map(block => {
271
+ if (!block || block.type !== 'tool_result') return block;
272
+ const texts = Array.isArray(block.content)
273
+ ? block.content.filter(child => child.type === 'text').map(child => child.text)
274
+ : [String(block.content)];
275
+ const text = texts.join('\n').trim() || EMPTY_TOOL_RESULT_TEXT;
276
+ const { is_error: _flag, ...rest } = block;
277
+ return { ...rest, content: [{ type: 'text', text }] };
278
+ })
279
+ };
280
+ break;
281
+ }
282
+ return out;
283
+ }
284
+
168
285
  /**
169
286
  * Both ceilings, in the order that matters: drop stale observations first
170
287
  * (which removes their images too), then enforce the image budget on what
171
- * is left.
288
+ * is left, then make every tool_result one the API accepts (which has to
289
+ * come last: whether an `is_error` result still carries an image is only
290
+ * known once the image budget is applied).
172
291
  *
173
292
  * @param {Array} messages
174
293
  * @param {{maxImages?: number, keepObservations?: number}} [opts]
175
294
  * @returns {Array}
176
295
  */
177
296
  export function prepareMessages(messages, { maxImages = MAX_IMAGES_IN_CONTEXT, keepObservations = KEEP_OBSERVATIONS } = {}) {
178
- return pruneImages(pruneObservations(messages, keepObservations), maxImages);
297
+ return validToolResults(pruneImages(pruneObservations(messages, keepObservations), maxImages));
179
298
  }
180
299
 
181
300
  /**
@@ -189,4 +308,4 @@ export function shrinkImages(current) {
189
308
  return Math.max(0, Math.floor(current / 2));
190
309
  }
191
310
 
192
- export default { prepareMessages, pruneImages, pruneObservations, countImages, shrinkImages, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS };
311
+ export default { prepareMessages, validToolResults, validToolResult, repairLastTurn, pruneImages, pruneObservations, countImages, shrinkImages, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS };
@@ -1,9 +1,21 @@
1
1
  export const CONTROLLERS = ['standard', 'jev', 'rune'];
2
+ // The playtesters by name. `geri` and `freki` are the documented flag values;
3
+ // the server's wire ids `standard` and `jev` stay accepted as hidden aliases
4
+ // so older scripts and saved jobs keep working. Every value is mapped to its
5
+ // wire id before it reaches the server or a journal.
6
+ export const DISPLAY_NAMES = Object.freeze({ standard: 'Geri', jev: 'Freki', rune: 'Experimental playtester' });
7
+ const ALIASES = Object.freeze({ geri: 'standard', freki: 'jev', standard: 'standard', jev: 'jev', rune: 'rune' });
8
+ /** The wire id for a flag value, or the value unchanged when it names nothing known. */
9
+ export function wireId(value) {
10
+ const key = String(value).trim().toLowerCase();
11
+ return Object.hasOwn(ALIASES, key) ? ALIASES[key] : String(value);
12
+ }
13
+ export function displayName(id) { return DISPLAY_NAMES[id] || 'Playtester'; }
2
14
  export function controllerPlan(options = {}) {
3
15
  if (options.compareWith && options.controller) throw new Error('Use --controller for one playthrough or --compare-with for a comparison.');
4
16
  if (!options.compareWith && !options.controller) return null;
5
- const plan = options.compareWith ? ['standard', ...String(options.compareWith).split(',')] : [options.controller];
6
- if (plan.length > 3 || plan.some(x => !CONTROLLERS.includes(x)) || new Set(plan).size !== plan.length) throw new Error('Choose standard, jev or rune once each. --compare-with jev runs standard and Jev separately.');
17
+ const plan = (options.compareWith ? ['standard', ...String(options.compareWith).split(',')] : [options.controller]).map(wireId);
18
+ if (plan.length > 3 || plan.some(x => !CONTROLLERS.includes(x)) || new Set(plan).size !== plan.length) throw new Error('Choose geri or freki once each. --compare-with freki plays Geri and Freki separately.');
7
19
  return plan;
8
20
  }
9
21
  export function quoteMatchesPlan(quote, plan, personas) {