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.

TypeMeaning
nilNo value. A call documented as returning nil returns no useful result.
booltrue or false. Callback conditions use DejiScript truthiness; nil, 0, "" and empty containers are false.
numberAn integer or float. Required numbers must be finite; NaN and infinity fail the call.
stringA DejiScript string. Values are not implicitly converted unless the call says so.
arrayA DejiScript array of plain values.
dictA DejiScript dictionary with string or scalar keys.
rectA dictionary with numeric x, y, width and height keys, in logical LCD units.
pointA dictionary with numeric x and y keys, in logical LCD units.
functionA DejiScript function. Registration and subscription reject other values.
ctxThe restricted canvas object passed to a screen or minigame draw callback.
anyA 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.

SignatureReturnsCapability
api.log(value, ...)nilNone
api.now()numberNone
api.pet()dictpet.read
api.game_time()dictNone
api.apply_effect(kind, amount, reason?)boolpet.modify
api.game_state()dictstate.read
api.pet_presentation()dictpet.presentation
api.play_pet_reaction(name, options?)boolpet.presentation
api.stop_pet_reaction()boolpet.presentation
api.register_pet_stat(spec)stringpet.stats
api.pet_stat_get(id, fallback?)anypet.stats
api.pet_stat_set(id, value)boolpet.stats
api.pet_stat_add(id, delta)boolpet.stats
api.pet_storage_get(key, fallback?)anypet.stats
api.pet_storage_set(key, value)boolpet.stats
api.notify(message)boolnotify
api.open_screen(id)boolui
api.close_screen()boolui
api.register_screen(spec)stringui
api.register_menu_entry(spec)boolui
api.register_home_entry(spec)stringui.home
api.register_food(spec)stringfoods
api.register_collection_entry(spec)stringui.collections
api.register_main_screen_layer(spec)stringui.main
api.register_command(spec)boolconsole
api.register_minigame(spec)stringminigames
api.finish_minigame(won)boolminigames
api.register_item(spec)stringitems
api.give_item(id, amount?)boolitems
api.take_item(id, amount?)boolitems
api.item_count(id)numberitems
api.register_unlockable(spec)boolcontent.unlock
api.unlock_content(kind, id, amount?)boolcontent.unlock
api.set_content_unlocked(kind, id, unlocked)boolcontent.unlock
api.is_content_unlocked(kind, id)boolNone
api.give_sticker(id, amount?)boolcontent.unlock
api.subscribe(name, callback)boolevents
api.on(name, callback)boolevents
api.register_update(callback, hz?)boolevents
api.set_visitors_enabled(enabled)boolstate.modify
api.spawn_visitor(spec)boolstate.modify
api.dismiss_visitor()boolstate.modify
api.add_poo(slot?)boolstate.modify
api.remove_poo(slot)boolstate.modify
api.clear_poos()boolstate.modify
api.set_pet_status(flag, enabled)boolstate.modify
api.queue_gift(spec)boolstate.modify
api.dismiss_mod_gift()boolstate.modify
api.storage_get(key, fallback?)anystorage
api.storage_set(key, value)boolstorage
api.storage_save()boolstorage
api.set_schema(version)boolstorage
api.on_migrate(from_version, callback)boolstorage
api.load_image(path)stringui
api.image_size(asset_id)dict or nilui
api.sfx(name)boolui
api.register_settings_section(spec)stringsettings
api.register_settings_row(spec)stringsettings
api.settings_get(id, fallback?)anysettings
api.settings_set(id, value)boolsettings
api.content_list(kind)arraycontent
api.content_info(kind, id)dictcontent
api.mod_id()stringNone
api.api_version()numberNone
api.has_capability(name)boolNone

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
}
FieldTypeRequiredMeaning
idstringScript modsStable 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.
titlestringOptionalDisplay name in the Mods screen, Games menu and Workshop tools.
authorstringOptionalDisplay author.
versionstringOptionalFree-form mod version shown to players.
typestringScript mods"content" (default) or "script". A script mod must declare "script".
entrystringScript modsRelative path to the .sgd entry script inside the mod, normally scripts/main.sgd.
api_versionnumberScript modsMod 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_versionstringOptionalMinimum Dejinochi version, for example 1.1.0. The mod is rejected on an older game.
capabilitiesarrayScript modsNon-empty array of known capability strings. A call outside the declared set fails the call and disables the mod.
dependenciesarrayOptionalRequired mod ids as strings, or objects {"id": "...", "optional": true}. A missing required dependency is an error; a missing optional dependency is a warning.
descriptionstringOptionalDescription used by the Mods screen and Workshop tools.
icon, icon_scalearray, numberOptionalExisting 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

CapabilityGrants
pet.readapi.pet() and the pet snapshots in events.
pet.modifyapi.apply_effect(...).
eventsapi.subscribe, api.on and api.register_update.
uiapi.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.homeapi.register_home_entry and bounded home-tile drawing.
foodsapi.register_food and the food consumption callback.
ui.collectionsapi.register_collection_entry and Collections menu rows.
ui.mainapi.register_main_screen_layer, full-LCD home layers, pointer input and focused key input.
pet.presentationapi.pet_presentation, api.play_pet_reaction and api.stop_pet_reaction.
state.readapi.game_state and its complete snapshot.
state.modifyValidated visitor, poo, sleeping/sick and mod-gift modifiers.
minigamesapi.register_minigame, api.finish_minigame, and canvas drawing for registered minigames.
storageapi.storage_get, api.storage_set, api.storage_save, api.set_schema and api.on_migrate.
pet.statsapi.register_pet_stat, api.pet_stat_get, api.pet_stat_set, api.pet_stat_add, api.pet_storage_get and api.pet_storage_set.
settingsapi.register_settings_section, api.register_settings_row, api.settings_get and api.settings_set.
notifyapi.notify(...) on the normal feedback caption.
contentapi.content_list and api.content_info read-only catalogue queries.
content.unlockapi.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.
itemsapi.register_item, api.give_item, api.take_item and api.item_count.
consoleapi.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

ItemLimit
Script entry256 KiB.
Image loaded by api.load_image2 MiB, 1024 pixels per side, PNG/JPEG/WebP.
ZIP archive64 MiB expanded, 2,000 entries.
PathsRelative and inside the mod. Absolute paths, .., drive/colon paths and symbolic links are rejected.
DependenciesStrings or objects with id and optional optional. Required dependencies must be installed, enabled and valid.
Screens32 per mod, 128 total.
Games menu entries32 per mod, 128 total.
Items64 per mod, 256 total.
Home entries4 per mod, 32 total.
Pet stats16 per mod, 32 visible stats total.
Settings4 sections and 32 rows per mod.
Foods16 per mod, 32 total.
Collection entries4 per mod, 32 total.
Main-screen layers2 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.

CallbackArgumentsReturnsWhen it runs
on_init()NonenilAfter 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()NonenilAfter on_init and after migrations registered inside on_init succeed.
on_deactivate()NonenilWhen 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.

SituationResult
Missing capabilityThe call records an error and disables the mod.
Invalid required argumentExamples 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 failureAn 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 nameapi.subscribe accepts it, but the host never dispatches that name.
Callback executionEach invocation starts with a fresh execution budget. A failure disables only that mod.
Non-string value in a string parameterUnless a call says otherwise, the host uses the default value (usually "") and the call returns its documented failure.
LimitValue
Evaluation steps per callback250,000
Wall time per callback40 ms
Call depth48
Loop iterations100,000
Items in an array or dictionary8,192
Draw commands per frame2,000
Text per draw command512 characters
Notification message240 characters
Pet effect magnitude50
Events dispatched per tick256; a queue above 1,024 pending events is cleared.
Periodic callback catch-up8 calls per tick
Mod storage64 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 buckets256 per mod.

Runtime, identity and time

CallReturnsCapabilityBehaviour
api.log(value, ...)nilNoneTakes 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()numberNoneCurrent Unix timestamp in seconds. Use it for offline growth and cooldowns.
api.mod_id()stringNoneThe manifest id of the calling mod.
api.api_version()numberNoneThe host API contract version. This is not the value from the manifest.
api.has_capability(name)boolNoneExact match against the capabilities declared in the manifest.

Pet and game time

CallReturnsCapabilityBehaviour
api.pet()dictpet.readA copy of the current pet snapshot. Returns an empty dictionary only when no pet model is available.
api.game_time()dictNoneCurrent Unix time, in-game clock time and the current simulation-speed multiplier.
api.apply_effect(kind, amount, reason?)boolpet.modifyApplies 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:

KeyTypeMeaning
uuidstringOpaque host-owned identity for this pet. Stable across save/load and after graduation; do not change it.
namestringPet name.
formstringCurrent form id.
stagestringCurrent life stage name.
agenumberAge in game minutes.
happinessnumberHappiness, 0-100.
hungernumberHunger, 0-100.
healthnumberHealth, 0-100.
sleepnumberRest, 0-100.
sleepingboolWhether the pet is asleep.
sickboolWhether the pet is sick.
readyboolWhether the pet is ready to graduate.

Game-time snapshot

KeyTypeMeaning
unix_timenumberSystem Unix timestamp in seconds.
clock_timenumberThe game's simulated clock time.
simulation_speednumberCurrent 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>.

KindEffect
happinessAdds 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.
hungerAdds the amount to hunger and clamps the result to 0-100. Emits pet.effect_applied.
healthAdds the amount to health and clamps the result to 0-100. Emits pet.effect_applied.
sleepAdds the amount to rest and clamps the result to 0-100. Emits pet.effect_applied.
careRecords 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

CallReturnsCapabilityBehaviour
api.notify(message)boolnotifyShows a trimmed message on the normal feedback caption, capped at 240 characters. Returns false for an empty or non-string message.
api.sfx(name)booluiPlays one named stock sound and returns true. Unknown names return false.
Sound nameStock event
clickUI click.
confirmUI confirm.
backUI back.
deniedUI denied.
successMinigame success.
failureMinigame failure.
pickupSticker pickup.
happyPet 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.

CallReturnsCapabilityBehaviour
api.register_screen(spec)stringuiRegisters 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)booluiAdds 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)booluiOpens 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()booluiCloses 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
titlestringOptionalScreen title shown by the host, defaulting to the local id and truncated to 64 characters.
drawfunctionYesdraw(ctx). Rebuilds the screen immediately before every rendered frame.
on_openfunctionOptionalon_open(). Load screen state here.
on_closefunctionOptionalon_close(). Runs when the player really leaves the screen, not on a cosmetic UI rebuild.
on_updatefunctionOptionalon_update(delta). Runs every frame while the screen is open.
on_actionfunctionOptionalon_action(event). Runs on a left-button press on a button or hit region. event.hit is its id.
on_pointerfunctionOptionalon_pointer(event). Receives pointer movement and any press or release not consumed by on_action.
on_keyfunctionOptionalon_key(action). Receives left, right, up, down, accept or cancel.
statusfunctionOptionalAccepted and stored for compatibility. Screens do not currently call it; minigames use their own status callback.

Menu entry spec

KeyTypeRequiredMeaning
labelstringYesVisible label, truncated to 64 characters. An empty label fails registration.
screenstringYesLocal or full id of this mod's screen. The entry is hidden until that screen exists.
ordernumberOptionalSort order, default 100. Lower values appear first; equal orders sort by label.
availablefunctionOptionalavailable(). Return a truthy value to show the entry. A false result hides it.

Images

CallReturnsCapabilityBehaviour
api.load_image(path)stringuiLoads 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 niluiReturns {"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.

CallReturnsCapabilityBehaviour
api.register_home_entry(spec)stringui.homeRegisters 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
labelstringOptionalAccessibility and fallback label, defaulting to the local id and truncated to 64 characters.
screenstringYesLocal or full id of this mod's registered screen. The entry is hidden until that screen exists.
iconstringOptionalAsset id returned by api.load_image. The icon takes precedence over draw.
icon_scalenumberOptionalNative scale for the icon, default 0. Zero fits the icon to the tile; positive values use that pixel scale.
drawfunctionOptionaldraw(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.
offsetdictOptionalTile-local {"x": number, "y": number} offset for the icon/draw content, default {0, 0}.
hover_sizedictOptionalTile-local {"x": number, "y": number} hover box, centred on the content. Omit for the full tile.
badgefunctionOptionalbadge() -> string or nil. Short host-rendered status text, truncated to 16 characters.
ordernumberOptionalSort order, default 100. Lower values appear first.
availablefunctionOptionalavailable() -> bool. A false result hides the entry.
descriptionstringOptionalHover 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.

CallReturnsCapabilityBehaviour
api.register_food(spec)stringfoodsRegisters 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
labelstringYesDisplay name, truncated to 64 characters.
descriptionstringOptionalHover hint, truncated to 120 characters.
ordernumberOptionalSort order among mod foods, default 100.
availablefunctionOptionalavailable() -> bool. A false result hides the food.
on_consumefunctionYeson_consume(context). Called once when the pet eats the food.
on_consume context keyTypeMeaning
foodstringThe full registered food id.
too_fullboolWhether the pet was above the overfeeding threshold before consumption.
petdictThe same snapshot returned by api.pet().
timedictThe 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.

CallReturnsCapabilityBehaviour
api.register_collection_entry(spec)stringui.collectionsRegisters 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
labelstringYesDisplay label, truncated to 64 characters.
screenstringYesLocal or full id of this mod's registered screen. The entry is hidden until the screen exists.
descriptionstringOptionalHover hint, truncated to 120 characters.
ordernumberOptionalSort order, default 100.
availablefunctionOptionalavailable() -> 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.

PropertyTypeMeaning
ctx.widthnumberLogical canvas width, 308.
ctx.heightnumberLogical canvas height, 189 for screens and 231 for minigames.
ctx.elapsednumberSeconds since this canvas first drew, for animation.
CallReturnsBehaviour
ctx.rect(x, y, w, h, color?)nilFilled 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?)nilLine segment. width defaults to 1 and clamps to 1..16. color defaults to ink.
ctx.text(x, y, text, size?, color?)nilCanvas-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?)nilStock 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)nilStock 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?)nilDraws 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?)nilDraws 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?)nilInvisible 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()nilClears all commands and hit regions recorded so far in this frame. The host already clears them before each draw.
ctx.hovered()stringId of the hovered button or hit region, or "".
ctx.finish(won)nilFinishes 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

ValueResult
"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 1Grey 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.

Input

Pointer events are plain dictionaries in logical canvas coordinates.

KeyTypePresent onMeaning
typestringAll pointer events"move", "press" or "release".
x, ynumberAll pointer eventsPosition in logical canvas coordinates.
buttonstringPress and release"left". Movement events omit it.
hitstringAll pointer eventsThe 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.

ActionKeyboard or controller input
left, right, up, downArrow keys or D-pad.
acceptEnter, keypad Enter or Space; controller A.
cancelEscape; 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.

CallReturnsCapabilityBehaviour
api.register_main_screen_layer(spec)stringui.mainRegisters 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
layerstringYesbackground, under_pet or over_pet.
drawfunctionYesdraw(ctx). Runs while the home pet screen is visible. The full LCD is available and clipped to its bounds.
on_updatefunctionOptionalon_update(delta). Runs while the layer is visible.
on_pointerfunctionOptionalon_pointer(event). Receives pointer movement, press and release events that core controls did not consume. event.hit is the layer hit id.
on_keyfunctionOptionalon_key(action). Receives keys only while the layer has host-controlled focus.
availablefunctionOptionalavailable() -> bool. A false result hides and skips the layer.
ordernumberOptionalSort 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.

CallReturnsCapabilityBehaviour
api.register_minigame(spec)stringminigamesRegisters 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)boolminigamesFinishes 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
titlestringOptionalDisplay name, defaulting to the local id and truncated to 64 characters.
drawfunctionYesdraw(ctx). Draws the full minigame canvas.
on_startfunctionOptionalon_start(). Runs once when the session starts.
on_updatefunctionOptionalon_update(delta). Runs every frame while the game is active.
on_pointerfunctionOptionalon_pointer(event). Receives pointer movement, press and release events.
on_keyfunctionOptionalon_key(action). Receives the same actions as screens.
statusfunctionOptionalstatus(). Returns the top-caption objective text. A nil result falls back to the title.
availablefunctionOptionalavailable(). Return a truthy value to list and allow the game. A false result hides it and prevents starting.
on_finishfunctionOptionalon_finish(won). Runs after the host accepts the result. Apply mod-side rewards here.
on_cancelfunctionOptionalon_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

CallReturnsCapabilityBehaviour
api.subscribe(name, callback)booleventsSubscribes 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)booleventsAlias for api.subscribe.
api.register_update(callback, hz?)booleventsRuns 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.

EventPayload fieldsWhen it fires
game.loadedpet: dict, time: dictAfter enabled code mods load and their on_init subscriptions are registered.
game.startedpet: dict, time: dictAfter the game UI and runtime finish starting.
game.minute_elapsedclock_time: number, unix_time: numberOnce per simulated minute.
pet.fedfood: string, too_full: bool, pet: dictAfter a successful feed.
pet.pattedhappiness: number, pet: dictAfter petting.
pet.treatedhealth: number, pet: dictAfter medicine is used.
pet.sleep_started, pet.woke_upmanual: bool, pet: dictOn sleep or wake. manual is true for the light action and false for automatic waking.
pet.evolvedfrom_stage: string, to_stage: string, form: string, pet: dictWhen the pet reaches a new life stage.
pet.graduateduuid: string, name: string, form: string, quality: stringWhen a pet graduates. uuid is the graduating pet's stable identity.
pet.happiness_changedvalue: number, delta: number (effect changes only), source: stringWhen happiness changes. The pat event has no delta; effect changes include it. A mod effect source is <mod id>:<reason>.
pet.effect_appliedkind: string, amount: number, source: stringAfter a valid effect from api.apply_effect.
minigame.startedid: string, modded: boolWhen a minigame starts. A modded id is the full registered id.
minigame.completedid: string, won: bool, modded: boolAfter the host finishes a minigame.
minigame.cancelledid: string, modded: boolWhen an active minigame is cancelled.
visitor.arrived, visitor.leftvisitor: dictWhen a visitor appears or leaves. The payload is the visitor snapshot.
visitor.pettedvisitor: dictAfter the player pets the visitor.
gift.pending, gift.opened, gift.clearedgift: dictWhen a gift is queued, opened or cleared. The payload is the gift snapshot.
poo.added, poo.removedslot: number, optional visible: bool, poos: dictWhen a poo is added or removed.
poo.visibility_changedpoos: dictWhen deferred poos become visible or are re-hidden.
pet.sick_changedsick: bool, pet: dictWhen the sick flag changes.
pet.sleeping_changedsleeping: bool, pet: dictWhen the sleeping flag changes.
pet.ready_changedready: bool, pet: dictWhen the pet becomes ready to graduate.
pet.stage_up_startedstage_up: dict, optional from_stage: string, pet: dictWhen the stage-up celebration starts.
pet.stage_up_acknowledgedstage_up: dict, pet: dictWhen the player acknowledges the stage-up celebration.
graduation.startedgraduation_started: bool, pet: dictWhen the graduation sequence starts.
ui.page_changedpage: string, previous: string, UI flagsOn a real page transition.
pet.reaction_started, pet.reaction_finishedreaction: string, name: string, target: dict, duration: number, interrupted: bool, pose: stringWhen 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.

KeyTypeMeaning
pagestringCurrent host page.
is_home, is_modal, is_settings, is_collectionsboolCurrent page category flags.
is_game_activeboolWhether a minigame is running.
minigamedictEmpty, or id, modded, phase and status.
actiondictname, remaining and queue_length for the current pet action sequence.
stage_updictactive, from_stage, state and elapsed.
graduation_started, demo, gaming_mode, window_minimizedboolSession and presentation flags.
petdictExtended pet snapshot described below.
pet_presentation, visitor_presentationdictVisual snapshots described under Pet presentation.
timedictSame fields as api.game_time().
visitordictactive, enabled, source, name, form, persona, remaining, hovered, petting_remaining.
giftdictpending, on_screen, opened, source, kind, recipient, occasion, sticker_id, item_id, minigame_id.
poosdicttotal, visible, deferred_slots, reveal_remaining and entries.
items, stickers, shells, achievements, visitsdictOwnership, unlock, achievement and visit-timer summaries.
blockingdictvisitor and gift flags for state that blocks normal play.
is_interactiveboolWhether the home screen is in a normal interactive state.

Extended pet state

game_state().pet contains every field from api.pet(), plus:

KeyTypeMeaning
poo_count, visible_poo_countnumberTotal and currently visible poos.
poosarrayEntries with slot, age_hours and visible.
playdictfatigue (dict of minigame id to number), request_id (string), request_remaining (number) and request_wait (number).
final_touchboolWhether the pet has had its final graduation touch.
childhood, is_childhoodboolWhether the pet is in a childhood stage.
is_neglected, is_needy, is_tuckered_outboolDerived pet-state checks.
seconds_until_age_upnumberSeconds until the next life-stage change.
care_qualitystringCurrent graduation care rating.
foodsdictFood id or base food name to a numeric feed count.
historydictChildhood 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.
lifetimedictWhole-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().

KeyShape
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.

CallBehaviour
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.

CallReturnsBehaviour
api.pet_presentation()dictPresentation snapshot for the current pet. Same data appears as game_state().pet_presentation.
api.play_pet_reaction(name, options?)boolStarts a presentation-only host reaction. Fails while the pet is busy or in an incompatible state.
api.stop_pet_reaction()boolStops a reaction owned by this mod.

Pet presentation snapshot

KeyTypeMeaning
visibleboolWhether the pet is currently drawn on the home screen.
form, posestringCurrent form and renderer pose.
rect, interaction_rect, visible_boundsdictLogical LCD rectangles with x, y, width and height.
anchor, form_offsetdictCurrent anchor and form offset as {x, y}.
frame, frame_progress, fpsnumberAnimation frame, progress within the frame and animation rate.
scalenumberPresentation scale.
facingstringleft, right or center.
busyboolWhether another action, reaction, gift, modal or minigame owns the pet.
reactionstringActive reaction name, or "" when none is active.
reaction_remainingnumberSeconds left in the active reaction, or 0.0.
reaction_targetpointActive 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}.

KeyTypeMeaning
visibleboolWhether the visitor is on screen.
formstringVisitor form id.
posestringVisitor renderer pose.
rectrectVisitor interaction rectangle.
anchorpointVisitor anchor position.
interaction_rectrectVisitor interaction rectangle.

Pet reactions

Allowed reaction names: idle, happy, unhappy, hungry, sick, sleep, wake, eat, care, clean, play, proud, look_at, approach and interact.

OptionTypeMeaning
durationnumberReaction length, clamped to 0.5-8 seconds. Default 1.6.
targetdict{x, y} in logical LCD coordinates for look_at, approach and interact.
posestringOptional safe pose: Idle, Happy, Unhappy, Hungry, Sick, Sleeping, Proud, Eat, Care, Clean or Play.
emoteboolWhether 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>.

CallReturnsCapabilityBehaviour
api.register_item(spec)stringitemsRegisters 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?)boolitemsAdds 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?)boolitemsConsumes owned copies. amount defaults to 1. Returns false when the amount is non-positive or the count is insufficient.
api.item_count(id)numberitemsReads the owned count. Returns 0 when the item is not owned by this mod.

Item spec

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
titlestringOptionalDisplay name, defaulting to the local id and truncated to 64 characters.
descriptionstringOptionalDescription, truncated to 240 characters.
giftableboolOptionalWhether the ordinary item-gift flow may offer it. Defaults to false; non-giftable items are custom-only.
on_usefunctionOptionalon_use(). Runs when an owned item is selected in the Items menu.
screenstringOptionalScreen 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.

CallReturnsCapabilityBehaviour
api.register_unlockable(spec)boolcontent.unlockRegisters 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?)boolcontent.unlockGrants 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)boolcontent.unlockExplicitly 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)boolNoneReads 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?)boolcontent.unlockGrants owned sticker copies. amount defaults to 1 and values below 1 are treated as 1.

Unlockable spec

KeyTypeRequiredMeaning
kindstringYes"shell" or "sticker". Items use the item API instead.
idstringYesId of a shell or sticker defined in this mod's data files.
hintstringOptionalLocked-state hint, truncated to 160 characters.
is_unlockedfunctionYesis_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.

CallReturnsCapabilityBehaviour
api.storage_get(key, fallback?)anystorageReturns 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)boolstorageWrites 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()boolstorageRequests an immediate save through the normal save manager. Returns the save result, or true when no save manager is attached.
api.set_schema(version)boolstorageRecords 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)boolstorageRegisters 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 ruleLimit or result
Allowed valuesnil, booleans, finite numbers, strings, arrays and dictionaries.
Dictionary keysString, integer, float or boolean.
Per mod64 KiB.
All mod state512 KiB.
Nesting depth8.
Items per array or dictionary512.
String length8,192 characters; longer strings are truncated on write.
Engine objectsRejected. 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.

CallReturnsCapabilityBehaviour
api.register_pet_stat(spec)stringpet.statsRegisters 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 fallbackpet.statsReads 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)boolpet.statsSets 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)boolpet.statsAdds 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?)anypet.statsReads 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)boolpet.statsWrites 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
labelstringYesDisplay label, truncated to 64 characters.
minnumberOptionalMinimum value, default 0. Must be less than max.
maxnumberOptionalMaximum value, default 100. Must be greater than min.
defaultnumberOptionalStarting value for a pet with no stored value, default 0 and clamped to min..max.
decay_per_hournumberOptionalAmount applied by the normal pet simulation per simulated hour, default 0. Use a negative value to drain.
offline_decay_per_hournumberOptionalAmount applied during offline catch-up, defaulting to decay_per_hour.
visibleboolOptionalWhether the stat appears under Stats > Mod stats, default true.
ordernumberOptionalSort order on the Mod stats page, default 100.
formatfunctionOptionalformat(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.

CallReturnsCapabilityBehaviour
api.register_settings_section(spec)stringsettingsRegisters 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)stringsettingsRegisters 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?)anysettingsReads a row's stored value, or its default. Accepts a local or full id.
api.settings_set(id, value)boolsettingsValidates 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

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
titlestringYesDisplay title, truncated to 64 characters.
locationstringOptionalWhere the section appears: mods (default), settings, preferences, gameplay_settings or system_settings.
ordernumberOptionalSort order, default 100. Mod entries append after core rows.
descriptionstringOptionalHover hint, truncated to 120 characters.

Settings row spec

KeyTypeRequiredMeaning
idstringYesLocal id, 1-48 characters of lowercase a-z, 0-9, _ or -.
sectionstringOptionalmods by default, another allowed location, or this mod's full section id.
labelstringYesDisplay label, truncated to 64 characters.
typestringYestoggle, choice or slider.
defaultanyOptionalTyped default. Toggle uses a boolean; choice uses one of its option values; slider uses a number clamped to its range.
optionsarrayChoice onlyNon-empty array of values, or objects {"value": ..., "label": "..."}.
min, max, stepnumberSlider onlyRequired for a slider. min must be less than max; step must be positive.
hintstringOptionalHover hint, truncated to 120 characters.
ordernumberOptionalSort order, default 100.
availablefunctionOptionalavailable() -> bool. Hides the row when false.
on_changefunctionOptionalon_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.

CallReturnsCapabilityBehaviour
api.content_list(kind)arraycontentReturns an array of string ids for the requested kind. Unknown kinds return an empty array.
api.content_info(kind, id)dictcontentReturns sanitized catalogue metadata for one entry. Unknown kinds or ids return an empty dictionary.
kindcontent_list resultcontent_info keys
forms or petsForm ids.id, adult, collectible, name.
shellsShell ids.Whitelisted keys from the shell definition: id, name, name_id, path, scale, pixels, adult, collectible, distribution, unlock.
stickersSticker ids.The same whitelisted keys as shells.
assetsAsset 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.

CallReturnsCapabilityBehaviour
api.register_command(spec)boolconsoleRegisters one command. Returns true on success. An invalid name, missing handler or duplicate command fails the mod.

Command spec

KeyTypeRequiredMeaning
namestringYes1-32 characters of lowercase a-z, 0-9, _ or -. The host trims and lowercases it.
usagestringOptionalUsage text shown by the console, defaulting to the command name and truncated to 160 characters.
descriptionstringOptionalDescription text, truncated to 240 characters.
handlerfunctionYeshandler(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