@vibe-engine/cli 0.1.0 → 0.1.2
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/dist/assets.d.ts +1 -0
- package/dist/assets.js +13 -7
- package/dist/create.js +3 -0
- package/dist/main.js +11 -4
- package/dist/run.d.ts +2 -0
- package/dist/run.js +1 -1
- package/dist/session-daemon.d.ts +1 -0
- package/dist/session-daemon.js +103 -0
- package/dist/session-host.d.ts +29 -0
- package/dist/session-host.js +226 -0
- package/dist/session.d.ts +6 -0
- package/dist/session.js +256 -0
- package/dist/typecheck.d.ts +15 -0
- package/dist/typecheck.js +68 -0
- package/package.json +4 -4
- package/templates/arena-3d/AGENTS.md +4 -4
- package/templates/arena-3d/tests/arena.test.ts +1 -1
- package/templates/platformer-2d/AGENTS.md +4 -4
- package/templates/platformer-2d/tests/gameplay.test.ts +1 -1
- package/templates/shooter-2d-pvp/AGENTS.md +12 -11
- package/templates/shooter-2d-pvp/README.md +1 -1
- package/templates/shooter-2d-pvp/src/components/gun.component.ts +2 -13
- package/templates/shooter-2d-pvp/src/events/combat.events.ts +0 -2
- package/templates/shooter-2d-pvp/src/level/build.ts +2 -2
- package/templates/shooter-2d-pvp/src/listeners/effects.listener.ts +2 -22
- package/templates/shooter-2d-pvp/src/listeners/players.listener.ts +3 -2
- package/templates/shooter-2d-pvp/src/maps/arena.map.ts +1 -1
- package/templates/shooter-2d-pvp/src/rules/damage.ts +4 -19
- package/templates/shooter-2d-pvp/src/scenes/arena.scene.ts +2 -2
- package/templates/shooter-2d-pvp/src/systems/combat.system.ts +3 -13
- package/templates/shooter-2d-pvp/src/systems/gun.system.ts +9 -30
- package/templates/shooter-2d-pvp/src/systems/view.system.ts +1 -1
- package/templates/shooter-2d-pvp/tests/pvp.test.ts +26 -38
package/dist/assets.d.ts
CHANGED
package/dist/assets.js
CHANGED
|
@@ -5,6 +5,7 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { SHADER_PRESETS, shaderProblems, uiThemeAssets } from '@vibe-engine/core';
|
|
6
6
|
import { PROJECT_ERRORS, createWorld, loadProject, walk } from './project.js';
|
|
7
7
|
import { checkBoundaries } from './boundary.js';
|
|
8
|
+
import { typecheck } from './typecheck.js';
|
|
8
9
|
import { withSource } from './source.js';
|
|
9
10
|
export const assets = defineCommand({
|
|
10
11
|
name: 'assets',
|
|
@@ -24,11 +25,12 @@ export const assets = defineCommand({
|
|
|
24
25
|
});
|
|
25
26
|
export const check = defineCommand({
|
|
26
27
|
name: 'check',
|
|
27
|
-
summary: 'Load the project and every scene (setup + first tick) and report every problem: discovery, assets, ids, setup errors, client/server boundary',
|
|
28
|
-
flags: {},
|
|
29
|
-
output: { ok: 'true when there are no problems', scenes: 'scenes checked', assets: 'assets in the catalog' },
|
|
30
|
-
errors: { ...PROJECT_ERRORS, 'check-failed': 'one or more problems; detail.problems lists each with code (scene-failed, boundary-violation, asset-missing, shader-missing, shader-invalid...), scene and source' },
|
|
31
|
-
async run({ io }) {
|
|
28
|
+
summary: 'Load the project and every scene (setup + first tick) and report every problem: TypeScript errors, discovery, assets, ids, setup errors, client/server boundary',
|
|
29
|
+
flags: { types: { type: 'boolean', default: true, doc: 'run the TypeScript typecheck (--no-types skips it)' } },
|
|
30
|
+
output: { ok: 'true when there are no problems', scenes: 'scenes checked', assets: 'assets in the catalog', typecheck: "'ok', or why it did not run (no typescript in the project, --no-types)" },
|
|
31
|
+
errors: { ...PROJECT_ERRORS, 'check-failed': 'one or more problems; detail.problems lists each with code (type-error, scene-failed, boundary-violation, asset-missing, shader-missing, shader-invalid...), scene and source (file:line[:column])' },
|
|
32
|
+
async run({ flags, io }) {
|
|
33
|
+
const types = flags.types ? typecheck(io.cwd) : null; // em paralelo com o resto
|
|
32
34
|
const project = await loadProject(io.cwd); // problema de projeto: um erro só, com o código dele
|
|
33
35
|
const problems = [];
|
|
34
36
|
const shaders = { ...SHADER_PRESETS, ...Object.fromEntries(project.shaders.map((s) => [s.id, s.def])) };
|
|
@@ -61,6 +63,10 @@ export const check = defineCommand({
|
|
|
61
63
|
for (const b of existsSync(src) ? checkBoundaries(io.cwd, walk(src)) : []) {
|
|
62
64
|
problems.push({ code: 'boundary-violation', message: `${b.file}:${b.line}: ${b.rule} ('${b.target}')`, source: `${b.file}:${b.line}` });
|
|
63
65
|
}
|
|
66
|
+
const tc = types ? await types : { ran: false, reason: 'skipped (--no-types)' };
|
|
67
|
+
// Erros de tipo primeiro: muitas vezes explicam a falha de cena logo abaixo.
|
|
68
|
+
if (tc.ran)
|
|
69
|
+
problems.unshift(...tc.errors.map((e) => ({ code: 'type-error', message: `${e.file}:${e.line}:${e.column}: ${e.code} ${e.message}`, source: `${e.file}:${e.line}:${e.column}` })));
|
|
64
70
|
if (problems.length) {
|
|
65
71
|
throw new CliError('check-failed', `${problems.length} problem${problems.length > 1 ? 's' : ''}`, {
|
|
66
72
|
detail: { problems },
|
|
@@ -68,9 +74,9 @@ export const check = defineCommand({
|
|
|
68
74
|
hint: problems.map((p) => (p.scene ? `${p.scene}: ${p.message}` : p.message)).join(' | '),
|
|
69
75
|
});
|
|
70
76
|
}
|
|
71
|
-
return { ok: true, scenes: project.scenes.length, assets: project.assets.length };
|
|
77
|
+
return { ok: true, scenes: project.scenes.length, assets: project.assets.length, typecheck: tc.ran ? 'ok' : tc.reason };
|
|
72
78
|
},
|
|
73
79
|
human(o) {
|
|
74
|
-
return `ok · ${o.scenes} scenes · ${o.assets} assets`;
|
|
80
|
+
return `ok · ${o.scenes} scenes · ${o.assets} assets · types ${o.typecheck}`;
|
|
75
81
|
},
|
|
76
82
|
});
|
package/dist/create.js
CHANGED
|
@@ -45,6 +45,9 @@ export const create = defineCommand({
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
|
48
|
+
// O pnpm 10+ segura pacotes recém-publicados (minimumReleaseAge): sem isto, um jogo criado logo depois de uma versão nova da engine não instala.
|
|
49
|
+
if (PUBLISHED)
|
|
50
|
+
writeFileSync(join(dir, 'pnpm-workspace.yaml'), '# Versões novas da engine (@vibe-engine/*) entram na hora; o resto segue a política do pnpm.\nminimumReleaseAgeExclude:\n - "@vibe-engine/*"\n');
|
|
48
51
|
const configPath = join(dir, 'vibe.config.ts');
|
|
49
52
|
writeFileSync(configPath, readFileSync(configPath, 'utf8').replace(/name: '[^']*'/, `name: '${name}'`));
|
|
50
53
|
return { dir: relative(io.cwd, dir) || '.', template, files, next: [`cd ${relative(io.cwd, dir)}`, 'pnpm install', 'pnpm dev'] };
|
package/dist/main.js
CHANGED
|
@@ -9,6 +9,7 @@ import { build, dev } from './web.js';
|
|
|
9
9
|
import { create } from './create.js';
|
|
10
10
|
import { serve } from './serve.js';
|
|
11
11
|
import { testCmd } from './test-run.js';
|
|
12
|
+
import { SESSION_COMMANDS } from './session.js';
|
|
12
13
|
const describe = (c) => ({
|
|
13
14
|
name: c.name,
|
|
14
15
|
summary: c.summary,
|
|
@@ -20,12 +21,12 @@ const describe = (c) => ({
|
|
|
20
21
|
const help = defineCommand({
|
|
21
22
|
name: 'help',
|
|
22
23
|
summary: 'List commands with their flags, output fields and error codes',
|
|
23
|
-
positionals: [{ name: 'command', doc: 'show a single command' }],
|
|
24
|
+
positionals: [{ name: 'command', doc: 'show a single command' }, { name: 'subcommand', doc: "for two-word commands ('session step')" }],
|
|
24
25
|
flags: { tree: { type: 'boolean', default: false, doc: 'every command with its full schema (with --json)' } },
|
|
25
26
|
output: { commands: 'commands with name, summary, positionals, flags, output and errors' },
|
|
26
27
|
errors: {},
|
|
27
28
|
async run({ positionals }) {
|
|
28
|
-
const name = positionals
|
|
29
|
+
const name = positionals.length ? positionals.join(' ') : undefined;
|
|
29
30
|
if (name === undefined)
|
|
30
31
|
return { commands: COMMANDS.map(describe) };
|
|
31
32
|
const cmd = COMMANDS.find((c) => c.name === name);
|
|
@@ -35,15 +36,18 @@ const help = defineCommand({
|
|
|
35
36
|
},
|
|
36
37
|
human({ commands }) {
|
|
37
38
|
if (commands.length > 1)
|
|
38
|
-
return ['vibe <command> [flags] (add --json for machine output)', '', ...commands.map((c) => ` ${c.name.padEnd(
|
|
39
|
+
return ['vibe <command> [flags] (add --json for machine output)', '', ...commands.map((c) => ` ${c.name.padEnd(16)} ${c.summary}`), '', 'vibe help <command> shows flags and error codes.'].join('\n');
|
|
39
40
|
const c = commands[0];
|
|
40
41
|
const flags = Object.entries(c.flags).map(([n, f]) => ` --${n} <${f.type}>${f.default !== undefined ? ` (default ${f.default})` : ''}\n ${f.doc}`);
|
|
41
42
|
const errors = Object.entries(c.errors).map(([code, when]) => ` ${code.padEnd(18)} ${when}`);
|
|
42
43
|
return [`vibe ${c.name} — ${c.summary}`, '', 'flags:', ...flags, '', 'errors:', ...errors].join('\n');
|
|
43
44
|
},
|
|
44
45
|
});
|
|
45
|
-
export const COMMANDS = [create, run, testCmd, dev, serve, build, info, assets, check, map, help];
|
|
46
|
+
export const COMMANDS = [create, run, testCmd, dev, serve, build, info, assets, check, map, ...SESSION_COMMANDS, help];
|
|
46
47
|
function unknownCommand(name) {
|
|
48
|
+
const group = COMMANDS.filter((c) => c.name.startsWith(`${name} `));
|
|
49
|
+
if (group.length)
|
|
50
|
+
return new CliError('unknown-command', `'${name}' needs a subcommand`, { expected: group.map((c) => c.name).join(' | '), hint: `vibe help ${group[0].name}` });
|
|
47
51
|
return new CliError('unknown-command', `unknown command '${name}'`, { expected: COMMANDS.map((c) => c.name).join(' | '), hint: 'vibe help --tree --json lists every command' });
|
|
48
52
|
}
|
|
49
53
|
/** Roda a CLI e devolve o exit code: 0 ok, 1 erro do comando, 2 uso errado. */
|
|
@@ -53,6 +57,9 @@ export async function main(argv, io) {
|
|
|
53
57
|
let [name = 'help', ...rest] = argv;
|
|
54
58
|
if (name.startsWith('-'))
|
|
55
59
|
[name, rest] = ['help', argv];
|
|
60
|
+
// Comandos de duas palavras ('session step'): o segundo argumento faz parte do nome.
|
|
61
|
+
if (rest[0] && !rest[0].startsWith('-') && COMMANDS.some((c) => c.name === `${name} ${rest[0]}`))
|
|
62
|
+
[name, rest] = [`${name} ${rest[0]}`, rest.slice(1)];
|
|
56
63
|
const cmd = COMMANDS.find((c) => c.name === name);
|
|
57
64
|
if (!cmd)
|
|
58
65
|
throw unknownCommand(name);
|
package/dist/run.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type World } from '@vibe-engine/core';
|
|
1
2
|
export interface RunOutput {
|
|
2
3
|
runId: string;
|
|
3
4
|
scene: string;
|
|
@@ -16,3 +17,4 @@ export interface RunOutput {
|
|
|
16
17
|
};
|
|
17
18
|
}
|
|
18
19
|
export declare const run: import("./registry.ts").CommandSpec<RunOutput>;
|
|
20
|
+
export declare function pickScene(world: World, scene: string | undefined): string;
|
package/dist/run.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Processo de uma sessão (`vibe session start` o cria, separado do terminal).
|
|
3
|
+
* Protocolo RFC-003: POST /rpc com `{ protocolVersion: 1, requestId, method, payload }`
|
|
4
|
+
* e `Authorization: Bearer <token>`, só em 127.0.0.1. O token e a porta ficam em
|
|
5
|
+
* `.vibe/sessions/<id>.json` (modo 600). Sem chamadas por `idleMinutes`, sai sozinho.
|
|
6
|
+
*/
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
11
|
+
import { CliError } from './registry.js';
|
|
12
|
+
import { PROTOCOL_VERSION, createSessionHost, sessionsDir } from './session-host.js';
|
|
13
|
+
const MAX_BODY = 1 << 20;
|
|
14
|
+
const opts = JSON.parse(process.argv[2]);
|
|
15
|
+
const ipc = (m) => process.send?.(m);
|
|
16
|
+
let host;
|
|
17
|
+
try {
|
|
18
|
+
host = await createSessionHost(opts);
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
const e = err instanceof CliError ? err : new CliError('internal', err.message);
|
|
22
|
+
ipc({ error: e.toJSON().error });
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
const token = randomBytes(24).toString('hex');
|
|
26
|
+
const file = join(sessionsDir(opts.root), `${opts.id}.json`);
|
|
27
|
+
let idle;
|
|
28
|
+
const touch = () => {
|
|
29
|
+
clearTimeout(idle);
|
|
30
|
+
idle = setTimeout(() => shutdown(), opts.idleMinutes * 60_000);
|
|
31
|
+
};
|
|
32
|
+
const shutdown = () => {
|
|
33
|
+
host.close();
|
|
34
|
+
rmSync(file, { force: true });
|
|
35
|
+
rmSync(file.replace(/\.json$/, '.log'), { force: true }); // fechou limpo: o log só fica quando o processo morre
|
|
36
|
+
server.close();
|
|
37
|
+
process.exit(0);
|
|
38
|
+
};
|
|
39
|
+
const authorized = (header) => {
|
|
40
|
+
const want = Buffer.from(`Bearer ${token}`);
|
|
41
|
+
const got = Buffer.from(header ?? '');
|
|
42
|
+
return got.length === want.length && timingSafeEqual(got, want);
|
|
43
|
+
};
|
|
44
|
+
const server = createServer((req, res) => {
|
|
45
|
+
const reply = (status, body) => {
|
|
46
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
47
|
+
res.end(JSON.stringify(body));
|
|
48
|
+
};
|
|
49
|
+
// Host diferente de 127.0.0.1:porta = página de outro site tentando falar com a sessão (DNS rebinding).
|
|
50
|
+
if (req.method !== 'POST' || req.url !== '/rpc' || req.headers.host !== `127.0.0.1:${port}`)
|
|
51
|
+
return reply(404, { ok: false });
|
|
52
|
+
if (!authorized(req.headers.authorization))
|
|
53
|
+
return reply(401, { ok: false, error: { code: 'session-unauthorized', message: 'missing or wrong session token' } });
|
|
54
|
+
let size = 0;
|
|
55
|
+
const chunks = [];
|
|
56
|
+
req.on('data', (c) => {
|
|
57
|
+
size += c.length;
|
|
58
|
+
if (size > MAX_BODY)
|
|
59
|
+
req.destroy();
|
|
60
|
+
else
|
|
61
|
+
chunks.push(c);
|
|
62
|
+
});
|
|
63
|
+
req.on('end', async () => {
|
|
64
|
+
touch();
|
|
65
|
+
let msg;
|
|
66
|
+
try {
|
|
67
|
+
msg = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return reply(400, { ok: false, error: { code: 'usage', message: 'body is not JSON' } });
|
|
71
|
+
}
|
|
72
|
+
const requestId = typeof msg.requestId === 'string' ? msg.requestId : null;
|
|
73
|
+
if (msg.protocolVersion !== PROTOCOL_VERSION)
|
|
74
|
+
return reply(400, { requestId, ok: false, error: { code: 'protocol-mismatch', message: `session speaks protocol ${PROTOCOL_VERSION}, got ${msg.protocolVersion}`, hint: 'the CLI and the session come from different engine versions: stop the session and start it again' } });
|
|
75
|
+
if (typeof msg.method !== 'string' || (msg.payload !== undefined && (typeof msg.payload !== 'object' || msg.payload === null)))
|
|
76
|
+
return reply(400, { requestId, ok: false, error: { code: 'usage', message: 'expected { method: string, payload?: object }' } });
|
|
77
|
+
if (msg.method === 'stop') {
|
|
78
|
+
reply(200, { requestId, ok: true, result: { session: opts.id, stopped: true } });
|
|
79
|
+
return setImmediate(shutdown);
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
reply(200, { requestId, ok: true, result: await host.call(msg.method, (msg.payload ?? {})) });
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
const e = err instanceof CliError ? err : new CliError('internal', err.message);
|
|
86
|
+
reply(200, { requestId, ok: false, error: e.toJSON().error });
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
let port = 0;
|
|
91
|
+
server.listen(0, '127.0.0.1', () => {
|
|
92
|
+
port = server.address().port;
|
|
93
|
+
const status = host.call('status', {});
|
|
94
|
+
void status.then((s) => {
|
|
95
|
+
const info = { id: opts.id, pid: process.pid, port, token, scene: s.scene, seed: s.seed, startedAt: new Date().toISOString() };
|
|
96
|
+
mkdirSync(sessionsDir(opts.root), { recursive: true });
|
|
97
|
+
writeFileSync(file, JSON.stringify(info, null, 2), { mode: 0o600 });
|
|
98
|
+
touch();
|
|
99
|
+
ipc({ ready: info });
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
process.on('SIGTERM', shutdown);
|
|
103
|
+
process.on('SIGINT', shutdown);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
2
|
+
/** O que `.vibe/sessions/<id>.json` guarda: como achar e falar com a sessão. */
|
|
3
|
+
export interface SessionFile {
|
|
4
|
+
id: string;
|
|
5
|
+
pid: number;
|
|
6
|
+
port: number;
|
|
7
|
+
token: string;
|
|
8
|
+
scene: string;
|
|
9
|
+
seed: number;
|
|
10
|
+
startedAt: string;
|
|
11
|
+
}
|
|
12
|
+
export declare const sessionsDir: (root: string) => string;
|
|
13
|
+
export interface SessionOptions {
|
|
14
|
+
id: string;
|
|
15
|
+
root: string;
|
|
16
|
+
scene?: string;
|
|
17
|
+
seed?: number;
|
|
18
|
+
saveDir?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface SessionEvent {
|
|
21
|
+
frame: number;
|
|
22
|
+
name: string;
|
|
23
|
+
payload: unknown;
|
|
24
|
+
}
|
|
25
|
+
export interface SessionHost {
|
|
26
|
+
call(method: string, payload: Record<string, unknown>): Promise<object>;
|
|
27
|
+
close(): void;
|
|
28
|
+
}
|
|
29
|
+
export declare function createSessionHost(opts: SessionOptions): Promise<SessionHost>;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sessão viva (#31, #33, #34): um World do projeto, parado no tick 0, que só
|
|
3
|
+
* anda com `step` (ou `resume`, em tempo real). Toda resposta leva `frame` e
|
|
4
|
+
* `revision`; quem manda `revision` antiga num comando que muda o estado recebe
|
|
5
|
+
* `session-revision-stale` em vez de agir sobre um estado que não viu.
|
|
6
|
+
*
|
|
7
|
+
* Roda no processo da sessão (`session-daemon.ts`); os testes chamam direto.
|
|
8
|
+
*/
|
|
9
|
+
import { join, resolve } from 'node:path';
|
|
10
|
+
import { LOCAL_PLAYER } from '@vibe-engine/core';
|
|
11
|
+
import { CliError } from './registry.js';
|
|
12
|
+
import { createWorld, loadProject } from './project.js';
|
|
13
|
+
import { withSource } from './source.js';
|
|
14
|
+
import { fileSaveStore } from './save-store.js';
|
|
15
|
+
import { pickScene } from './run.js';
|
|
16
|
+
export const PROTOCOL_VERSION = 1;
|
|
17
|
+
export const sessionsDir = (root) => join(root, '.vibe', 'sessions');
|
|
18
|
+
/** Eventos guardados pela sessão (os mais antigos saem primeiro). */
|
|
19
|
+
const EVENT_LOG_MAX = 5000;
|
|
20
|
+
const MUTATING = new Set(['step', 'resume', 'reset', 'input']);
|
|
21
|
+
export async function createSessionHost(opts) {
|
|
22
|
+
const project = await loadProject(opts.root);
|
|
23
|
+
let seed = opts.seed ?? 1;
|
|
24
|
+
let scene = '';
|
|
25
|
+
let world = null;
|
|
26
|
+
let revision = 0;
|
|
27
|
+
let timer = null;
|
|
28
|
+
let lastError = null;
|
|
29
|
+
const log = [];
|
|
30
|
+
const fail = (err) => {
|
|
31
|
+
const e = err;
|
|
32
|
+
const src = withSource(e, opts.root);
|
|
33
|
+
lastError = { frame: world.frame, message: e.message, ...src };
|
|
34
|
+
throw new CliError('world-error', e.message, { detail: { frame: world.frame }, ...src, hint: 'fix the file in source, then `vibe session reset` (the state is inconsistent after an error)' });
|
|
35
|
+
};
|
|
36
|
+
async function open(nextScene, nextSeed) {
|
|
37
|
+
const w = await createWorld(project, nextSeed, opts.saveDir ? { saves: fileSaveStore(resolve(opts.root, opts.saveDir)) } : {});
|
|
38
|
+
const s = pickScene(w, nextScene ?? project.config.startScene);
|
|
39
|
+
world = w;
|
|
40
|
+
seed = nextSeed;
|
|
41
|
+
scene = s;
|
|
42
|
+
log.length = 0;
|
|
43
|
+
lastError = null;
|
|
44
|
+
await world.start(s).catch(fail);
|
|
45
|
+
}
|
|
46
|
+
function step(frames) {
|
|
47
|
+
for (let i = 0; i < frames; i++) {
|
|
48
|
+
const from = world.frame;
|
|
49
|
+
try {
|
|
50
|
+
world.step(1);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
revision++;
|
|
54
|
+
fail(err);
|
|
55
|
+
}
|
|
56
|
+
for (const e of world.observe({ entityIds: [], sinceFrame: from }).events)
|
|
57
|
+
log.push({ frame: e.frame, name: e.name, payload: e.payload });
|
|
58
|
+
}
|
|
59
|
+
if (log.length > EVENT_LOG_MAX)
|
|
60
|
+
log.splice(0, log.length - EVENT_LOG_MAX);
|
|
61
|
+
revision++;
|
|
62
|
+
}
|
|
63
|
+
const pause = () => {
|
|
64
|
+
if (timer)
|
|
65
|
+
clearInterval(timer);
|
|
66
|
+
timer = null;
|
|
67
|
+
};
|
|
68
|
+
const head = () => ({ session: opts.id, frame: world.frame, revision });
|
|
69
|
+
const status = () => ({
|
|
70
|
+
...head(),
|
|
71
|
+
scene: world.sceneControl.id ?? scene,
|
|
72
|
+
seed,
|
|
73
|
+
running: timer !== null,
|
|
74
|
+
simTimeMs: (world.frame * 1000) / world.tickRate,
|
|
75
|
+
tickRate: world.tickRate,
|
|
76
|
+
hash: world.hash(),
|
|
77
|
+
entities: Object.keys(world.observe({ components: [] }).entities).length,
|
|
78
|
+
error: lastError,
|
|
79
|
+
});
|
|
80
|
+
await open(opts.scene, seed);
|
|
81
|
+
const methods = {
|
|
82
|
+
status,
|
|
83
|
+
step(p) {
|
|
84
|
+
if (timer)
|
|
85
|
+
throw new CliError('session-running', 'the session is running in real time', { hint: 'vibe session pause, then step' });
|
|
86
|
+
const frames = p.frames ?? 1;
|
|
87
|
+
if (!Number.isInteger(frames) || frames < 0)
|
|
88
|
+
throw new CliError('usage', `frames must be a non-negative integer, got ${frames}`, { expected: 'integer >= 0' });
|
|
89
|
+
const from = world.frame;
|
|
90
|
+
step(frames);
|
|
91
|
+
const counts = {};
|
|
92
|
+
for (const e of log)
|
|
93
|
+
if (e.frame >= from)
|
|
94
|
+
counts[e.name] = (counts[e.name] ?? 0) + 1;
|
|
95
|
+
return { ...status(), stepped: frames, events: counts };
|
|
96
|
+
},
|
|
97
|
+
pause() {
|
|
98
|
+
pause();
|
|
99
|
+
return status();
|
|
100
|
+
},
|
|
101
|
+
resume() {
|
|
102
|
+
if (!timer) {
|
|
103
|
+
timer = setInterval(() => {
|
|
104
|
+
try {
|
|
105
|
+
step(1);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
pause(); // o erro fica em `status().error`
|
|
109
|
+
}
|
|
110
|
+
}, 1000 / world.tickRate);
|
|
111
|
+
}
|
|
112
|
+
return status();
|
|
113
|
+
},
|
|
114
|
+
async reset(p) {
|
|
115
|
+
pause();
|
|
116
|
+
if (p.seed !== undefined && !Number.isInteger(p.seed))
|
|
117
|
+
throw new CliError('usage', `seed must be an integer, got ${p.seed}`, { expected: 'integer' });
|
|
118
|
+
await open(p.scene ?? scene, p.seed ?? seed);
|
|
119
|
+
revision++;
|
|
120
|
+
return status();
|
|
121
|
+
},
|
|
122
|
+
input(p) {
|
|
123
|
+
const changes = Array.isArray(p.changes) ? toChanges(p.changes) : single(p);
|
|
124
|
+
for (const c of changes) {
|
|
125
|
+
checkValue(c.action, c.value);
|
|
126
|
+
if (c.frame < world.frame)
|
|
127
|
+
throw new CliError('input-invalid', `change for tick ${c.frame} is in the past (session is at tick ${world.frame})`, { expected: `frame >= ${world.frame}` });
|
|
128
|
+
}
|
|
129
|
+
world.input.schedule(changes);
|
|
130
|
+
revision++;
|
|
131
|
+
return { ...head(), scheduled: changes };
|
|
132
|
+
},
|
|
133
|
+
query(p) {
|
|
134
|
+
const want = list(p.with);
|
|
135
|
+
const all = Object.entries(world.observe({}).entities).filter(([, comps]) => want.every((c) => c in comps));
|
|
136
|
+
const offset = Number(p.cursor ?? 0);
|
|
137
|
+
const limit = Number(p.limit ?? 50);
|
|
138
|
+
if (!Number.isInteger(offset) || offset < 0)
|
|
139
|
+
throw new CliError('usage', `cursor must come from a previous query, got '${p.cursor}'`);
|
|
140
|
+
const page = all.slice(offset, offset + limit).map(([id, comps]) => ({ id, components: Object.keys(comps) }));
|
|
141
|
+
const next = offset + limit < all.length ? String(offset + limit) : null;
|
|
142
|
+
return { ...head(), total: all.length, entities: page, next };
|
|
143
|
+
},
|
|
144
|
+
inspect(p) {
|
|
145
|
+
const id = String(p.entity ?? '');
|
|
146
|
+
const obs = world.observe({ entityIds: [id] });
|
|
147
|
+
const comps = obs.entities[id];
|
|
148
|
+
if (!comps) {
|
|
149
|
+
const ids = Object.keys(world.observe({ components: [] }).entities);
|
|
150
|
+
throw new CliError('entity-not-found', `entity '${id}' does not exist at tick ${world.frame}`, { detail: { entities: ids.slice(0, 20), total: ids.length }, hint: 'vibe session query lists entity ids' });
|
|
151
|
+
}
|
|
152
|
+
const only = list(p.components);
|
|
153
|
+
const components = only.length ? Object.fromEntries(Object.entries(comps).filter(([c]) => only.includes(c))) : comps;
|
|
154
|
+
return { ...head(), entity: id, hidden: obs.hidden.includes(id), components };
|
|
155
|
+
},
|
|
156
|
+
events(p) {
|
|
157
|
+
const since = Number(p.since ?? 0);
|
|
158
|
+
const filters = list(p.filter);
|
|
159
|
+
const limit = Number(p.limit ?? 100);
|
|
160
|
+
const match = (name) => !filters.length || filters.some((f) => (f.endsWith('*') ? name.startsWith(f.slice(0, -1)) : name === f));
|
|
161
|
+
const found = log.filter((e) => e.frame >= since && match(e.name));
|
|
162
|
+
return { ...head(), total: found.length, oldest: log[0]?.frame ?? null, events: found.slice(-limit) };
|
|
163
|
+
},
|
|
164
|
+
state(p) {
|
|
165
|
+
const obs = world.observe({});
|
|
166
|
+
return { ...head(), scene: obs.scene, states: obs.states, resources: obs.resources, inputs: world.input.recorded().slice(-Number(p.inputs ?? 20)) };
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
function single(p) {
|
|
170
|
+
const action = String(p.action ?? '');
|
|
171
|
+
const player = p.player ?? LOCAL_PLAYER;
|
|
172
|
+
const at = p.at === undefined ? world.frame : Number(p.at);
|
|
173
|
+
if (!Number.isInteger(at))
|
|
174
|
+
throw new CliError('usage', `at must be a tick number, got ${p.at}`);
|
|
175
|
+
const spec = actionSpec(action);
|
|
176
|
+
if (p.press) {
|
|
177
|
+
if (spec.type !== 'button')
|
|
178
|
+
throw new CliError('input-invalid', `'${action}' is a ${spec.type}; only buttons can be pressed`, { expected: 'a value instead of --press' });
|
|
179
|
+
return [{ frame: at, player, action, value: true }, { frame: at + 1, player, action, value: false }];
|
|
180
|
+
}
|
|
181
|
+
if (p.value === undefined)
|
|
182
|
+
throw new CliError('usage', `input '${action}' needs a value or --press`, { expected: spec.type === 'button' ? 'true | false' : spec.type === 'vector2' ? '[x,y]' : 'a number' });
|
|
183
|
+
const value = p.value;
|
|
184
|
+
const out = [{ frame: at, player, action, value }];
|
|
185
|
+
if (p.frames !== undefined) {
|
|
186
|
+
const n = Number(p.frames);
|
|
187
|
+
if (!Number.isInteger(n) || n < 1)
|
|
188
|
+
throw new CliError('usage', `frames must be a positive integer, got ${p.frames}`);
|
|
189
|
+
out.push({ frame: at + n, player, action, value: spec.type === 'button' ? false : spec.type === 'vector2' ? [0, 0] : 0 });
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
function actionSpec(action) {
|
|
194
|
+
const spec = world.inputMap?.actions[action];
|
|
195
|
+
if (!spec)
|
|
196
|
+
throw new CliError('input-invalid', `unknown action '${action}'`, { expected: 'an action declared in defineInput', detail: { actions: Object.keys(world.inputMap?.actions ?? {}) } });
|
|
197
|
+
return spec;
|
|
198
|
+
}
|
|
199
|
+
function checkValue(action, value) {
|
|
200
|
+
const { type } = actionSpec(action);
|
|
201
|
+
const ok = type === 'button' ? typeof value === 'boolean' : type === 'vector2' ? Array.isArray(value) && value.length === 2 && value.every((n) => typeof n === 'number') : typeof value === 'number';
|
|
202
|
+
if (!ok)
|
|
203
|
+
throw new CliError('input-invalid', `'${action}' is a ${type}, got ${JSON.stringify(value)}`, { expected: type === 'button' ? 'true | false' : type === 'vector2' ? '[x,y]' : 'a number' });
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
async call(method, payload) {
|
|
207
|
+
const fn = methods[method];
|
|
208
|
+
if (!fn)
|
|
209
|
+
throw new CliError('usage', `unknown session method '${method}'`, { expected: Object.keys(methods).join(' | ') });
|
|
210
|
+
if (MUTATING.has(method) && payload.revision !== undefined && payload.revision !== revision) {
|
|
211
|
+
throw new CliError('session-revision-stale', `revision ${payload.revision} is old; the session is at revision ${revision} (tick ${world.frame})`, { detail: head(), hint: 'vibe session status, look at the new state, then retry with its revision' });
|
|
212
|
+
}
|
|
213
|
+
return fn(payload);
|
|
214
|
+
},
|
|
215
|
+
close: pause,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function toChanges(raw) {
|
|
219
|
+
return raw.map((c, i) => {
|
|
220
|
+
const ok = c && typeof c === 'object' && Number.isInteger(c.frame) && c.frame >= 0 && typeof c.action === 'string' && 'value' in c && (c.player === undefined || typeof c.player === 'string');
|
|
221
|
+
if (!ok)
|
|
222
|
+
throw new CliError('input-invalid', `changes[${i}] is not a valid change`, { expected: '{ frame: integer >= 0, action: string, value, player?: string }', detail: { index: i, got: c } });
|
|
223
|
+
return { frame: c.frame, action: c.action, value: c.value, player: c.player ?? LOCAL_PLAYER };
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
const list = (v) => (v === undefined || v === null || v === '' ? [] : String(v).split(',').map((s) => s.trim()).filter(Boolean));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type CommandSpec } from './registry.ts';
|
|
2
|
+
import { type SessionFile } from './session-host.ts';
|
|
3
|
+
/** Sessões abertas no projeto; arquivos de processos mortos são apagados. */
|
|
4
|
+
export declare function listSessions(root: string): SessionFile[];
|
|
5
|
+
export declare function callSession(s: SessionFile, method: string, payload?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
6
|
+
export declare const SESSION_COMMANDS: CommandSpec<any>[];
|