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.
- package/README.md +53 -31
- package/docs/ADAPTERS.md +1 -1
- package/package.json +3 -3
- package/src/cli.js +22 -9
- package/src/commands/brief.js +1 -1
- package/src/commands/build.js +23 -1
- package/src/commands/hosted.js +5 -3
- package/src/commands/run.js +42 -10
- package/src/hosted/archivePreflight.js +47 -2
- package/src/hosted/buildStatus.js +37 -0
- package/src/hosted/buildUpload.js +39 -3
- package/src/hosted/recordedRun.js +24 -12
- package/src/hosted/status.js +5 -4
- package/src/run/comparison.js +7 -5
- package/src/run/context.js +122 -3
- package/src/run/controllers.js +14 -2
- package/src/run/drivers/web.js +371 -136
- package/src/run/model.js +18 -1
- package/src/run/openPr.js +8 -1
- package/src/run/personaLoop.js +167 -21
- package/src/run/resume.js +11 -1
- package/src/run/serveBuild.js +137 -0
- package/src/run/tools.js +31 -3
- package/src/ui/index.js +21 -6
package/src/run/personaLoop.js
CHANGED
|
@@ -2,7 +2,7 @@ import { rewriteMarkdown } from './dropped.js';
|
|
|
2
2
|
import { selectAction, JEV_CONTROLLER_PROMPT } from './actionSelector.js';
|
|
3
3
|
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { prepareMessages, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS, shrinkImages } from './context.js';
|
|
5
|
+
import { prepareMessages, repairLastTurn, MAX_IMAGES_IN_CONTEXT, KEEP_OBSERVATIONS, shrinkImages } from './context.js';
|
|
6
6
|
import { withRollingCacheBreakpoint } from './fixLoop.js';
|
|
7
7
|
import { callStepWithRetry, ProxyError, STEPS } from './model.js';
|
|
8
8
|
import { RUN_FILES } from './paths.js';
|
|
@@ -76,6 +76,25 @@ const ABOVE_MINOR = Object.freeze(['blocker', 'major']);
|
|
|
76
76
|
/** What a capped finding's description gains, so the reader knows why. */
|
|
77
77
|
export const NETWORK_CAP_NOTE = 'Severity capped at minor by the runner: the only evidence is automatic network notes, and a failed request is a finding above minor only when the persona saw the game break because of it.';
|
|
78
78
|
|
|
79
|
+
/** How each way of leaving the build reads in a note. */
|
|
80
|
+
const OFF_SITE_VIA = Object.freeze({
|
|
81
|
+
navigation: 'a link, form or script on the page',
|
|
82
|
+
'new window': 'a new window',
|
|
83
|
+
redirect: 'a redirect',
|
|
84
|
+
navigate: 'the persona\'s navigate'
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The network note for one attempt to leave the build.
|
|
89
|
+
*
|
|
90
|
+
* @param {{host?: string, via?: string}} attempt
|
|
91
|
+
* @returns {string}
|
|
92
|
+
*/
|
|
93
|
+
export function offSiteNoteText(attempt) {
|
|
94
|
+
const via = OFF_SITE_VIA[attempt && attempt.via] || 'the page';
|
|
95
|
+
return `off-site: ${via} tried to leave the build for ${(attempt && attempt.host) || 'another site'}; the runner kept the page on the build.`;
|
|
96
|
+
}
|
|
97
|
+
|
|
79
98
|
/** A persona note kind as a report finding category. */
|
|
80
99
|
// `waiting` has no category on purpose: a "waiting for X to finish" note is
|
|
81
100
|
// context, and nothing turns it into a finding.
|
|
@@ -331,6 +350,18 @@ export async function runPersona(args) {
|
|
|
331
350
|
// worth keeping, by the same rule as a 402 during play.
|
|
332
351
|
const play = { actionsTaken: outcome.actionsTaken, quitReason: 'cost_cap', quitDetail: String(error.message || '') };
|
|
333
352
|
await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt, endedAt: new Date().toISOString(), log, preservedMarkdown: error.completedReportMarkdown });
|
|
353
|
+
} else if (error && error.reportIncomplete && !args.signal?.aborted) {
|
|
354
|
+
// The run played; only the report step could not finish. Its notes are
|
|
355
|
+
// the report, by the same rule as a 402 in the report step. Under budget
|
|
356
|
+
// pressure that is a budget stop; otherwise the run is marked failed, so
|
|
357
|
+
// the unit is refunded, and the report still carries what it saw.
|
|
358
|
+
outcome.state = error.budgetPressure ? 'budget_exceeded' : 'failed';
|
|
359
|
+
outcome.quitReason = error.budgetPressure ? 'cost_cap' : 'error';
|
|
360
|
+
const actionsTaken = Math.max(outcome.actionsTaken || 0, actionLogFrom(actionRecords).length);
|
|
361
|
+
const play = { actionsTaken, quitReason: outcome.quitReason, quitDetail: safeErrorDetail(error, localBrief) };
|
|
362
|
+
await writeSomeReport({ outcome, runDirectory, persona, driverName, target, notes, screenshots, actionRecords, play, skill, ledger, runId, jobId, startedAt,
|
|
363
|
+
endedAt: new Date().toISOString(), log, quitReason: outcome.quitReason, reason: REPORT_INCOMPLETE_REASON, bareReason: REPORT_INCOMPLETE_REASON,
|
|
364
|
+
preservedMarkdown: error.completedReportMarkdown });
|
|
334
365
|
} else if (error instanceof ProxyError && error.isClosed) {
|
|
335
366
|
outcome.state = 'canceled';
|
|
336
367
|
outcome.quitReason = 'error';
|
|
@@ -530,23 +561,39 @@ async function playLoop({
|
|
|
530
561
|
turns += 1;
|
|
531
562
|
let answer;
|
|
532
563
|
const askedAt = Date.now();
|
|
564
|
+
const askAct = () => callWithImageRetry({
|
|
565
|
+
client,
|
|
566
|
+
jobId,
|
|
567
|
+
runId,
|
|
568
|
+
step: STEPS.personaAct,
|
|
569
|
+
system,
|
|
570
|
+
messages,
|
|
571
|
+
tools: playTools,
|
|
572
|
+
maxTokens: ACT_MAX_TOKENS,
|
|
573
|
+
escalate: shouldEscalate(persona),
|
|
574
|
+
imageBudget,
|
|
575
|
+
keepObservations,
|
|
576
|
+
onImageBudget: next => {
|
|
577
|
+
imageBudget = next;
|
|
578
|
+
}
|
|
579
|
+
});
|
|
533
580
|
try {
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
}
|
|
581
|
+
try {
|
|
582
|
+
answer = await askAct();
|
|
583
|
+
} catch (error) {
|
|
584
|
+
// The provider refused the body. Every tool_result is already made
|
|
585
|
+
// valid before it is sent (./context.js), so this is a shape nobody
|
|
586
|
+
// has seen yet: the newest turn is rewritten as plain text and asked
|
|
587
|
+
// once more. A second refusal ends play, and the run still reports
|
|
588
|
+
// from its step log (runPersona's error path), because a run that
|
|
589
|
+
// played never comes back empty.
|
|
590
|
+
if (!(error instanceof ProxyError) || error.code !== 'upstream_rejected') throw error;
|
|
591
|
+
log(`the model provider rejected this turn (${error.message}); retrying once with the last turn as plain text.`);
|
|
592
|
+
transcript.write({ kind: 'provider_rejected', retry: true, code: error.code, provider_type: error.figures.provider_type || null, provider_message: error.figures.provider_message || null });
|
|
593
|
+
const repaired = repairLastTurn(messages);
|
|
594
|
+
messages.splice(0, messages.length, ...repaired);
|
|
595
|
+
answer = await askAct();
|
|
596
|
+
}
|
|
550
597
|
} catch (error) {
|
|
551
598
|
if (error instanceof ProxyError && error.isBudget) {
|
|
552
599
|
budgetExceeded = true;
|
|
@@ -663,6 +710,7 @@ async function playLoop({
|
|
|
663
710
|
ok: !executed.error,
|
|
664
711
|
error: executed.error,
|
|
665
712
|
changed: executed.changed,
|
|
713
|
+
...(executed.refused ? { refused: executed.refused } : {}),
|
|
666
714
|
actions
|
|
667
715
|
};
|
|
668
716
|
transcript.write(actionLine);
|
|
@@ -691,6 +739,13 @@ async function playLoop({
|
|
|
691
739
|
// declared wedged for doing the right thing.
|
|
692
740
|
if (ACTION_TOOLS.includes(toolUse.name)) unchanged = executed.changed ? 0 : unchanged + 1;
|
|
693
741
|
}
|
|
742
|
+
if (executed.refused) {
|
|
743
|
+
// A refused off-site navigation is a step that changed nothing: it
|
|
744
|
+
// counts toward the stuck limit like any other, and play goes on.
|
|
745
|
+
unchanged += 1;
|
|
746
|
+
recentActions.push(`${toolUse.name}: refused, off-site`);
|
|
747
|
+
if (recentActions.length > 10) recentActions.shift();
|
|
748
|
+
}
|
|
694
749
|
onProgress({ phase: 'playing', persona: persona.slug, actions, maxActions, tool: toolUse.name });
|
|
695
750
|
}
|
|
696
751
|
|
|
@@ -732,6 +787,24 @@ async function playLoop({
|
|
|
732
787
|
asides.push(`The game logged ${consoleErrors.length} error(s): ${consoleErrors.map(entry => entry.text).join(' | ').slice(0, 800)}${shot ? ` A screenshot is saved at ${shot.relativePath}.` : ''}`);
|
|
733
788
|
}
|
|
734
789
|
|
|
790
|
+
// Every attempt to leave the build this turn (a clicked link, a form, a
|
|
791
|
+
// new window, a script or a server redirect, or a refused navigate) is a
|
|
792
|
+
// network note: the runner kept the page on the build, and the report
|
|
793
|
+
// step reads it as context. A persona told "Refused" already knows; a
|
|
794
|
+
// timer redirect between actions is only ever seen here.
|
|
795
|
+
const leaving = typeof driver.offSiteAttempts === 'function' ? driver.offSiteAttempts() : [];
|
|
796
|
+
for (const attempt of leaving) {
|
|
797
|
+
const note = {
|
|
798
|
+
kind: 'network',
|
|
799
|
+
text: offSiteNoteText(attempt),
|
|
800
|
+
automatic: true,
|
|
801
|
+
off_site: true,
|
|
802
|
+
url: String(attempt.url || attempt.host || '').slice(0, 200)
|
|
803
|
+
};
|
|
804
|
+
noted(note);
|
|
805
|
+
transcript.write({ kind: 'note', note: scrubSecrets(note, secrets) });
|
|
806
|
+
}
|
|
807
|
+
|
|
735
808
|
const wedged = unchanged >= STUCK_LIMIT;
|
|
736
809
|
if (!wedged && unchanged > 0 && unchanged % STUCK_HINT_AFTER === 0) {
|
|
737
810
|
transcript.write({ kind: 'stuck', unchanged, fatal: false });
|
|
@@ -845,6 +918,11 @@ async function reportPhase({
|
|
|
845
918
|
let maxTokens = REPORT_MAX_TOKENS;
|
|
846
919
|
let shrunk = false;
|
|
847
920
|
let lastCandidate = null;
|
|
921
|
+
// The largest output ceiling a turn has already been cut off at. A retry
|
|
922
|
+
// below it is built to fail (pt_run_ed0941d6a976a93efa46: cut off at 4096,
|
|
923
|
+
// then asked again at 2326 and cut off again), so no retry goes below it.
|
|
924
|
+
let cutOffAt = 0;
|
|
925
|
+
let cutOffs = 0;
|
|
848
926
|
for (let attempt = 1; ; attempt += 1) {
|
|
849
927
|
let answer;
|
|
850
928
|
const askedAt = Date.now();
|
|
@@ -863,8 +941,14 @@ async function reportPhase({
|
|
|
863
941
|
} catch (error) {
|
|
864
942
|
if (!(error instanceof ProxyError && error.isBudget)) throw error;
|
|
865
943
|
const bodyChars = JSON.stringify({ messages, system, tools: REPORT_TOOLS, max_tokens: maxTokens, stream: true }).length;
|
|
866
|
-
const
|
|
867
|
-
|
|
944
|
+
const fits = shrunk ? null : reportTokensThatFit(error, maxTokens, bodyChars);
|
|
945
|
+
// After a cut-off, only a ceiling at least as large as the one that was
|
|
946
|
+
// cut off is worth paying for. Anything less goes to the step-log report.
|
|
947
|
+
const smaller = fits && fits >= cutOffAt ? fits : null;
|
|
948
|
+
if (fits && !smaller && !lastCandidate) {
|
|
949
|
+
log(`the report was cut off at ${cutOffAt} output tokens and the remaining model budget only fits ${fits}, which would be cut off too, so the report is written from the notes instead.`);
|
|
950
|
+
transcript.write({ kind: 'report_cut_off_no_room', cut_off_at: cutOffAt, fits });
|
|
951
|
+
} else if (!smaller && !shrunk && !lastCandidate) {
|
|
868
952
|
log(hasBudgetFigures(error)
|
|
869
953
|
? `even the smallest report (${REPORT_MIN_TOKENS} output tokens) does not fit the remaining model budget once the request itself is paid for, so the report is written from the notes instead.`
|
|
870
954
|
: 'the report turn was refused for budget with no budget figures in the refusal, so there is nothing to size a retry from; the report is written from the notes instead.');
|
|
@@ -874,6 +958,9 @@ async function reportPhase({
|
|
|
874
958
|
transcript.write({ kind: 'report_budget_retry', attempt, max_tokens: smaller, figures: error.figures || {} });
|
|
875
959
|
log(`the report turn did not fit the remaining model budget; asking again with an output ceiling of ${smaller} tokens.`);
|
|
876
960
|
maxTokens = smaller;
|
|
961
|
+
// A smaller ceiling needs a shorter report: say so, or the model
|
|
962
|
+
// writes the same length and is cut off.
|
|
963
|
+
askShorter(messages, smaller);
|
|
877
964
|
continue;
|
|
878
965
|
}
|
|
879
966
|
// A report already written on an earlier turn is the report, with its
|
|
@@ -988,6 +1075,26 @@ async function reportPhase({
|
|
|
988
1075
|
...missingSections.map(section => `report.md has no "${section}" section`)
|
|
989
1076
|
];
|
|
990
1077
|
|
|
1078
|
+
const cutOff = answer.stopReason === 'max_tokens';
|
|
1079
|
+
if (cutOff) {
|
|
1080
|
+
cutOffs += 1;
|
|
1081
|
+
cutOffAt = Math.max(cutOffAt, maxTokens);
|
|
1082
|
+
transcript.write({ kind: 'report_cut_off', attempt, max_tokens: maxTokens, cut_offs: cutOffs });
|
|
1083
|
+
// With its repair spent, a report.json already written beats another
|
|
1084
|
+
// metered turn; the server has the final word on it, as after a repair.
|
|
1085
|
+
if (lastCandidate && (repaired || cutOffs >= 2)) {
|
|
1086
|
+
report = lastCandidate;
|
|
1087
|
+
log(`the report turn was cut off at ${maxTokens} output tokens; keeping the report.json already written (${lint.length} problem(s)).`);
|
|
1088
|
+
break;
|
|
1089
|
+
}
|
|
1090
|
+
if (cutOffs >= 2) {
|
|
1091
|
+
log(`the report turn was cut off at its output limit twice (${maxTokens} tokens), so the report is written from the notes instead.`);
|
|
1092
|
+
throw reportIncomplete({ markdown, secrets, budgetPressure: shrunk || play.budgetWarned || play.budgetExceeded || play.reserveStopped,
|
|
1093
|
+
message: `The report step was cut off at its ${maxTokens} token output limit twice.` });
|
|
1094
|
+
}
|
|
1095
|
+
log(`the report turn was cut off at ${maxTokens} output tokens; asking once more for a shorter report with the same ceiling.`);
|
|
1096
|
+
}
|
|
1097
|
+
|
|
991
1098
|
// Every tool_use the next request echoes back needs its tool_result, or
|
|
992
1099
|
// the API refuses the request. A write cut off at the token limit is
|
|
993
1100
|
// malformed: it was not saved, and it is answered so.
|
|
@@ -999,11 +1106,16 @@ async function reportPhase({
|
|
|
999
1106
|
continued = true;
|
|
1000
1107
|
messages.push({ role: 'assistant', content: assistantContent(answer) });
|
|
1001
1108
|
messages.push({ role: 'user', content: toolResults.concat([{ type: 'text', text: CONTINUE_WITH_JSON }]) });
|
|
1109
|
+
if (cutOff) askShorter(messages, maxTokens);
|
|
1002
1110
|
continue;
|
|
1003
1111
|
}
|
|
1004
1112
|
|
|
1005
|
-
|
|
1006
|
-
|
|
1113
|
+
// A first cut-off on the repair turn still gets its one shorter retry.
|
|
1114
|
+
if (repaired && !(cutOff && cutOffs === 1)) {
|
|
1115
|
+
// No report.json after the repair: the run still played, so the notes
|
|
1116
|
+
// become the report rather than an empty one.
|
|
1117
|
+
if (!candidate) throw reportIncomplete({ markdown, secrets, budgetPressure: shrunk || play.budgetWarned || play.budgetExceeded || play.reserveStopped,
|
|
1118
|
+
message: `the report step did not produce a valid report.json: ${lint.join('; ')}` });
|
|
1007
1119
|
// Still imperfect after the repair: keep it, record the lint, and let
|
|
1008
1120
|
// the server have the final word. It validates the same schema and
|
|
1009
1121
|
// drops unevidenced findings itself, so this is a report with known
|
|
@@ -1021,6 +1133,7 @@ async function reportPhase({
|
|
|
1021
1133
|
role: 'user',
|
|
1022
1134
|
content: toolResults.concat([{ type: 'text', text: repairInstruction(validation.details, evidenceProblems, missingSections) }])
|
|
1023
1135
|
});
|
|
1136
|
+
if (cutOff) askShorter(messages, maxTokens);
|
|
1024
1137
|
}
|
|
1025
1138
|
|
|
1026
1139
|
// One bounded look at the evidence: each blocker or major (at most
|
|
@@ -1257,6 +1370,39 @@ export function buildReportRequest({ skill, persona, brief, localBrief = {}, int
|
|
|
1257
1370
|
return { system, messages: [{ role: 'user', content: [{ type: 'text', text: scrubSecrets(text, secrets) }] }] };
|
|
1258
1371
|
}
|
|
1259
1372
|
|
|
1373
|
+
/** What a report turn is told when its ceiling is tight or it was cut off. */
|
|
1374
|
+
export function shorterReportInstruction(maxTokens) {
|
|
1375
|
+
return `Your report has to fit in ${maxTokens} output tokens, and the last one did not. Write it much shorter: at most 5 findings, each description and repro step one or two short sentences, `
|
|
1376
|
+
+ 'and a report.md of about 250 words that keeps its four sections. Write the files in one turn and do not restate the notes.';
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
/** Add the shorter-report instruction to the last user message, which is the next request's question. */
|
|
1380
|
+
function askShorter(messages, maxTokens) {
|
|
1381
|
+
const last = messages[messages.length - 1];
|
|
1382
|
+
if (!last || last.role !== 'user') return;
|
|
1383
|
+
const text = shorterReportInstruction(maxTokens);
|
|
1384
|
+
const content = typeof last.content === 'string' ? [{ type: 'text', text: last.content }] : [...(last.content || [])];
|
|
1385
|
+
if (content.some(block => block && block.type === 'text' && block.text === text)) return;
|
|
1386
|
+
messages[messages.length - 1] = { ...last, content: [...content, { type: 'text', text }] };
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
/**
|
|
1390
|
+
* The report step could not finish: the caller writes the report from the
|
|
1391
|
+
* step log (notes, screenshots and actions), because a run that played never
|
|
1392
|
+
* comes back empty. A report.md completed on the way is kept as a draft.
|
|
1393
|
+
*/
|
|
1394
|
+
function reportIncomplete({ markdown, secrets, budgetPressure, message }) {
|
|
1395
|
+
const error = Object.assign(new Error(message), { reportIncomplete: true, budgetPressure: Boolean(budgetPressure) });
|
|
1396
|
+
if (typeof markdown === 'string' && markdown.trim()) {
|
|
1397
|
+
const safeMarkdown = scrubSecrets(markdown, secrets);
|
|
1398
|
+
if (Buffer.byteLength(safeMarkdown, 'utf8') <= 256 * 1024 && scanForSecrets(safeMarkdown).length === 0) error.completedReportMarkdown = safeMarkdown;
|
|
1399
|
+
}
|
|
1400
|
+
return error;
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/** The reason a step-log report gives when the report step could not finish. */
|
|
1404
|
+
export const REPORT_INCOMPLETE_REASON = 'The report step could not finish within its output limit and the run\'s model budget. What the persona saw is below, and report.json carries the notes as unreviewed findings.';
|
|
1405
|
+
|
|
1260
1406
|
/** The smallest output ceiling worth retrying a report turn with. */
|
|
1261
1407
|
export const REPORT_MIN_TOKENS = 1536;
|
|
1262
1408
|
|
package/src/run/resume.js
CHANGED
|
@@ -9,6 +9,7 @@ import { reconcileDroppedFindings } from './dropped.js';
|
|
|
9
9
|
import { createReportValidator, writeReportFiles } from './report.js';
|
|
10
10
|
import * as stateFile from './state.js';
|
|
11
11
|
import { playJob, resolvePersonas } from '../commands/run.js';
|
|
12
|
+
import { serveBuildDir } from './serveBuild.js';
|
|
12
13
|
|
|
13
14
|
/** Server states that only a live process can be in, and this one is resuming it. */
|
|
14
15
|
const ABANDONED_MID_RUN = Object.freeze(['launching', 'playing']);
|
|
@@ -115,7 +116,16 @@ export async function resumeJob({ api, gameId, jobId, job, runs, state, repoRoot
|
|
|
115
116
|
}
|
|
116
117
|
|
|
117
118
|
const driverName = journal.driver || options.driver || 'playwright_web';
|
|
118
|
-
|
|
119
|
+
// A build served by `run --build-dir` lived on a port that died with that
|
|
120
|
+
// process: serve the same folder again (or the one passed now) and play there.
|
|
121
|
+
let servedTarget = null;
|
|
122
|
+
if (driverName === 'playwright_web' && (options.buildDir || journal.buildDir)) {
|
|
123
|
+
try { servedTarget = (await (injected.serveBuildDir || serveBuildDir)(options.buildDir || journal.buildDir)).url; } catch (error) {
|
|
124
|
+
log(`${error.message} Pass --build-dir with the build folder, or --build-url.`);
|
|
125
|
+
return EXIT.ENVIRONMENT;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const target = servedTarget || journal.target || options.buildUrl || options.godotProject;
|
|
119
129
|
if (!target) {
|
|
120
130
|
log('The journal does not say what this job was pointed at. Pass --build-url or --godot-project.');
|
|
121
131
|
return EXIT.ENVIRONMENT;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { CliError } from '../errors.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The local web server behind `run --build-dir`: an exported web build served
|
|
8
|
+
* from 127.0.0.1 on a free port, with the headers engines' web exports need
|
|
9
|
+
* and a static file server usually does not send.
|
|
10
|
+
*
|
|
11
|
+
* - `application/wasm` for `.wasm`, so the browser compiles while it downloads.
|
|
12
|
+
* - Content-Encoding for an engine's pre-compressed files (`x.wasm.br`,
|
|
13
|
+
* `x.framework.js.gz`), with the type of the file inside. Unity's Brotli and
|
|
14
|
+
* gzip builds refuse to start without it.
|
|
15
|
+
* - Cross-origin isolation on every response (COOP `same-origin`, COEP
|
|
16
|
+
* `credentialless`), so a threaded export (Godot with threads, love.js,
|
|
17
|
+
* Emscripten `-pthread`) gets SharedArrayBuffer. `credentialless` rather than
|
|
18
|
+
* `require-corp`: a local game may still load a font or image from another
|
|
19
|
+
* host, and that should keep working, without cookies.
|
|
20
|
+
* - `no-store`, so a rebuilt export is never played from a stale cache.
|
|
21
|
+
*
|
|
22
|
+
* It reads only files under the build folder (no symlink out of it), answers
|
|
23
|
+
* GET and HEAD only, and listens on the loopback address only.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const CONTENT_TYPES = Object.freeze({
|
|
27
|
+
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
28
|
+
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
|
|
29
|
+
'.map': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
30
|
+
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.ico': 'image/x-icon', '.mp3': 'audio/mpeg',
|
|
31
|
+
'.ogg': 'audio/ogg', '.wav': 'audio/wav', '.m4a': 'audio/mp4', '.mp4': 'video/mp4', '.webm': 'video/webm',
|
|
32
|
+
'.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf', '.txt': 'text/plain; charset=utf-8',
|
|
33
|
+
'.xml': 'application/xml', '.pck': 'application/octet-stream', '.data': 'application/octet-stream',
|
|
34
|
+
'.mem': 'application/octet-stream', '.unityweb': 'application/octet-stream'
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const ENCODINGS = Object.freeze({ '.br': 'br', '.gz': 'gzip' });
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The type and encoding a file is served with. `.unityweb` is Unity's own
|
|
41
|
+
* fallback format, decoded by its loader, so it is sent as it is.
|
|
42
|
+
* @param {string} file
|
|
43
|
+
* @returns {Record<string, string>}
|
|
44
|
+
*/
|
|
45
|
+
export function contentHeaders(file) {
|
|
46
|
+
const ext = path.extname(file).toLowerCase();
|
|
47
|
+
const encoding = ENCODINGS[ext];
|
|
48
|
+
if (encoding) {
|
|
49
|
+
const inner = path.extname(file.slice(0, -ext.length)).toLowerCase();
|
|
50
|
+
if (inner && CONTENT_TYPES[inner]) return { 'content-type': CONTENT_TYPES[inner], 'content-encoding': encoding };
|
|
51
|
+
}
|
|
52
|
+
return { 'content-type': CONTENT_TYPES[ext] || 'application/octet-stream' };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Headers on every response. */
|
|
56
|
+
export const ISOLATION_HEADERS = Object.freeze({
|
|
57
|
+
'cache-control': 'no-store',
|
|
58
|
+
'cross-origin-opener-policy': 'same-origin',
|
|
59
|
+
'cross-origin-embedder-policy': 'credentialless',
|
|
60
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
61
|
+
'x-content-type-options': 'nosniff'
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The page to open in a build folder: `index.html` when there is one,
|
|
66
|
+
* otherwise the only `.html` file at the top (a Godot export keeps its
|
|
67
|
+
* project name, `jump-bunny.html`). Null when there is no single page.
|
|
68
|
+
* @param {string[]} names the folder's top-level file names
|
|
69
|
+
* @returns {string|null}
|
|
70
|
+
*/
|
|
71
|
+
export function pickEntry(names) {
|
|
72
|
+
if (names.includes('index.html')) return 'index.html';
|
|
73
|
+
const pages = names.filter(name => /\.html?$/i.test(name));
|
|
74
|
+
return pages.length === 1 ? pages[0] : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Start serving a build folder.
|
|
79
|
+
* @param {string} dir
|
|
80
|
+
* @param {{entry?: string|null, host?: string}} [options]
|
|
81
|
+
* @returns {Promise<{url: string, origin: string, entry: string, root: string, close: () => Promise<void>}>}
|
|
82
|
+
*/
|
|
83
|
+
export async function serveBuildDir(dir, { entry = null, host = '127.0.0.1' } = {}) {
|
|
84
|
+
let root;
|
|
85
|
+
try {
|
|
86
|
+
root = await realpath(path.resolve(dir));
|
|
87
|
+
if (!(await stat(root)).isDirectory()) throw new Error('not a directory');
|
|
88
|
+
} catch {
|
|
89
|
+
throw new CliError(`--build-dir ${dir} is not a folder. Point it at the folder your engine exported for the web (the one with the .html page).`);
|
|
90
|
+
}
|
|
91
|
+
const names = (await readdir(root, { withFileTypes: true })).filter(item => item.isFile()).map(item => item.name);
|
|
92
|
+
const page = entry || pickEntry(names);
|
|
93
|
+
if (!page) {
|
|
94
|
+
throw new CliError(`--build-dir ${dir} has no index.html and no single .html page. Export the game for the web, or name its page in the folder${names.some(name => /\.html?$/i.test(name)) ? ' (there is more than one .html file: open the right one with --build-url)' : ''}.`);
|
|
95
|
+
}
|
|
96
|
+
const server = createServer((req, res) => {
|
|
97
|
+
respond(root, req, res).catch(() => { if (!res.headersSent) res.writeHead(500, ISOLATION_HEADERS); res.end(); });
|
|
98
|
+
});
|
|
99
|
+
await new Promise((resolve, reject) => {
|
|
100
|
+
server.once('error', reject);
|
|
101
|
+
server.listen(0, host, resolve);
|
|
102
|
+
});
|
|
103
|
+
// The server lives as long as the run that started it, and never keeps the
|
|
104
|
+
// process alive on its own once the run is over.
|
|
105
|
+
server.unref();
|
|
106
|
+
const origin = `http://${host}:${server.address().port}`;
|
|
107
|
+
const url = `${origin}/${page.split('/').map(encodeURIComponent).join('/')}`;
|
|
108
|
+
return { url, origin, entry: page, root, close: () => new Promise(resolve => server.close(() => resolve())) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function respond(root, req, res) {
|
|
112
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
113
|
+
res.writeHead(405, { ...ISOLATION_HEADERS, allow: 'GET, HEAD' });
|
|
114
|
+
return res.end();
|
|
115
|
+
}
|
|
116
|
+
let rel;
|
|
117
|
+
try { rel = decodeURIComponent(new URL(req.url, 'http://local').pathname); } catch {
|
|
118
|
+
res.writeHead(400, ISOLATION_HEADERS);
|
|
119
|
+
return res.end();
|
|
120
|
+
}
|
|
121
|
+
if (rel.includes('\0')) { res.writeHead(400, ISOLATION_HEADERS); return res.end(); }
|
|
122
|
+
if (rel.endsWith('/')) rel += 'index.html';
|
|
123
|
+
const file = path.resolve(root, '.' + rel);
|
|
124
|
+
if (file !== root && !file.startsWith(root + path.sep)) { res.writeHead(404, ISOLATION_HEADERS); return res.end(); }
|
|
125
|
+
let real;
|
|
126
|
+
try {
|
|
127
|
+
const info = await lstat(file);
|
|
128
|
+
real = await realpath(file);
|
|
129
|
+
if (!real.startsWith(root + path.sep) || !(await stat(real)).isFile() || (!info.isFile() && !info.isSymbolicLink())) throw new Error('outside');
|
|
130
|
+
} catch {
|
|
131
|
+
res.writeHead(404, ISOLATION_HEADERS);
|
|
132
|
+
return res.end();
|
|
133
|
+
}
|
|
134
|
+
const body = await readFile(real);
|
|
135
|
+
res.writeHead(200, { ...contentHeaders(real), ...ISOLATION_HEADERS, 'content-length': body.length });
|
|
136
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
137
|
+
}
|
package/src/run/tools.js
CHANGED
|
@@ -335,6 +335,19 @@ export async function executeTool({ driver, toolUse, onNote, onScreenshot, stale
|
|
|
335
335
|
: action.ref && staleRefs
|
|
336
336
|
? { ok: false, changed: false, error: STALE_REF_MESSAGE, driverError: true }
|
|
337
337
|
: await driver.act(action);
|
|
338
|
+
// The runner refused to leave the build. The persona is told so in plain
|
|
339
|
+
// text and plays on: it is a step that changed nothing, never an error and
|
|
340
|
+
// never a run failure. No observation either, because nothing moved.
|
|
341
|
+
if (outcome.refused === 'off_site') {
|
|
342
|
+
return {
|
|
343
|
+
result: toolResult(toolUse.id, offSiteRefusalText(outcome.host)),
|
|
344
|
+
observation: null,
|
|
345
|
+
spentAction: ACTION_TOOLS.includes(toolUse.name),
|
|
346
|
+
changed: false,
|
|
347
|
+
error: null,
|
|
348
|
+
refused: 'off_site'
|
|
349
|
+
};
|
|
350
|
+
}
|
|
338
351
|
const observation = await driver.observe();
|
|
339
352
|
const spentAction = ACTION_TOOLS.includes(toolUse.name) && outcome.ok;
|
|
340
353
|
const prefix = outcome.ok
|
|
@@ -350,11 +363,25 @@ export async function executeTool({ driver, toolUse, onNote, onScreenshot, stale
|
|
|
350
363
|
};
|
|
351
364
|
}
|
|
352
365
|
|
|
366
|
+
/**
|
|
367
|
+
* What the persona is told when the runner refuses to leave the build.
|
|
368
|
+
*
|
|
369
|
+
* @param {string} [host]
|
|
370
|
+
* @returns {string}
|
|
371
|
+
*/
|
|
372
|
+
export function offSiteRefusalText(host) {
|
|
373
|
+
return `Refused: that link leaves the build under test (${host || 'another site'}). Stay on this page and use its controls.`;
|
|
374
|
+
}
|
|
375
|
+
|
|
353
376
|
/**
|
|
354
377
|
* A tool_result whose content is the new observation, with the screenshot
|
|
355
378
|
* attached as an image when the driver decided the text was too thin to
|
|
356
379
|
* play from. Images are pruned from history by the caller: the act step
|
|
357
|
-
* accepts a very small number of image blocks per request.
|
|
380
|
+
* accepts a very small number of image blocks per request. When the screenshot
|
|
381
|
+
* rides along, a failed action is NOT flagged `is_error`: the Messages API
|
|
382
|
+
* refuses an `is_error` result that carries an image, and the image is the
|
|
383
|
+
* persona's only view of a canvas game. The "That did not work" prefix
|
|
384
|
+
* already says what the flag would.
|
|
358
385
|
*
|
|
359
386
|
* @param {string} id
|
|
360
387
|
* @param {Object} observation
|
|
@@ -382,7 +409,8 @@ export function observationResult(id, observation, prefix = '', isError = false)
|
|
|
382
409
|
}
|
|
383
410
|
});
|
|
384
411
|
}
|
|
385
|
-
|
|
412
|
+
const withImage = content.length > 1;
|
|
413
|
+
return { type: 'tool_result', tool_use_id: id, content, ...(isError && !withImage ? { is_error: true } : {}) };
|
|
386
414
|
}
|
|
387
415
|
|
|
388
416
|
/**
|
|
@@ -429,4 +457,4 @@ function message(error) {
|
|
|
429
457
|
return String(error && error.message ? error.message : error);
|
|
430
458
|
}
|
|
431
459
|
|
|
432
|
-
export default { PLAY_TOOLS, REPORT_TOOLS, executeTool, actionFor, toolResult, observationResult };
|
|
460
|
+
export default { PLAY_TOOLS, REPORT_TOOLS, executeTool, actionFor, toolResult, observationResult, offSiteRefusalText };
|
package/src/ui/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createInterface } from 'node:readline/promises';
|
|
2
2
|
import { stableStringify } from '../fsutil.js';
|
|
3
|
+
import { CliError, ExitCode } from '../errors.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Terminal output, in one place.
|
|
@@ -183,22 +184,36 @@ export function spinner(label) {
|
|
|
183
184
|
};
|
|
184
185
|
}
|
|
185
186
|
|
|
187
|
+
/** The one line printed when a question needs a terminal and there is none. */
|
|
188
|
+
export const NO_TERMINAL_MESSAGE = 'No terminal to confirm in: pass --yes to accept the shown price and hold.';
|
|
189
|
+
|
|
190
|
+
function noTerminal(message = NO_TERMINAL_MESSAGE) {
|
|
191
|
+
const error = new CliError(message, ExitCode.FAILURE);
|
|
192
|
+
error.code = 'no_terminal';
|
|
193
|
+
return error;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** True for the error confirm() throws when there is no terminal to ask in. */
|
|
197
|
+
export const isNoTerminal = error => error instanceof CliError && error.code === 'no_terminal';
|
|
198
|
+
|
|
186
199
|
/**
|
|
187
200
|
* Ask a yes or no question.
|
|
188
201
|
*
|
|
189
|
-
* `--yes` skips it
|
|
190
|
-
* answer would hang a CI job forever,
|
|
191
|
-
*
|
|
192
|
-
*
|
|
202
|
+
* `--yes` skips it. A non interactive stdin is an error, not an answer: a
|
|
203
|
+
* prompt nobody can answer would hang a CI job forever, and piped text such as
|
|
204
|
+
* `echo y |` is never taken as consent, because the question is usually
|
|
205
|
+
* "shall I spend your money". Quietly declining instead left people wondering
|
|
206
|
+
* why nothing happened, so the error says what to do.
|
|
193
207
|
*
|
|
194
208
|
* @param {string} question
|
|
195
|
-
* @param {{yes?: boolean, input?: object, output?: object}} [options]
|
|
209
|
+
* @param {{yes?: boolean, input?: object, output?: object, noTerminalMessage?: string}} [options]
|
|
210
|
+
* noTerminalMessage replaces the line for a question that is not about money.
|
|
196
211
|
* @returns {Promise<boolean>}
|
|
197
212
|
*/
|
|
198
213
|
export async function confirm(question, options = {}) {
|
|
199
214
|
if (options.yes) return true;
|
|
200
215
|
const input = options.input || process.stdin;
|
|
201
|
-
if (!input.isTTY && !options.input)
|
|
216
|
+
if (!input.isTTY && !options.input) throw noTerminal(options.noTerminalMessage);
|
|
202
217
|
|
|
203
218
|
const rl = createInterface({ input, output: options.output || stream });
|
|
204
219
|
try {
|