Mod API reference
The complete Dejinochi Mod API surface: every method, callback, registration schema, event payload and limit, including home layers, foods, Collections, pet presentation and game-state access.
Declare api_version in manifest.json; the running game rejects a mod that asks for an API contract it does not implement. A missing capability or an invalid required argument records an error and disables only that mod. DejiScript syntax, values and built-ins are documented in the DejiScript reference.
Reference conventions
Signatures use square brackets for optional arguments and an ellipsis for a variadic argument. Types describe the value the host accepts or returns.
| Type | Meaning |
nil | No value. A call documented as returning nil returns no useful result. |
bool | true or false. Callback conditions use DejiScript truthiness; nil, 0, "" and empty containers are false. |
number | An integer or float. Required numbers must be finite; NaN and infinity fail the call. |
string | A DejiScript string. Values are not implicitly converted unless the call says so. |
array | A DejiScript array of plain values. |
dict | A DejiScript dictionary with string or scalar keys. |
rect | A dictionary with numeric x, y, width and height keys, in logical LCD units. |
point | A dictionary with numeric x and y keys, in logical LCD units. |
function | A DejiScript function. Registration and subscription reject other values. |
ctx | The restricted canvas object passed to a screen or minigame draw callback. |
any | A plain DejiScript value: nil, boolean, number, string, array or dictionary. |
Every code mod receives one api object. The host validates every argument and copies data across the sandbox. Engine objects such as textures, nodes and callables never cross into script code.
Call index
Every method on api is listed here. Detailed behaviour follows in the grouped sections.
| Signature | Returns | Capability |
api.log(value, ...) | nil | None |
api.now() | number | None |
api.pet() | dict | pet.read |
api.game_time() | dict | None |
api.apply_effect(kind, amount, reason?) | bool | pet.modify |
api.game_state() | dict | state.read |
api.pet_presentation() | dict | pet.presentation |
api.play_pet_reaction(name, options?) | bool | pet.presentation |
api.stop_pet_reaction() | bool | pet.presentation |
api.register_pet_stat(spec) | string | pet.stats |
api.pet_stat_get(id, fallback?) | any | pet.stats |
api.pet_stat_set(id, value) | bool | pet.stats |
api.pet_stat_add(id, delta) | bool | pet.stats |
api.pet_storage_get(key, fallback?) | any | pet.stats |
api.pet_storage_set(key, value) | bool | pet.stats |
api.notify(message) | bool | notify |
api.open_screen(id) | bool | ui |
api.close_screen() | bool | ui |
api.register_screen(spec) | string | ui |
api.register_menu_entry(spec) | bool | ui |
api.register_home_entry(spec) | string | ui.home |
api.register_food(spec) | string | foods |
api.register_collection_entry(spec) | string | ui.collections |
api.register_main_screen_layer(spec) | string | ui.main |
api.register_command(spec) | bool | console |
api.register_minigame(spec) | string | minigames |
api.finish_minigame(won) | bool | minigames |
api.register_item(spec) | string | items |
api.give_item(id, amount?) | bool | items |
api.take_item(id, amount?) | bool | items |
api.item_count(id) | number | items |
api.register_unlockable(spec) | bool | content.unlock |
api.unlock_content(kind, id, amount?) | bool | content.unlock |
api.set_content_unlocked(kind, id, unlocked) | bool | content.unlock |
api.is_content_unlocked(kind, id) | bool | None |
api.give_sticker(id, amount?) | bool | content.unlock |
api.subscribe(name, callback) | bool | events |
api.on(name, callback) | bool | events |
api.register_update(callback, hz?) | bool | events |
api.set_visitors_enabled(enabled) | bool | state.modify |
api.spawn_visitor(spec) | bool | state.modify |
api.dismiss_visitor() | bool | state.modify |
api.add_poo(slot?) | bool | state.modify |
api.remove_poo(slot) | bool | state.modify |
api.clear_poos() | bool | state.modify |
api.set_pet_status(flag, enabled) | bool | state.modify |
api.queue_gift(spec) | bool | state.modify |
api.dismiss_mod_gift() | bool | state.modify |
api.storage_get(key, fallback?) | any | storage |
api.storage_set(key, value) | bool | storage |
api.storage_save() | bool | storage |
api.set_schema(version) | bool | storage |
api.on_migrate(from_version, callback) | bool | storage |
api.load_image(path) | string | ui |
api.image_size(asset_id) | dict or nil | ui |
api.sfx(name) | bool | ui |
api.register_settings_section(spec) | string | settings |
api.register_settings_row(spec) | string | settings |
api.settings_get(id, fallback?) | any | settings |
api.settings_set(id, value) | bool | settings |
api.content_list(kind) | array | content |
api.content_info(kind, id) | dict | content |
api.mod_id() | string | None |
api.api_version() | number | None |
api.has_capability(name) | bool | None |
Manifest, entry and capabilities
A script mod is an ordinary mod folder or ZIP with "type": "script" and a relative DejiScript entry file. It may also contain data-mod files.
{
"id": "author.my_mod",
"title": "My Mod",
"author": "Author",
"version": "1.0.0",
"type": "script",
"entry": "scripts/main.sgd",
"api_version": 5,
"min_game_version": "1.1.0",
"capabilities": [
"pet.read",
"pet.modify",
"pet.presentation",
"events",
"ui",
"ui.home",
"ui.collections",
"ui.main",
"foods",
"minigames",
"storage",
"settings",
"state.read",
"state.modify",
"notify",
"content",
"content.unlock",
"items",
"console"
],
"dependencies": [],
"description": "What the mod does.",
"icon": [".##.", "####", ".##."],
"icon_scale": 2
}
| Field | Type | Required | Meaning |
id | string | Script mods | Stable lowercase namespaced identity and storage namespace. Use at least two dot-separated parts. Each part is 1-48 characters of a-z, 0-9, _ or -; the whole id is 3-128 characters. Keep it unchanged after release. |
title | string | Optional | Display name in the Mods screen, Games menu and Workshop tools. |
author | string | Optional | Display author. |
version | string | Optional | Free-form mod version shown to players. |
type | string | Script mods | "content" (default) or "script". A script mod must declare "script". |
entry | string | Script mods | Relative path to the .sgd entry script inside the mod, normally scripts/main.sgd. |
api_version | number | Script mods | Mod API contract version. Use the version supported by the target game; the host rejects a package that requests a contract it does not implement. |
min_game_version | string | Optional | Minimum Dejinochi version, for example 1.1.0. The mod is rejected on an older game. |
capabilities | array | Script mods | Non-empty array of known capability strings. A call outside the declared set fails the call and disables the mod. |
dependencies | array | Optional | Required mod ids as strings, or objects {"id": "...", "optional": true}. A missing required dependency is an error; a missing optional dependency is a warning. |
description | string | Optional | Description used by the Mods screen and Workshop tools. |
icon, icon_scale | array, number | Optional | Existing ASCII pixel-art icon format and its display scale. |
An invalid declared id is replaced by a generated fallback for a data mod; a script mod without a valid namespaced id is rejected. Absolute paths, paths containing .., unsafe ZIP entries, unreadable archives and symbolic links are rejected.
api_version selects the API contract the mod was built against. The host rejects a package that requests a contract it does not implement; use min_game_version for features that depend on content or game fixes rather than API shape.
Capabilities
| Capability | Grants |
pet.read | api.pet() and the pet snapshots in events. |
pet.modify | api.apply_effect(...). |
events | api.subscribe, api.on and api.register_update. |
ui | api.open_screen, api.close_screen, api.register_screen, api.register_menu_entry, api.load_image, api.image_size, api.sfx, and canvas drawing for registered screens. |
ui.home | api.register_home_entry and bounded home-tile drawing. |
foods | api.register_food and the food consumption callback. |
ui.collections | api.register_collection_entry and Collections menu rows. |
ui.main | api.register_main_screen_layer, full-LCD home layers, pointer input and focused key input. |
pet.presentation | api.pet_presentation, api.play_pet_reaction and api.stop_pet_reaction. |
state.read | api.game_state and its complete snapshot. |
state.modify | Validated visitor, poo, sleeping/sick and mod-gift modifiers. |
minigames | api.register_minigame, api.finish_minigame, and canvas drawing for registered minigames. |
storage | api.storage_get, api.storage_set, api.storage_save, api.set_schema and api.on_migrate. |
pet.stats | api.register_pet_stat, api.pet_stat_get, api.pet_stat_set, api.pet_stat_add, api.pet_storage_get and api.pet_storage_set. |
settings | api.register_settings_section, api.register_settings_row, api.settings_get and api.settings_set. |
notify | api.notify(...) on the normal feedback caption. |
content | api.content_list and api.content_info read-only catalogue queries. |
content.unlock | api.register_unlockable, api.unlock_content, api.set_content_unlocked and api.give_sticker for content owned by this mod. api.is_content_unlocked does not need this capability. |
items | api.register_item, api.give_item, api.take_item and api.item_count. |
console | api.register_command. Commands run only when typed into the debug console. |
api.log, api.now, api.game_time, api.mod_id, api.api_version, api.has_capability and api.is_content_unlocked need no capability.
Package and validation limits
| Item | Limit |
| Script entry | 256 KiB. |
Image loaded by api.load_image | 2 MiB, 1024 pixels per side, PNG/JPEG/WebP. |
| ZIP archive | 64 MiB expanded, 2,000 entries. |
| Paths | Relative and inside the mod. Absolute paths, .., drive/colon paths and symbolic links are rejected. |
| Dependencies | Strings or objects with id and optional optional. Required dependencies must be installed, enabled and valid. |
| Screens | 32 per mod, 128 total. |
| Games menu entries | 32 per mod, 128 total. |
| Items | 64 per mod, 256 total. |
| Home entries | 4 per mod, 32 total. |
| Pet stats | 16 per mod, 32 visible stats total. |
| Settings | 4 sections and 32 rows per mod. |
| Foods | 16 per mod, 32 total. |
| Collection entries | 4 per mod, 32 total. |
| Main-screen layers | 2 per mod, 8 total. |
Lifecycle callbacks
Top-level statements run once when the mod is loaded. Top-level var declarations persist for the session, and functions capture the scope where they were defined.
| Callback | Arguments | Returns | When it runs |
on_init() | None | nil | After top-level declarations and any migrations registered at top level. Register screens, home entries, layers, foods, collections, stats, settings, commands, items and subscriptions here. |
on_activate() | None | nil | After on_init and after migrations registered inside on_init succeed. |
on_deactivate() | None | nil | When the mod is disabled, updated or the game closes, before registrations and assets are removed. |
All three callbacks are optional. A throwing or invalid callback disables the mod, removes its registrations and closes its active screen or minigame. on_deactivate runs for a normal unload, not for a callback that already failed.
Values, errors and limits
Scripts only see nil, booleans, numbers, strings, arrays, dictionaries, user functions and the whitelisted api and canvas host objects. There are no engine classes, nodes, files, network calls, Steam handles or other mods' data.
| Situation | Result |
| Missing capability | The call records an error and disables the mod. |
| Invalid required argument | Examples include a non-finite number, a non-function callback, a malformed id or a duplicate registration. The call records an error and disables the mod. |
| Logical failure | An unknown target, content the mod does not own, an insufficient item count or an unavailable screen returns false, "", [], {} or nil and leaves the mod loaded. |
| Unknown event name | api.subscribe accepts it, but the host never dispatches that name. |
| Callback execution | Each invocation starts with a fresh execution budget. A failure disables only that mod. |
| Non-string value in a string parameter | Unless a call says otherwise, the host uses the default value (usually "") and the call returns its documented failure. |
| Limit | Value |
| Evaluation steps per callback | 250,000 |
| Wall time per callback | 40 ms |
| Call depth | 48 |
| Loop iterations | 100,000 |
| Items in an array or dictionary | 8,192 |
| Draw commands per frame | 2,000 |
| Text per draw command | 512 characters |
| Notification message | 240 characters |
| Pet effect magnitude | 50 |
| Events dispatched per tick | 256; a queue above 1,024 pending events is cleared. |
| Periodic callback catch-up | 8 calls per tick |
| Mod storage | 64 KiB per mod across global, per-pet and settings data; 512 KiB total; depth 8; 512 items per container; 8,192 characters per string. |
| Pet state buckets | 256 per mod. |
Runtime, identity and time
| Call | Returns | Capability | Behaviour |
api.log(value, ...) | nil | None | Takes at least one argument, converts each value with str, joins them with spaces and writes one [Mod <id>] line to the Godot output. The line is capped at 1,024 characters. Use this or the DejiScript print built-in. |
api.now() | number | None | Current Unix timestamp in seconds. Use it for offline growth and cooldowns. |
api.mod_id() | string | None | The manifest id of the calling mod. |
api.api_version() | number | None | The host API contract version. This is not the value from the manifest. |
api.has_capability(name) | bool | None | Exact match against the capabilities declared in the manifest. |
Pet and game time
| Call | Returns | Capability | Behaviour |
api.pet() | dict | pet.read | A copy of the current pet snapshot. Returns an empty dictionary only when no pet model is available. |
api.game_time() | dict | None | Current Unix time, in-game clock time and the current simulation-speed multiplier. |
api.apply_effect(kind, amount, reason?) | bool | pet.modify | Applies one pet effect through the normal gameplay controller, records the interaction, saves and emits events. Returns true when the effect kind is valid and applied. |
Pet snapshot
api.pet() and the pet field in events return this dictionary:
| Key | Type | Meaning |
uuid | string | Opaque host-owned identity for this pet. Stable across save/load and after graduation; do not change it. |
name | string | Pet name. |
form | string | Current form id. |
stage | string | Current life stage name. |
age | number | Age in game minutes. |
happiness | number | Happiness, 0-100. |
hunger | number | Hunger, 0-100. |
health | number | Health, 0-100. |
sleep | number | Rest, 0-100. |
sleeping | bool | Whether the pet is asleep. |
sick | bool | Whether the pet is sick. |
ready | bool | Whether the pet is ready to graduate. |
Game-time snapshot
| Key | Type | Meaning |
unix_time | number | System Unix timestamp in seconds. |
clock_time | number | The game's simulated clock time. |
simulation_speed | number | Current simulation multiplier, normally 1.0. |
Pet effects
amount must be a finite number with an absolute value no greater than 50. reason is optional, defaults to "mod" and is limited to 64 characters. The event source is reported as <mod id>:<reason>.
| Kind | Effect |
happiness | Adds the amount to happiness and clamps the result to 0-100. Emits pet.happiness_changed with a delta when the value changes, then pet.effect_applied. |
hunger | Adds the amount to hunger and clamps the result to 0-100. Emits pet.effect_applied. |
health | Adds the amount to health and clamps the result to 0-100. Emits pet.effect_applied. |
sleep | Adds the amount to rest and clamps the result to 0-100. Emits pet.effect_applied. |
care | Records a care action without changing a numeric need. Emits pet.effect_applied. |
An unknown kind returns false without disabling the mod. An amount above 50 or below -50 fails the call and disables the mod.
Feedback and sound
| Call | Returns | Capability | Behaviour |
api.notify(message) | bool | notify | Shows a trimmed message on the normal feedback caption, capped at 240 characters. Returns false for an empty or non-string message. |
api.sfx(name) | bool | ui | Plays one named stock sound and returns true. Unknown names return false. |
| Sound name | Stock event |
click | UI click. |
confirm | UI confirm. |
back | UI back. |
denied | UI denied. |
success | Minigame success. |
failure | Minigame failure. |
pickup | Sticker pickup. |
happy | Pet happy reaction. |
Screens and menu entries
A screen draws in a 308 by 189 logical area below the normal title and Back bar. Returned screen ids use the form <mod id>:<local id>. Menu entries appear in the Games list after the official minigames.
| Call | Returns | Capability | Behaviour |
api.register_screen(spec) | string | ui | Registers a screen and returns its full id. Returns "" and fails the mod on a malformed, duplicate or draw-less screen. |
api.register_menu_entry(spec) | bool | ui | Adds a Games-list entry. Returns true when the spec is recorded. An unresolved screen or a false available callback hides the entry. |
api.open_screen(id) | bool | ui | Opens one of this mod's screens by local or full id. Returns false for an unknown screen, another mod's screen or when the host UI is unavailable. |
api.close_screen() | bool | ui | Closes the active screen when it belongs to this mod, or when no mod screen is active. Returns false when another mod's screen is active. |
Screen spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
title | string | Optional | Screen title shown by the host, defaulting to the local id and truncated to 64 characters. |
draw | function | Yes | draw(ctx). Rebuilds the screen immediately before every rendered frame. |
on_open | function | Optional | on_open(). Load screen state here. |
on_close | function | Optional | on_close(). Runs when the player really leaves the screen, not on a cosmetic UI rebuild. |
on_update | function | Optional | on_update(delta). Runs every frame while the screen is open. |
on_action | function | Optional | on_action(event). Runs on a left-button press on a button or hit region. event.hit is its id. |
on_pointer | function | Optional | on_pointer(event). Receives pointer movement and any press or release not consumed by on_action. |
on_key | function | Optional | on_key(action). Receives left, right, up, down, accept or cancel. |
status | function | Optional | Accepted and stored for compatibility. Screens do not currently call it; minigames use their own status callback. |
| Key | Type | Required | Meaning |
label | string | Yes | Visible label, truncated to 64 characters. An empty label fails registration. |
screen | string | Yes | Local or full id of this mod's screen. The entry is hidden until that screen exists. |
order | number | Optional | Sort order, default 100. Lower values appear first; equal orders sort by label. |
available | function | Optional | available(). Return a truthy value to show the entry. A false result hides it. |
Images
| Call | Returns | Capability | Behaviour |
api.load_image(path) | string | ui | Loads a PNG, JPEG or WebP from a relative path inside the mod and returns an asset id for ctx.sprite. The file must be no larger than 2 MiB and no more than 1024 pixels per side. Repeated paths reuse the cached asset. Failure returns "" and fails the mod. |
api.image_size(asset_id) | dict or nil | ui | Returns {"width": number, "height": number} for a loaded asset, or nil for an unknown id. |
Home entries
A home entry puts one of the mod's screens on the pet home screen. It is a first-class view entry, not a Games-list entry and not a minigame. Use it for something like Pocket Bonsai: the bonsai tree opens from home, while the associated Catch the Dew game stays in Games.
| Call | Returns | Capability | Behaviour |
api.register_home_entry(spec) | string | ui.home | Registers a home entry and returns its full id <mod id>:home:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit entry. |
Home entry spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
label | string | Optional | Accessibility and fallback label, defaulting to the local id and truncated to 64 characters. |
screen | string | Yes | Local or full id of this mod's registered screen. The entry is hidden until that screen exists. |
icon | string | Optional | Asset id returned by api.load_image. The icon takes precedence over draw. |
icon_scale | number | Optional | Native scale for the icon, default 0. Zero fits the icon to the tile; positive values use that pixel scale. |
draw | function | Optional | draw(ctx). Draws inside the host-sized tile. ctx.width and ctx.height are the tile dimensions. The host clips the tile and adds focus, hover, pressed, disabled and badge rendering. ctx.caption is ignored here. |
offset | dict | Optional | Tile-local {"x": number, "y": number} offset for the icon/draw content, default {0, 0}. |
hover_size | dict | Optional | Tile-local {"x": number, "y": number} hover box, centred on the content. Omit for the full tile. |
badge | function | Optional | badge() -> string or nil. Short host-rendered status text, truncated to 16 characters. |
order | number | Optional | Sort order, default 100. Lower values appear first. |
available | function | Optional | available() -> bool. A false result hides the entry. |
description | string | Optional | Hover hint, truncated to 120 characters. |
Home entries occupy host-managed tiles in the gaps between the core home icons. The manifest icon is used only in the Mods menu; use icon or draw for the home tile. offset moves the icon or drawn content and its hover box together; hover_size controls the hover highlight, defaulting to the full tile. Tile drawing is presentation only; the host owns the click target, so ctx.button and ctx.hit do not receive input inside a home tile. Tiles cannot cover the pet, poos, captions, tutorial hints, the six core icons or the Settings path. If more entries exist than the home screen has room for, the host adds a More tile that opens a host-rendered list. A tile draw failure disables only the owning mod. At most 4 home entries per mod and 32 overall are allowed.
function on_init()
api.register_screen({
"id": "bonsai",
"title": "Pocket Bonsai",
"draw": draw_bonsai,
"on_open": open_bonsai,
"on_action": bonsai_action
})
api.register_home_entry({
"id": "bonsai",
"label": "Bonsai",
"screen": "bonsai",
"order": 10,
"badge": bonsai_badge
})
end
Custom foods
A mod food appears after the three base foods on the Food page. The base foods are never replaced, hidden or reordered. The mod's consumption callback decides what the food does.
| Call | Returns | Capability | Behaviour |
api.register_food(spec) | string | foods | Registers a food and returns its full id <mod id>:food:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit food. |
Food spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
label | string | Yes | Display name, truncated to 64 characters. |
description | string | Optional | Hover hint, truncated to 120 characters. |
order | number | Optional | Sort order among mod foods, default 100. |
available | function | Optional | available() -> bool. A false result hides the food. |
on_consume | function | Yes | on_consume(context). Called once when the pet eats the food. |
on_consume context key | Type | Meaning |
food | string | The full registered food id. |
too_full | bool | Whether the pet was above the overfeeding threshold before consumption. |
pet | dict | The same snapshot returned by api.pet(). |
time | dict | The same snapshot returned by api.game_time(). |
The callback is the only place that applies a mod food's effects. The base nutrition table is not applied. Use the normal APIs, such as api.apply_effect, api.pet_stat_add, api.give_item or api.notify; those calls still require their own capabilities. The host records the full food id in the pet's food history, records the feeding interaction once, plays the normal eating presentation, saves and emits pet.fed after a successful callback. A failed callback rolls back the feed, disables only that mod and does not emit a successful feed. At most 16 foods per mod and 32 total are allowed.
api.register_food({
"id": "moon_berry",
"label": "Moon Berry",
"description": "A quiet snack.",
"order": 20,
"on_consume": eat_berry
})
function eat_berry(context)
api.apply_effect("happiness", 3, "moon_berry")
api.notify("The pet enjoyed the Moon Berry.")
end
Collections entries
A collections entry adds a host-rendered row to the top-level Collections menu and opens one of the mod's screens. It does not replace the Shells, Species, Graduates, Stickers or Items rows.
| Call | Returns | Capability | Behaviour |
api.register_collection_entry(spec) | string | ui.collections | Registers a Collections row and returns its full id <mod id>:collection:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit entry. |
Collection entry spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
label | string | Yes | Display label, truncated to 64 characters. |
screen | string | Yes | Local or full id of this mod's registered screen. The entry is hidden until the screen exists. |
description | string | Optional | Hover hint, truncated to 120 characters. |
order | number | Optional | Sort order, default 100. |
available | function | Optional | available() -> bool. A false result hides the entry. |
Mod rows append after the core Collections rows. Selecting one opens the referenced screen with Collections as the back target. At most 4 entries per mod and 32 total are allowed.
Canvas reference
The host passes one ctx object to every draw callback. Coordinates are logical pixels. Draw calls append validated commands; the host performs all rendering after the callback returns. A screen canvas is 308 by 189; a minigame canvas is 308 by 231.
| Property | Type | Meaning |
ctx.width | number | Logical canvas width, 308. |
ctx.height | number | Logical canvas height, 189 for screens and 231 for minigames. |
ctx.elapsed | number | Seconds since this canvas first drew, for animation. |
| Call | Returns | Behaviour |
ctx.rect(x, y, w, h, color?) | nil | Filled rectangle. x and y clamp to -100000..100000; w and h clamp to 0..100000. color defaults to ink. |
ctx.line(x1, y1, x2, y2, color?, width?) | nil | Line segment. width defaults to 1 and clamps to 1..16. color defaults to ink. |
ctx.text(x, y, text, size?, color?) | nil | Canvas-pixel text. size defaults to 12 and clamps to 6..48. Text is truncated to 512 characters. No automatic alignment or ellipsis. |
ctx.label(x, y, w, h, text, options?) | nil | Stock text inside fixed bounds, with pixel-font snapping, alignment and ellipsis. options.align is "left", "center" (default) or "right"; options.size is a number from 0 to 48, where 0 or omission uses the configured stock size; options.color defaults to ink. Text is truncated to 512 characters and must be a single line. |
ctx.caption(text) | nil | Stock footer line. The last call in a frame wins. Empty text clears it. A hover hint replaces the caption. The host owns its position and sizing. |
ctx.sprite(asset_id, x, y, scale?) | nil | Draws an image returned by api.load_image. scale defaults to 1 and clamps to 0.25..16. An empty or unknown asset id fails the callback. |
ctx.button(id, x, y, w, h, label, options?) | nil | Draws a standard button and registers a click region. options.enabled defaults to true; options.hover sets the footer hint; options.style is "boxed" (default) or "menu", which removes the outline and uses a stock label. An empty id fails the callback. |
ctx.hit(id, x, y, w, h, options?) | nil | Invisible click region for custom-drawn controls. options.enabled defaults to true; options.hover sets the footer hint. An empty id fails the callback. |
ctx.clear() | nil | Clears all commands and hit regions recorded so far in this frame. The host already clears them before each draw. |
ctx.hovered() | string | Id of the hovered button or hit region, or "". |
ctx.finish(won) | nil | Finishes the active modded minigame with a boolean result. Available only on a minigame canvas; on a screen it fails the callback. Calling api.finish_minigame has the same effect and works outside draw. |
Hit regions are tested in reverse registration order, so a later button or hit wins when regions overlap. Disabled regions are skipped. Hover text is shown in the stock footer.
Colours
| Value | Result |
"ink" | The player's configured ink colour. This is the default. |
"dim" or "disabled" | The configured disabled-text colour. |
"paper", "background" or "transparent" | Fully transparent. |
"white" or "black" | Pure white or black. |
Hex string such as "#344839" | Parsed as a colour. An invalid string falls back to the call's default colour. |
| Number from 0 to 1 | Grey level, clamped to 0..1. |
A non-string, non-number, non-nil colour value fails the callback. All other drawing arguments are validated and clamped as listed above.
Pointer events are plain dictionaries in logical canvas coordinates.
| Key | Type | Present on | Meaning |
type | string | All pointer events | "move", "press" or "release". |
x, y | number | All pointer events | Position in logical canvas coordinates. |
button | string | Press and release | "left". Movement events omit it. |
hit | string | All pointer events | The button or hit-region id under the pointer, or "". |
When a screen provides on_action, a press with a non-empty hit calls on_action(event) instead of on_pointer. Movement, releases and presses outside a hit region go to on_pointer. Modded minigames use the same pointer surface but have no on_action; their on_pointer receives every pointer event and can read event.hit.
| Action | Keyboard or controller input |
left, right, up, down | Arrow keys or D-pad. |
accept | Enter, keypad Enter or Space; controller A. |
cancel | Escape; controller B. Back or Escape also leaves a screen and runs on_close. |
Key events do not synthesize pointer events. Use on_key for keyboard and controller navigation.
Main-screen layers
A main-screen layer draws on the home pet screen while the pet is visible. It uses the same validated canvas commands as screens and minigames, but the canvas is the full 308 by 231 LCD. Layers are separate from home-entry tiles and custom screens.
| Call | Returns | Capability | Behaviour |
api.register_main_screen_layer(spec) | string | ui.main | Registers a home-screen layer and returns its full id <mod id>:layer:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit layer. |
Main-screen layer spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
layer | string | Yes | background, under_pet or over_pet. |
draw | function | Yes | draw(ctx). Runs while the home pet screen is visible. The full LCD is available and clipped to its bounds. |
on_update | function | Optional | on_update(delta). Runs while the layer is visible. |
on_pointer | function | Optional | on_pointer(event). Receives pointer movement, press and release events that core controls did not consume. event.hit is the layer hit id. |
on_key | function | Optional | on_key(action). Receives keys only while the layer has host-controlled focus. |
available | function | Optional | available() -> bool. A false result hides and skips the layer. |
order | number | Optional | Sort order within the same layer, default 100. |
Layers are visible only on the home pet screen and are hidden during modal pages, gifts, minigames, stage-up, graduation and other non-home pages. Core chrome, the six home icons, captions, tutorial hints, Settings > Mods and the disable path stay above mod layers and receive input first. A press on a layer's ctx.button or ctx.hit gives that layer host-controlled key focus; pressing an empty area clears focus. Draw and callback failures disable only the owning mod. At most 2 layers per mod and 8 total are allowed.
api.register_main_screen_layer({
"id": "visitor_badge",
"layer": "over_pet",
"order": 40,
"draw": draw_badge,
"on_update": update_badge,
"on_pointer": badge_pointer
})
function draw_badge(ctx)
var state = api.game_state()
if state.visitor.active:
ctx.label(8, 8, 120, 16, "Visitor: " + state.visitor.name)
end
Custom minigames
A registered minigame appears in the normal Games list. Dejinochi still owns starting, completion, happiness rewards, hunger and sleep costs, fatigue, gifts, reactions and saving. The mod owns only simulation, drawing and input. The canvas is 308 by 231, and the normal objective caption remains above it.
| Call | Returns | Capability | Behaviour |
api.register_minigame(spec) | string | minigames | Registers a minigame and returns its full id mod:<mod id>:<local id>. Returns "" and fails the mod on a malformed, duplicate or draw-less game. |
api.finish_minigame(won) | bool | minigames | Finishes the active minigame owned by this mod with a boolean win result. Returns false when no matching game is active. Do not call it from on_finish. |
Minigame spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
title | string | Optional | Display name, defaulting to the local id and truncated to 64 characters. |
draw | function | Yes | draw(ctx). Draws the full minigame canvas. |
on_start | function | Optional | on_start(). Runs once when the session starts. |
on_update | function | Optional | on_update(delta). Runs every frame while the game is active. |
on_pointer | function | Optional | on_pointer(event). Receives pointer movement, press and release events. |
on_key | function | Optional | on_key(action). Receives the same actions as screens. |
status | function | Optional | status(). Returns the top-caption objective text. A nil result falls back to the title. |
available | function | Optional | available(). Return a truthy value to list and allow the game. A false result hides it and prevents starting. |
on_finish | function | Optional | on_finish(won). Runs after the host accepts the result. Apply mod-side rewards here. |
on_cancel | function | Optional | on_cancel(). Runs when the round is cancelled before completion. |
Call api.finish_minigame(true), api.finish_minigame(false) or ctx.finish(won) to end the round. The host then applies the normal reward flow. Modded games do not count toward official minigame achievements or demo limits.
Events and periodic updates
| Call | Returns | Capability | Behaviour |
api.subscribe(name, callback) | bool | events | Subscribes a DejiScript function to an event. Names are trimmed and lowercased; valid names are 1-96 characters of a-z, 0-9, ., _ or -. Duplicate callbacks are ignored. Returns true when subscribed. |
api.on(name, callback) | bool | events | Alias for api.subscribe. |
api.register_update(callback, hz?) | bool | events | Runs callback(delta) at a low rate while the mod is enabled. hz defaults to 4.0 and clamps to 0.1-30. The callback receives the frame's real elapsed seconds, clamped to 5. At most 8 catch-up calls run per tick. Timers continue while the game is minimized. |
Event payloads are fresh dictionaries. Dispatch is synchronous after the operation succeeds. Re-entrant emissions are queued, duplicate callbacks are ignored, and a failing callback disables only its mod. There is no unsubscribe call; disabling or reloading a mod clears its subscriptions.
| Event | Payload fields | When it fires |
game.loaded | pet: dict, time: dict | After enabled code mods load and their on_init subscriptions are registered. |
game.started | pet: dict, time: dict | After the game UI and runtime finish starting. |
game.minute_elapsed | clock_time: number, unix_time: number | Once per simulated minute. |
pet.fed | food: string, too_full: bool, pet: dict | After a successful feed. |
pet.patted | happiness: number, pet: dict | After petting. |
pet.treated | health: number, pet: dict | After medicine is used. |
pet.sleep_started, pet.woke_up | manual: bool, pet: dict | On sleep or wake. manual is true for the light action and false for automatic waking. |
pet.evolved | from_stage: string, to_stage: string, form: string, pet: dict | When the pet reaches a new life stage. |
pet.graduated | uuid: string, name: string, form: string, quality: string | When a pet graduates. uuid is the graduating pet's stable identity. |
pet.happiness_changed | value: number, delta: number (effect changes only), source: string | When happiness changes. The pat event has no delta; effect changes include it. A mod effect source is <mod id>:<reason>. |
pet.effect_applied | kind: string, amount: number, source: string | After a valid effect from api.apply_effect. |
minigame.started | id: string, modded: bool | When a minigame starts. A modded id is the full registered id. |
minigame.completed | id: string, won: bool, modded: bool | After the host finishes a minigame. |
minigame.cancelled | id: string, modded: bool | When an active minigame is cancelled. |
visitor.arrived, visitor.left | visitor: dict | When a visitor appears or leaves. The payload is the visitor snapshot. |
visitor.petted | visitor: dict | After the player pets the visitor. |
gift.pending, gift.opened, gift.cleared | gift: dict | When a gift is queued, opened or cleared. The payload is the gift snapshot. |
poo.added, poo.removed | slot: number, optional visible: bool, poos: dict | When a poo is added or removed. |
poo.visibility_changed | poos: dict | When deferred poos become visible or are re-hidden. |
pet.sick_changed | sick: bool, pet: dict | When the sick flag changes. |
pet.sleeping_changed | sleeping: bool, pet: dict | When the sleeping flag changes. |
pet.ready_changed | ready: bool, pet: dict | When the pet becomes ready to graduate. |
pet.stage_up_started | stage_up: dict, optional from_stage: string, pet: dict | When the stage-up celebration starts. |
pet.stage_up_acknowledged | stage_up: dict, pet: dict | When the player acknowledges the stage-up celebration. |
graduation.started | graduation_started: bool, pet: dict | When the graduation sequence starts. |
ui.page_changed | page: string, previous: string, UI flags | On a real page transition. |
pet.reaction_started, pet.reaction_finished | reaction: string, name: string, target: dict, duration: number, interrupted: bool, pose: string | When a host-owned pet reaction starts or ends. |
Complete game state
With the state.read capability, api.game_state() returns a fresh deep-copied plain-data snapshot of gameplay, progression and UI state. It is safe to call from screens, minigames, home tiles, main-screen layers and periodic callbacks.
| Key | Type | Meaning |
page | string | Current host page. |
is_home, is_modal, is_settings, is_collections | bool | Current page category flags. |
is_game_active | bool | Whether a minigame is running. |
minigame | dict | Empty, or id, modded, phase and status. |
action | dict | name, remaining and queue_length for the current pet action sequence. |
stage_up | dict | active, from_stage, state and elapsed. |
graduation_started, demo, gaming_mode, window_minimized | bool | Session and presentation flags. |
pet | dict | Extended pet snapshot described below. |
pet_presentation, visitor_presentation | dict | Visual snapshots described under Pet presentation. |
time | dict | Same fields as api.game_time(). |
visitor | dict | active, enabled, source, name, form, persona, remaining, hovered, petting_remaining. |
gift | dict | pending, on_screen, opened, source, kind, recipient, occasion, sticker_id, item_id, minigame_id. |
poos | dict | total, visible, deferred_slots, reveal_remaining and entries. |
items, stickers, shells, achievements, visits | dict | Ownership, unlock, achievement and visit-timer summaries. |
blocking | dict | visitor and gift flags for state that blocks normal play. |
is_interactive | bool | Whether the home screen is in a normal interactive state. |
Extended pet state
game_state().pet contains every field from api.pet(), plus:
| Key | Type | Meaning |
poo_count, visible_poo_count | number | Total and currently visible poos. |
poos | array | Entries with slot, age_hours and visible. |
play | dict | fatigue (dict of minigame id to number), request_id (string), request_remaining (number) and request_wait (number). |
final_touch | bool | Whether the pet has had its final graduation touch. |
childhood, is_childhood | bool | Whether the pet is in a childhood stage. |
is_neglected, is_needy, is_tuckered_out | bool | Derived pet-state checks. |
seconds_until_age_up | number | Seconds until the next life-stage change. |
care_quality | string | Current graduation care rating. |
foods | dict | Food id or base food name to a numeric feed count. |
history | dict | Childhood statistics. Keys: childhood_time, average_happiness, average_satiation, average_sleepiness, time_spent_hungry, time_spent_neglected, time_spent_sick, time_spent_asleep, count_care_actions, count_play_interactions, count_pats, count_games_played, count_games_won, count_sickness_episodes, count_overfed, count_chocolate_feeds, count_morning_interactions, count_night_interactions, count_timed_interactions, count_total_interactions, count_neglect_episodes. All values are numbers. |
lifetime | dict | Whole-life statistics. Keys: lifetime_time, average_happiness, average_satiation, time_spent_neglected, time_spent_sick, count_overfed, count_neglect_episodes. All values are numbers. |
Nested state shapes
These exact objects appear inside api.game_state().
| Key | Shape |
minigame | {} when inactive, otherwise {"id": string, "modded": bool, "phase": string, "status": string}. |
action | {"name": string, "remaining": number, "queue_length": number}. |
stage_up | {"active": bool, "from_stage": string, "state": string, "elapsed": number}. |
blocking | {"visitor": bool, "gift": bool}. |
visitor | {"active": bool, "enabled": bool, "source": string, "name": string, "form": string, "persona": string, "remaining": number, "hovered": bool, "petting_remaining": number}. |
gift | {"pending": bool, "on_screen": bool, "opened": bool, "source": string, "kind": string, "recipient": string, "occasion": string, "sticker_id": string, "item_id": string, "minigame_id": string}. |
poos | {"total": number, "visible": number, "deferred_slots": array of numbers, "reveal_remaining": number, "entries": array of {"slot": number, "age_hours": number, "visible": bool}}. |
items | {"owned": array of strings, "counts": dict of string to number, "simulation_speed": number}. |
stickers | {"book_unlocked": bool, "unlocked": array of strings, "unlocked_count": number, "total": number}. |
shells | {"unlocked": array of strings, "unlocked_count": number, "total": number}. |
achievements | {"completed": array of strings}. |
visits | {"next": number, "next_friend": number, "after_stage_up": number, "after_visit": number, "blocked_for_age_up": bool}. |
State modifiers
With the state.modify capability, change safe runtime state through validated host APIs. Every call returns bool and routes through the normal controllers, save path and events.
| Call | Behaviour |
api.set_visitors_enabled(enabled) | Session visitor toggle. Disabling removes an active visitor. |
api.spawn_visitor(spec) | Spawns a mod-owned visitor. Spec fields: name, form (must be installed), optional persona, optional state and optional duration (1-3600 seconds). Fails while a visitor is already active. |
api.dismiss_visitor() | Removes the active visitor through the normal path. |
api.add_poo(slot?) | Adds a poo. Optional slot is 0-3; omit or pass a negative value for the first free slot. Fails for an egg, a full board or an occupied slot. |
api.remove_poo(slot) | Removes the poo in a 0-3 slot. |
api.clear_poos() | Removes every poo. |
api.set_pet_status(flag, enabled) | Sets sleeping or sick. Fails for an egg; sleeping fails while the pet is ready to graduate. |
api.queue_gift(spec) | Queues a gift containing exactly one mod-owned sticker_id or item_id. Optional occasion, max 32 characters. Fails if another gift is pending. |
api.dismiss_mod_gift() | Dismisses only a gift queued by this mod. |
Mods cannot alter official achievements, Steam statistics, base progression totals, save identity, official minigames, graduation, page navigation or the disable path. Invalid ids, slots, forms, ranges and cross-mod ownership fail.
Pet presentation and reactions
With the pet.presentation capability, read the pet's live on-screen presentation and request host-owned visual reactions.
| Call | Returns | Behaviour |
api.pet_presentation() | dict | Presentation snapshot for the current pet. Same data appears as game_state().pet_presentation. |
api.play_pet_reaction(name, options?) | bool | Starts a presentation-only host reaction. Fails while the pet is busy or in an incompatible state. |
api.stop_pet_reaction() | bool | Stops a reaction owned by this mod. |
Pet presentation snapshot
| Key | Type | Meaning |
visible | bool | Whether the pet is currently drawn on the home screen. |
form, pose | string | Current form and renderer pose. |
rect, interaction_rect, visible_bounds | dict | Logical LCD rectangles with x, y, width and height. |
anchor, form_offset | dict | Current anchor and form offset as {x, y}. |
frame, frame_progress, fps | number | Animation frame, progress within the frame and animation rate. |
scale | number | Presentation scale. |
facing | string | left, right or center. |
busy | bool | Whether another action, reaction, gift, modal or minigame owns the pet. |
reaction | string | Active reaction name, or "" when none is active. |
reaction_remaining | number | Seconds left in the active reaction, or 0.0. |
reaction_target | point | Active reaction target as {"x": number, "y": number}, or {} when no reaction has a target. |
All rect values use {"x": number, "y": number, "width": number, "height": number}. All point values use {"x": number, "y": number}. pose is one of Idle, Happy, Unhappy, Hungry, Sick, Sleeping, Proud, Eat, Care, Clean or Play. When the host renderer is unavailable, api.pet_presentation() returns {}.
{
"visible": true,
"form": "dejinochi.form.kerochi",
"pose": "Idle",
"rect": {"x": 102.0, "y": 62.0, "width": 104.0, "height": 104.0},
"anchor": {"x": 106.0, "y": 66.0},
"interaction_rect": {"x": 102.0, "y": 62.0, "width": 104.0, "height": 104.0},
"visible_bounds": {"x": 110.0, "y": 70.0, "width": 88.0, "height": 88.0},
"frame": 0,
"frame_progress": 0.25,
"fps": 2.0,
"scale": 1.0,
"facing": "center",
"busy": false,
"reaction": "",
"reaction_remaining": 0.0,
"reaction_target": {},
"form_offset": {"x": 0.0, "y": 0.0}
}
Visitor presentation snapshot
game_state().visitor_presentation uses this shape. When no visitor is visible it returns exactly {"visible": false}.
| Key | Type | Meaning |
visible | bool | Whether the visitor is on screen. |
form | string | Visitor form id. |
pose | string | Visitor renderer pose. |
rect | rect | Visitor interaction rectangle. |
anchor | point | Visitor anchor position. |
interaction_rect | rect | Visitor interaction rectangle. |
Pet reactions
Allowed reaction names: idle, happy, unhappy, hungry, sick, sleep, wake, eat, care, clean, play, proud, look_at, approach and interact.
| Option | Type | Meaning |
duration | number | Reaction length, clamped to 0.5-8 seconds. Default 1.6. |
target | dict | {x, y} in logical LCD coordinates for look_at, approach and interact. |
pose | string | Optional safe pose: Idle, Happy, Unhappy, Hungry, Sick, Sleeping, Proud, Eat, Care, Clean or Play. |
emote | bool | Whether to show the host emote for compatible poses. Default true. |
Reactions are presentation-only and never change needs, saves, progression, achievements or Steam totals. They are rejected during stage-up, graduation, gifts, modal pages, official minigames and action sequences. Sickness and sleep can suppress incompatible reactions. approach and interact move on the home LCD and return the pet to its normal anchor. Removing the mod cancels its active reaction.
api.play_pet_reaction("approach", {"target": {"x": 220, "y": 140}})
api.play_pet_reaction("interact", {
"target": {"x": 220, "y": 140},
"pose": "Happy",
"duration": 2.0
})
Items
Code mods can register items that appear in Collections > Items once owned. The host owns persistent counts, gifting and the menu entry; the mod owns the use logic. Registered item ids have the form mod:<mod id>:item:<local id>.
| Call | Returns | Capability | Behaviour |
api.register_item(spec) | string | items | Registers a mod-owned item and returns its full id. Returns "" and fails the mod on a malformed or duplicate item. |
api.give_item(id, amount?) | bool | items | Adds owned copies. amount defaults to 1 and is converted to an integer; values below 1 are treated as 1. Use the full id returned by register_item. |
api.take_item(id, amount?) | bool | items | Consumes owned copies. amount defaults to 1. Returns false when the amount is non-positive or the count is insufficient. |
api.item_count(id) | number | items | Reads the owned count. Returns 0 when the item is not owned by this mod. |
Item spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
title | string | Optional | Display name, defaulting to the local id and truncated to 64 characters. |
description | string | Optional | Description, truncated to 240 characters. |
giftable | bool | Optional | Whether the ordinary item-gift flow may offer it. Defaults to false; non-giftable items are custom-only. |
on_use | function | Optional | on_use(). Runs when an owned item is selected in the Items menu. |
screen | string | Optional | Screen opened on use when on_use is absent. Use a local or full id of this mod's screen. |
Counts persist in the normal item save section. Unknown mod item counts survive disabling or uninstalling the mod and are restored when it registers the item again. Base items cannot be replaced or changed.
Mod-owned unlocks
Mods can gate their own shells and stickers without touching official achievements, Steam statistics or base-game progression. A mod can only unlock content that belongs to its own package.
| Call | Returns | Capability | Behaviour |
api.register_unlockable(spec) | bool | content.unlock | Registers an unlock predicate and hint for a shell or sticker owned by this mod. The content must exist in this mod's data. Returns false for another mod's or base content. |
api.unlock_content(kind, id, amount?) | bool | content.unlock | Grants owned content through normal state. kind is shell, sticker or item. amount defaults to 1; shells ignore it, stickers and items treat values below 1 as 1. |
api.set_content_unlocked(kind, id, unlocked) | bool | content.unlock | Explicitly unlocks or locks owned content. Shells use the normal unlock/lock path; stickers are granted one copy or locked; items are set owned or cleared. |
api.is_content_unlocked(kind, id) | bool | None | Reads this mod's owned content state. Shells and stickers also consult registered unlock providers. Returns false for content owned by another mod or the base game. |
api.give_sticker(id, amount?) | bool | content.unlock | Grants owned sticker copies. amount defaults to 1 and values below 1 are treated as 1. |
Unlockable spec
| Key | Type | Required | Meaning |
kind | string | Yes | "shell" or "sticker". Items use the item API instead. |
id | string | Yes | Id of a shell or sticker defined in this mod's data files. |
hint | string | Optional | Locked-state hint, truncated to 160 characters. |
is_unlocked | function | Yes | is_unlocked(). Return a truthy value when the content should be available. |
Mod shells without unlock metadata remain always available for compatibility. Base shells, stickers and items never use mod providers. Custom-only stickers use "distribution": "custom" in their data definition and are excluded from normal gift rolls.
{
"id": "author.shell.moon",
"path": "shells/moon.png",
"unlock": {
"type": "custom",
"hint": "Collect two items"
}
}
function on_init()
api.register_unlockable({
"kind": "shell",
"id": "author.shell.moon",
"hint": "Collect two items",
"is_unlocked": moon_ready
})
end
function moon_ready()
return api.storage_get("purchases", 0) >= 2
end
Persistent storage
Each mod gets a private namespace in the save's mod_state section. Unknown namespaces are preserved while a mod is disabled or uninstalled.
| Call | Returns | Capability | Behaviour |
api.storage_get(key, fallback?) | any | storage | Returns the stored value for key, or fallback when absent. fallback defaults to nil. Keys are trimmed and limited to 128 characters; an empty key fails the mod. |
api.storage_set(key, value) | bool | storage | Writes a sanitized value into the live save state. Returns false for an invalid value, an oversized container or an exceeded size limit. Call storage_save for an immediate write; otherwise the normal autosave writes it later. |
api.storage_save() | bool | storage | Requests an immediate save through the normal save manager. Returns the save result, or true when no save manager is attached. |
api.set_schema(version) | bool | storage | Records the mod's schema version. version is an integer from 1 to 100000; values outside that range fail the mod. |
api.on_migrate(from_version, callback) | bool | storage | Registers callback(current_schema) for stored schemas at or below from_version. Migrations run in ascending order. Register at top level to run before on_init, or inside on_init to run immediately afterwards. If the callback does not advance the schema, the host increments it by one. |
| Storage value rule | Limit or result |
| Allowed values | nil, booleans, finite numbers, strings, arrays and dictionaries. |
| Dictionary keys | String, integer, float or boolean. |
| Per mod | 64 KiB. |
| All mod state | 512 KiB. |
| Nesting depth | 8. |
| Items per array or dictionary | 512. |
| String length | 8,192 characters; longer strings are truncated on write. |
| Engine objects | Rejected. Textures, nodes and other engine values cannot be stored. |
var state = {}
function on_init()
api.on_migrate(1, migrate_v1)
state = api.storage_get("garden", default_state())
end
function default_state()
return {"plots": [], "harvests": 0}
end
function save_garden()
api.storage_set("garden", state)
api.storage_save()
end
function migrate_v1(from_version)
state = api.storage_get("garden", default_state())
if not has(state, "harvests"):
state.harvests = 0
end
save_garden()
api.set_schema(2)
end
Pet stats and per-pet storage
Pet stats belong to one individual pet. The host gives every current pet and archived pet an opaque uuid; api.pet() and pet event payloads include it, and pet.graduated reports the graduating pet's id. Values for one pet never leak into the next pet.
| Call | Returns | Capability | Behaviour |
api.register_pet_stat(spec) | string | pet.stats | Registers a stat and returns its full id <mod id>:stat:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit stat. |
api.pet_stat_get(id, fallback?) | number or fallback | pet.stats | Reads this mod's stat for the current pet. Accepts a local or full id. Returns fallback when the stat is unknown or belongs to another mod. |
api.pet_stat_set(id, value) | bool | pet.stats | Sets this mod's stat for the current pet, clamped to the registered range. Returns false for an unknown stat. A non-finite or non-number value fails the call and disables the mod. |
api.pet_stat_add(id, delta) | bool | pet.stats | Adds to this mod's stat and clamps the result. Returns false for an unknown stat. A non-finite or non-number delta fails the call and disables the mod. |
api.pet_storage_get(key, fallback?) | any | pet.stats | Reads this mod's private storage for the current pet, or fallback when absent. An empty or non-string key fails the mod. |
api.pet_storage_set(key, value) | bool | pet.stats | Writes this mod's private storage for the current pet. Returns false for an invalid value or size limit. An empty or non-string key fails the mod. |
Pet stat spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
label | string | Yes | Display label, truncated to 64 characters. |
min | number | Optional | Minimum value, default 0. Must be less than max. |
max | number | Optional | Maximum value, default 100. Must be greater than min. |
default | number | Optional | Starting value for a pet with no stored value, default 0 and clamped to min..max. |
decay_per_hour | number | Optional | Amount applied by the normal pet simulation per simulated hour, default 0. Use a negative value to drain. |
offline_decay_per_hour | number | Optional | Amount applied during offline catch-up, defaulting to decay_per_hour. |
visible | bool | Optional | Whether the stat appears under Stats > Mod stats, default true. |
order | number | Optional | Sort order on the Mod stats page, default 100. |
format | function | Optional | format(value) -> string or nil. Returns a display string up to 64 characters, or nil for the host's default number formatting. Called on UI refresh, not every frame. |
Visible stats open from a Mod stats entry on the Stats page and appear on a host-rendered, paginated subpage. The host applies decay_per_hour through the normal pet simulation, including the hourglass speed; offline_decay_per_hour applies during offline catch-up. At most 16 stats per mod and 32 visible stats overall are allowed. A formatter failure disables the mod.
Per-pet storage is scoped to the current pet and survives save/load and graduation. It uses the same value rules and key limit as global storage, while api.storage_get/set remains available for lineage-wide data. Use api.storage_save() for an immediate write; otherwise the normal autosave includes it. Each mod may keep at most 256 pet buckets, and global, per-pet and settings data share the per-mod size limit.
function on_init()
api.register_pet_stat({
"id": "discipline",
"label": "Discipline",
"min": 0, "max": 100, "default": 50,
"decay_per_hour": -2,
"offline_decay_per_hour": -0.5,
"format": format_discipline
})
api.pet_storage_set("visits", 0)
end
function format_discipline(value)
return str(value) + "%"
end
function reward_patience()
api.pet_stat_add("discipline", 5)
api.pet_storage_set("visits", api.pet_storage_get("visits", 0) + 1)
end
Settings
With the settings capability, register typed sections and rows in the normal settings menus. The host renders the rows with the stock menu style. Mods never draw settings UI and cannot replace, hide or reorder core rows.
| Call | Returns | Capability | Behaviour |
api.register_settings_section(spec) | string | settings | Registers a section and returns its full id <mod id>:section:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit section. |
api.register_settings_row(spec) | string | settings | Registers a typed row and returns its full id <mod id>:row:<local id>. Returns "" and fails the mod on a malformed, duplicate or over-limit row. |
api.settings_get(id, fallback?) | any | settings | Reads a row's stored value, or its default. Accepts a local or full id. |
api.settings_set(id, value) | bool | settings | Validates and stores a value for a row. Returns false for an unknown row or a value that does not match the row's type and range. Does not call on_change. |
Settings section spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
title | string | Yes | Display title, truncated to 64 characters. |
location | string | Optional | Where the section appears: mods (default), settings, preferences, gameplay_settings or system_settings. |
order | number | Optional | Sort order, default 100. Mod entries append after core rows. |
description | string | Optional | Hover hint, truncated to 120 characters. |
Settings row spec
| Key | Type | Required | Meaning |
id | string | Yes | Local id, 1-48 characters of lowercase a-z, 0-9, _ or -. |
section | string | Optional | mods by default, another allowed location, or this mod's full section id. |
label | string | Yes | Display label, truncated to 64 characters. |
type | string | Yes | toggle, choice or slider. |
default | any | Optional | Typed default. Toggle uses a boolean; choice uses one of its option values; slider uses a number clamped to its range. |
options | array | Choice only | Non-empty array of values, or objects {"value": ..., "label": "..."}. |
min, max, step | number | Slider only | Required for a slider. min must be less than max; step must be positive. |
hint | string | Optional | Hover hint, truncated to 120 characters. |
order | number | Optional | Sort order, default 100. |
available | function | Optional | available() -> bool. Hides the row when false. |
on_change | function | Optional | on_change(value). Runs after a player-driven edit. Programmatic settings_set does not call it. |
Sections and rows attach to the Settings root, Settings > Mods, or the Gameplay and System settings pages. A section opens a host-rendered subpage containing its rows. Toggle rows show Label: On/Off; choice rows cycle through their options; slider rows increment by step and wrap back to min after max. Player edits save through the normal save path. At most 4 sections and 32 rows per mod are allowed; mod rows always append after core rows, and the Settings root and Settings > Mods remain host-owned.
var section = ""
function on_init()
section = api.register_settings_section({
"id": "discipline",
"title": "Discipline",
"location": "mods"
})
api.register_settings_row({
"id": "strictness",
"section": section,
"label": "Strictness",
"type": "slider",
"min": 0, "max": 5, "step": 1, "default": 1,
"on_change": strictness_changed
})
end
function strictness_changed(value)
api.storage_set("strictness", value)
end
Content queries
With the content capability, read the currently loaded catalogue. Results are plain data; textures and engine objects are not exposed.
| Call | Returns | Capability | Behaviour |
api.content_list(kind) | array | content | Returns an array of string ids for the requested kind. Unknown kinds return an empty array. |
api.content_info(kind, id) | dict | content | Returns sanitized catalogue metadata for one entry. Unknown kinds or ids return an empty dictionary. |
kind | content_list result | content_info keys |
forms or pets | Form ids. | id, adult, collectible, name. |
shells | Shell ids. | Whitelisted keys from the shell definition: id, name, name_id, path, scale, pixels, adult, collectible, distribution, unlock. |
stickers | Sticker ids. | The same whitelisted keys as shells. |
assets | Asset ids. | The same whitelisted keys, when present. |
Only keys that exist in the definition are returned. content_info never returns raw textures or internal catalogue paths outside the whitelist.
Console commands
With the console capability, register commands for the debug console. Commands are always namespaced by the registering mod.
| Call | Returns | Capability | Behaviour |
api.register_command(spec) | bool | console | Registers one command. Returns true on success. An invalid name, missing handler or duplicate command fails the mod. |
Command spec
| Key | Type | Required | Meaning |
name | string | Yes | 1-32 characters of lowercase a-z, 0-9, _ or -. The host trims and lowercases it. |
usage | string | Optional | Usage text shown by the console, defaulting to the command name and truncated to 160 characters. |
description | string | Optional | Description text, truncated to 240 characters. |
handler | function | Yes | handler(args). Receives an array of string arguments after the command name. |
The handler may return a string, an array of lines, or nothing. Returned text is limited to 4,096 characters. The callback still needs the normal capabilities for any gameplay API it calls. In the console, use mod to list commands, mod <mod_id> to list one mod's commands, or mod <mod_id> <command> [args...] to run one. Tab completes mod ids and command names.
function on_init()
api.register_command({
"name": "garden_status",
"usage": "garden_status",
"description": "Print the garden's current state.",
"handler": garden_status
})
end
function garden_status(args)
return "Garden: " + str(api.storage_get("garden", {}))
end
Minimal complete mod
{
"id": "author.hello_pet",
"title": "Hello Pet",
"author": "Author",
"version": "1.0.0",
"type": "script",
"entry": "scripts/main.sgd",
"api_version": 5,
"capabilities": ["events", "notify", "storage"]
}
var fed_count = 0
function on_init()
fed_count = api.storage_get("fed_count", 0)
api.subscribe("pet.fed", on_fed)
api.notify("Hello Pet is installed!")
end
function on_fed(payload)
fed_count = fed_count + 1
api.storage_set("fed_count", fed_count)
api.notify("Yum! " + str(payload.food) + ". Fed " + str(fed_count) + " time(s).")
end
function on_deactivate()
api.storage_save()
end
Place the folder or ZIP in the mods directory from Install & test, restart, enable it in the Mods screen and feed the pet.
Security model
- No scene tree, nodes, engine objects, global GDScript scope,
OS, filesystem, network, Steam or resource-loader access.
- A separate interpreter, API object, registrations, timers and storage per mod.
- All drawing, input routing, image loading and gameplay changes are validated and performed by the host.
- A failing mod is disabled without crashing the game or other mods.
The sandbox is designed for untrusted Workshop content but is still software. Report validation or interpreter bugs rather than assuming absolute security.
Related guides