@idosgames/mcp 0.1.2 → 0.1.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@idosgames/mcp",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "MCP server that serves the iDosGames Module & Skills Registry to AI coding agents (Claude Code, Codex, Cursor…): list/pull composable game modules and the host scaffold, and load skills for @idosgames/core, the module contract, and composition.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,7 +11,7 @@
11
11
  },
12
12
  {
13
13
  "path": "package.json",
14
- "content": "{\n \"name\": \"@idosgames/host-starter\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"description\": \"The seed project for the AI Coder: a host shell that composes feature modules. Fresh projects start here with zero modules; the developer/agent plugs modules into src/modules.ts.\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"//\": \"Versions are pinned exactly: this is a seed for AI Coder projects, which build offline against a dependency allowlist baked at these versions (see scripts/pack-builder.mjs). Modules bring their own engine deps (three/phaser) when added.\",\n \"dependencies\": {\n \"@idosgames/app-shell\": \"0.1.2\",\n \"@idosgames/core\": \"0.1.3\",\n \"@idosgames/module-sdk\": \"0.1.1\",\n \"@idosgames/react\": \"0.1.0\",\n \"react\": \"19.2.7\",\n \"react-dom\": \"19.2.7\"\n },\n \"devDependencies\": {\n \"@types/react\": \"19.2.17\",\n \"@types/react-dom\": \"19.2.3\",\n \"@vitejs/plugin-react\": \"4.7.0\",\n \"typescript\": \"5.9.3\",\n \"vite\": \"5.4.21\"\n }\n}\n"
14
+ "content": "{\n \"name\": \"@idosgames/host-starter\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"description\": \"The seed project for the AI Coder: a host shell that composes feature modules. Fresh projects start here with zero modules; the developer/agent plugs modules into src/modules.ts.\",\n \"scripts\": {\n \"dev\": \"vite\",\n \"build\": \"vite build\",\n \"preview\": \"vite preview\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"//\": \"Versions are pinned exactly: this is a seed for AI Coder projects, which build offline against a dependency allowlist baked at these versions (see scripts/pack-builder.mjs). Modules bring their own engine deps (three/phaser) when added.\",\n \"dependencies\": {\n \"@idosgames/app-shell\": \"0.1.7\",\n \"@idosgames/core\": \"0.2.0\",\n \"@idosgames/module-sdk\": \"0.1.3\",\n \"@idosgames/react\": \"0.1.1\",\n \"@idosgames/wallet\": \"0.1.13\",\n \"@tanstack/react-query\": \"5.101.2\",\n \"react\": \"19.2.7\",\n \"react-dom\": \"19.2.7\",\n \"wagmi\": \"3.7.2\"\n },\n \"devDependencies\": {\n \"@types/react\": \"19.2.17\",\n \"@types/react-dom\": \"19.2.3\",\n \"@vitejs/plugin-react\": \"6.0.4\",\n \"typescript\": \"5.9.3\",\n \"vite\": \"8.1.5\"\n }\n}\n"
15
15
  },
16
16
  {
17
17
  "path": "src/config.ts",
@@ -23,27 +23,35 @@
23
23
  },
24
24
  {
25
25
  "path": "src/idos.title.ts",
26
- "content": "// The project's IDENTITY file — the ONE centralized place the Title id lives.\n//\n// On platform-created projects the platform GENERATES this file when it creates the project; there\n// the AI editor is denied write access to this path on purpose — do not edit it by hand. On a\n// manually scaffolded project (get_host_scaffold / copied template) there is no generator: YOU fill\n// IDOS_TITLE_ID here yourself. Either way, do not import anything into this file, and do not bind\n// the title anywhere else (.env.local is a local-dev fallback for the raw template only).\n//\n// It is the highest-priority source of the Title id (see config.ts for the full chain). It is baked\n// into the bundle rather than read from the URL because a build has to keep working where there is\n// no URL to read — packaged as a mobile app, embedded in an iframe, or opened from a shared link\n// that dropped its query string.\n//\n// It holds the CANONICAL (production) title. The DEV title is derived from it, never stored here —\n// one project has one identity, and DEV/PROD is an environment on top of that identity.\n\n/** Canonical (production) Title id. Empty only in the raw template, before the platform seeds it. */\nexport const IDOS_TITLE_ID = \"\";\n\n/** Build key for this title, if the title enforces one. */\nexport const IDOS_BUILD_KEY = \"\";\n\n/** Environment this artifact defaults to. Web builds may override it (see config.ts); a packaged\n * mobile build cannot, so a DEV app is produced by generating this file with \"dev\". */\nexport const IDOS_DEFAULT_ENV: \"prod\" | \"dev\" = \"prod\";\n\n/**\n * Whether this title was created as web3. Set by the platform from the same toggle the publisher\n * used at title creation.\n *\n * It is baked here rather than read from the title's blockchain config because the login screen\n * needs it BEFORE there is a session, and `client.title.getTitlePublicConfiguration()` requires one.\n * LoginScreen.tsx uses it only as the default for which providers to offer that list is ordinary\n * editable code, so a title that goes web3 later just gets the wallet button added there.\n */\nexport const IDOS_WEB3 = false;\n\n/**\n * NetworkID the wallet login challenge is issued for (e.g. \"bsc\", \"base\", \"solana\"). Empty on\n * web2 titles. Baked for the same reason as everything else here: the login screen needs it before\n * there is a session, and the title's blockchain config is only readable once logged in.\n */\nexport const IDOS_WEB3_NETWORK_ID = \"\";\n"
26
+ "content": "// The project's IDENTITY file — the ONE centralized place the Title id lives.\n//\n// On platform-created projects the platform GENERATES this file when it creates the project; there\n// the AI editor is denied write access to this path on purpose — do not edit it by hand. On a\n// manually scaffolded project (get_host_scaffold / copied template) there is no generator: YOU fill\n// IDOS_TITLE_ID here yourself. Either way, do not import anything into this file, and do not bind\n// the title anywhere else (.env.local is a local-dev fallback for the raw template only).\n//\n// It is the highest-priority source of the Title id (see config.ts for the full chain). It is baked\n// into the bundle rather than read from the URL because a build has to keep working where there is\n// no URL to read — packaged as a mobile app, embedded in an iframe, or opened from a shared link\n// that dropped its query string.\n//\n// It holds the CANONICAL (production) title. The DEV title is derived from it, never stored here —\n// one project has one identity, and DEV/PROD is an environment on top of that identity.\n\n/** Canonical (production) Title id. Empty only in the raw template, before the platform seeds it. */\nexport const IDOS_TITLE_ID = \"\";\n\n/** Build key for this title, if the title enforces one. */\nexport const IDOS_BUILD_KEY = \"\";\n\n/** Environment this artifact defaults to. Web builds may override it (see config.ts); a packaged\n * mobile build cannot, so a DEV app is produced by generating this file with \"dev\". */\nexport const IDOS_DEFAULT_ENV: \"prod\" | \"dev\" = \"prod\";\n\n/**\n * Whether this title was created as web3. Set by the platform from the same toggle the publisher\n * used at title creation.\n *\n * It no longer gates the login screen wallet sign-in is always offered (see walletLogin.tsx).\n * Kept as baked metadata for code that wants to know the title's web3 origin BEFORE there is a\n * session (`client.title.getTitlePublicConfiguration()` requires one).\n */\nexport const IDOS_WEB3 = false;\n\n/**\n * NetworkID the wallet login challenge is issued for (e.g. \"bsc\", \"base\", \"solana\"). Empty on\n * web2 titles. Baked for the same reason as everything else here: the login screen needs it before\n * there is a session, and the title's blockchain config is only readable once logged in.\n */\nexport const IDOS_WEB3_NETWORK_ID = \"\";\n\n/**\n * WalletConnect Cloud / Reown project id (dashboard.reown.com). Enables MOBILE wallet login via\n * WalletConnect (QR on desktop, deep-link on phones); without it only browser-extension wallets\n * are offered and mobile login is unavailable. Set per-title in the blockchain config\n * (Blockchain.WalletLogin.WalletConnectProjectId) — the platform bakes it here. Baked, not read at\n * runtime, for the same reason as IDOS_WEB3_NETWORK_ID: the login screen runs before there is a\n * session, and the title's blockchain config is only readable once logged in.\n */\nexport const IDOS_WEB3_WALLETCONNECT_PROJECT_ID = \"\";\n"
27
27
  },
28
28
  {
29
29
  "path": "src/LoginScreen.tsx",
30
- "content": "import { useState, type CSSProperties, type ReactNode } from \"react\";\nimport type { LoginScreenProps } from \"@idosgames/app-shell\";\nimport { ENV_GOOGLE_CLIENT_ID } from \"./env\";\nimport { IDOS_WEB3 } from \"./idos.title\";\n\n// The Login scene. The host runtime owns WHEN this is shown (the auth gate in\n// @idosgames/app-shell); this file owns what it LOOKS like and which providers it offers.\n// Edit freely — branding, layout, copy, buttons.\n//\n// Providers on `client.auth`: loginWithDeviceID (guest), loginWithEmail + registerWithEmail,\n// loginWithGoogle, loginWithTelegram, loginWithWallet, loginWithPlatformToken, plus resetPassword.\n//\n// A provider is only rendered when it can actually complete, so players never meet a dead button:\n// guest / email — always available, no external setup.\n// Google — needs VITE_IDOS_GOOGLE_CLIENT_ID and the Google Identity script on the page.\n// wallet — needs the connector; pass `renderWalletLogin` from main.tsx (see below).\n\nexport interface LoginScreenExtras {\n /**\n * Wallet sign-in, supplied by the project when it has the connector installed.\n *\n * Wiring it: add `@idosgames/wallet` to package.json, then render a button that connects the\n * wallet (wagmi) and calls `loginWithWalletEvm({ client, clients, networkID })` from\n * `@idosgames/wallet` — it runs requestWalletChallenge → personal_sign → loginWithWallet and\n * logs the client in. Call `onAuthenticated()` when it resolves ok.\n *\n * Note: a wallet session is never restored silently (a fresh signature is required on every\n * launch), so keep at least one other provider for players who want to come straight back in.\n */\n renderWalletLogin?: (props: {\n client: LoginScreenProps[\"client\"];\n onAuthenticated: () => void;\n disabled: boolean;\n }) => ReactNode;\n}\n\ntype Mode = \"menu\" | \"email\";\n\n/** Minimal Google Identity surface — declared here so the template needs no @types/google.accounts. */\ntype GoogleIdentity = {\n accounts: {\n id: {\n initialize(config: {\n client_id: string;\n callback: (response: { credential?: string }) => void;\n }): void;\n prompt(): void;\n };\n };\n};\n\nexport function LoginScreen({\n client,\n onAuthenticated,\n renderWalletLogin,\n}: LoginScreenProps & LoginScreenExtras): ReactNode {\n const [mode, setMode] = useState<Mode>(\"menu\");\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const [email, setEmail] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [registering, setRegistering] = useState(false);\n\n const [remember, setRemember] = useState(true);\n\n /** Every provider goes through here, so one place owns the busy flag and the error surface. */\n const run = async (\n login: () => Promise<{ ok: boolean; error?: string }>,\n ): Promise<void> => {\n setBusy(true);\n setError(null);\n // \"Remember me\" is read when the login completes, so set it before starting one. Off = this\n // session works normally but is not written to storage, so the next launch lands here again.\n client.auth.setRememberSession(remember);\n const result = await login();\n if (result.ok) {\n onAuthenticated();\n return;\n }\n setError(result.error ?? \"Sign-in failed. Please try again.\");\n setBusy(false);\n };\n\n const signInWithGoogle = (): void => {\n const google = (globalThis as { google?: GoogleIdentity }).google;\n if (!google) {\n setError(\n \"Google sign-in is unavailable: the Google Identity script did not load.\",\n );\n return;\n }\n setError(null);\n google.accounts.id.initialize({\n client_id: ENV_GOOGLE_CLIENT_ID,\n callback: (response) => {\n if (!response.credential) {\n setError(\"Google sign-in was cancelled.\");\n return;\n }\n void run(() => client.auth.loginWithGoogle(response.credential ?? \"\"));\n },\n });\n google.accounts.id.prompt();\n };\n\n return (\n <div style={styles.root}>\n <div style={styles.card}>\n <h1 style={styles.title}>Sign in</h1>\n\n {mode === \"menu\" && (\n <div style={styles.stack}>\n {IDOS_WEB3 &&\n renderWalletLogin?.({ client, onAuthenticated, disabled: busy })}\n\n {ENV_GOOGLE_CLIENT_ID && (\n <button\n type=\"button\"\n style={styles.button}\n onClick={signInWithGoogle}\n disabled={busy}\n >\n Continue with Google\n </button>\n )}\n\n <button\n type=\"button\"\n style={styles.button}\n onClick={() => setMode(\"email\")}\n disabled={busy}\n >\n Continue with email\n </button>\n\n <button\n type=\"button\"\n style={styles.ghost}\n onClick={() => void run(() => client.auth.loginWithDeviceID())}\n disabled={busy}\n >\n {busy ? \"Signing in…\" : \"Play as guest\"}\n </button>\n </div>\n )}\n\n {mode === \"email\" && (\n <div style={styles.stack}>\n <input\n style={styles.input}\n type=\"email\"\n placeholder=\"Email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n disabled={busy}\n autoFocus\n />\n <input\n style={styles.input}\n type=\"password\"\n placeholder=\"Password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n disabled={busy}\n />\n <button\n type=\"button\"\n style={{ ...styles.button, ...styles.primary }}\n onClick={() =>\n void run(() =>\n registering\n ? client.auth.registerWithEmail(email, password)\n : client.auth.loginWithEmail(email, password),\n )\n }\n disabled={busy || !email || !password}\n >\n {busy\n ? \"Please wait…\"\n : registering\n ? \"Create account\"\n : \"Sign in\"}\n </button>\n <button\n type=\"button\"\n style={styles.ghost}\n onClick={() => setRegistering((v) => !v)}\n disabled={busy}\n >\n {registering ? \"I already have an account\" : \"Create an account\"}\n </button>\n <button\n type=\"button\"\n style={styles.ghost}\n onClick={() => {\n setMode(\"menu\");\n setError(null);\n }}\n disabled={busy}\n >\n Back\n </button>\n </div>\n )}\n\n {/* Applies to every provider above. A wallet sign-in ignores it — those are never\n restored silently, a fresh signature is required on each launch. */}\n <label style={{ ...styles.remember, opacity: busy ? 0.6 : 1 }}>\n <input\n type=\"checkbox\"\n checked={remember}\n disabled={busy}\n onChange={(e) => setRemember(e.target.checked)}\n />\n Remember me\n </label>\n\n {error && <p style={styles.error}>{error}</p>}\n </div>\n </div>\n );\n}\n\nconst styles: Record<string, CSSProperties> = {\n root: {\n position: \"absolute\",\n inset: 0,\n display: \"grid\",\n placeItems: \"center\",\n background: \"#0c0a18\",\n color: \"#e8e6f3\",\n font: \"14px system-ui, sans-serif\",\n },\n card: { width: \"min(340px, 88vw)\", display: \"grid\", gap: \"18px\" },\n remember: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n justifySelf: \"center\",\n cursor: \"pointer\",\n color: \"#a9a4c7\",\n },\n title: { margin: 0, fontSize: \"22px\", fontWeight: 600, textAlign: \"center\" },\n stack: { display: \"grid\", gap: \"10px\" },\n button: {\n padding: \"11px 16px\",\n borderRadius: \"8px\",\n border: \"1px solid #4c4470\",\n background: \"#221d3d\",\n color: \"inherit\",\n font: \"inherit\",\n cursor: \"pointer\",\n },\n primary: { background: \"#4c3fa8\", borderColor: \"#6152c7\" },\n ghost: {\n padding: \"8px\",\n border: \"none\",\n background: \"none\",\n color: \"#a49dc8\",\n font: \"inherit\",\n cursor: \"pointer\",\n },\n input: {\n padding: \"11px 12px\",\n borderRadius: \"8px\",\n border: \"1px solid #3a3358\",\n background: \"#15122a\",\n color: \"inherit\",\n font: \"inherit\",\n },\n error: { margin: 0, color: \"#ff9b9b\", textAlign: \"center\" },\n};\n"
30
+ "content": "import { useState, type CSSProperties, type ReactNode } from \"react\";\nimport type { LoginScreenProps } from \"@idosgames/app-shell\";\nimport { ENV_GOOGLE_CLIENT_ID } from \"./env\";\nimport { LOGO_DATA_URL } from \"./logo\";\n\n// The Login scene. The host runtime owns WHEN this is shown (the auth gate in\n// @idosgames/app-shell); this file owns what it LOOKS like and which providers it offers.\n// Edit freely — branding, layout, copy, buttons.\n//\n// Providers on `client.auth`: loginWithDeviceID (guest), loginWithEmail + registerWithEmail,\n// loginWithGoogle, loginWithTelegram, loginWithWallet, loginWithPlatformToken, plus resetPassword.\n//\n// A provider is only rendered when it can actually complete, so players never meet a dead button:\n// guest / email — always available, no external setup.\n// Google — needs VITE_IDOS_GOOGLE_CLIENT_ID and the Google Identity script on the page.\n// wallet — always offered; ./walletLogin owns the wagmi config and the challenge network.\n\nexport interface LoginScreenExtras {\n /**\n * Wallet sign-in. Supplied by ./walletLogin (wired in main.tsx), which renders the ready-made\n * `WalletLogin` from `@idosgames/wallet/react`: connect → sign the challenge → session, then\n * `onAuthenticated()`. The screen passes its own `style` so the button matches the theme.\n *\n * Note: a wallet session is never restored silently (a fresh signature is required on every\n * launch), so keep at least one other provider for players who want to come straight back in.\n */\n renderWalletLogin?: (props: {\n client: LoginScreenProps[\"client\"];\n onAuthenticated: () => void;\n disabled: boolean;\n style?: CSSProperties;\n }) => ReactNode;\n}\n\ntype Mode = \"menu\" | \"email\";\n\n/** Minimal Google Identity surface — declared here so the template needs no @types/google.accounts. */\ntype GoogleIdentity = {\n accounts: {\n id: {\n initialize(config: {\n client_id: string;\n callback: (response: { credential?: string }) => void;\n }): void;\n prompt(): void;\n };\n };\n};\n\nexport function LoginScreen({\n client,\n onAuthenticated,\n renderWalletLogin,\n}: LoginScreenProps & LoginScreenExtras): ReactNode {\n const [mode, setMode] = useState<Mode>(\"menu\");\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const [email, setEmail] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [registering, setRegistering] = useState(false);\n\n const [remember, setRemember] = useState(true);\n\n /** Every provider goes through here, so one place owns the busy flag and the error surface. */\n const run = async (\n login: () => Promise<{ ok: boolean; error?: string }>,\n ): Promise<void> => {\n setBusy(true);\n setError(null);\n // \"Remember me\" is read when the login completes, so set it before starting one. Off = this\n // session works normally but is not written to storage, so the next launch lands here again.\n client.auth.setRememberSession(remember);\n const result = await login();\n if (result.ok) {\n onAuthenticated();\n return;\n }\n setError(result.error ?? \"Sign-in failed. Please try again.\");\n setBusy(false);\n };\n\n const signInWithGoogle = (): void => {\n const google = (globalThis as { google?: GoogleIdentity }).google;\n if (!google) {\n setError(\n \"Google sign-in is unavailable: the Google Identity script did not load.\",\n );\n return;\n }\n setError(null);\n google.accounts.id.initialize({\n client_id: ENV_GOOGLE_CLIENT_ID,\n callback: (response) => {\n if (!response.credential) {\n setError(\"Google sign-in was cancelled.\");\n return;\n }\n void run(() => client.auth.loginWithGoogle(response.credential ?? \"\"));\n },\n });\n google.accounts.id.prompt();\n };\n\n return (\n <div style={styles.root}>\n {/* Placeholder color is a pseudo-element, unreachable from inline styles — this one rule is\n the whole reason for the style tag. */}\n <style>{`.idos-input::placeholder { color: rgba(255, 255, 255, 0.65); }`}</style>\n <div style={styles.card}>\n <img src={LOGO_DATA_URL} alt=\"iDos Games\" style={styles.logo} />\n <h1 style={styles.title}>Sign in</h1>\n\n {mode === \"menu\" && (\n <div style={styles.stack}>\n {renderWalletLogin?.({\n client,\n onAuthenticated,\n disabled: busy,\n style: { ...styles.button, ...styles.primary },\n })}\n\n {ENV_GOOGLE_CLIENT_ID && (\n <button\n type=\"button\"\n style={styles.button}\n onClick={signInWithGoogle}\n disabled={busy}\n >\n Continue with Google\n </button>\n )}\n\n <button\n type=\"button\"\n style={styles.button}\n onClick={() => setMode(\"email\")}\n disabled={busy}\n >\n Continue with email\n </button>\n\n <button\n type=\"button\"\n style={styles.ghost}\n onClick={() => void run(() => client.auth.loginWithDeviceID())}\n disabled={busy}\n >\n {busy ? \"Signing in…\" : \"Play as guest\"}\n </button>\n </div>\n )}\n\n {mode === \"email\" && (\n <div style={styles.stack}>\n <input\n className=\"idos-input\"\n style={styles.input}\n type=\"email\"\n placeholder=\"Email\"\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n disabled={busy}\n autoFocus\n />\n <input\n className=\"idos-input\"\n style={styles.input}\n type=\"password\"\n placeholder=\"Password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n disabled={busy}\n />\n <button\n type=\"button\"\n style={{ ...styles.button, ...styles.primary }}\n onClick={() =>\n void run(() =>\n registering\n ? client.auth.registerWithEmail(email, password)\n : client.auth.loginWithEmail(email, password),\n )\n }\n disabled={busy || !email || !password}\n >\n {busy\n ? \"Please wait…\"\n : registering\n ? \"Create account\"\n : \"Sign in\"}\n </button>\n <button\n type=\"button\"\n style={styles.ghost}\n onClick={() => setRegistering((v) => !v)}\n disabled={busy}\n >\n {registering ? \"I already have an account\" : \"Create an account\"}\n </button>\n <button\n type=\"button\"\n style={styles.ghost}\n onClick={() => {\n setMode(\"menu\");\n setError(null);\n }}\n disabled={busy}\n >\n Back\n </button>\n </div>\n )}\n\n {/* Applies to every provider above. A wallet sign-in ignores it — those are never\n restored silently, a fresh signature is required on each launch. */}\n <label style={{ ...styles.remember, opacity: busy ? 0.6 : 1 }}>\n <input\n type=\"checkbox\"\n checked={remember}\n disabled={busy}\n onChange={(e) => setRemember(e.target.checked)}\n style={styles.switchInput}\n />\n <span\n style={{\n ...styles.switchTrack,\n background: remember ? \"#fff\" : \"rgba(255, 255, 255, 0.3)\",\n }}\n >\n <span\n style={{\n ...styles.switchKnob,\n left: remember ? \"21px\" : \"3px\",\n background: remember ? \"#0d66fe\" : \"#fff\",\n }}\n />\n </span>\n Remember me\n </label>\n\n {error && <p style={styles.error}>{error}</p>}\n </div>\n </div>\n );\n}\n\n// Brand look: iDos Games blue with the white logo; controls are translucent white on top of it,\n// the primary action is solid white with blue text.\nconst styles: Record<string, CSSProperties> = {\n root: {\n position: \"absolute\",\n inset: 0,\n display: \"grid\",\n placeItems: \"center\",\n background: \"#0d66fe\",\n color: \"#fff\",\n font: \"14px system-ui, sans-serif\",\n },\n card: { width: \"min(340px, 88vw)\", display: \"grid\", gap: \"18px\" },\n logo: {\n width: \"180px\",\n justifySelf: \"center\",\n userSelect: \"none\",\n pointerEvents: \"none\",\n },\n remember: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n justifySelf: \"center\",\n cursor: \"pointer\",\n color: \"rgba(255, 255, 255, 0.85)\",\n },\n // The switch: a hidden real checkbox (keyboard/a11y) with a drawn track + knob on top.\n switchInput: { position: \"absolute\", opacity: 0, width: 0, height: 0 },\n switchTrack: {\n position: \"relative\",\n width: \"42px\",\n height: \"24px\",\n borderRadius: \"12px\",\n transition: \"background 0.15s\",\n flexShrink: 0,\n },\n switchKnob: {\n position: \"absolute\",\n top: \"3px\",\n width: \"18px\",\n height: \"18px\",\n borderRadius: \"50%\",\n transition: \"left 0.15s, background 0.15s\",\n },\n title: { margin: 0, fontSize: \"22px\", fontWeight: 600, textAlign: \"center\" },\n stack: { display: \"grid\", gap: \"10px\" },\n button: {\n padding: \"11px 16px\",\n borderRadius: \"8px\",\n border: \"1px solid rgba(255, 255, 255, 0.4)\",\n background: \"rgba(255, 255, 255, 0.14)\",\n color: \"inherit\",\n font: \"inherit\",\n cursor: \"pointer\",\n },\n primary: {\n background: \"#fff\",\n borderColor: \"#fff\",\n color: \"#0d66fe\",\n fontWeight: 600,\n },\n ghost: {\n padding: \"8px\",\n border: \"none\",\n background: \"none\",\n color: \"rgba(255, 255, 255, 0.85)\",\n font: \"inherit\",\n cursor: \"pointer\",\n },\n input: {\n padding: \"11px 12px\",\n borderRadius: \"8px\",\n border: \"1px solid rgba(255, 255, 255, 0.35)\",\n background: \"rgba(255, 255, 255, 0.12)\",\n color: \"inherit\",\n font: \"inherit\",\n },\n error: { margin: 0, color: \"#ffd7d7\", textAlign: \"center\" },\n};\n"
31
+ },
32
+ {
33
+ "path": "src/logo.ts",
34
+ "content": "// The iDos Games logo (white), inlined as an SVG data-URI so it needs no asset pipeline: it\n// survives the template seed (text files only) and builds identically under real vite and the\n// classic preview bundler. Swap the string to rebrand.\n//\n// Composition mirrors the original brand mark: the spartan helmet on top, \"iDOS GAMES\" in one\n// line below it. The three path groups are the untouched brand-source paths (helmet / iDOS /\n// GAMES), positioned with transforms.\n\nconst LOGO_SVG = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 860 690\" fill=\"#fff\"><g transform=\"translate(243 -2)\"><path d=\"M147.333 12.333c-13.6 2.534-12.533 1.2-12.933 15.067l-.4 12.267-4.533-11.067c-2.534-6-5.067-10.933-5.734-10.933-2.666 0-27.866 8.666-36.533 12.666-11.733 5.334-26.667 14.8-36.133 22.934l-6.934 5.866L51.6 69.267c8.133 11.066 7.333 11.466-5.067 2.933-7.6-5.067-8.4-5.333-11.466-3.733-3.467 1.866-18.4 17.333-20.4 21.2-.8 1.6 7.066 8.8 33.733 30.933l34.667 28.933 8.8-8.266c14.666-13.867 28.666-22 48.133-28.267 9.067-2.933 14.8-3.733 28.533-4.4 34.267-1.333 60 7.467 81.6 28.133 21.6 20.4 34.934 49.6 37.467 81.734l.8 11.2 14.8 4.533c8.133 2.533 23.733 7.333 34.667 10.8 10.933 3.333 20.4 5.6 21.066 4.933 1.6-1.6 6.134-20.533 7.734-32.666.8-6 1.333-17.6 1.066-25.6l-.4-14.667-8-1.067c-4.4-.533-10.133-1.466-12.666-1.866l-4.667-.8 4.667-1.2c16.933-4.534 18.666-5.2 18.666-8 0-5.467-9.6-31.334-16.666-44.8-4-7.6-10.667-18.667-14.934-24.667-9.866-13.867-31.333-35.467-45.2-45.2-10.4-7.467-34.4-20.933-37.2-21.067-.8 0-4 4-7.333 8.8-3.2 4.8-6.133 8.134-6.4 7.334s.4-5.6 1.6-10.667c1.2-5.2 2.133-9.6 2.133-9.867 0-.933-19.866-6.133-34.4-9.066-14.8-2.934-49.333-4.4-59.6-2.534\"/><path d=\"M157.867 125.533c-21.067 3.334-42.134 14.8-57.467 31.334-13.333 14.133-13.733 12.8 5.6 22 9.2 4.4 16.667 8.266 16.667 8.533s-1.334.4-2.934.133c-13.866-2.133-41.6-5.866-41.733-5.6-.267.267-7.467 28.534-16.267 63.067l-16 62.667 7.334.4c4 .266 7.466.266 7.6 0 .266-.267 3.866-13.867 8.133-30.4 4.267-16.534 8.267-30.8 8.933-31.734.934-1.2 11.067-1.6 42.4-1.6 32.134 0 41.2.4 41.2 1.6 0 .934-1.733 4.667-3.866 8.4L153.733 261l-35.066 6.933c-19.334 3.867-35.2 7.2-35.467 7.467-.667.667-29.867 113.467-29.467 113.867.267.133 23.734-3.6 52.4-8.534l52-8.8 20.4-39.866c11.2-22 20.667-39.734 20.934-39.467.4.533-1.334 26.8-2.8 40.8l-.667 6.933 6.267-3.2c21.2-10.666 52.4-13.466 86.933-8l5.867.934-5.6-7.334C286.4 318.6 281.2 310.6 278 304.867c-5.867-10.134-6-10.8-6-21.867 0-6.267 1.467-20 3.333-30.667 1.867-10.666 3.334-19.466 3.334-19.466 0-.134-9.067-4.267-20.134-9.334s-19.466-9.333-18.8-9.6c.8-.266 7.734.8 15.6 2.267 7.734 1.6 14.4 2.8 14.8 2.8 1.2 0 .4-10.533-1.466-18-7.2-27.733-28-53.467-53.734-66-16.4-8-40.8-12-57.066-9.467\"/><path d=\"M235.6 346.333c-24 4.534-44.133 13.867-68.267 31.467-14 10.267-28.533 18.133-47.733 25.867-23.467 9.466-52.8 32.666-64.4 50.666l-2.533 4L58 454.2c9.333-7.333 30.133-19.467 49.333-28.667C173.733 393.667 246.4 382.2 312.8 393c11.2 1.733 39.2 8.533 45.067 10.8 2.266.8 2.266.667.8-2.267-4-7.6-15.6-21.866-25.867-31.466-12-11.467-24.667-18.934-37.6-22.4-11.467-3.067-46.267-3.867-59.6-1.334\"/></g><g transform=\"translate(-460 467)\"><path d=\"M721.533 34.467c-14.933 5.466-22 17.466-22.933 38.666-.933 24.134 3.467 32.8 30.267 59.867 19.6 19.867 22.933 25.2 22.933 37.867.133 13.466-6.133 20.133-16.933 18.4-9.067-1.467-12.534-7.867-12.534-22.667V159H696.6l.667 13.333c.533 11.467 1.2 14.4 4.933 22 7.067 14.267 16.8 19.6 36.4 19.734 10.667.133 12.267-.134 20.667-4.4 7.6-3.867 9.733-5.867 13.2-11.734 7.6-12.533 9.066-32 3.733-47.6-3.733-11.066-10.667-20.4-27.867-37.2-19.866-19.6-22.533-24.133-22.666-38.4 0-8.933.4-10.533 3.2-13.6 6.266-6.666 18.266-5.6 22.133 2 1.067 2 2 7.067 2 11.2v7.334h27.067l-.934-9.2c-1.6-18.267-8.266-30.267-20-36.4-7.2-3.867-29.2-4.8-37.6-1.6M630.067 34.867c-11.734 4.666-18 11.6-21.734 24.4-1.866 6.4-2 15.333-1.733 67.2l.4 59.866 3.733 7.6c6.8 13.867 18.534 20.267 36.934 20.267 13.733 0 22.933-3.333 30.666-11.067 10.934-11.066 11.2-12.533 11.734-74.666.266-35.734-.134-56.934-1.067-62.8-2.667-16.134-11.6-27.467-24.8-31.467-8.933-2.667-26.4-2.267-34.133.667m28.666 26.8 3.6 4v56.666c0 40.934-.4 57.467-1.6 60-3.6 8-15.6 9.734-22.666 3.467l-4.4-3.867-.4-56.533c-.267-51.733-.134-56.8 2-61.067 3.066-5.866 7.6-8.266 14.4-7.466 3.733.4 6.4 1.866 9.066 4.8M511.667 123.133v89.334l29.066-.4c28.8-.4 28.934-.4 36.667-4.267 9.467-4.533 14.4-10.933 17.467-22.4 2-7.333 2.266-15.467 1.866-65.733l-.4-57.334-4.266-8.8c-8.267-16.666-17.2-19.866-55.334-19.866h-25.066zm53.6-60.266 4.4 3.866.4 52.8c.266 35.067-.134 54.4-1.067 58-2 7.467-5.733 9.6-18.667 10.4l-10.666.8V59h10.666c9.867 0 10.934.267 14.934 3.867M471.667 145v67.333h26.666V77.667h-26.666zM471.667 48.333V63h26.666V33.667h-26.666z\"/></g><g transform=\"translate(-106 244)\"><path d=\"M893.4 259.733c-6.8 3.467-9.2 5.6-12.667 11.467-10.666 17.733-9.2 42.933 3.467 62.267 2.8 4.266 12.267 14.8 20.933 23.333 9.867 9.467 17.067 17.733 18.934 21.6 5.6 11.333 5.2 25.333-.934 30.8-3.466 3.067-11.333 4.133-16.133 2.133-5.867-2.4-8-7.466-8-19.333v-10h-27.067l.8 11.6c1.2 15.867 3.867 24.133 10.267 31.333 7.467 8.534 16.4 12.134 30 12.267 19.067.133 30.133-5.733 37.333-19.867 3.734-7.466 4-8.666 4-24 0-16 0-16.133-5.2-26.666-4.4-9.2-7.733-13.2-23.066-28.534-21.067-21.066-24.8-27.066-24.934-40.4-.133-10.4 2.8-15.6 9.734-17.6 10.133-2.933 17.2 3.334 18.4 16.267l.8 8.267H955.4l-.8-10.8c-.533-8.4-1.6-12.667-4.8-19.2-7.067-14.134-16.667-19.334-36.133-19.334-10.667 0-12.534.4-20.267 4.4M791 346v89.333h76v-24h-48v-54.666h37.333v-24H819V282h48v-25.333h-76zM661.667 346v89.333h22.666l.134-63.066c0-34.534.533-61.734 1.066-60.267.534 1.467 5.467 29.867 10.8 62.933l9.867 60.4h13.067c7.2 0 13.066-.4 13.066-1.066 0-3.067 18.8-124.8 19.334-125.334.4-.4.666 27.867.666 62.8v63.6h25.334V256.667h-38l-9.2 61.6c-5.067 34-9.6 62.133-10 62.666-.534.534-5.334-26.4-10.667-60-5.467-33.466-10.133-61.733-10.533-62.666-.4-1.2-5.467-1.6-19.067-1.6h-18.533zM586.467 258.267c-.8 2.666-27.467 172.4-27.467 174.933 0 1.867 1.733 2.133 12 2.133h11.867l.8-4.4c.533-2.266 1.6-9.333 2.4-15.6l1.6-11.333 17.6-.4 17.466-.4 1.467 8.4c.8 4.667 1.733 11.867 2.267 16l.933 7.733h13.733c7.6 0 13.867-.266 13.867-.666 0-.8-26.533-168.134-27.467-173.734l-.8-4.266h-19.866c-14.8 0-20.134.4-20.4 1.6M613 336.533c3.333 23.067 5.867 42.134 5.6 42.4-.4.267-6.533.267-13.867.134l-13.2-.4 4.934-33.334c2.8-18.4 5.733-38.4 6.666-44.666C604.2 292.533 605 290.133 605.8 292c.533 1.467 3.867 21.467 7.2 44.533M497.267 257.2c-10.134 3.733-15.2 8.267-19.867 17.733L473 284l-.4 59.067c-.4 51.2-.133 60.133 1.733 66.533 5.6 19.333 17.067 27.333 39.467 27.467 10.267.133 12.267-.267 20.133-4.134 9.334-4.533 13.867-9.733 17.867-20.266 2-4.934 2.4-12 2.933-41.067l.534-34.933h-38.934v23.866l6.4.4 6.267.4v19.334c0 13.466-.533 20.666-1.867 23.733-5.066 12-23.333 10.4-26.8-2.4-.933-3.6-1.333-23.2-1.066-59.067.4-48.533.666-54.133 2.666-57.333 3.334-4.8 11.2-7.067 17.6-4.933 6.934 2.266 9.067 7.2 9.867 22.933l.667 13.067H555.4l-.8-15.734c-.8-18-3.067-25.6-9.867-33.466-7.466-8.8-13.466-11.2-29.066-11.734-9.067-.266-14.934.134-18.4 1.467\"/></g></svg>`;\n\n/** White iDos Games logo (helmet over wordmark) as an `<img src>`-ready data-URI. */\nexport const LOGO_DATA_URL = `data:image/svg+xml;utf8,${encodeURIComponent(LOGO_SVG)}`;\n"
31
35
  },
32
36
  {
33
37
  "path": "src/main.tsx",
34
- "content": "import { createIDosGamesClient } from \"@idosgames/core\";\nimport { mountHost } from \"@idosgames/app-shell\";\nimport { modules } from \"./modules\";\nimport { LoginScreen } from \"./LoginScreen\";\nimport { renderWalletLogin } from \"./walletLogin\";\nimport { TITLE_ID, BUILD_KEY } from \"./config\";\nimport { IS_DEV } from \"./env\";\n\nconst app = document.getElementById(\"app\");\nif (!app) throw new Error(\"#app container not found\");\n\n// Always runs against the real backend (https://api.idosgames.com) via the global fetch.\nconst client = createIDosGamesClient({\n titleID: TITLE_ID,\n buildKey: BUILD_KEY.length > 0 ? BUILD_KEY : undefined,\n throttleMs: 0,\n});\n\nclient.on(\"error:global\", (message) => {\n console.error(\"[idos] global error:\", message);\n});\nclient.on(\"error:connection\", (message) => {\n console.error(\"[idos] connection error:\", message);\n});\n\nif (IS_DEV) {\n (\n globalThis as typeof globalThis & { idosClient?: typeof client }\n ).idosClient = client;\n}\n\n// The host owns sign-in: mountHost replays the previous session (autoLogin) and, when there is\n// none, renders the login screen. Do NOT log in here — that would skip the screen, and with it the\n// player's ability to pick a provider or switch accounts.\n//\n// Wallet sign-in comes from ./walletLogin — a no-op on web2 titles, the real button on web3 ones.\nmountHost({\n container: app,\n client,\n modules,\n renderLogin: (props) => (\n <LoginScreen {...props} renderWalletLogin={renderWalletLogin} />\n ),\n});\n"
38
+ "content": "// ПЕРВЫЙ импорт сознательно: зонд превью ставит перехват console/ошибок при загрузке своего\n// модуля, и всё, что упадёт ниже по старту (включая config.ts на нераспознанном тайтле), уже\n// попадёт в его лог — а значит доедет до AI-кодера. Вне превью не делает ничего.\nimport { installPreviewProbe } from \"./previewProbe\";\nimport { createIDosGamesClient } from \"@idosgames/core\";\nimport { mountHost } from \"@idosgames/app-shell\";\nimport { modules } from \"./modules\";\nimport { LoginScreen } from \"./LoginScreen\";\nimport { renderWalletLogin } from \"./walletLogin\";\nimport { TITLE_ID, BUILD_KEY } from \"./config\";\nimport { IS_DEV } from \"./env\";\n\n// Тайтл зонду — отдельным вызовом: сам он встал раньше, чем config.ts успел его разрешить.\ninstallPreviewProbe({ titleId: TITLE_ID });\n\nconst app = document.getElementById(\"app\");\nif (!app) throw new Error(\"#app container not found\");\n\n// Always runs against the real backend (https://api.idosgames.com) via the global fetch.\nconst client = createIDosGamesClient({\n titleID: TITLE_ID,\n buildKey: BUILD_KEY.length > 0 ? BUILD_KEY : undefined,\n throttleMs: 0,\n});\n\nclient.on(\"error:global\", (message) => {\n console.error(\"[idos] global error:\", message);\n});\nclient.on(\"error:connection\", (message) => {\n console.error(\"[idos] connection error:\", message);\n});\n\nif (IS_DEV) {\n (\n globalThis as typeof globalThis & { idosClient?: typeof client }\n ).idosClient = client;\n}\n\n// The host owns sign-in: mountHost replays the previous session (autoLogin) and, when there is\n// none, renders the login screen. Do NOT log in here — that would skip the screen, and with it the\n// player's ability to pick a provider or switch accounts.\n//\n// Wallet sign-in comes from ./walletLogin — always offered; that file owns the wagmi config and\n// the challenge network.\nmountHost({\n container: app,\n client,\n modules,\n renderLogin: (props) => (\n <LoginScreen {...props} renderWalletLogin={renderWalletLogin} />\n ),\n});\n"
35
39
  },
36
40
  {
37
41
  "path": "src/modules.ts",
38
42
  "content": "import type { Module } from \"@idosgames/module-sdk\";\n\n// The list of feature modules this project composes. A fresh project starts empty and shows the\n// host's \"no modules\" state. Add a module by copying it into src/modules/<id>/ and registering it\n// here — the AI Coder seeder appends to this array, and you can also edit it by hand.\n//\n// Example, after copying a module into src/modules/board-game/:\n// import { boardGameModule } from \"./modules/board-game\";\n// export const modules: Module[] = [boardGameModule];\nexport const modules: Module[] = [];\n"
39
43
  },
44
+ {
45
+ "path": "src/previewProbe.ts",
46
+ "content": "// Зонд превью: даёт AI-кодеру ГЛАЗА на работающее приложение.\n//\n// Живёт ВНУТРИ iframe с игрой, потому что иначе никак: превью грузится с домена бандлера, и\n// родительская страница (дашборд) по правилам браузера в его DOM залезть не может — единственная\n// щель между ними это postMessage. Зонд эту щель и обслуживает: сериализует DOM в компактное\n// дерево, копит console/сеть и умеет кликать по элементам, найденным в прошлом readPage.\n//\n// Отдельный слой — АВТОМАТИЧЕСКОЕ наблюдение за отрисованной игрой (см. ниже): полотна, кадры,\n// three.js, цвет экрана. Он работает без всякого участия игры и именно поэтому нужен: контракт\n// `exposeToAgent` даёт больше, но его кто-то должен написать, а произвольной игре не напишет никто.\n//\n// ДВА ИНВАРИАНТА, которые нельзя нарушать:\n//\n// 1. Зонд молчит, пока с ним не поздоровались с РАЗРЕШЁННОГО origin. Публичный сайт\n// idosgames.com тоже встраивает игры в iframe — там hello никто не пришлёт, и весь этот код\n// останется мёртвым. Ответ всегда уходит на event.origin, никогда на \"*\".\n// 2. Никакого `import.meta` и прочего, на чём падает классический бандлер превью (см. env.ts):\n// детект среды — только рантаймовый.\n//\n// Подключается ПЕРВОЙ строкой main.tsx: тогда перехват console/ошибок стоит раньше, чем всё\n// остальное успевает упасть, и агент увидит причину падения старта, а не пустоту.\n\n/** Метка протокола: всё, что без неё, зонда не касается. */\nconst WIRE = \"idos-preview-probe/1\";\n\n/** Кто имеет право разговаривать с зондом. Всё остальное игнорируется молча. */\nconst ALLOWED_ORIGIN_HOSTS = [\"platform.idosgames.com\"];\n\n/** Сколько записей console храним. Ring buffer: старое вытесняется. */\nconst CONSOLE_LIMIT = 100;\n\n/** Сколько сетевых вызовов храним. */\nconst NETWORK_LIMIT = 50;\n\n/** Потолок дерева: узлов, глубины и символов. Держит снапшот в разумных токенах. */\nconst MAX_NODES = 400;\nconst MAX_DEPTH = 15;\nconst MAX_TREE_CHARS = 8000;\n\n/** Обрезка текста узла — модели хватает начала, а полный текст раздувает снапшот. */\nconst MAX_TEXT = 80;\n\n/** Однотипных детей печатаем не больше этого, остальные схлопываем в «… +N more». */\nconst MAX_SIBLINGS = 12;\n\n/** Пауза после клика/ввода перед новым снимком: даём React дорисовать. */\nconst SETTLE_MS = 350;\n\n/** Кольцо отметок кадров — по нему считается fps. Хватает на несколько секунд при 60 fps. */\nconst FRAME_RING = 240;\n\n/** Сетка чтения пикселей: 6×6 = 36 точек. Каждая точка — отдельный синхронный readPixels. */\nconst PIXEL_GRID = 6;\n\n/** Сколько ждём кадр перед чтением пикселей. Не дождались — это и есть ответ: петля не идёт. */\nconst FRAME_WAIT_MS = 200;\n\n/** Потолок удержания синтетической клавиши: агент не должен уметь «зажать W» на минуту. */\nconst MAX_INPUT_HOLD_MS = 3000;\n\ntype ProbeRequest = {\n wire: typeof WIRE;\n id: string;\n cmd: string;\n args?: Record<string, unknown>;\n};\n\ntype ConsoleEntry = { level: string; text: string; at: number };\ntype NetworkEntry = {\n method: string;\n url: string;\n status: number | string;\n ms: number;\n at: number;\n};\n\nexport type PreviewProbeOptions = {\n /** Тайтл, против которого работает приложение — агенту важно видеть DEV это или PROD. */\n titleId?: string;\n};\n\n/**\n * Debug-поверхности модулей (см. `ctx.exposeToAgent` в @idosgames/module-sdk). Их выкладывает в\n * глобал host-shell; для отрисованных игр это ЕДИНСТВЕННЫЙ способ что-то узнать — у Three/Phaser\n * весь интерфейс это один `<canvas>`, и дерево DOM про него не расскажет ничего.\n */\ntype AgentModuleApi = {\n state?: () => unknown;\n actions?: Record<\n string,\n (args?: Record<string, unknown>) => unknown | Promise<unknown>\n >;\n describeActions?: Record<string, string>;\n};\n\n/** Состояние платформы, которое выкладывает host-shell (см. `publishHostState` в app-shell). */\ntype AgentHostState = {\n screen?: string;\n loggedIn?: boolean;\n userId?: string | null;\n titleId?: string | null;\n modules?: string[];\n};\n\ntype AgentGlobal = {\n version?: number;\n modules?: Record<string, AgentModuleApi>;\n host?: AgentHostState;\n};\n\nfunction agentGlobal(): AgentGlobal | undefined {\n return (globalThis as typeof globalThis & { __IDOS_AGENT__?: AgentGlobal })\n .__IDOS_AGENT__;\n}\n\nfunction agentModules(): Record<string, AgentModuleApi> {\n return agentGlobal()?.modules ?? {};\n}\n\nconst consoleLog: ConsoleEntry[] = [];\nconst networkLog: NetworkEntry[] = [];\n\n/** Элементы последнего снимка: клик адресуется по ref_N отсюда. */\nlet refs = new Map<string, Element>();\n\nlet installed = false;\nlet probeOptions: PreviewProbeOptions = {};\n\n/* ------------------------------------------------------------------ утилиты */\n\nfunction push<T>(buf: T[], entry: T, limit: number): void {\n buf.push(entry);\n if (buf.length > limit) buf.shift();\n}\n\nfunction clip(text: string, max: number): string {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length > max ? `${flat.slice(0, max)}…` : flat;\n}\n\n/** Безопасная печать аргумента console: объекты в JSON, циклы и геттеры-бомбы не роняют зонд. */\nfunction stringifyArg(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value instanceof Error) return `${value.name}: ${value.message}`;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAllowedOrigin(origin: string): boolean {\n try {\n const url = new URL(origin);\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\")\n return true;\n return ALLOWED_ORIGIN_HOSTS.includes(url.hostname);\n } catch {\n return false;\n }\n}\n\n/* -------------------------------------------------------- сбор console/сети */\n\nfunction captureConsole(): void {\n const levels = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n for (const level of levels) {\n const original = console[level].bind(console);\n console[level] = (...args: unknown[]): void => {\n push(\n consoleLog,\n {\n level,\n text: clip(args.map(stringifyArg).join(\" \"), 300),\n at: Date.now(),\n },\n CONSOLE_LIMIT,\n );\n original(...args);\n };\n }\n\n window.addEventListener(\"error\", (event) => {\n const where = event.filename\n ? ` (${event.filename}:${event.lineno}:${event.colno})`\n : \"\";\n push(\n consoleLog,\n {\n level: \"error\",\n text: clip(`Uncaught ${event.message}${where}`, 300),\n at: Date.now(),\n },\n CONSOLE_LIMIT,\n );\n });\n\n window.addEventListener(\"unhandledrejection\", (event) => {\n push(\n consoleLog,\n {\n level: \"error\",\n text: clip(`Unhandled rejection: ${stringifyArg(event.reason)}`, 300),\n at: Date.now(),\n },\n CONSOLE_LIMIT,\n );\n });\n}\n\nfunction captureNetwork(): void {\n const originalFetch = window.fetch.bind(window);\n window.fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const started = Date.now();\n const url =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n const method = (\n init?.method ??\n (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\") ??\n \"GET\"\n ).toUpperCase();\n\n // Заголовки и тела НЕ пишем сознательно: в них сидит Bearer-тикет игрока, а лог уезжает в LLM.\n try {\n const response = await originalFetch(input, init);\n push(\n networkLog,\n {\n method,\n url: clip(url, 200),\n status: response.status,\n ms: Date.now() - started,\n at: started,\n },\n NETWORK_LIMIT,\n );\n return response;\n } catch (error: unknown) {\n push(\n networkLog,\n {\n method,\n url: clip(url, 200),\n status: `failed: ${stringifyArg(error)}`,\n ms: Date.now() - started,\n at: started,\n },\n NETWORK_LIMIT,\n );\n throw error;\n }\n };\n}\n\n/* ------------------------------------------ автоматический слой наблюдения */\n\n// Всё, что ниже, работает БЕЗ какой-либо кооперации со стороны игры — в этом весь смысл.\n// Контракт `exposeToAgent` даёт данные лучше, но его должен кто-то НАПИСАТЬ, а произвольной (и тем\n// более будущей) игре его не напишет никто. Поэтому зонд снимает сам всё, что можно снять с движка\n// и с полотна: есть ли WebGL-контекст, идут ли кадры, сколько draw-вызовов, что говорит three.js о\n// сцене и камере, и не залит ли кадр одним цветом.\n//\n// Скриншотов здесь нет и не будет (решение владельца): наружу уходят ТОЛЬКО числа. Зато число\n// «все 36 проб одного цвета #ffffff» ловит белый экран не хуже картинки.\n\n/** Настоящий rAF, снятый ДО перехвата: им зонд ждёт кадр, не накручивая собственный счётчик. */\nconst rawRaf: ((cb: FrameRequestCallback) => number) | null =\n typeof window !== \"undefined\" &&\n typeof window.requestAnimationFrame === \"function\"\n ? window.requestAnimationFrame.bind(window)\n : null;\n\ntype CanvasRecord = {\n canvas: HTMLCanvasElement;\n /** Как контекст запрашивали: \"2d\" | \"webgl\" | \"webgl2\" | \"webgpu\" | … */\n kind: string;\n gl: WebGLRenderingContext | WebGL2RenderingContext | null;\n ctx2d: CanvasRenderingContext2D | null;\n /** Отметки «кадр отрисован» (clear/clearRect) — по ним считается настоящий fps. */\n frames: number;\n /** Вызовы отрисовки: у Three/Phaser их десятки-сотни за кадр. */\n draws: number;\n lastDrawAt: number;\n};\n\n/** Сколько полотен помним. Больше игре и не нужно, а временные canvas'ы иначе растут без конца. */\nconst MAX_CANVAS_RECORDS = 24;\n\nconst canvasRecords: CanvasRecord[] = [];\n\n/** Отметки кадров: по полотну (надёжнее) и по rAF (петля жива, даже если ничего не рисуется). */\nconst glFrameTimes: number[] = [];\nconst rafFrameTimes: number[] = [];\n\nfunction markFrame(ring: number[]): void {\n ring.push(Date.now());\n if (ring.length > FRAME_RING) ring.shift();\n}\n\n/** Сколько отметок пришлось на последнюю секунду. Это и есть fps — без усреднения по сессии. */\nfunction perSecond(ring: number[]): number {\n const cutoff = Date.now() - 1000;\n let count = 0;\n for (let i = ring.length - 1; i >= 0; i--) {\n if ((ring[i] ?? 0) < cutoff) break;\n count++;\n }\n return count;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\"\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction num(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\n/**\n * Подменить метод объекта счётчиком. Пишем в САМ объект, а не в прототип: у WebGL-контекста метод\n * лежит на прототипе, и собственное свойство просто перекрывает его для этого экземпляра — чужие\n * контексты (и чужие вкладки) остаются нетронутыми.\n */\nfunction countCalls(target: unknown, name: string, tick: () => void): void {\n const holder = target as Record<string, unknown> | null;\n if (!holder) return;\n const current = holder[name];\n if (typeof current !== \"function\") return;\n const original = current as (...args: unknown[]) => unknown;\n holder[name] = function (this: unknown, ...args: unknown[]): unknown {\n try {\n tick();\n } catch {\n /* счётчик не имеет права ломать отрисовку */\n }\n return original.apply(this, args);\n };\n}\n\n/** Инструментовка полотна: кадры отдельно, вызовы отрисовки отдельно. */\nfunction instrument(rec: CanvasRecord): void {\n const frame = (): void => {\n rec.frames++;\n rec.lastDrawAt = Date.now();\n // В общий счётчик fps идут только полотна НА СТРАНИЦЕ: временные canvas'ы, на которых движки\n // рисуют текстуры и текст, чистятся так же часто и накрутили бы «кадры» на пустом месте.\n if (rec.canvas.isConnected) markFrame(glFrameTimes);\n };\n const draw = (): void => {\n rec.draws++;\n };\n\n if (rec.gl) {\n // clear зовут один раз за кадр практически все движки — он и служит границей кадра.\n countCalls(rec.gl, \"clear\", frame);\n for (const method of [\n \"drawArrays\",\n \"drawElements\",\n \"drawArraysInstanced\",\n \"drawElementsInstanced\",\n ]) {\n countCalls(rec.gl, method, draw);\n }\n return;\n }\n\n if (rec.ctx2d) {\n countCalls(rec.ctx2d, \"clearRect\", frame);\n for (const method of [\n \"drawImage\",\n \"fillRect\",\n \"fill\",\n \"stroke\",\n \"fillText\",\n ]) {\n countCalls(rec.ctx2d, method, draw);\n }\n }\n}\n\nfunction registerContext(\n canvas: HTMLCanvasElement,\n kind: string,\n ctx: unknown,\n): void {\n // Повторный getContext возвращает тот же объект — второй раз инструментовать нельзя.\n if (canvasRecords.some((rec) => rec.canvas === canvas && rec.kind === kind))\n return;\n\n // Потолок списка обязателен: движки создают временные полотна пачками (текстуры из текста,\n // атласы), и без него зонд держал бы ссылку на каждое — утечка памяти плюс линейный поиск,\n // который растёт с каждым кадром. Первыми уходят полотна, которых уже нет на странице.\n if (canvasRecords.length >= MAX_CANVAS_RECORDS) {\n for (let i = canvasRecords.length - 1; i >= 0; i--) {\n if (!canvasRecords[i]?.canvas.isConnected) canvasRecords.splice(i, 1);\n }\n while (canvasRecords.length >= MAX_CANVAS_RECORDS) canvasRecords.shift();\n }\n\n const isGl =\n kind === \"webgl\" || kind === \"webgl2\" || kind === \"experimental-webgl\";\n const rec: CanvasRecord = {\n canvas,\n kind,\n gl: isGl ? (ctx as WebGLRenderingContext | WebGL2RenderingContext) : null,\n ctx2d: kind === \"2d\" ? (ctx as CanvasRenderingContext2D) : null,\n frames: 0,\n draws: 0,\n lastDrawAt: 0,\n };\n canvasRecords.push(rec);\n instrument(rec);\n}\n\n/**\n * Перехват `getContext`. Ставится ДО импорта движка (зонд — первый импорт main.tsx), поэтому ни\n * одно полотно мимо не проходит, чем бы игра ни рисовала: Three, Phaser, Pixi, сырой WebGL, 2d.\n *\n * Заодно ТОЛЬКО В ПРЕВЬЮ навязывается `preserveDrawingBuffer: true`. По умолчанию содержимое\n * WebGL-буфера действительно лишь до композитинга кадра, и снаружи кадра оттуда читается пустота —\n * то есть статичная сцена, которая рисуется один раз, выглядела бы «чёрным экраном». С флагом\n * последний нарисованный кадр остаётся читаемым в любой момент. Цена — небольшая потеря\n * производительности, и платит её только вкладка с превью: в собранной игре зонда нет.\n */\nfunction captureCanvases(): void {\n type GetContext = (\n this: HTMLCanvasElement,\n id: string,\n options?: unknown,\n ) => unknown;\n\n const proto = HTMLCanvasElement.prototype;\n const original = proto.getContext as unknown as GetContext;\n\n const patched: GetContext = function (this: HTMLCanvasElement, id, options) {\n let effective = options;\n try {\n const kind = String(id);\n if (\n kind === \"webgl\" ||\n kind === \"webgl2\" ||\n kind === \"experimental-webgl\"\n ) {\n // Копия, а не правка чужого объекта: игра могла передать свой конфиг и переиспользовать его.\n effective = {\n ...(asRecord(options) ?? {}),\n preserveDrawingBuffer: true,\n };\n }\n } catch {\n effective = options;\n }\n\n const ctx = original.call(this, id, effective);\n try {\n if (ctx) registerContext(this, String(id), ctx);\n } catch {\n /* наблюдение не имеет права мешать игре получить контекст */\n }\n return ctx;\n };\n\n proto.getContext = patched as unknown as typeof proto.getContext;\n}\n\n/** Перехват rAF: показывает, что цикл приложения вообще крутится, даже если полотна нет. */\nfunction captureFrames(): void {\n if (!rawRaf) return;\n window.requestAnimationFrame = (callback: FrameRequestCallback): number =>\n rawRaf((time) => {\n markFrame(rafFrameTimes);\n callback(time);\n });\n}\n\n/* ---------------------------------------------------------------- three.js */\n\nconst three: {\n renderer: Record<string, unknown> | null;\n scene: Record<string, unknown> | null;\n camera: Record<string, unknown> | null;\n scenes: number;\n} = { renderer: null, scene: null, camera: null, scenes: 0 };\n\n/**\n * Канал, по которому three.js сам представляется наблюдателю.\n *\n * `WebGLRenderer` и `Scene` в своих конструкторах проверяют глобал `__THREE_DEVTOOLS__` и, если он\n * есть, шлют в него событие `observe` со ссылкой на себя. Задуман он для расширения-девтулзов, но\n * это ровно то, что нужно здесь: никакой правки игры, а на выходе живой рендерер со счётчиками.\n * Глобал обязан существовать ДО создания рендерера — отсюда установка при импорте зонда.\n */\nfunction captureThree(): void {\n const holder = globalThis as typeof globalThis & {\n __THREE_DEVTOOLS__?: EventTarget;\n };\n\n // Если глобал уже кто-то поставил (расширение three-devtools) — подписываемся, а не затираем.\n const target: EventTarget = holder.__THREE_DEVTOOLS__ ?? new EventTarget();\n holder.__THREE_DEVTOOLS__ = target;\n\n target.addEventListener(\"observe\", (event: Event) => {\n try {\n const detail = asRecord((event as CustomEvent<unknown>).detail);\n if (!detail) return;\n\n if (detail[\"isScene\"] === true) {\n three.scenes++;\n three.scene ??= detail;\n return;\n }\n\n // Рендерер узнаём по паре info + domElement: это его, и только его, поверхность.\n if (detail[\"info\"] && detail[\"domElement\"]) {\n three.renderer = detail;\n watchRender(detail);\n }\n } catch {\n /* чужой объект не обязан быть таким, как мы ждём */\n }\n });\n}\n\n/**\n * Подмена `renderer.render(scene, camera)`: это единственный способ узнать, какие сцену и камеру\n * игра рисует ПРЯМО СЕЙЧАС. Событие `observe` про камеру не рассказывает вообще, а сцен у игры\n * может быть несколько (меню, мир, миникарта).\n */\nfunction watchRender(renderer: Record<string, unknown>): void {\n if (renderer[\"__idosProbeWatched\"] === true) return;\n const original = renderer[\"render\"];\n if (typeof original !== \"function\") return;\n\n renderer[\"__idosProbeWatched\"] = true;\n const call = original as (...args: unknown[]) => unknown;\n renderer[\"render\"] = function (this: unknown, ...args: unknown[]): unknown {\n const scene = asRecord(args[0]);\n const camera = asRecord(args[1]);\n if (scene) three.scene = scene;\n if (camera) three.camera = camera;\n return call.apply(this, args);\n };\n}\n\nfunction threeSnapshot(): Record<string, unknown> | null {\n if (!three.renderer && !three.scene) return null;\n const out: Record<string, unknown> = {};\n\n const info = asRecord(three.renderer?.[\"info\"]);\n const render = asRecord(info?.[\"render\"]);\n const memory = asRecord(info?.[\"memory\"]);\n if (render) {\n // `calls` у WebGLRenderer, `drawCalls` у WebGPURenderer — представляются они одинаково.\n out[\"drawCalls\"] = num(render[\"calls\"]) ?? num(render[\"drawCalls\"]);\n out[\"triangles\"] = num(render[\"triangles\"]);\n out[\"lines\"] = num(render[\"lines\"]);\n out[\"points\"] = num(render[\"points\"]);\n out[\"framesRendered\"] = num(render[\"frame\"]);\n }\n if (memory) {\n out[\"geometries\"] = num(memory[\"geometries\"]);\n out[\"textures\"] = num(memory[\"textures\"]);\n }\n\n const scene = three.scene;\n const traverse = scene?.[\"traverse\"];\n if (scene && typeof traverse === \"function\") {\n let total = 0;\n let meshes = 0;\n let lights = 0;\n let hidden = 0;\n try {\n (traverse as (cb: (obj: unknown) => void) => void).call(\n scene,\n (obj: unknown) => {\n if (total > 20000) return; // защита от сцены-монстра: считаем, но не вечно\n total++;\n const node = asRecord(obj);\n if (!node) return;\n if (node[\"isMesh\"] === true) meshes++;\n if (node[\"isLight\"] === true) lights++;\n if (node[\"visible\"] === false) hidden++;\n },\n );\n out[\"scene\"] = {\n name: typeof scene[\"name\"] === \"string\" ? scene[\"name\"] : null,\n objects: total,\n meshes,\n lights,\n hidden,\n scenesCreated: three.scenes,\n };\n } catch {\n out[\"scene\"] = { error: \"scene.traverse failed\" };\n }\n }\n\n // Позиция и направление камеры — прямо из мировой матрицы: третий столбец это её «взгляд»\n // (с минусом — камера в three смотрит вдоль -Z). Так не нужен импорт three ради Vector3.\n const elements = asRecord(three.camera?.[\"matrixWorld\"])?.[\"elements\"] as\n ArrayLike<number> | undefined;\n if (elements && elements.length >= 16) {\n const dx = -(elements[8] ?? 0);\n const dy = -(elements[9] ?? 0);\n const dz = -(elements[10] ?? 0);\n const len = Math.hypot(dx, dy, dz) || 1;\n out[\"camera\"] = {\n pos: {\n x: round(elements[12] ?? 0),\n y: round(elements[13] ?? 0),\n z: round(elements[14] ?? 0),\n },\n lookDir: {\n x: round(dx / len),\n y: round(dy / len),\n z: round(dz / len),\n },\n fov: num(three.camera?.[\"fov\"]),\n };\n }\n\n return out;\n}\n\nfunction round(value: number, digits = 2): number {\n const k = 10 ** digits;\n return Math.round(value * k) / k;\n}\n\n/* ------------------------------------------------------------------- Pixi */\n\nconst pixi: {\n app: Record<string, unknown> | null;\n renderer: Record<string, unknown> | null;\n version: string | null;\n} = { app: null, renderer: null, version: null };\n\n/**\n * Канал, по которому PixiJS сам представляется наблюдателю — точный аналог `__THREE_DEVTOOLS__`.\n *\n * Pixi 8 при инициализации зовёт `globalThis.__PIXI_APP_INIT__(app, VERSION)`, а его рендерер —\n * `__PIXI_RENDERER_INIT__(renderer, VERSION)` (см. `utils/global/globalHooks`). Хуки задуманы для\n * расширения-девтулзов, и это ровно то, что нужно: игру править не надо, а на выходе живые\n * Application и Renderer. Ставить их обязательно ДО инициализации Pixi — отсюда установка при\n * импорте зонда.\n *\n * Оба хука ставятся не «вместо», а «поверх»: прежний (расширение браузера) вызывается следом.\n */\nfunction capturePixi(): void {\n type Hook = (target: unknown, version?: string) => void;\n const holder = globalThis as typeof globalThis & {\n __PIXI_APP_INIT__?: Hook;\n __PIXI_RENDERER_INIT__?: Hook;\n };\n\n const previousApp = holder.__PIXI_APP_INIT__;\n holder.__PIXI_APP_INIT__ = (app: unknown, version?: string): void => {\n try {\n pixi.app = asRecord(app);\n pixi.version = version ?? pixi.version;\n } catch {\n /* чужой объект не обязан быть таким, как мы ждём */\n }\n previousApp?.(app, version);\n };\n\n const previousRenderer = holder.__PIXI_RENDERER_INIT__;\n holder.__PIXI_RENDERER_INIT__ = (\n renderer: unknown,\n version?: string,\n ): void => {\n try {\n pixi.renderer = asRecord(renderer);\n pixi.version = version ?? pixi.version;\n } catch {\n /* см. выше */\n }\n previousRenderer?.(renderer, version);\n };\n}\n\n/** Обход дерева отображения Pixi: у него нет `traverse`, только `children`. */\nfunction countPixiTree(root: Record<string, unknown>): Record<string, unknown> {\n let total = 0;\n let hidden = 0;\n let depth = 0;\n\n const walk = (node: Record<string, unknown>, level: number): void => {\n if (total > 20000) return; // потолок как у three: считаем, но не вечно\n total++;\n if (node[\"visible\"] === false || node[\"renderable\"] === false) hidden++;\n if (level > depth) depth = level;\n\n const children = node[\"children\"];\n if (!Array.isArray(children)) return;\n for (const child of children) {\n const record = asRecord(child);\n if (record) walk(record, level + 1);\n }\n };\n\n walk(root, 0);\n // Сам корень объектом сцены не считаем — интересно, что В нём.\n return { objects: Math.max(total - 1, 0), hidden, depth };\n}\n\nfunction pixiSnapshot(): Record<string, unknown> | null {\n const app = pixi.app;\n const renderer = pixi.renderer ?? asRecord(app?.[\"renderer\"]);\n if (!app && !renderer) return null;\n\n const out: Record<string, unknown> = { version: pixi.version };\n\n if (renderer) {\n const type = renderer[\"type\"];\n out[\"renderer\"] = {\n // `name` у Pixi 8 это \"webgl\"/\"webgpu\"; `type` — числовой флаг того же самого.\n backend:\n typeof renderer[\"name\"] === \"string\"\n ? renderer[\"name\"]\n : (num(type) ?? null),\n width: num(renderer[\"width\"]),\n height: num(renderer[\"height\"]),\n resolution: num(renderer[\"resolution\"]),\n };\n }\n\n const ticker = asRecord(app?.[\"ticker\"]);\n if (ticker) {\n const fps = num(ticker[\"FPS\"]);\n out[\"ticker\"] = {\n fps: fps === null ? null : round(fps, 1),\n started: ticker[\"started\"] ?? null,\n };\n }\n\n const stage = asRecord(app?.[\"stage\"]);\n if (stage) {\n const tree = countPixiTree(stage);\n out[\"stage\"] = {\n ...tree,\n label:\n typeof stage[\"label\"] === \"string\"\n ? stage[\"label\"]\n : typeof stage[\"name\"] === \"string\"\n ? stage[\"name\"]\n : null,\n };\n }\n\n return out;\n}\n\n/* ----------------------------------------------------------------- Phaser */\n\n/**\n * У Phaser канала самопредставления НЕТ — и это проверено, а не предположено: `Game.boot` пишет\n * `window.PHASER_GAME = this` только под флагом `WEBGL_DEBUG`, а из готовых сборок\n * (`dist/phaser.esm.js`, которые и ставит npm) эта ветка вырезана целиком.\n *\n * Поэтому игру приходится ИСКАТЬ, а не ждать. Два источника, оба без кооперации игры:\n * 1. `window.PHASER_GAME` — есть в отладочных сборках и в превью, если бандлер взял `main`\n * (у Phaser это исходники, а не dist);\n * 2. скан собственных ключей `window` на сигнатуру `Phaser.Game`.\n *\n * Поиск ленивый (только при сборке снимка) и с кэшем: перебирать глобалы каждый кадр незачем.\n */\n// Кэшируется ИМЯ глобала, а не сам объект: игру можно пересоздать (host-shell перемонтирует сцену\n// при смене режима), и ссылка на прежнюю осталась бы живой в памяти — зонд честно показывал бы\n// уничтоженную игру. Перечитывание по ключу всегда отдаёт текущую.\nlet phaserKey: string | null = null;\n\nfunction looksLikePhaserGame(value: unknown): boolean {\n const game = asRecord(value);\n if (!game) return false;\n return (\n typeof game[\"isBooted\"] === \"boolean\" &&\n asRecord(game[\"scene\"]) !== null &&\n Array.isArray(asRecord(game[\"scene\"])?.[\"scenes\"]) &&\n asRecord(game[\"loop\"]) !== null\n );\n}\n\nfunction findPhaserGame(): Record<string, unknown> | null {\n const holder = globalThis as typeof globalThis & Record<string, unknown>;\n\n const at = (key: string): Record<string, unknown> | null => {\n try {\n return looksLikePhaserGame(holder[key]) ? asRecord(holder[key]) : null;\n } catch {\n // Чтение чужого свойства window может бросить (кросс-доменный фрейм) — не наша забота.\n return null;\n }\n };\n\n if (phaserKey) {\n const cached = at(phaserKey);\n if (cached) return cached;\n phaserKey = null;\n }\n\n for (const key of [\"PHASER_GAME\", ...Object.keys(holder)]) {\n const found = at(key);\n if (found) {\n phaserKey = key;\n return found;\n }\n }\n return null;\n}\n\nfunction phaserSnapshot(): Record<string, unknown> | null {\n const game = findPhaserGame();\n if (!game) return null;\n\n const out: Record<string, unknown> = {\n booted: game[\"isBooted\"] ?? null,\n running: game[\"isRunning\"] ?? null,\n };\n\n const fps = num(asRecord(game[\"loop\"])?.[\"actualFps\"]);\n if (fps !== null) out[\"fps\"] = round(fps, 1);\n\n const renderer = asRecord(game[\"renderer\"]);\n if (renderer) {\n // У Phaser `type` — числовая константа: 1 = CANVAS, 2 = WEBGL.\n const type = num(renderer[\"type\"]);\n out[\"renderer\"] = {\n backend: type === 2 ? \"webgl\" : type === 1 ? \"canvas\" : (type ?? null),\n width: num(renderer[\"width\"]),\n height: num(renderer[\"height\"]),\n };\n }\n\n const scenes = asRecord(game[\"scene\"])?.[\"scenes\"];\n if (Array.isArray(scenes)) {\n const list: Record<string, unknown>[] = [];\n for (const raw of scenes.slice(0, 12)) {\n const sys = asRecord(asRecord(raw)?.[\"sys\"]);\n const settings = asRecord(sys?.[\"settings\"]);\n const displayList = asRecord(sys?.[\"displayList\"]);\n const camera = asRecord(asRecord(sys?.[\"cameras\"])?.[\"main\"]);\n\n const entry: Record<string, unknown> = {\n key: settings?.[\"key\"] ?? null,\n active: settings?.[\"active\"] ?? null,\n visible: settings?.[\"visible\"] ?? null,\n objects: Array.isArray(displayList?.[\"list\"])\n ? (displayList[\"list\"] as unknown[]).length\n : null,\n };\n if (camera) {\n entry[\"camera\"] = {\n scrollX: round(num(camera[\"scrollX\"]) ?? 0),\n scrollY: round(num(camera[\"scrollY\"]) ?? 0),\n zoom: round(num(camera[\"zoom\"]) ?? 1),\n };\n }\n list.push(entry);\n }\n out[\"scenes\"] = list;\n // «Активная» сцена — та, что реально обновляется: по ней и судят, что происходит на экране.\n out[\"activeScenes\"] = list.filter((s) => s[\"active\"] === true).length;\n }\n\n return out;\n}\n\n/* ------------------------------------------------------------- пиксели */\n\nfunction hex(r: number, g: number, b: number): string {\n const part = (v: number): string => v.toString(16).padStart(2, \"0\");\n return `#${part(r)}${part(g)}${part(b)}`;\n}\n\n/**\n * Чтение редкой сетки пикселей — 36 точек вместо картинки: скриншотов здесь нет по решению\n * владельца, а «все 36 проб одного цвета» ловит белый экран ничуть не хуже.\n *\n * Читать можно в любой момент, потому что зонд принудительно включает `preserveDrawingBuffer`\n * (см. `captureCanvases`); без него содержимое буфера пропадало бы сразу после композитинга кадра.\n */\nfunction readGrid(rec: CanvasRecord): number[][] | null {\n const width = rec.canvas.width;\n const height = rec.canvas.height;\n if (width < 2 || height < 2) return null;\n\n const at = (i: number, size: number): number =>\n Math.min(size - 1, Math.floor(((i + 0.5) / PIXEL_GRID) * size));\n\n if (rec.gl) {\n const gl = rec.gl;\n if (gl.isContextLost()) return null;\n\n // Игра могла оставить привязанным свой render target — тогда мы прочли бы не экран. Снимаем\n // привязку на время чтения и возвращаем ровно ту, что была.\n const previous = gl.getParameter(\n gl.FRAMEBUFFER_BINDING,\n ) as WebGLFramebuffer | null;\n if (previous) gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n const pixel = new Uint8Array(4);\n const samples: number[][] = [];\n for (let iy = 0; iy < PIXEL_GRID; iy++) {\n for (let ix = 0; ix < PIXEL_GRID; ix++) {\n gl.readPixels(\n at(ix, width),\n at(iy, height),\n 1,\n 1,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n pixel,\n );\n samples.push([\n pixel[0] ?? 0,\n pixel[1] ?? 0,\n pixel[2] ?? 0,\n pixel[3] ?? 0,\n ]);\n }\n }\n\n if (previous) gl.bindFramebuffer(gl.FRAMEBUFFER, previous);\n return samples;\n }\n\n if (rec.ctx2d) {\n const samples: number[][] = [];\n for (let iy = 0; iy < PIXEL_GRID; iy++) {\n for (let ix = 0; ix < PIXEL_GRID; ix++) {\n const data = rec.ctx2d.getImageData(\n at(ix, width),\n at(iy, height),\n 1,\n 1,\n ).data;\n samples.push([data[0] ?? 0, data[1] ?? 0, data[2] ?? 0, data[3] ?? 0]);\n }\n }\n return samples;\n }\n\n return null;\n}\n\nfunction pixelStats(samples: number[][]): Record<string, unknown> {\n const colours = new Set<string>();\n let transparent = 0;\n let r = 0;\n let g = 0;\n let b = 0;\n\n for (const [pr, pg, pb, pa] of samples) {\n const alpha = pa ?? 0;\n if (alpha < 8) transparent++;\n r += pr ?? 0;\n g += pg ?? 0;\n b += pb ?? 0;\n colours.add(hex(pr ?? 0, pg ?? 0, pb ?? 0));\n }\n\n const n = samples.length || 1;\n const uniform = colours.size <= 1;\n const average = hex(Math.round(r / n), Math.round(g / n), Math.round(b / n));\n\n return {\n sampled: samples.length,\n distinctColours: colours.size,\n uniform,\n colour: uniform ? ([...colours][0] ?? null) : null,\n averageColour: average,\n transparentSamples: transparent,\n note: uniform\n ? `every sampled pixel is the same colour — the frame is a flat fill (a blank/white/black screen looks exactly like this)`\n : `${colours.size} distinct colours across ${samples.length} samples — something is actually drawn`,\n };\n}\n\n/** Прочитать сетку прямо сейчас, обернув всё, что может пойти не так, в ответ, а не в исключение. */\nfunction readNow(\n rec: CanvasRecord,\n extra: Record<string, unknown>,\n): Record<string, unknown> {\n try {\n const samples = readGrid(rec);\n return samples\n ? { ...pixelStats(samples), ...extra }\n : { sampled: 0, note: \"could not read pixels from this canvas\" };\n } catch (error: unknown) {\n return { sampled: 0, note: `pixel read failed: ${stringifyArg(error)}` };\n }\n}\n\n/**\n * Прочитать пиксели, по возможности — в кадре, где что-то нарисовано.\n *\n * Сначала ждём кадр с отрисовкой: у живой игры это самая свежая картинка. Не дождались — читаем всё\n * равно: буфер сохраняется принудительно (см. `captureCanvases`), поэтому там лежит ПОСЛЕДНИЙ\n * нарисованный кадр. Отдать в такой ситуации «ничего не вижу» было бы худшим из ответов: именно\n * когда петля встала, картинка нужнее всего.\n */\nfunction samplePixels(rec: CanvasRecord): Promise<Record<string, unknown>> {\n return new Promise((resolve) => {\n if (!rawRaf) {\n resolve(\n readNow(rec, {\n drewDuringSample: false,\n frameNote: \"read outside an animation frame\",\n }),\n );\n return;\n }\n\n let attempts = 0;\n let settled = false;\n const finish = (value: Record<string, unknown>): void => {\n if (settled) return;\n settled = true;\n window.clearTimeout(timer);\n resolve(value);\n };\n\n const timer = window.setTimeout(\n () =>\n finish(\n readNow(rec, {\n drewDuringSample: false,\n staleFrame: true,\n frameNote:\n `nothing was drawn within ${FRAME_WAIT_MS}ms, so this is the LAST frame the game ` +\n \"rendered, not a live one — the render loop is stopped, the scene only redraws on \" +\n \"demand, or the preview tab is in the background\",\n }),\n ),\n FRAME_WAIT_MS,\n );\n\n const tick = (): void => {\n if (settled) return;\n const before = rec.frames + rec.draws;\n rawRaf(() => {\n if (settled) return;\n const drew = rec.frames + rec.draws > before;\n attempts++;\n // Ещё один шанс поймать кадр с отрисовкой; на третьей попытке читаем как есть.\n if (!drew && attempts < 3) {\n tick();\n return;\n }\n finish(readNow(rec, { drewDuringSample: drew }));\n });\n };\n\n tick();\n });\n}\n\n/* --------------------------------------------------------- сборка снимка */\n\n/** Полотна документа, самое большое — первым: оно почти всегда и есть игра. */\nfunction canvasesByArea(): {\n el: HTMLCanvasElement;\n rec: CanvasRecord | null;\n}[] {\n const list = Array.from(document.querySelectorAll(\"canvas\")).map((el) => ({\n el,\n rec: canvasRecords.find((rec) => rec.canvas === el) ?? null,\n }));\n return list.sort(\n (a, b) => b.el.width * b.el.height - a.el.width * a.el.height,\n );\n}\n\nfunction describeCanvas(entry: {\n el: HTMLCanvasElement;\n rec: CanvasRecord | null;\n}): Record<string, unknown> {\n const rect = entry.el.getBoundingClientRect();\n const rec = entry.rec;\n return {\n context: rec?.kind ?? \"unknown (context created before the probe, or none)\",\n buffer: `${entry.el.width}x${entry.el.height}`,\n onScreen: `${Math.round(rect.width)}x${Math.round(rect.height)}`,\n visible: rect.width > 0 && rect.height > 0,\n framesDrawn: rec?.frames ?? null,\n drawCalls: rec?.draws ?? null,\n msSinceLastDraw:\n rec && rec.lastDrawAt > 0 ? Date.now() - rec.lastDrawAt : null,\n };\n}\n\nfunction platformState(): Record<string, unknown> {\n const host = agentGlobal()?.host;\n return {\n titleId: probeOptions.titleId ?? host?.titleId ?? null,\n url: window.location.href,\n // Экран хоста: loading | login | game. «Игрок не залогинен» — самая частая причина того, что\n // «игра не работает», и без этой строки агент ищет причину в коде игры.\n screen: host?.screen ?? \"unknown (host state not published)\",\n loggedIn: host?.loggedIn ?? null,\n userId: host?.userId ?? null,\n modulesInstalled: host?.modules ?? null,\n };\n}\n\n/**\n * Автоматический слой: что видно в приложении БЕЗ его участия.\n *\n * Возвращается всегда — и когда модули открылись агенту, и когда нет. Слепой тишины быть не должно:\n * даже у игры, о которой никто ничего не рассказал, есть полотно, кадры и цвет экрана.\n */\nasync function observeRuntime(options: {\n pixels: boolean;\n}): Promise<Record<string, unknown>> {\n const canvases = canvasesByArea();\n const main = canvases[0] ?? null;\n const notes: string[] = [];\n\n const glFps = perSecond(glFrameTimes);\n const rafFps = perSecond(rafFrameTimes);\n const rendering: Record<string, unknown> = {\n fps: glFps > 0 ? glFps : rafFps,\n fpsSource:\n glFps > 0 ? \"canvas clear() calls\" : \"requestAnimationFrame callbacks\",\n animationFramesPerSecond: rafFps,\n canvasFramesPerSecond: glFps,\n };\n\n // Движки опрашиваются ДО заметок про «ничего не анимируется»: их собственный счётчик кадров эту\n // заметку отменяет, и выдать обе разом значило бы противоречить самому себе в одном ответе.\n const threeInfo = threeSnapshot();\n const pixiInfo = pixiSnapshot();\n const phaserInfo = phaserSnapshot();\n\n // Кадры, о которых отчитывается САМ движок. Им веры больше, чем счётчику по полотну: движок не\n // обязан чистить буфер каждый кадр, и тогда наш счётчик занижает. Поймано вживую — Phaser\n // сообщал 60, а полотно давало 1.\n const engineFps =\n num(phaserInfo?.[\"fps\"]) ?? num(asRecord(pixiInfo?.[\"ticker\"])?.[\"fps\"]);\n const canvasFps = glFps > 0 ? glFps : rafFps;\n const engineRunning = engineFps !== null && engineFps > 5;\n if (engineFps !== null) rendering[\"engineFps\"] = engineFps;\n\n if (!main) {\n notes.push(\n \"No <canvas> in the document: this is a DOM app (or the game has not mounted its canvas yet). Read the page instead.\",\n );\n } else if (engineRunning && canvasFps <= 5) {\n notes.push(\n `The engine reports ${engineFps} fps while the canvas counter sees almost none. Trust the engine: the counter only sees frames that clear the buffer, and a page that has just rebuilt has not accumulated any yet. The game IS running.`,\n );\n } else if (rafFps === 0 && glFps === 0) {\n // Порядок причин здесь не случаен: пауза стоит ПЕРВОЙ, потому что она самая частая и самая\n // безобидная. Живой прогон показал именно её — игра ждала клика по полотну, а заметка звучала\n // как «петля мертва», то есть звала чинить исправное.\n notes.push(\n \"Nothing is animating: no animation frame ran in the last second. Most often the game is simply PAUSED and waiting for the player to click the canvas (a click via SendInput starts it — check the frames again after that). It is also normal for a scene that only redraws on demand. Only if neither applies is the render loop actually dead (an exception inside it, or it was never started) — the console says which.\",\n );\n }\n\n if (!threeInfo && !pixiInfo && !phaserInfo && main?.rec) {\n notes.push(\n \"A canvas is present but no engine identified itself: three.js and PixiJS announce themselves automatically, and Phaser is looked up in the page globals. So this is either another engine (Babylon, raw WebGL/2d), or Phaser that keeps its Game object out of reach. The canvas numbers above (fps, draw calls, pixels) still hold — only the scene/camera detail is missing.\",\n );\n }\n\n let pixels: Record<string, unknown> | null = null;\n if (options.pixels && main?.rec) {\n pixels = await samplePixels(main.rec);\n if (pixels[\"uniform\"] === true) {\n notes.push(\n \"The sampled frame is ONE flat colour. Together with a live fps that usually means the scene renders but nothing is in view (camera inside geometry, everything culled, materials/lights missing); with fps 0 it means nothing is being drawn at all.\",\n );\n }\n }\n\n return {\n platform: platformState(),\n canvas: main ? describeCanvas(main) : null,\n otherCanvases: canvases.length > 1 ? canvases.length - 1 : 0,\n rendering,\n three: threeInfo,\n pixi: pixiInfo,\n phaser: phaserInfo,\n pixels,\n notes,\n };\n}\n\n/** Однострочная выжимка автоматического слоя — она подмешивается в снимок страницы. */\nfunction summarize(observation: Record<string, unknown>): string {\n const parts: string[] = [];\n\n const canvas = asRecord(observation[\"canvas\"]);\n if (canvas)\n parts.push(\n `canvas ${String(canvas[\"buffer\"])} (${String(canvas[\"context\"])})`,\n );\n\n const rendering = asRecord(observation[\"rendering\"]);\n if (rendering) parts.push(`${String(rendering[\"fps\"])} fps`);\n\n const threeInfo = asRecord(observation[\"three\"]);\n if (threeInfo) {\n const scene = asRecord(threeInfo[\"scene\"]);\n if (scene)\n parts.push(`three.js scene: ${String(scene[\"objects\"])} objects`);\n if (threeInfo[\"drawCalls\"] !== null && threeInfo[\"drawCalls\"] !== undefined)\n parts.push(`${String(threeInfo[\"drawCalls\"])} draw calls`);\n }\n\n const pixiInfo = asRecord(observation[\"pixi\"]);\n const pixiStage = asRecord(pixiInfo?.[\"stage\"]);\n if (pixiStage)\n parts.push(`PixiJS stage: ${String(pixiStage[\"objects\"])} display objects`);\n\n const phaserInfo = asRecord(observation[\"phaser\"]);\n if (phaserInfo) {\n const scenes = phaserInfo[\"scenes\"];\n parts.push(\n `Phaser: ${String(phaserInfo[\"activeScenes\"] ?? 0)} active scene(s)` +\n (Array.isArray(scenes) ? ` of ${scenes.length}` : \"\"),\n );\n }\n\n const pixels = asRecord(observation[\"pixels\"]);\n if (pixels && num(pixels[\"sampled\"])) {\n parts.push(\n pixels[\"uniform\"] === true\n ? `the whole frame is ${String(pixels[\"colour\"])}`\n : `${String(pixels[\"distinctColours\"])} distinct colours on screen`,\n );\n }\n\n const platform = asRecord(observation[\"platform\"]);\n if (platform && platform[\"screen\"])\n parts.push(`host screen: ${String(platform[\"screen\"])}`);\n\n return parts.join(\", \");\n}\n\n/* ------------------------------------------------------ синтетический ввод */\n\n// Универсальные «руки» — для игр, которые НЕ описали свои действия через `exposeToAgent`.\n// Работает не всегда, и это честно сказано в ответе: движок, который гейтит ввод на Pointer Lock,\n// синтетические события игнорирует, а Pointer Lock в кросс-доменном iframe запрещён браузером.\n\nconst KEY_CODES: Record<string, number> = {\n Space: 32,\n Enter: 13,\n Escape: 27,\n Tab: 9,\n Backspace: 8,\n ArrowLeft: 37,\n ArrowUp: 38,\n ArrowRight: 39,\n ArrowDown: 40,\n ShiftLeft: 16,\n ShiftRight: 16,\n ControlLeft: 17,\n ControlRight: 17,\n};\n\n/** `key` по `code`: движки читают то одно, то другое, поэтому заполняем оба. */\nfunction keyFromCode(code: string): string {\n if (code.startsWith(\"Key\")) return code.slice(3).toLowerCase();\n if (code.startsWith(\"Digit\")) return code.slice(5);\n if (code === \"Space\") return \" \";\n if (code.startsWith(\"Shift\")) return \"Shift\";\n if (code.startsWith(\"Control\")) return \"Control\";\n if (code.startsWith(\"Alt\")) return \"Alt\";\n return code;\n}\n\nfunction legacyKeyCode(code: string): number {\n const known = KEY_CODES[code];\n if (known) return known;\n if (code.startsWith(\"Key\")) return code.charCodeAt(3);\n if (code.startsWith(\"Digit\")) return 48 + Number(code.slice(5));\n return 0;\n}\n\n/** Кого считаем игрой: самое большое полотно, иначе — активный элемент. */\nfunction inputTarget(): EventTarget {\n const main = canvasesByArea()[0];\n return main?.el ?? document.activeElement ?? document.body ?? window;\n}\n\nfunction keyEvent(type: string, code: string): KeyboardEvent {\n const event = new KeyboardEvent(type, {\n code,\n key: keyFromCode(code),\n bubbles: true,\n cancelable: true,\n composed: true,\n });\n // keyCode/which в конструкторе не поддерживаются, а игры на них до сих пор смотрят.\n const legacy = legacyKeyCode(code);\n Object.defineProperty(event, \"keyCode\", { get: () => legacy });\n Object.defineProperty(event, \"which\", { get: () => legacy });\n return event;\n}\n\nfunction wait(ms: number): Promise<void> {\n return new Promise((resolve) => window.setTimeout(resolve, ms));\n}\n\nasync function sendKey(code: string, ms: number): Promise<void> {\n const target = inputTarget();\n if (target instanceof HTMLElement) target.focus?.();\n target.dispatchEvent(keyEvent(\"keydown\", code));\n await wait(Math.min(Math.max(ms, 16), MAX_INPUT_HOLD_MS));\n target.dispatchEvent(keyEvent(\"keyup\", code));\n}\n\n/** Координата: 0..1 читается как доля полотна, больше — как CSS-пиксели. */\nfunction resolveCoord(value: unknown, size: number): number {\n const n = typeof value === \"number\" && Number.isFinite(value) ? value : 0.5;\n return n >= 0 && n <= 1 ? n * size : n;\n}\n\n/** Типы, после которых кнопка уже отпущена: у них `buttons` обязан быть нулём. */\nconst RELEASE_EVENTS = new Set([\n \"mouseup\",\n \"pointerup\",\n \"click\",\n \"mousemove\",\n \"pointermove\",\n]);\n\n/**\n * Событие указателя. Для `pointer*` строим именно PointerEvent: движки на pointer-событиях\n * (Phaser 4) читают у него `pointerId`/`isPrimary`, и обычный MouseEvent они отбрасывают.\n */\nfunction pointerLikeEvent(\n type: string,\n x: number,\n y: number,\n button: number,\n movement?: { dx: number; dy: number },\n): MouseEvent {\n const init: PointerEventInit = {\n clientX: x,\n clientY: y,\n button,\n buttons: RELEASE_EVENTS.has(type) ? 0 : 1 << button,\n bubbles: true,\n cancelable: true,\n composed: true,\n movementX: movement?.dx ?? 0,\n movementY: movement?.dy ?? 0,\n };\n\n if (type.startsWith(\"pointer\") && typeof PointerEvent === \"function\") {\n return new PointerEvent(type, {\n ...init,\n pointerId: 1,\n pointerType: \"mouse\",\n isPrimary: true,\n });\n }\n return new MouseEvent(type, init);\n}\n\nasync function sendClick(\n xArg: unknown,\n yArg: unknown,\n button: number,\n): Promise<void> {\n const target = inputTarget();\n const element = target instanceof Element ? target : document.body;\n const rect = element.getBoundingClientRect();\n const x = rect.left + resolveCoord(xArg, rect.width);\n const y = rect.top + resolveCoord(yArg, rect.height);\n\n for (const type of [\"pointerdown\", \"mousedown\"]) {\n target.dispatchEvent(pointerLikeEvent(type, x, y, button));\n }\n await wait(30);\n for (const type of [\"pointerup\", \"mouseup\", \"click\"]) {\n target.dispatchEvent(pointerLikeEvent(type, x, y, button));\n }\n}\n\nasync function sendMove(dx: number, dy: number): Promise<void> {\n const target = inputTarget();\n const element = target instanceof Element ? target : document.body;\n const rect = element.getBoundingClientRect();\n const x = rect.left + rect.width / 2 + dx;\n const y = rect.top + rect.height / 2 + dy;\n // movementX/movementY — то, что читает камера от первого лица; clientX/Y — то, что читают\n // обычные обработчики. Заполняем оба, чтобы не гадать, какой путь у игры.\n target.dispatchEvent(pointerLikeEvent(\"mousemove\", x, y, 0, { dx, dy }));\n target.dispatchEvent(pointerLikeEvent(\"pointermove\", x, y, 0, { dx, dy }));\n await wait(16);\n}\n\n/**\n * Синтетический ввод + снимок ПОСЛЕ него (как readPage после клика).\n *\n * Ответ всегда несёт `pointerLockActive`: если игра требует захвата указателя, ввод до неё не\n * дойдёт — и агент должен прочитать это как «управление не проверено», а не «управление сломано».\n */\nasync function sendInput(raw: unknown): Promise<unknown> {\n const args = asRecord(raw) ?? {};\n const type = String(args[\"type\"] ?? \"key\");\n\n switch (type) {\n case \"key\": {\n const code = String(args[\"code\"] ?? args[\"key\"] ?? \"\");\n if (!code)\n throw new Error(\"input type 'key' needs a code, e.g. \\\"KeyW\\\"\");\n await sendKey(code, Number(args[\"ms\"] ?? 200));\n break;\n }\n case \"click\":\n await sendClick(args[\"x\"], args[\"y\"], Number(args[\"button\"] ?? 0));\n break;\n case \"move\":\n await sendMove(Number(args[\"dx\"] ?? 0), Number(args[\"dy\"] ?? 0));\n break;\n default:\n throw new Error(`unknown input type '${type}' — use key | click | move`);\n }\n\n await settle();\n // Именно на истинность, а не `!== null`: там, где Pointer Lock не поддержан вовсе, свойство\n // приходит `undefined`, и строгое сравнение объявило бы захват активным, которого нет.\n const locked = Boolean(document.pointerLockElement);\n return {\n sent: { type, ...args },\n pointerLockActive: locked,\n note: locked\n ? \"Pointer Lock is active, so the game receives this input the same way it receives the player's.\"\n : \"Synthetic input was dispatched. If the game gates controls on Pointer Lock it ignored this — Pointer Lock cannot be acquired inside the preview iframe. A module's exposeToAgent actions are the reliable path.\",\n observation: await observeRuntime({ pixels: true }),\n modules: moduleSurfaces(),\n };\n}\n\n/* ------------------------------------------------------- сериализация DOM */\n\nconst SKIP_TAGS = new Set([\n \"SCRIPT\",\n \"STYLE\",\n \"LINK\",\n \"META\",\n \"NOSCRIPT\",\n \"TEMPLATE\",\n \"HEAD\",\n]);\n\nconst INTERACTIVE_TAGS = new Set([\n \"BUTTON\",\n \"A\",\n \"INPUT\",\n \"SELECT\",\n \"TEXTAREA\",\n]);\n\nfunction isInteractive(el: Element): boolean {\n if (INTERACTIVE_TAGS.has(el.tagName)) return true;\n const role = el.getAttribute(\"role\");\n if (\n role === \"button\" ||\n role === \"link\" ||\n role === \"tab\" ||\n role === \"menuitem\"\n )\n return true;\n return el.hasAttribute(\"data-testid\") && el.hasAttribute(\"tabindex\");\n}\n\nfunction isVisible(el: Element): boolean {\n const rect = el.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) return true;\n // Нулевой прямоугольник у контейнера — норма (например, обёртка с absolute-детьми):\n // считаем видимым, если браузер не выключил его целиком.\n const style = window.getComputedStyle(el);\n return style.display !== \"none\" && style.visibility !== \"hidden\";\n}\n\n/** Собственный текст узла — без текста детей (их напечатают они сами). */\nfunction ownText(el: Element): string {\n let text = \"\";\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) text += node.textContent ?? \"\";\n }\n return clip(text, MAX_TEXT);\n}\n\nfunction describe(el: Element, ref: string | null): string {\n const parts: string[] = [el.tagName.toLowerCase()];\n\n const id = el.getAttribute(\"id\");\n if (id) parts[0] += `#${id}`;\n\n const cls = el.getAttribute(\"class\");\n if (cls) {\n const first = cls.trim().split(/\\s+/).slice(0, 2).join(\".\");\n if (first) parts[0] += `.${first}`;\n }\n\n if (ref) parts.push(`[${ref}]`);\n\n const label = el.getAttribute(\"aria-label\");\n const testId = el.getAttribute(\"data-testid\");\n if (testId) parts.push(`testid=${testId}`);\n\n const text = ownText(el) || (label ? clip(label, MAX_TEXT) : \"\");\n if (text) parts.push(JSON.stringify(text));\n\n const flags: string[] = [];\n if (el.hasAttribute(\"disabled\")) flags.push(\"disabled\");\n if ((el as HTMLInputElement).checked) flags.push(\"checked\");\n if (el.tagName === \"INPUT\" || el.tagName === \"TEXTAREA\") {\n const value = (el as HTMLInputElement).value;\n if (value) flags.push(`value=${JSON.stringify(clip(value, 40))}`);\n const placeholder = el.getAttribute(\"placeholder\");\n if (placeholder)\n flags.push(`placeholder=${JSON.stringify(clip(placeholder, 40))}`);\n }\n if (el.tagName === \"CANVAS\") {\n const canvas = el as HTMLCanvasElement;\n flags.push(`${canvas.width}x${canvas.height}`);\n }\n if (flags.length) parts.push(`(${flags.join(\", \")})`);\n\n return parts.join(\" \");\n}\n\nfunction readDom(): { tree: string; truncated: boolean } {\n refs = new Map<string, Element>();\n const lines: string[] = [];\n let nodes = 0;\n let refSeq = 0;\n let truncated = false;\n\n const walk = (el: Element, depth: number): void => {\n if (truncated) return;\n if (SKIP_TAGS.has(el.tagName)) return;\n if (nodes >= MAX_NODES || depth > MAX_DEPTH) {\n truncated = true;\n return;\n }\n\n const visible = isVisible(el);\n let ref: string | null = null;\n if (visible && isInteractive(el)) {\n ref = `ref_${++refSeq}`;\n refs.set(ref, el);\n }\n\n const line = `${\" \".repeat(depth)}${describe(el, ref)}${visible ? \"\" : \" (hidden)\"}`;\n lines.push(line);\n nodes++;\n\n // В скрытое поддерево не спускаемся: сам факт «модалка есть и она скрыта» полезен, её\n // внутренности — нет.\n if (!visible) return;\n\n const children = Array.from(el.children);\n const shown = children.slice(0, MAX_SIBLINGS);\n for (const child of shown) walk(child, depth + 1);\n if (children.length > shown.length) {\n lines.push(\n `${\" \".repeat(depth + 1)}… +${children.length - shown.length} more sibling(s)`,\n );\n }\n };\n\n if (document.body) walk(document.body, 0);\n\n let tree = lines.join(\"\\n\");\n if (tree.length > MAX_TREE_CHARS) {\n tree = `${tree.slice(0, MAX_TREE_CHARS)}\\n… (tree truncated)`;\n truncated = true;\n }\n\n return { tree, truncated };\n}\n\n/**\n * Полотно, которое стоит считать «главным экраном»: либо оно занимает заметную часть окна, либо в\n * дереве вообще не за что зацепиться. Маленький canvas рядом с обычным интерфейсом (график,\n * спарклайн, аватар) главным экраном не объявляем — иначе снимок каждой DOM-страницы обрастал бы\n * рассказом про отрисованную игру, которой там нет.\n */\nfunction dominantCanvas(): {\n el: HTMLCanvasElement;\n rec: CanvasRecord | null;\n} | null {\n const main = canvasesByArea()[0];\n if (!main) return null;\n\n const rect = main.el.getBoundingClientRect();\n const viewport = window.innerWidth * window.innerHeight;\n const share = viewport > 0 ? (rect.width * rect.height) / viewport : 0;\n if (share >= 0.15) return main;\n\n // Нулевой прямоугольник — не обязательно «полотна не видно»: измерять могли до раскладки. Тогда\n // судим по размеру самого буфера, иначе снимок игры с HUD-кнопкой молча терял бы весь рассказ\n // про экран (поймано прогоном под jsdom, где размеров нет вообще).\n const unmeasured = rect.width === 0 && rect.height === 0;\n if (unmeasured && main.el.width >= 200 && main.el.height >= 200) return main;\n\n return refs.size === 0 ? main : null;\n}\n\n/**\n * Снимок страницы: дерево DOM плюс — у отрисованной игры — выжимка автоматического наблюдения.\n *\n * У Three/Phaser дерево честно пустое: весь мир внутри одного `<canvas>`. Раньше здесь стояла\n * только пометка «это не пустой экран», и агент оставался ни с чем. Теперь в ту же строку уезжают\n * настоящие цифры (кадры, объекты сцены, цвет полотна) — их зонд добывает сам, без участия игры.\n */\nasync function readPage(): Promise<{ tree: string; truncated: boolean }> {\n const page = readDom();\n // Порядок важен: `dominantCanvas` смотрит на `refs`, которые заполняет `readDom`.\n if (!dominantCanvas()) return page;\n\n const exposed = Object.keys(agentModules());\n const head =\n \"\\n\\n[This screen is drawn into a <canvas>: the DOM above says nothing about what happens \" +\n \"inside it, so a tree with nothing in it is NOT an empty screen.\";\n\n let note = head;\n try {\n const summary = summarize(await observeRuntime({ pixels: true }));\n if (summary) note += ` Observed automatically: ${summary}.`;\n } catch {\n /* автоматический слой не обязан удаваться — дерево важнее и уже собрано */\n }\n\n note +=\n exposed.length > 0\n ? ` Call GetGameState for the full picture — modules exposing a debug surface: ${exposed.join(\", \")}.]`\n : ` Call GetGameState for the full picture. No module exposes a debug surface ` +\n `(ctx.exposeToAgent), so gameplay state beyond these numbers is not observable — adding that ` +\n `surface to the game module is what makes it observable.]`;\n\n return { tree: page.tree + note, truncated: page.truncated };\n}\n\n/* ------------------------------------------------------------- действия */\n\nfunction settle(): Promise<void> {\n return new Promise((resolve) => window.setTimeout(resolve, SETTLE_MS));\n}\n\nfunction resolveRef(ref: unknown): Element {\n if (typeof ref !== \"string\") throw new Error(\"ref is required\");\n const el = refs.get(ref);\n if (!el) throw new Error(`${ref} is unknown — call readPage first`);\n if (!el.isConnected)\n throw new Error(\n `${ref} is no longer in the document — call readPage again`,\n );\n return el;\n}\n\nasync function clickRef(ref: unknown): Promise<unknown> {\n const el = resolveRef(ref);\n if (typeof (el as HTMLElement).click !== \"function\")\n throw new Error(\"element is not clickable\");\n (el as HTMLElement).click();\n await settle();\n return readPage();\n}\n\nasync function typeIntoRef(ref: unknown, text: unknown): Promise<unknown> {\n const el = resolveRef(ref);\n if (!(el instanceof HTMLInputElement) && !(el instanceof HTMLTextAreaElement))\n throw new Error(\"element is not a text field\");\n\n // Контролируемому React-полю мало el.value = …: React слушает нативный сеттер, и без него\n // состояние компонента не обновится, а значение откатится на следующем рендере.\n const proto =\n el instanceof HTMLInputElement\n ? HTMLInputElement.prototype\n : HTMLTextAreaElement.prototype;\n const setter = Object.getOwnPropertyDescriptor(proto, \"value\")?.set;\n if (setter) setter.call(el, String(text ?? \"\"));\n else el.value = String(text ?? \"\");\n\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n await settle();\n return readPage();\n}\n\n/* ------------------------------------------------- состояние игровых модулей */\n\n/**\n * Снимок всех модулей, которые открылись агенту, плюс перечень их действий.\n *\n * Ошибку в чужом `state()` не роняем на весь ответ: один сломанный модуль не должен ослеплять\n * агента по остальным — он получит текст ошибки ровно на месте этого модуля.\n */\nfunction moduleSurfaces(): Record<string, unknown> {\n const modules = agentModules();\n const ids = Object.keys(modules);\n if (ids.length === 0) {\n return {\n available: false,\n hint:\n \"No module exposes a debug surface (ctx.exposeToAgent), so nothing beyond the automatic \" +\n \"observation above can be seen: player position, score, current turn and the ability to DRIVE \" +\n \"the game all come from that surface. If you need them, add exposeToAgent to the game module's \" +\n \"setup() — it is a few lines and it is what makes the game verifiable from here.\",\n };\n }\n\n const out: Record<string, unknown> = {};\n for (const id of ids) {\n const api = modules[id];\n try {\n out[id] = {\n state: api?.state ? api.state() : null,\n actions: api?.describeActions ?? {},\n };\n } catch (error: unknown) {\n out[id] = { error: stringifyArg(error) };\n }\n }\n return { available: true, modules: out };\n}\n\n/**\n * Ответ на `gameState`: автоматический слой ВСЕГДА, поверхности модулей — если они есть.\n *\n * Порядок именно такой и он важен: даже игра, о которой никто ничего не рассказал, отвечает\n * цифрами (полотно, кадры, сцена, цвет экрана), а не пустотой. «Мне ничего не видно» — худший\n * из возможных ответов: он неотличим от «на экране пусто» и толкает агента чинить исправное.\n */\nasync function gameState(): Promise<unknown> {\n return {\n observed: await observeRuntime({ pixels: true }),\n exposedByGame: moduleSurfaces(),\n };\n}\n\n/** Выполнить действие модуля и вернуть состояние ПОСЛЕ него — как readPage после клика. */\nasync function gameAction(\n moduleId: unknown,\n action: unknown,\n rawArgs: unknown,\n): Promise<unknown> {\n const modules = agentModules();\n const id = typeof moduleId === \"string\" ? moduleId : Object.keys(modules)[0];\n if (!id) throw new Error(\"no module exposes actions\");\n\n const api = modules[id];\n if (!api) throw new Error(`unknown module '${id}'`);\n\n const name = typeof action === \"string\" ? action : \"\";\n const fn = api.actions?.[name];\n if (!fn) {\n const known = Object.keys(api.actions ?? {}).join(\", \") || \"none\";\n throw new Error(\n `unknown action '${name}' for '${id}' — available: ${known}`,\n );\n }\n\n const callArgs =\n rawArgs && typeof rawArgs === \"object\"\n ? (rawArgs as Record<string, unknown>)\n : {};\n const result = await fn(callArgs);\n\n // Состояние после действия — то, ради чего действие и звали.\n return {\n module: id,\n action: name,\n result: result ?? null,\n state: api.state ? api.state() : null,\n };\n}\n\n/* ---------------------------------------------------------------- протокол */\n\nasync function handle(\n cmd: string,\n args: Record<string, unknown>,\n): Promise<unknown> {\n switch (cmd) {\n case \"hello\":\n return {\n ready: true,\n titleId: probeOptions.titleId ?? null,\n url: window.location.href,\n };\n\n case \"readPage\": {\n const page = await readPage();\n return {\n ...page,\n url: window.location.href,\n titleId: probeOptions.titleId ?? null,\n };\n }\n\n case \"console\":\n return { console: consoleLog.slice(), network: networkLog.slice() };\n\n case \"click\":\n return await clickRef(args[\"ref\"]);\n\n case \"type\":\n return await typeIntoRef(args[\"ref\"], args[\"text\"]);\n\n case \"gameState\":\n return await gameState();\n\n case \"gameAction\":\n return await gameAction(args[\"module\"], args[\"action\"], args[\"args\"]);\n\n case \"input\":\n return await sendInput(args[\"args\"]);\n\n default:\n throw new Error(`unknown command '${cmd}'`);\n }\n}\n\n/**\n * Ставит зонд (и дополняет его данными о тайтле при повторном вызове).\n *\n * Модуль ставит зонд САМ при импорте — см. вызов внизу файла. Это не стилистика: перехват\n * console обязан встать раньше, чем упадёт что-нибудь на старте (например config.ts, который\n * бросает при нераспознанном тайтле), а вызовы из main.tsx исполняются уже ПОСЛЕ того, как\n * отработали тела всех импортированных модулей. Поэтому в main.tsx этот импорт стоит первым.\n *\n * Вне iframe (обычный запуск игры) не делает ничего.\n */\nexport function installPreviewProbe(options: PreviewProbeOptions = {}): void {\n probeOptions = { ...probeOptions, ...options };\n if (installed) return;\n if (typeof window === \"undefined\") return;\n // Не в iframe — значит это не превью дашборда. Ни перехватов, ни слушателей.\n if (window.self === window.top) return;\n\n installed = true;\n captureConsole();\n captureNetwork();\n // Перехваты автоматического наблюдения ставятся ЗДЕСЬ, при импорте зонда, и это единственный\n // момент, когда они успевают: `getContext` надо подменить раньше, чем движок создаст полотно, а\n // глобалы `__THREE_DEVTOOLS__` и `__PIXI_*_INIT__` — раньше, чем three.js и Pixi построят свои\n // рендереры (оба смотрят на них при инициализации и второго шанса представиться не дают).\n // Phaser своего канала не имеет вовсе — его игру ищут лениво, при сборке снимка.\n captureFrames();\n captureCanvases();\n captureThree();\n capturePixi();\n\n window.addEventListener(\"message\", (event: MessageEvent) => {\n const data = event.data as ProbeRequest | undefined;\n if (!data || data.wire !== WIRE || typeof data.id !== \"string\") return;\n // Чужой встраиватель (публичный сайт) сюда не пройдёт — и не узнает, что зонд вообще есть.\n if (!isAllowedOrigin(event.origin)) return;\n\n const source = event.source as Window | null;\n if (!source) return;\n\n const reply = (payload: Record<string, unknown>): void => {\n source.postMessage({ wire: WIRE, id: data.id, ...payload }, event.origin);\n };\n\n void handle(data.cmd, data.args ?? {})\n .then((result) => reply({ ok: true, data: result }))\n .catch((error: unknown) =>\n reply({ ok: false, error: stringifyArg(error) }),\n );\n });\n}\n\n// Само-установка при импорте — см. комментарий выше.\ninstallPreviewProbe();\n"
47
+ },
40
48
  {
41
49
  "path": "src/vite-env.d.ts",
42
50
  "content": "/// <reference types=\"vite/client\" />\n"
43
51
  },
44
52
  {
45
53
  "path": "src/walletLogin.tsx",
46
- "content": "import type { LoginScreenExtras } from \"./LoginScreen\";\n\n// Wallet sign-in seam.\n//\n// This is the web2 version: no wallet button, and the point of keeping it in its own file —\n// no import of `@idosgames/wallet`, so a non-crypto game never pulls wagmi/viem/solana into its\n// bundle just to render a login screen.\n//\n// For a title created with the web3 toggle the platform REPLACES this file at project creation\n// with a version that renders `WalletLogin` from `@idosgames/wallet/react`, and adds that package\n// to package.json. To add wallet sign-in to a title that was not created as web3, install\n// `@idosgames/wallet` and write that version here yourself:\n//\n// import { bsc } from \"wagmi/chains\";\n// import { WalletLogin, createEvmWalletConfig } from \"@idosgames/wallet/react\";\n// const wagmiConfig = createEvmWalletConfig({ chains: [bsc] });\n// export const renderWalletLogin: LoginScreenExtras[\"renderWalletLogin\"] = (props) => (\n// <WalletLogin {...props} networkID=\"bsc\" wagmiConfig={wagmiConfig} />\n// );\n\nexport const renderWalletLogin: LoginScreenExtras[\"renderWalletLogin\"] =\n undefined;\n"
54
+ "content": "import { LazyWalletLogin } from \"@idosgames/wallet/react/lazy\";\nimport type { LoginScreenExtras } from \"./LoginScreen\";\nimport { ENV_WALLETCONNECT_PROJECT_ID } from \"./env\";\nimport {\n IDOS_WEB3_NETWORK_ID,\n IDOS_WEB3_WALLETCONNECT_PROJECT_ID,\n} from \"./idos.title\";\n\n// Wallet sign-in seam — ON by default: every project offers \"Sign in with wallet\".\n//\n// The button uses the SDK's default EVM chain set (no `chains` prop). The challenge network comes\n// from the title (IDOS_WEB3_NETWORK_ID, baked by the platform); the \"bsc\" fallback keeps the button\n// alive on titles that did not pick a network at creation. A title whose Blockchain config is empty\n// will surface the server's error under the button — fix that by configuring the network (backend\n// MCP: get_blockchain / save_blockchain), not by hiding the button. To restrict the chains, import\n// them from this same subpath (mainnet, bsc, polygon, base, arbitrum, optimism, sepolia,\n// polygonAmoy — plain objects, safe to import) and pass `chains={[…]}`.\n//\n// For a title created with the web3 toggle the platform regenerates this file with the title's own\n// network. Keeping the seam in its own file is what makes that swap (and your own edits) safe.\n//\n// The import is \"@idosgames/wallet/react/lazy\", NOT \"@idosgames/wallet/react\" that matters. The\n// wallet stack (Reown AppKit) reaches `viem/chains` → `ox`, whose top-level `2n ** (24n - 1n)`\n// constants the live preview's classic bundler compiles into `Math.pow` — a Number-only API that\n// throws on BigInt, blanking the preview before any game code runs. The lazy entry keeps all of that\n// out of the page until the player actually taps sign-in, so the preview stays usable; real builds\n// behave identically either way.\n//\n// walletConnectProjectId adds MOBILE wallets via the WalletConnect QR/deep-link modal; without it\n// the button only works with injected wallets (MetaMask & co) and mobile login is unavailable. It\n// comes from the title's blockchain config (IDOS_WEB3_WALLETCONNECT_PROJECT_ID, baked by the\n// platform); VITE_WALLETCONNECT_PROJECT_ID in .env.local is a local-dev fallback.\n//\n// No `chains` is passed on purpose: the button falls back to the SDK's default EVM chain set, which\n// is the SAME list the in-game wallet panel uses. That shared list is what lets the login and the\n// panel share one wallet config, so a wallet connected here stays connected in the game.\n\nexport const renderWalletLogin: LoginScreenExtras[\"renderWalletLogin\"] = ({\n client,\n onAuthenticated,\n disabled,\n style,\n}) => (\n <LazyWalletLogin\n client={client}\n networkID={IDOS_WEB3_NETWORK_ID || \"bsc\"}\n onAuthenticated={onAuthenticated}\n disabled={disabled}\n style={style}\n walletConnectProjectId={\n IDOS_WEB3_WALLETCONNECT_PROJECT_ID ||\n ENV_WALLETCONNECT_PROJECT_ID ||\n undefined\n }\n />\n);\n"
47
55
  },
48
56
  {
49
57
  "path": "tsconfig.json",
@@ -1,15 +1,15 @@
1
1
  {
2
- "generatedFromCommit": "0e6d7a0b1db746a991f118ffb6dc42c07ec5ac9d",
2
+ "generatedFromCommit": "d12deae18316d281a4c5eb90f407ee19464cf29d",
3
3
  "runtimePackages": {
4
- "@idosgames/core": "0.1.4",
5
- "@idosgames/wallet": "0.1.2",
6
- "@idosgames/module-sdk": "0.1.1",
7
- "@idosgames/react": "0.1.0",
8
- "@idosgames/app-shell": "0.1.2"
4
+ "@idosgames/core": "0.2.0",
5
+ "@idosgames/wallet": "0.1.13",
6
+ "@idosgames/module-sdk": "0.1.3",
7
+ "@idosgames/react": "0.1.1",
8
+ "@idosgames/app-shell": "0.1.7"
9
9
  },
10
10
  "host": {
11
11
  "id": "host-starter",
12
- "fileCount": 13
12
+ "fileCount": 15
13
13
  },
14
14
  "modules": [
15
15
  {
@@ -46,15 +46,12 @@
46
46
  },
47
47
  "version": "0.1.0",
48
48
  "dependencies": {
49
- "@idosgames/core": "0.1.3",
50
- "@idosgames/module-sdk": "0.1.1",
51
- "@idosgames/react": "0.1.0",
52
- "@idosgames/wallet": "0.1.2",
53
- "@solana/wallet-adapter-base": "0.9.27",
54
- "@solana/wallet-adapter-react": "0.15.39",
49
+ "@idosgames/core": "0.2.0",
50
+ "@idosgames/module-sdk": "0.1.3",
51
+ "@idosgames/react": "0.1.1",
52
+ "@idosgames/wallet": "0.1.13",
55
53
  "@tanstack/react-query": "5.101.2",
56
54
  "react": "19.2.7",
57
- "react-dom": "19.2.7",
58
55
  "three": "0.185.1",
59
56
  "viem": "2.55.2",
60
57
  "wagmi": "3.7.2"
@@ -95,16 +92,13 @@
95
92
  },
96
93
  "version": "0.1.0",
97
94
  "dependencies": {
98
- "@idosgames/core": "0.1.3",
99
- "@idosgames/module-sdk": "0.1.1",
100
- "@idosgames/react": "0.1.0",
101
- "@idosgames/wallet": "0.1.2",
102
- "@solana/wallet-adapter-base": "0.9.27",
103
- "@solana/wallet-adapter-react": "0.15.39",
95
+ "@idosgames/core": "0.2.0",
96
+ "@idosgames/module-sdk": "0.1.3",
97
+ "@idosgames/react": "0.1.1",
98
+ "@idosgames/wallet": "0.1.13",
104
99
  "@tanstack/react-query": "5.101.2",
105
100
  "phaser": "4.2.1",
106
101
  "react": "19.2.7",
107
- "react-dom": "19.2.7",
108
102
  "viem": "2.55.2",
109
103
  "wagmi": "3.7.2"
110
104
  },
@@ -144,10 +138,10 @@
144
138
  },
145
139
  "version": "0.1.0",
146
140
  "dependencies": {
147
- "@idosgames/module-sdk": "0.1.1",
141
+ "@idosgames/module-sdk": "0.1.3",
148
142
  "three": "0.185.1"
149
143
  },
150
- "fileCount": 37
144
+ "fileCount": 38
151
145
  }
152
146
  ],
153
147
  "skills": [
@@ -165,7 +159,7 @@
165
159
  },
166
160
  {
167
161
  "name": "cloud-code",
168
- "description": "Call custom server-side game logic on the iDosGames TypeScript SDK (@idosgames/core) via client.cloudCode (CloudCodeService): execute a title-defined cloud script by name with an arbitrary JSON args payload and get back its arbitrary JSON result. Use this whenever the user wants to run custom/bespoke server logic, a \"cloud script\", \"cloud function\", \"server callable\", crafting/trading/matchmaking logic not covered by a dedicated SDK module, or otherwise touches client.cloudCode, CloudCodeService, or ExecuteCloudCodeResponse — even if they don't name the module explicitly."
162
+ "description": ""
169
163
  },
170
164
  {
171
165
  "name": "collection-system",
@@ -195,6 +189,10 @@
195
189
  "name": "game-loop-system",
196
190
  "description": "Build a board-style core game loop on the iDosGames TypeScript SDK (@idosgames/core) via client.gameLoop (GameLoopService): roll dice around a board, attack/raid other players' or bots' cities, build up buildings, resolve Special (Instant/Timed) tile choices, and run the cooperative Community Chest group meter. Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants a dice/roll board loop, an attack or raid/heist mini-game, city building, survival/Special tile events, or a co-op group-progress feature — or otherwise touches client.gameLoop, GameLoopService, GameLoopModels, BoardLoopState, BoardLoopDefinition, or CommunityChest — even if they don't name the module explicitly. templates/board-game is built entirely on this module."
197
191
  },
192
+ {
193
+ "name": "idosgames-agent-debug-surface",
194
+ "description": "Make a module observable and controllable by the AI Coder's agent through ctx.exposeToAgent — the ModuleAgentApi contract (state, actions, describeActions) that backs the GetGameState and GameAction tools. Read it BEFORE writing any module that renders into a canvas (three.js, Phaser, Pixi, raw WebGL/2d) — publishing the surface and avoiding Pointer Lock are part of building one. Also use it whenever a rendered game has to be debugged or verified in the live preview, when the agent reports \"the DOM shows nothing about this game\", or when a developer adds player/world state or agent-drivable actions to a module."
195
+ },
198
196
  {
199
197
  "name": "idosgames-compose-modules",
200
198
  "description": "Merge several iDosGames modules into one game — combine genres (e.g. board-game + idle-rpg), share progress across modes, and add always-on chrome. Use this whenever a developer wants to COMBINE or MERGE multiple iDosGames templates/modules into a single title, switch between game modes, share currency/inventory across modules, or asks how the Mode Router, the nav-bar, activeOnly panels, the cross-module event bus, or host-level shared state work. Builds on idosgames-getting-started (scaffolding) and idosgames-module-contract (a single module)."
@@ -241,7 +239,7 @@
241
239
  },
242
240
  {
243
241
  "name": "quest-system",
244
- "description": "Build a quest / daily-task system in a game on the iDosGames TypeScript SDK (@idosgames/core) via client.quest (QuestService): load quest and cycle definitions, load the player's quest progress state, add progress toward a metric, claim a completed quest's reward, claim a points-track milestone reward, claim a group-completion (grand) reward, and refresh cycles (dailies/ weeklies) forward. Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants daily/weekly quest screens, task lists, objective/progress trackers, battle-pass-style points tracks, milestone reward ladders, quest-group completion bonuses, or otherwise touches client.quest, QuestService, QuestDefinitions, UserQuestState, QuestPointsTrackView, or MilestoneDefinition — even if they don't name the module explicitly."
242
+ "description": ""
245
243
  },
246
244
  {
247
245
  "name": "referral-system",
@@ -271,9 +269,13 @@
271
269
  "name": "timed-event-system",
272
270
  "description": "Build a time-boxed live-ops event system in a game on the iDosGames TypeScript SDK (@idosgames/core) via client.timedEvent (TimedEventService): load active events and their title-wide definitions, read the player's per-event-instance token progress, spend event tokens (single + batch), grant event tokens (single + batch, server/trigger-driven), and claim milestone rewards as token balances cross thresholds (single, batch, and claim-all). Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants limited-time events, seasonal/live-ops event screens, event-token or event-currency progress bars, milestone/reward-track UIs, chain/rotation events, Coin-Master-style bonus windows, or otherwise touches client.timedEvent, TimedEventService, TimedEventDefinitions, ActiveEventInfo, EventTokenProgress, or MilestoneDefinition — even if they don't name the module explicitly."
273
271
  },
272
+ {
273
+ "name": "title-custom-data",
274
+ "description": "Read title-wide shared data in a game on the iDosGames TypeScript SDK (@idosgames/core) via client.titleCustomData (TitleCustomDataService): the key-value store every player of a title sees — live event state, global counters and progress bars, server-side thresholds, feature flags, remote config. Use this whenever the user wants a value that is the SAME for all players (a server-wide event, a global goal, a kill switch, a balancing knob changed without a rebuild), or touches client.titleCustomData, TitleCustomDataService, GetPublicTitleDataResponse, TitleDataScope or TitleDataBucket — even if they don't name the module. For per-player values use user-custom-data; to WRITE title data at runtime use cloud-code."
275
+ },
274
276
  {
275
277
  "name": "title-system",
276
- "description": "Fetch the iDosGames TypeScript SDK (@idosgames/core) title-level bootstrap config via client.title (TitleService): the full title public configuration bundle, title-wide public custom data, server time, and the standalone currency/item definitions endpoints. Also documents the config-section registry (`client.data.config.getSection<T>(\"Section\")`) that every other module's skill depends on. Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants app boot/init sequences, server time sync, title-wide custom data, or otherwise touches client.title, TitleService, TitlePublicConfigurationModel, getTitlePublicConfiguration, or the title-level GetCurrencyDefinitions / GetItemDefinitions calls — even if they don't name the module explicitly."
278
+ "description": "Fetch the iDosGames TypeScript SDK (@idosgames/core) title-level bootstrap config via client.title (TitleService): the full title public configuration bundle, server time, and the standalone currency/item definitions endpoints. Also documents the config-section registry (`client.data.config.getSection<T>(\"Section\")`) that every other module's skill depends on. Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and wants app boot/init sequences or server time sync, or otherwise touches client.title, TitleService, TitlePublicConfigurationModel, getTitlePublicConfiguration, or the title-level GetCurrencyDefinitions / GetItemDefinitions calls — even if they don't name the module explicitly."
277
279
  },
278
280
  {
279
281
  "name": "user-custom-data",