Friends, stats and achievements
Friends
Section titled “Friends”The friends namespace reads the local user’s friend list, friend state and avatars, and sends game invites. SteamIDs are bigint values.
const steamworks = require('steamworks.js')const client = steamworks.init(appId)
// 0x4 = immediate friends (FriendFlags.IMMEDIATE)for (const friend of client.friends.getFriends(0x4)) { const state = client.friends.getFriendState(friend.steamId64) const avatar = client.friends.getMediumAvatar(friend.steamId64) // Buffer of RGBA pixels, or null console.log(friend.nickName ?? friend.name, state, avatar?.length ?? 0)}
// Invite a friend to the current game with a connect stringclient.friends.inviteUserToGame(friendSteamId, 'lobby=abc')
// Remove the Rich Presence keys set with localplayer.setRichPresenceclient.friends.clearRichPresence()getFriendStatereturns aFriendStatevalue;getFriendGamePlayedreturns the AppID of the game a friend is playing, ornull.- Avatars are
nulluntil Steam has loaded them. Callclient.friends.requestUserInformation(steamId64, true)to ask for a user’s information, and wait for thePersonaStateChangecallback before reading it again. - Name and state updates arrive through
runCallbacks(), whichinit()already calls on a timer.
Stats, Achievements and Leaderboards
Section titled “Stats, Achievements and Leaderboards”stats gains float stats, the achievement count and a request for another user’s stats. achievement gains global unlock percentages and the data an achievement page needs: display name, description, hidden flag, unlock time, progress limits and icon. The leaderboard namespace finds and creates leaderboards, uploads scores and downloads entries.
const steamworks = require('steamworks.js')const client = steamworks.init(appId)
client.stats.setFloat('distance', 12.5)console.log(client.stats.getFloat('distance')) // 12.5, or null when the stat is not definedconsole.log(client.stats.getNumAchievements())
// Global unlock percentages: call the request first, then read each achievementawait client.achievement.requestGlobalPercentages()console.log(client.achievement.getAchievedPercent('FIRST_RUN')) // 0 to 100, or null
// Leaderboards: 0 = Ascending, 0 = Numeric; upload with 0 = KeepBest, download with 0 = Globalconst board = await client.leaderboard.findOrCreate('Fastest', 0, 0)if (board) { const result = await board.uploadScore(0, 1234, []) // null when Steam did not accept the upload const top = await board.downloadEntries(0, 0, 10, 0) // ranks 0 to 9 console.log(board.getName(), board.getEntryCount(), result, top)}requestUserStats(steamId64)only starts the request. Its result arrives through theUserStatsReceivedcallback (seecallback.register).- The Promise-returning functions (
requestGlobalPercentages,find,findOrCreate,uploadScore,downloadEntries) resolve when Steam answers. Steam delivers those answers insiderunCallbacks().init()runs it about 30 times a second, so you do not need to call it yourself while the client is initialized. - A Promise rejects with a readable message when Steam reports a failure. When the answer is lost, the message says the outcome is unknown, so check the data before retrying an upload.
Achievement display data
Section titled “Achievement display data”achievement.getAll() and achievement.getInfo(name) return what a client needs to list achievements. Call requestGlobalPercentages() first to fill globalPercent.
await client.achievement.requestGlobalPercentages()
for (const item of client.achievement.getAll()) { // item: { name, displayName?, description?, hidden?, unlocked, unlockTime?, globalPercent?, progressLimits? } const when = item.unlockTime === undefined ? null : new Date(item.unlockTime * 1000) console.log(item.displayName ?? item.name, item.unlocked, when, item.globalPercent)}
// Icon as raw RGBA pixels; loadIcon waits for Steam to fetch it, getIcon does notconst icon = await client.achievement.loadIcon('FIRST_RUN', 3000) // { width, height, rgba: Buffer } or nullunlockTimeis in seconds since 1970-01-01 UTC. It is left out for a locked achievement and for unlocks that Steam has no time for (Steam reports0for unlocks before December 2009).displayName,descriptionandhiddencome from Steam’s localized achievement data. They are left out when Steam has no data, for example before the user’s stats have arrived.getInforeturnsnullwhen Steam cannot read the achievement (unknown name, stats not received). That is a failed lookup, not a locked achievement.getAllskips such entries, so compare its length withstats.getNumAchievements().names()returns an empty array when the app defines no achievements instead of throwing.progressLimits(alsogetProgressLimits(name)) gives the min and max of the stat that Steam links to the achievement, or is left out when there is none. Steam’s achievement API does not return the current value: read the linked stat withstats.getIntorstats.getFloat.indicateProgress(name, current, max)shows the Steam overlay progress notice. It never unlocks the achievement.getIconandloadIconreturnnullwhile Steam has not fetched the icon and when the achievement has no icon. Steam picks the locked or unlocked artwork from the user’s state. Convert the RGBA pixels to PNG on your side if you need a file.- Not verified against a live Steam client in this checkout: only the export list and the TypeScript declarations are tested offline.
Global stats, achievement ranking, utils and apps
Section titled “Global stats, achievement ranking, utils and apps”stats gains other users’ stats, global stats with daily history, average-rate stats and the current player count. achievement.getMostAchievedAchievements() returns the global ranking. leaderboard gains attachUgc and downloadEntriesForUsers. utils gains the Steam universe, IPv6 state, file signature check and text filter. apps gains DLC listing and install control, file details, timed trial, beta branches and proof-of-purchase keys.
const steamworks = require('steamworks.js')const client = steamworks.init(appId)
// Global stats: request first, then read. int64 values are BigInts; history is newest day firstawait client.stats.requestGlobalStats(7)console.log(client.stats.getGlobalInt('total_kills'), client.stats.getGlobalIntHistory('total_kills', 7))
// Achievement ranking, most achieved first; needs requestGlobalPercentages() firstawait client.achievement.requestGlobalPercentages()console.log(client.achievement.getMostAchievedAchievements()) // [{ name, percent, achieved }]
// DLC and beta branches. installDlc and setActiveBeta change the local installationconst dlcs = client.apps.getDlcs() // [{ appId, available, name }]const betas = client.apps.getBetas() // [{ name, description, buildId, flags, isDefault, isSelected, ... }]
// Text filter: initFilterText() first; 2 = Chatclient.utils.initFilterText()const filtered = client.utils.filterText(2, 76561198000000000n, 'some chat text') // { text, filteredCount } or nullgetUserIntandgetUserFloatneedrequestUserStats(steamId64)to have completed for that user. They returnnullwhen the stat is missing or the user’s stats are not loaded.- Promises from
requestGlobalStats,getNumberOfCurrentPlayers,attachUgc,downloadEntriesForUsers,checkFileSignatureandgetFileDetailsresolve when Steam answers. That happens insiderunCallbacks(), whichinit()runs about 30 times a second. A Promise rejects with a readable message when Steam reports an error. requestGlobalStats(days)accepts at most 60 days, and the global history getters returnnullabove that. The global getters returnnulluntil the request completes.updateAvgRateStatchanges the local stats. Nothing reaches Steam untilstats.store(). Steam keeps the count as a 32-bit float.downloadEntriesForUserstakes at most 100 SteamIDs; more are rejected before Steam is called.attachUgcchanges the user’s leaderboard data on Steam.installDlc,uninstallDlc,markContentCorruptandsetActiveBetachange the local installation.setDlcContextonly tells Steam which DLC is being played.requestProofOfPurchaseKeyandrequestAllProofOfPurchaseKeysanswer through theAppProofOfPurchaseKeyResponsecallback (callback.register). The final callback of the full request hasappId0. The keys are secrets: do not log them.- Units:
getEarliestPurchaseUnixTimeis seconds since 1970-01-01 UTC.getDlcDownloadProgressandgetFileDetailsreport bytes as BigInts.getFileDetails().sha1is 40 lowercase hex characters.getSecondsSinceAppActiveandgetSecondsSinceComputerActiveare seconds.getCurrentBatteryPoweris a percentage, and 255 means AC power. - Sync calls return
nullorfalseon failure and do not throw. The SDK header does not say whatgetEarliestPurchaseUnixTimereturns without a purchase, and does not define theavailableflag of a DLC or the flags ofgetFileDetails. - Not verified against a live Steam client: all of the above. Only the export list and the TypeScript types are tested offline.
Inventory
Section titled “Inventory”client.inventory reads and changes the user’s Steam Inventory: item instances, item definitions, promotions, prices and purchases. Most calls resolve once Steam has answered.
const { items, timestamp, expired } = await client.inventory.getAllItems()for (const item of items) { // item: { itemId: bigint, definition: number, quantity: number, flags: number } console.log(item.itemId, item.definition, item.quantity)}
// Changes the real inventory: ask the user before you call thisconst { items: changed } = await client.inventory.consumeItem(items[0].itemId, 1)
// Items another player sent: null when Steam rejects the buffer or it belongs to someone elseconst verified = client.inventory.deserializeResult(received, senderSteamId)
// Property changes are one batch: set what you need, then submit onceconst update = client.inventory.startUpdateProperties()update?.setInt64(items[0].itemId, 'level', 3n)await update?.submit()- Each Promise resolves when Steam’s
SteamInventoryResultReady_tcallback arrives. Steam delivers that callback insiderunCallbacks(), whichinit()runs on a timer. Every async function takes an optionaltimeoutMs(default 30000). - A Promise rejects with a readable message when Steam reports an error. When no answer arrives within
timeoutMs, the message says the outcome is unknown: the change may still have happened, so check the inventory before you retry. - Functions that grant, create, consume, exchange, trade, buy or submit property changes change the user’s real inventory. Ask the user to confirm before you call them.
- Item instance ids, Steam ids and prices are
bigint, because they can exceed 2^53.definition,quantityandflagsarenumber. Prices are in the smallest unit of the currency thatrequestPrices()reports. expired: truemeans Steam may have changed the result since it was made, for example because an item was traded or consumed. The items are still returned.serializeItems(itemIds)returns a Buffer. Steam marks a serialized resultexpiredafter one hour.deserializeResult(data, steamId)is synchronous and returnsnullon failure, so pass the Steam id of the player who sent the buffer.loadItemDefinitions()only starts the load. This binding does not expose Steam’s definition-update callback, so it cannot tell you when the definitions are complete.getItemDefinitions()can return an incomplete list until then.startPurchase()resolves when Steam opens the transaction. The user completes the purchase in the Steam overlay, and the final result arrives later through Steam’s result-ready callback, not through this Promise.tradeItems()andsendItemDropHeartbeat()are deprecated by Steam. The SDK documents trading as not supported, sotradeItems()is expected to reject.- Not verified against a live Steam client: no call was made against a Steam account in this checkout. Only the export list, the TypeScript declarations and the pure conversion code are tested offline.
User, user-file and UGC calls (localplayer, auth, cloud)
Section titled “User, user-file and UGC calls (localplayer, auth, cloud)”localplayeradds the ISteamUser calls that were missing:getHSteamUser(),trackAppUsageEvent(),getUserDataFolder(), the voice calls (startVoiceRecording(),stopVoiceRecording(),getAvailableVoice(),getVoice(),decompressVoice(),getVoiceOptimalSampleRate()),isBehindNat(),advertiseGame(),getGameBadgeLevel(), the phone and two-factor checks,getMarketEligibility(),getDurationControl()andsetDurationControlOnlineState().authaddsrequestEncryptedAppTicket(),getEncryptedAppTicket()andrequestStoreAuthUrl(). The encrypted ticket is requested first, then read;getEncryptedAppTicket()does not call Steam.cloudadds the user-file callsgetQuota(),writeFileAsync(),openWriteStream()(aFileWriteStreamwithwriteChunk(),close()andcancel()),beginFileWriteBatch(),endFileWriteBatch()andgetLocalFileChanges().cloudalso adds the UGC callsdownloadUgc(),downloadUgcToLocation(),getUgcDownloadProgress(),getUgcDetails(),readUgc(),getCachedUgcCount()andgetCachedUgcHandle().- Steam ids and UGC handles are
bigint. A negative id or one of 2^64 or more is rejected before anything is sent. Results that Steam can leave empty come back asnull. - Async functions resolve through
runCallbacks(), whichinit()already calls. There is no timeout: if Steam never answers, the Promise stays pending. ForwriteFileAsync()and thedownloadUgc*()calls, the outcome is then unknown. writeFileAsync()andFileWriteStream.close()change the user’s cloud files, anddownloadUgc*()starts network transfers. Ask the user to confirm before you call them.- A
FileWriteStreamthat is garbage-collected withoutclose()orcancel()is closed by the wrapper, which commits the chunks written so far. When that happens depends on the garbage collector, so callclose()orcancel()yourself. - The legacy Workshop publishing calls of
ISteamRemoteStorageare not exposed;ISteamUGCreplaces them (see theworkshopnamespace). - Not verified against a live Steam client: no call was made against a Steam account in this checkout. Only the export list, the TypeScript declarations and the argument checks that run before any Steam call are tested offline.
ISteamFriends: groups, clans, clan chat, follows and profile items
Section titled “ISteamFriends: groups, clans, clan chat, follows and profile items”The friends namespace also covers the rest of ISteamFriends: friends groups, clans and clan officers, clan and friend chat, follower counts, equipped profile items, rich presence reads and clan activity counts. This example shows one call of each kind.
const steamworks = require('steamworks.js')const client = steamworks.init(appId)
// A cache read: no Steam request. Each group lists its members as SteamID64 bigints.for (const group of client.friends.getFriendGroups()) { console.log(group.name, group.members.length)}
async function readClanChat(clanChatId) { // 1 = ChatRoomEnterResponse.Success; other values are Steam's failure reasons if ((await client.friends.joinClanChatRoom(clanChatId)) !== 1) return null return client.friends.getClanChatMessage(clanChatId, 0) // ChatMessage or null}
async function readFollowing() { // One page of the following list, up to 50 SteamIDs per page const page = await client.friends.enumerateFollowingList(0) console.log(page.steamIds.length, page.totalCount)}- Units: SteamIDs and clan chat ids are
bigint. Indexes, counts andtotalCountarenumber.enumerateFollowingList(startIndex)returns at most 50 SteamIDs per page, the SDK’sk_cEnumerateFollowersMaxlimit. - Cache reads (
getFriendGroups(),getClans(),getFriendRichPresence(),getProfileItemPropertyString()) answer from data that Steam already holds. Without that data they returnnull,0or an empty list. Request it first:requestFriendRichPresence()(theFriendRichPresenceUpdatecallback follows), and the Promises ofrequestEquippedProfileItems(),downloadClanActivityCounts(),requestClanOfficerList()andgetClanInfo(). - The Promise calls (
joinClanChatRoom(),getFollowerCount(),isFollowing(),enumerateFollowingList(),requestEquippedProfileItems(),getClanInfo(),downloadClanActivityCounts(),requestClanOfficerList()) resolve throughrunCallbacks(), whichinit()already calls. They reject with Steam’s error text when Steam reports a failure. There is no timeout: a call that Steam never answers stays pending. joinClanChatRoom()resolves with aChatRoomEnterResponse. Only1(Success) means the room was joined. Values2to12are the SDK’s failure reasons.- Chat messages arrive as callbacks. Register
GameConnectedFriendChatMsg,GameConnectedClanChatMsg,GameConnectedChatJoinandGameConnectedChatLeavewithcallback.register(), and callsetListenForFriendsMessages(true)before you expect friend messages. The callbacks fire only fromrunCallbacks(). getClanChatMessage(clanChatId, index)andgetFriendMessage(steamId, index)return aChatMessageornull.sendClanChatMessage()andreplyToFriendMessage()return a boolean, which istrueonly when Steam accepts the message. Not verified: the order of the message index and what Steam returns for an index past the end.- Not verified against a live Steam client: no call was made against a Steam account in this checkout. Also unverified: a clan’s name before its download, a friend’s Steam level before Steam loads it, the value of an empty rich presence key, and what
registerProtocolInOverlayBrowser()does in the overlay. The export list, the TypeScript declarations, the enum values and the callback numbers are tested offline.
Steam HTTP (http)
Section titled “Steam HTTP (http)”Sends HTTP requests through the Steam client. It needs init() and a running, logged-in Steam client.
const client = steamworks.init(480)const response = await client.http.request({ method: 'GET', url: 'https://example.com/api/items', query: { page: '1' }, headers: { Accept: 'application/json' }, responseHeaders: ['ETag'], timeoutMs: 10000,})console.log(response.status, response.headers.ETag, response.body.toString('utf8'))request()resolves for every answer the server gives, including404and500, so checkstatusyourself. It rejects when the request cannot be created or sent, when Steam refuses a header or option, when Steam cannot complete the request, when no answer comes, or when the request times out.- Units:
timeoutMsis a total time limit in milliseconds. Unlike the inactivity timeout, it does not reset when data arrives. Steam’s default is no total limit. - Methods:
GET,HEAD,POST,PUT,DELETE,OPTIONSandPATCH, in any letter case.queryis added to the URL forGETand sent as form data for other methods.formis sent as form data.body(aBuffer) needs a method that accepts a body, cannot be combined withformorquery, and usescontentType(defaultapplication/octet-stream). responseHeadersnames the response headers to return. Steam cannot list all of them, so name each one you need. The response has no status text, because the SDK does not provide one.- Cookies:
client.http.createCookieContainer(allowResponsesToModify)makes a container that lasts for this process only. Pass it ascookieContainerand add cookies withsetCookie(host, url, cookie). - The promise resolves through
runCallbacks(), whichinit()already calls. - Not verified against a live Steam client: how HTTPS certificates are checked against a browser’s rules, and what
requireVerifiedCertificate: falsedoes.
Networking utilities (networkingUtils)
Section titled “Networking utilities (networkingUtils)”Ping locations, data centers (POPs), fake IP addresses and config values. These functions need init(). Reads that Steam cannot answer yet return null.
const client = steamworks.init(480)client.networkingUtils.initRelayNetworkAccess()// Ping data takes a few seconds to appear after relay access starts.const here = client.networkingUtils.getLocalPingLocation()const pops = client.networkingUtils.getPops() // id, code (for example 'iad') and ping for each data centerconst ms = here ? client.networkingUtils.estimatePingFromLocalHost(here.location) : nullgetLocalPingLocation()returns{ location, ageSeconds }, ornullwhen Steam has no ping data yet. Passlocationonly to the functions in this namespace, and do not parse it yourself.- Units: pings are milliseconds, ages are seconds, and
getLocalTimestamp()returns microseconds as abigint. That timestamp is comparable only within one run of the process. estimatePingFromLocalHost()andestimatePingBetweenLocations()returnnullwhen Steam cannot estimate, and throw when a location text is not understood.checkPingDataUpToDate(maxAgeSeconds)returnsfalsewhen the data is older than that, and Steam then starts a new measurement. Call it only when you need fresh data now, because Steam refreshes the data on its own.getRealIdentityForFakeIp()throws with Steam’s reason when the address is not a fake IP (InvalidParameter) or the mapping is unknown (NoMatch). Steam keeps the mapping for active connections and for a short time after they close.- Config values: the
setGlobalConfigValue*andsetConnectionConfigValue*functions returntruewhen Steam accepts the value andfalsewhen it refuses it. Connection functions take the raw connection handle as a number. TheConnectionobject does not expose that handle yet.getConfigValue(valueId, connection?)returns a number forint32andfloatvalues, abigintforint64values, a string forstringvalues, ornull. UsegetConfigValueInfo()for a value’s name, type and scope, anditerateGenericEditableConfigValues()to list the value numbers. - Not in this binding:
SetDebugOutputFunction, theSetGlobalCallback_*functions,SetGlobalConfigValuePtr, andSetConfigValue/SetConfigValueStruct. They need C function pointers orvoid*arguments. - Not verified against a live Steam client: the byte order of IPv4 numbers in
isFakeIpv4()andgetIpv4FakeIpType(), when ping data first appears, and whether every data center reports a code.
Timeline additions (timeline)
Section titled “Timeline additions (timeline)”Event handles and game phases on the Steam timeline. These functions need init(). If the Steam client does not provide the timeline, the functions that change it do nothing.
const client = steamworks.init(480)const { TimelineEventClipPriority } = client.timelineconst event = client.timeline.startRangeTimelineEvent('Boss fight', 'Round 1', 'steam_victory', 0, 0, TimelineEventClipPriority.Featured)if (event !== null) client.timeline.endRangeTimelineEvent(event, 0)client.timeline.setGamePhaseId('chapter-1')const answer = await client.timeline.doesGamePhaseRecordingExist('chapter-1')- Event handles are
bigintvalues, andnullmeans the timeline is unavailable. A handle is valid only in this run of the game. Passing a value that is not a handle from this API throws. - Units: offsets and durations are seconds, measured from now. Negative offsets are in the past.
recordingMsandlongestClipMsare milliseconds. - A range event must be ended with
endRangeTimelineEvent(). Steam discards range events that are still open when the game exits. doesEventRecordingExist()anddoesGamePhaseRecordingExist()return promises. They resolve duringrunCallbacks()and reject when the timeline is unavailable or Steam cannot answer.- A phase ID is at most 63 bytes and must not contain a NUL character. Calls with a longer ID throw.
clipPriorityisNone,StandardorFeatured.- Not verified against a live Steam client: what the overlay shows for
openOverlayToGamePhase()andopenOverlayToTimelineEvent(), and how the timeline behaves on Steam clients that do not support it.
Turn ideas into shipped software.
HagiCode is an agentic coding workspace. OpenSpec workflows plan the change, multi-agent execution carries it out, and Hero Scenario makes the long run visible, so ideas become shipped software.
- Smart
- OpenSpec workflows turn intent into a path from proposal to shipped change.
- Efficient
- Multi-agent execution runs research, build, and review in parallel.
- Fun
- Rich UI interactions make planning, agent work, and projects easier to follow.
© 2026 HagiCode | Powered By hagilight-starlight@0.23.0 | Branch: main | Commit: 7164ec7 | Built:
