Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/agent0ai/space-agent/llms.txt

Use this file to discover all available pages before exploring further.

Every framework-backed page in Space Agent boots through /mod/_core/framework/js/initFw.js, which calls initializeRuntime() and publishes a shared runtime on globalThis.space. This object is the stable contract between modules — it provides authenticated backend calls, per-user encryption, browser-window control, Markdown and YAML utilities, and cross-feature namespaces. The runtime is window-local and must never be published into parent, top, or sibling frames.
globalThis.space is scoped to the current window only. Do not assign it to window.parent, window.top, or any cross-frame reference.

space.api — Backend API Helpers

space.api is the canonical frontend client for authenticated backend calls. Same-tick fileRead calls are automatically coalesced into one /api/file_read request and re-sliced back to each caller. Identical in-flight extensions_load, file_read, file_info, file_list, file_paths, and user_self_info requests are deduplicated by request shape.

Identity

space.api.userSelfInfo()
Promise<SpaceUserSelfInfo>
Returns the current authenticated user’s identity snapshot.
const { username, fullName, groups, managedGroups, sessionId, userCryptoKeyId, userCryptoState } =
  await space.api.userSelfInfo();
const isAdmin = groups.includes('_admin');
const writableGroups = managedGroups;
sessionId, userCryptoKeyId, and userCryptoState are returned at runtime even though they do not appear in the base SpaceUserSelfInfo TypeScript type. Use them when binding the userCrypto session or checking encryption state.

File Operations

space.api.fileRead(path)
Promise<SpaceFileApiResult>
Read one file by logical path. Accepts a plain string, an object { path, encoding? }, or a batch form { files: [...] }. Same-tick calls coalesce automatically.
// Single file
const { content } = await space.api.fileRead('~/user.yaml');

// With encoding
const { content } = await space.api.fileRead({ path: '~/conf/personality.system.include.md', encoding: 'utf8' });

// Batch
const { files } = await space.api.fileRead({ files: ['~/user.yaml', '~/conf/personality.system.include.md'] });
space.api.fileList(pathOrOptions, recursive?)
Promise<SpaceFileApiResult>
List files at a logical path. The options object supports filtering by access level.
// List user files
const result = await space.api.fileList('~/', true);

// Writable roots only
const result = await space.api.fileList({ path: '~/', writableOnly: true });

// Git history repos for picker
const result = await space.api.fileList({ gitRepositories: true, access: 'write' });
space.api.folderDownloadUrl(pathOrOptions)
string
Returns a same-origin attachment URL for a permission-checked ZIP download of a folder. Use this instead of fetching the archive blob into browser memory.
const url = space.api.folderDownloadUrl('~/my-folder');
window.open(url);

Git History Helpers

These helpers are available when CUSTOMWARE_GIT_HISTORY=true (the default). They wrap the server-owned writable-layer history endpoints.
space.api.gitHistoryList(pathOrOptions?, limit?)
Promise<SpaceGitHistoryListResult>
Paginated commit listing for a writable owner root.
space.api.gitHistoryDiff(...)
Promise<SpaceGitHistoryDiffResult>
File diff for a specific commit.
const { patch, file } = await space.api.gitHistoryDiff({
  path: '~/',
  hash: 'abc1234',
  filePath: 'conf/personality.system.include.md'
});
space.api.gitHistoryPreview(...)
Promise<SpaceGitHistoryPreviewResult>
Preview affected files before a travel or revert operation, with an optional per-file patch.
space.api.gitHistoryRollback(...)
Promise<SpaceGitHistoryMutationResult>
Move HEAD to a past commit. Preserves newer commits in backend-owned refs so forward-travel still works.
const result = await space.api.gitHistoryRollback({ path: '~/', hash: 'abc1234' });
space.api.gitHistoryRevert(...)
Promise<SpaceGitHistoryMutationResult>
Create a new commit that undoes a past commit without resetting HEAD.
const result = await space.api.gitHistoryRevert({ path: '~/', hash: 'abc1234' });

space.utils — Utilities

Markdown

space.utils.markdown.render(text, target)
void
Renders Markdown text into a DOM element, replacing the target’s contents with a .markdown root.
const container = document.querySelector('#preview');
space.utils.markdown.render(markdownText, container);
space.utils.markdown.parseDocument(text)
{ frontmatter, body }
Parses Markdown frontmatter and returns the separated frontmatter object and body string.

User Crypto

space.utils.userCrypto provides session-scoped encryption for browser-owned secrets (API keys, personal settings, etc.). It restores the unlocked key from per-tab sessionStorage first, then from an encrypted localStorage blob via /api/user_crypto_session_key. In SINGLE_USER_APP=true mode, all operations short-circuit to plaintext pass-through.
space.utils.userCrypto.encryptText(plaintext)
Promise<string>
Encrypts a string. Returns a userCrypto:-prefixed ciphertext string.
space.utils.userCrypto.decryptText(ciphertext)
Promise<string>
Decrypts a userCrypto:-prefixed ciphertext string back to plaintext.
space.utils.userCrypto.encryptBytes(buffer)
Promise<ArrayBuffer>
Encrypts a binary buffer.
space.utils.userCrypto.decryptBytes(buffer)
Promise<ArrayBuffer>
Decrypts an encrypted binary buffer.
space.utils.userCrypto.status()
object
Returns the current encryption status — whether the browser key is unlocked, locked, or unavailable.
space.utils.userCrypto.clearSession()
void
Clears the in-tab sessionStorage key and the localStorage encrypted blob together. Called on logout or when the local blob cannot be decrypted for the current session.
// Encrypt an API key before storing it
const encrypted = await space.utils.userCrypto.encryptText(apiKey);
await space.api.fileWrite('~/conf/settings.yaml', `api_key: "${encrypted}"`);

// Decrypt on load
const decrypted = await space.utils.userCrypto.decryptText(encryptedValue);
In SINGLE_USER_APP=true, encryptText and decryptText are pass-throughs. Legacy userCrypto:-prefixed values stored from a multi-user session will surface as locked placeholders until the user replaces them.

YAML

space.utils.yaml.parse(text)
object
Parses a YAML string using the project-owned yaml-lite.js utility, which the server also imports directly for consistent behavior.
space.utils.yaml.stringify(obj)
string
Serializes a JavaScript object to YAML. Supports nested maps, lists, block scalars, and standard YAML quoting.
const data = space.utils.yaml.parse(fileContent);
data.full_name = 'Alice';
await space.api.fileWrite('~/user.yaml', space.utils.yaml.stringify(data));

space.browser — Web Browsing Runtime

space.browser controls all registered browser surfaces: popup windows opened via the Browser menu action, and inline <x-browser src="..."> elements in widgets or other app DOM. The public API uses numeric IDs (1, 2, …) even though the internal store tracks them as browser-1, browser-2, etc. Popup windows persist their URL, size, position, minimized state, and stacking data across page reloads.
Browser-control helpers (click, type, dom, etc.) require the packaged desktop runtime. In plain browser sessions they return a structured warning instead of attempting partial behavior.

Discovery and Management

space.browser.ids()        // → number[] of open browser IDs
space.browser.list()       // → SpaceBrowserWindowState[] for all open browsers
space.browser.count()      // → number of open browsers
space.browser.has(1)       // → boolean

await space.browser.open({ url: 'https://example.com' })   // open a new popup
await space.browser.create({ url: 'https://example.com' }) // alias for open
await space.browser.close(1)     // close one browser
await space.browser.closeAll()   // close all browsers

await space.browser.state(1)     // → SpaceBrowserWindowState (settled snapshot)
await space.browser.focus(1)     // bring to front
open(...) and create(...) translate bare hostnames like novinky.cz or localhost:3000 into browser-like URLs — https:// for ordinary domains, http:// for localhost and IP targets.
await space.browser.navigate(1, 'https://example.com/page')
await space.browser.back(1)
await space.browser.forward(1)
await space.browser.reload(1)
Navigation helpers wait for an observed browser-side navigation or loading transition before returning the settled snapshot. Stale old-guest bridge reads are blocked during that handoff.

Content Inspection

space.browser.content(id, options?)
Promise<SpaceBrowserCaptureResult>
Returns a human-readable typed-ref snapshot of the page. Non-visible content (hidden, aria-hidden, display:none, visibility:hidden, opacity:0, etc.) is omitted. Pass { selector } or { selectors: [...] } in options to scope the read to a CSS selector. Output uses compact typed-ref boxes:
[button 5] Submit
[input text 12] Search placeholder=Query value=ethereum
[checked checkbox 7] Email updates
[disabled muted button 18] Continue
[link 22] Documentation
[image 9] Hero image
space.browser.dom(id, options?)
Promise<SpaceBrowserCaptureResult>
Raw DOM snapshot for debugging. Both content and dom accept either { selector } or { selectors: [...] } in the options object for scoped reads.
space.browser.detail(id, ref)
Promise<SpaceBrowserDetailResult>
Richer state metadata for a single referenced node — the preferred low-token path for inspecting one destination or DOM target before acting on it.
const info = await space.browser.detail(1, 12);
// info.state.disabled, info.state.checked, info.descriptorTags, etc.

Reference-Targeted Actions

All ref-targeted actions return { action, state } where action.status carries visible-effect flags (SpaceBrowserActionStatus) and state is the settled SpaceBrowserWindowState snapshot.
action.status flags
SpaceBrowserActionStatus
// Click a button by ref number from content()
const { action, state } = await space.browser.click(1, 5);
if (action.status?.noObservedEffect) console.warn('Click had no visible effect');

// Type into an input
const { action, state } = await space.browser.type(1, 12, 'search query');

// Submit a form
const { action, state } = await space.browser.submit(1, 12);

// Type and submit in one step
const { action, state } = await space.browser.typeSubmit(1, 12, 'search query');

// Scroll to an element
const { action, state } = await space.browser.scroll(1, 22);

Raw Bridge and Evaluate

space.browser.send(id, type, payload)
Promise<any>
Send a raw bridge message to the in-page runtime. Use for custom extensions or advanced cases.
space.browser.evaluate(id, script)
Promise<any>
Last-resort escape hatch — executes JavaScript inside the browser page and returns the result. Use only when no ref-targeted action covers the need.
const title = await space.browser.evaluate(1, 'document.title');

Diagnostics

space.browser.setLogLevel('debug')   // 'debug' | 'info' | 'warn' | 'error' | 'silent'
The default log level is error. Raising it adds browser-bridge diagnostic noise to the console without affecting production behavior.

Other Runtime Namespaces

space.config

Frontend-exposed runtime parameters injected by the server into <meta name="space-config"> tags. Read with space.config.<paramName>. Only parameters explicitly marked frontend_exposed in the server runtime are available here.

space.fw

space.fw.createStore(name, model)
AlpineStore
Registers an Alpine store with init(), mount(refs), and unmount() lifecycle hooks.
space.fw.createStore('myFeature', {
  count: 0,
  init() { /* one-time setup */ },
  mount(refs) { /* DOM refs available */ },
  unmount() { /* cleanup */ }
});

space.proxy and space.fetchExternal

space.proxy.buildUrl(url)
string
Returns a same-origin proxied URL string. Use sparingly — prefer direct fetch() or space.fetchExternal() first.
space.fetchExternal(url)
Promise<Response>
Cross-origin fetch with automatic proxy fallback. If a direct request fails and the /api/proxy retry succeeds, the runtime caches that origin in memory and routes future requests for it through the backend immediately. Never hardcode third-party CORS proxy services.

space.download

File download helpers. Use for triggering browser-native downloads of content already in memory.

space.router

Hash router helpers for the authenticated app. Available on routed pages as both space.router and Alpine $router.
space.router.go('/agent');
space.router.go('/author/repo/custom-page');

space.onscreenAgent

Controls the floating overlay agent.
space.onscreenAgent.show();    // display the overlay
space.onscreenAgent.hide();    // hide the overlay
space.onscreenAgent.submit('Tell me about this page');  // submit a prompt

space.current and space.spaces

space.current exposes the active space’s widgets and metadata for widget authoring. space.spaces provides persisted space CRUD, widget upsert/patch/remove, layout helpers, and space duplication.
// List widgets in the current space
space.current.listWidgets();

// Read a widget's source
const source = await space.current.readWidget('my-widget');

// Create a new space
const space_ = await space.spaces.createSpace({ title: 'New Space', icon: '🚀' });

space.chat

The current prepared chat context, published by agent surfaces during an active turn.
space.chat.promptItems
SpaceChatPromptItem[]
Metadata list for all prompt contributors in the current turn: system prompt blocks, transient sections, history messages, and trimmed items.
space.chat.readLongMessage(options)
string
Read a trimmed prompt contributor by its id. Accepts { id, from?, to? } for range-limited reads.
space.chat.transient
SpaceChatTransient
Mutable registry for non-persisted transient context blocks. Use set(key, section), upsert(key, section), get(key), list(), delete(key), and clear().

space.visual

Small shared UI helpers exposed by _core/visual modules.
// Open the shared icon and color picker
space.visual.openIconColorSelector({
  icon: currentIcon,
  color: currentColor,
  onSelect: ({ icon, color }) => { /* update */ }
});

space.skills

space.skills.load(skillId)
Promise<void>
Load a skill by its ID into the current agent session’s context.
await space.skills.load('development/modules-routing');

space.extend

space.extend(importMeta, fn)
WrappedFunction
Wraps a function to expose /start and /end JS extension hook points. The wrapped function becomes async. Use from module entry points, not from feature components.
export const initialize = space.extend(import.meta, async function initialize() {
  // core boot logic
});

Build docs developers (and LLMs) love