# Build Apple shortcuts with Shortcuty Studio

Shortcuty Studio turns `.shortcuty` source into unsigned Apple Shortcuts workflows through the portable Python compiler. The authoritative action signatures and native type evidence are in [/docs/actions.json](/docs/actions.json). Use the exact call names and parameter names shown there. The [language guide](/docs/language.md), [project format](/docs/projects.md), and [tested recipes](/docs/recipes.md) cover authoring decisions.

## Agent workflow

1. Pick the entry file and decide what the shortcut should do. Use one `shortcut:` header and indented statements. Use `name = expression` for ordinary generated variables.
The standalone compiler supports `output name = action(...)` for direct
native producer bindings. Studio's existing preservation restrictions
still apply to AI edits; use ordinary supported calls for new AI output.
2. Look up each action with `get_action` or `/docs/actions.json`; the manual IDE Actions tab is deployment-dependent. Check `authoring_status` and `authoring_note` first: use supported calls for new code, structured syntax for control flow, and retain unsupported native records only when preserving imports. Read `parameters`, `required`, `type`, `enum_values`, `default_state`, and `source`. `Value` or an unknown contract is not proof that every value works on a device.
3. Put the shortcut's **name, glyph, color, visibility, accepted input, and other workflow settings in the Studio project**, not its source. Keep verified third-party app identities in `appReferences`. Use `inspect_project` with `{"mode": "apps"}` to read existing aliases; an Apps picker is available only in deployments that expose that control. A source call can then say `apps.open(app: "Safari")` or use a saved project app name. An unfamiliar name without a saved identity is an error.
4. Check the source before building. Fix errors and review warnings. Build to inspect native actions, iOS requirements, and third-party apps. A successful build proves compilation, not that an action succeeded on an Apple device.
5. AI edits may retain existing imported/native-preservation statements unchanged, or explicitly remove or move them. AI edits cannot invent, change, or duplicate those statements, including `native_action`, `native_extras`, and native annotations. Use supported authoring calls and structured control flow for new work. Supported sibling actions should remain normal editable calls. The compiler import language remains supported, but a manual editor is deployment-dependent; do not promise that control is available. This restriction applies to AI-proposed changes.
6. A `.shortcutystudio` project is the portable editable handoff format. Export it only when the current interface provides project export; the AI-only interface does not currently expose Download project, and Download shortcut is not an editable project export. It includes files, the entry path, metadata, and app references. A standalone `.shortcuty` file cannot carry a custom project's app identities or GUI settings.

## First project

```shortcuty
shortcut:
  greeting = text("Hello from Shortcuty Studio")
  result(greeting)
```

In the default AI-focused Studio, use the AI compiler-check and build-inspection tools, then review the generated result. Manual **Check**, **Build**, and Actions-tab controls require an enabled manual editor. `/docs/actions.json` is generated from the installed compiler; use that current catalog if an older example or external article disagrees.

## Generated text and comments

Use the amount of text the task needs. Routine prompts, menu labels, notifications and results should be short and clear. Avoid introductory paragraphs, repeated progress messages and comments that merely restate the next action. Add comments for non-obvious reasons, constraints or data formats.

A simple interaction can stay simple:

```shortcuty
shortcut:
  name = input("Name?")
  result("Hello, \(name).")
```

Keep useful detail for instructions, stories, accessibility, meaningful warnings and explicit requests for explanation. Do not shorten quoted/user-supplied content, remove required steps or change behavior just to save words. This is guidance, not a character cap or automatic text truncation. When editing, keep unrelated content intact.

For a troubleshooting intake, the extra guidance helps the person answer:

```shortcuty
shortcut:
  details = input("Describe the problem, when it started, and what you have already tried. Include any error message.")
  result(details)
```

## Source and runtime boundaries

- Text interpolation is written as `"Hello, \(name)"`. Use named assignments and lexical variable references; do not invent legacy arrow or dollar-variable syntax.
- Branches and loops can leave values absent. Use a condition or guard with `flow.stop()` or `exit()` when missing input must halt execution. `require(value, message: "...")` only asserts a type; it does not test presence, alert, or stop.
- An imported shortcut may contain actions with unverified type or iOS metadata. Keep those requirements marked unknown. Do not claim runtime success from a compiled preview.
- Never execute a public shortcut merely to validate its source. Review the native actions and request device testing separately if it matters.

- Never infer a valid serialized action from an App Intent declaration or its discoverability. Direct `com.apple.shortcuts.*` intent identifiers are unsupported for authoring. Use supported catalog calls such as `flow.stop()`, not `shortcuts.stop()`.

## Organizing shortcut source files

Keep a small shortcut in one file. Split larger workflows into a few focused helper modules when functions are reused or separate tasks become easier to maintain. Multi-file source still builds one native shortcut, not multiple installed shortcuts.

The entry file imports a helper with `import "Helpers/Greeting" as Greeting` before its `shortcut:` header and calls `Greeting.greet(value)` inside the body. `Helpers/Greeting.shortcuty` declares `def greet(value):` with an indented body returning a value on each continuing path. Imports are relative to their importing file; match names and case exactly. See [Functions and imports](/docs#functions) for the complete rules. Studio does not expose arbitrary disk files or remote modules. Media tools can supply project-owned asset manifests; use their exact returned paths.

For targeted edits, Studio reads the current project and file revisions, then uses `patch_project` to propose exact replacements across one or more supplied files. It compiles the proposal before updating the draft. A stale revision, conflicting anchor, cancellation, or compiler failure leaves the current draft unchanged. This does not apply the draft to the saved project: review it first. For protected imports, Studio needs a passing check of the current revision before it can compare the proposal's native output. When it cannot prove that the patch preserves unrelated native actions and their wiring, it leaves the draft alone. New helper files use `edit_project`; unmentioned files and metadata are retained.

## AI edit validation

Tool arguments must be valid JSON with unique object keys and finite numbers. Duplicate keys, `NaN`, and infinities are rejected rather than silently normalized. Invalid tool arguments receive an actionable error so the agent can repair the request before trying again. A successful write response is not a substitute for compiler validation of that exact project.

Native-preservation checks compare an AI proposal with the supplied project snapshot. They constrain changes to existing source; they do not authenticate its origin or establish that an imported action is safe to run.

## Grounded generation and repair checklist

Before writing, map each requested feature to supported language constructs and exact catalog calls. A call name that sounds plausible is not evidence. Use the reference already supplied; inspect an unfamiliar action's complete signature before choosing it. If the required behavior has no supported implementation, explain that specific gap instead of inventing a helper, action, binary decoder, asset, or native record.

Read the user's full request and continuation answers before writing. Honor required scope and explicit stop conditions. Do not silently replace a requested implementation with a subset, placeholder, external service, or simulation. Ask a necessary scope question before writing only when the user has not already decided. When a requirement cannot be met, use `stop` with a plain-text `reason` of at most 1000 characters. This ends the run with `terminationReason: "request_stopped"`, `ok: false`, and `compileValidated: false`, without a project snapshot or unsigned artifact. It is also valid after writing or checking a candidate: the candidate is discarded and the previous project remains unchanged.

The current client's exact `Stop—native-only full compatibility is required` answer is recognized before calling the provider, either on its own or as the final answer after a `Question:` paragraph. General requests containing words such as "stop" still go through normal authoring. Other unmet requirements depend on the agent choosing `stop`; prompt guidance is not a general capability verifier.

Check these frequent mistakes before a compiler pass:

- Date inputs: use `now()` and pass the resulting variable to `format_date(date, style: "short")` or `dates.format(date: date, date_style: "Short", time_style: "Short")`. Use the supported catalog calls for other date fields. The compiler emits the native date-editor representation; do not invent raw Apple token wrappers. Preserve imported native date values exactly unless the user requests a repair. A compiler pass is not device execution.
- Dictionary reads: use `record["key"]` for fixed keys or `record[key]` for a known Text key. Keep code-like keys such as `"01"` as text. Guard missing values.
- Lists: `items[index]` starts at 1. `items[first:last]` includes both endpoints; use Number expressions and supply both ends. These reads do not add runtime bounds checks.
- Files: `files.choose(select_multiple: false)` prompts at runtime; `files.pick(file: ...)` requires a configured file.
- Boolean decisions: bare `if flag:` and `guard flag` require Boolean and test truth, matching `flag ? yes : no`. Use `has value` or `if let` for presence. Arithmetic binds before comparisons in every context.
- Numeric work: keep arithmetic operands present and numeric; group arithmetic inside comparisons with parentheses. `if let` establishes presence, not an unknown value's content type.
- Runtime failures: a `web.request ... else` handles missing output, not hard network failures. Canceling a native input action may stop the shortcut.
- AI model selection: use `ai.ask(model: "Apple Intelligence on Device", ...)` for the On-Device picker choice. `"On-Device"` is its display label, not the native value; supported calls canonicalize that exact alias. Inspect `enum_values`, `enum_state`, and `literal_aliases` in the action contract. `observed_dynamic` choices are not exhaustive: unknown or runtime values need device verification. Preserve imported model values exactly; never claim local execution from a compile check.
- Imported source: keep preservation records unchanged unless explicitly removing or moving them; do not replace a compiler error with an invented raw action.

Read the compiler's full message, code, source range, and invocation chain. Fix the earliest source mistake that causes later errors, then repair other occurrences of the same pattern together. Preserve unrelated behavior and files. Do not repeatedly submit an unchanged draft, suppress errors with `require()`, or claim success from a tool response alone. Every changed draft must pass whole-project compiler validation. Finish only with the checked draft; if a tool or compiler limit prevents that, report the unresolved problem accurately.

A compiler/export test verifies source and native records. A browser debugger is a simulation. A native framework load verifies deserialization. None of these proves that arbitrary app actions, permissions, network calls, or file parsing work on a device.

For writes that update several entries as a shortcut runs, see [Updating dictionary keys in a loop](/docs/variables#updating-dictionary-keys-in-a-loop).

## Bounded in-app repair loop

Runs begin with a bounded work block: 8 model turns, 3 compiler checks and 7 minutes for new projects; 16 turns, 5 checks and 10 minutes for edits. Evidence of useful progress can extend the block within hard time, turn and compute limits. New research has a limited extension allowance; repeated reads or unchanged drafts are not progress. Context compaction makes room by replacing older successful read results with retrievable references while retaining requirements, decisions and current draft state. It does not grant unlimited compute or restart the budget.

When useful progress stalls, the harness first offers a bounded focused recovery with the outstanding errors and next-step guidance. It stops if that attempt does not recover. Repeated invalid tool calls likewise receive corrective guidance rather than unlimited retries. A plan or reference read still consumes a turn; status updates are not a turn counter.

Use `check: true` to validate a write in the same turn, against the same compiler-check budget. A last-turn repair is checked automatically when budget remains. Identical project snapshots reuse their exact prior check result. Finish only with the latest exact checked draft: a successful write, an older check, or a compiler pass without finishing is not completion.

If a provider response fails or a time/context limit interrupts work, a safe draft already written remains available for review and editing. Its compiler status reflects only the latest exact source. An interrupted request is not completed and has no downloadable artifact, even if that source previously passed the compiler. Review the draft and continue with a focused change. A stop request discards the new candidate instead. Cancellation and unsafe provider content never produce a recovered candidate.

Provider responses remain bounded in bytes and time. Only a complete valid response is used; partial streamed text is not executed as a tool call. Cancellation is checked when a response finishes as well as while it arrives. A retryable provider failure may receive one bounded model-response recovery attempt within the existing run budget. The failed response is not added to conversation history or executed. Recovery does not guarantee completion and can consume provider tokens.

## Interpreter-scale requests

Read the [interpreters reference](/docs/interpreters.md) before implementing a language runtime, CPU emulator, assembly runner, or virtual machine. Keep whole-program validation separate from execution: check unreachable instructions and code after a halt when the grammar applies to the whole program. Preserve line positions and addresses; do not trim or discard invalid/address-significant blank lines. The advertised grammar, normalization, range checks, and help text must agree. Define the supported grammar and semantics, implement parsing and runtime state explicitly, and use bounded dispatch with visible unsupported-syntax errors. Keep compatibility claims tied to native test evidence rather than compilation alone.

## Build inspection

The in-app agent can inspect warnings, compatibility unknowns, action counts and generated action parameters with `inspect_build`. Its compiler check includes a bounded build summary. Use `{"mode":"actions","offset":0,"limit":10}` to inspect generated actions and source locations. Optional `file` and `line` filter the result; follow `nextOffset` for another page. The agent checks compilation, but does not execute the shortcut. Device behavior and permissions still require review in Apple Shortcuts. The manual Studio debugger is separate from AI generation and is available only when the deployment enables the manual editor. In AI-only deployments, use the static compiler check and `inspect_build`; do not promise an accessible debugger or claim these tools run the shortcut.

## iPhone Duo and automation boundaries

Automation triggers: Apple documents iPhone Duo Opened or Closed automation in iOS 27.2. Automations are embedded in shared shortcuts and sync across devices in iOS 27. Use the documented triggers: block before all actions, with literal supported trigger calls; read_reference topic triggers gives exact contracts. iphone.closed() exports the fixture-backed close event, then device.lock_screen() handles locking. This meets authoring of automatic close-event configuration; do not stop merely because there is no callable fold sensor. Opened/either Duo encodings remain unverified. The original sample also checks apps.current and locks only with no active app; omit that guard when the user asked to always lock. Export is not installation or activation; the user reviews and enables the imported trigger in Apple Shortcuts. Enablement/confirmation flags are not verified portable source options. Get/Set Multitasking Mode are window-management modes, not fold states. Preserve unknown imported triggers and never invent raw trigger identities or selection parameters.

See [Duo action recipes](/docs/recipes.md) for the action-only example and import limits.

## End-to-end delivery review

Map the user's requested outcome to the final actions, not just the content being generated. Saving an HTML file is not playing its game. A request to play or open needs an appropriate launch path, while an explicit file-export request should remain export-only. Read the [HTML delivery guidance](/docs/calls.md) and [recipe](/docs/recipes.md) before generating an interactive page. Quick Look, Show Result, or a compiler pass is not proof that JavaScript executed.

Compiler-check and `inspect_build` summaries include `delivery`: bounded static HTML detection, browser/save/preview action counts, and advisory `warnings`. Review these before finishing. A missing-browser warning can expose a save-only substitution; it does not invalidate an intentional export. Presence of a browser action does not prove its input is connected to the HTML or that the target device accepts the URL. Encoded, split, or dynamic HTML may not be detected. This review does not execute a shortcut or replace native testing. Preserve the user's offline, native-only, no-hosting, and other constraints, and explain a delivery limitation before changing scope.


### Complete tool evidence

Use `search_actions` with `query` and optional `offset`/`limit` (1–12), following `nextOffset` for further matches. `omittedCalls` explicitly identifies definitions too large for a page. Use `get_action` for one exact native contract or `get_actions` for up to eight known calls in one lookup. Each contract states the supported inputs, options, and outputs. Neither substitutes a similar action or treats preservation-only records as new authoring support. A bounded batch lists omitted calls explicitly; look them up separately if needed.

`inspect_build` accepts the latest exact checked draft, including a failed check. Use `mode: "diagnostics"` to page errors and warnings, with optional relative `file` and positive `line`. Each diagnostic includes up to eight related call-site locations, with `relatedCount` and `relatedOmitted` making any remaining invocation-chain entries explicit. Use `mode: "compatibility"` with `section: "requirements"`, `"declaredRequirements"`, `"unknowns"`, `"unavailable"`, or `"apps"`; these pages do not take a source filter. All paged views support `offset`/`limit` (1–20). Follow `nextOffset` until null. Summary truncation does not mean the omitted records are irrelevant. Editing a draft invalidates its inspection result until that exact draft is checked again. Failed checks remain ineligible for completion. This is static compiler evidence, never native execution.


Use `inspect_project` (`mode: "files"` or `"imports"`) for the entry/import graph and native-preservation counts. `mode: "apps"` lists saved app aliases and bundle identifiers without exposing preserved native identity parameters; omit `file` in that mode. File/import modes read supplied source only and report opaque metadata presence without decoding it. Reachability is structural, not proof of execution. Use `search_project` for literal text, with an exact file plus a function or line range when the scope is known. Matches include source locations, short previews, and a revision. Use `read_project_file` to read one file per call. Request just the needed lines, with `expectedRevision` to reject stale locations. Read more only when needed. These are read-only views of supplied project files; they do not check the filesystem. Compiler repair feedback includes bounded excerpts at actual diagnostic locations; when no location exists, it does not guess one.

Automation syntax and exact supported contracts are in [Triggers](/docs/triggers.md).


## Asking only necessary questions

Proceed with sensible, reversible assumptions when the request already provides enough detail. Ask only when a consequential unresolved decision changes the outcome or is needed to honor a constraint. Do not repeat answered questions or ask the user to choose an obvious default. Use concise, natural wording in the user’s language and distinct, self-contained options. Explain a concrete tradeoff when useful, without implying unsupported features are available. Never ask for credentials or sensitive information.

The bounded `ask_user` tool accepts a single `{question, choices, multiple, required, placeholder}` object, or `{questions: [...]}` with one to three related question objects. Question text is at most 1000 characters. Offer at most five choices: each is a label of at most 120 characters or `{label, description}` with an optional description of at most 180 characters. `multiple` defaults to false and is only appropriate for compatible choices that can be combined. `required` defaults to true. The optional placeholder is at most 160 characters. Free text is always available. Do not preselect or infer an answer.

Selecting choices or typing does not submit. The user presses Continue to send the complete batch. Optional unanswered inputs are not agreement. Free text remains separate from selected choices, and answers stay available for an explicit retry after a failed request. New projects and account changes clear pending answers. The original request and every prior answer are retained in bounded continuation context; exceeding the limit produces an error rather than silently truncating requirements. An explicit stop selection ends without a draft or artifact. Ask before writing when a consequential choice is already known to be missing. If a new consequential ambiguity emerges after drafting, a resumable client can pause with ask_user and retain the exact draft and its validation state. Continue from that draft after the answer; changing it requires validation again. Otherwise finish a checked candidate or use stop to discard it.


## Third-party services and retired APIs

A compiled HTTP action does not establish that its endpoint exists, permits public access, or returns the expected schema. Check the current provider contract outside the in-app agent, which has no web access. Supply that contract when requesting an integration, and clearly identify any remaining unverified assumptions. Never invent endpoints or describe a compiler pass as a live API test.

The Songlink/Odesli public `v1-alpha.1` API was retired on July 31, 2026. Requests to `api.song.link` were verified on November 13, 2026 to return HTTP 401 with `PUBLIC_API_ACCESS_DEPRECATED`. This is a service-access error, not a missing Spotify or Apple Music catalog match. The [provider's retirement notice](https://linktree.notion.site/API-d0ebe08a5e304a55928405eb682f6741) says public song.link and album.link landing pages remain available; opening a page requires user interaction and does not deliver an automatic direct link.

Do not generate new conversion logic against that retired public API. An alternative automatic integration needs a documented supported service contract and any required access. Ask before substituting a browser/manual step, introducing paid/account requirements, or changing the destination service. Do not embed private service credentials in a shareable shortcut or use private webpage APIs to bypass retirement.

Validate the response contract before extracting success fields. A structured error payload must not become a misleading “no match” result. Keep valid no-match results, service/authentication errors, and native hard HTTP failures distinct. A following guard or `web.request` empty-output fallback does not catch a hard native failure. If the requested supported integration cannot be established, explain that specific blocker rather than claiming completion.


## Feasibility and useful alternatives

Before writing, the agent checks the requested outcome against supported actions, documented dependencies, and the user's constraints. It should explain a specific unsupported or impossible requirement instead of returning a working-looking placeholder. Unusual or ambitious requests should not be rejected just for their wording. There is no bad-word keyword filter.

The `stop` tool accepts an optional `suggestions` list with up to three distinct single-line alternative prompts, each at most 240 characters. These appear as quick suggestions alongside the stopped run. Selecting one only fills the request box; the user reviews it and presses Create or Update before a new request is sent. Suggestions never execute a shortcut, submit a request, or change the existing project on their own. They must preserve the user's goal and explicit constraints, and must not repeat options the user already declined. An explicit request to stop is honored without suggestions.

This guidance is not a universal capability detector. Compiler checking still does not prove native execution or external-service availability. The agent has no web search or scraper; it must be honest when current external facts cannot be verified.


### Efficient source inspection

Large projects start with a complete file manifest and explicitly partial source previews instead of replaying all source on each model turn. The full project remains intact for edits and compiler validation. Search results include exact Unicode-character offsets and a file revision. File reads default to 4,000 characters, can start at a character offset or a one-based line, and remain pageable up to 16,000 characters per read.

For repeated text, an exact patch can include both the search/read revision and a character offset. The entire file revision and the exact text at that position must match; otherwise the whole edit is rejected. All patches use the same pre-edit snapshot. Unique text patches still work without positional arguments. Successful large edit payloads are replaced by concise receipts in model history; current source can always be read again. Original user requirements, failed-tool feedback, imported native preservation rules, and whole-project checks are retained.

Saved app aliases and bundle identities remain discoverable without repeating opaque native parameters. The initial context includes up to 12 references; `inspect_project` with `mode: "apps"` pages the complete saved list.


## Reliable AI output and optional follow-up work

For model-generated text or saved memory, read the [compiled recipe](/docs/recipes.md). A model prompt is not a hard length limit, input validator, or error handler. Enforce required limits in source before using or saving the response. Normalize human conversational input before testing for blank content when whitespace is not meaningful; preserve exact input for code, passwords, or formats where spaces matter.

A fallback after an AI, network, or storage action handles successful empty output, not an action that throws or is canceled. Initializing a fallback before the action does not catch that error either. Do not promise uninterrupted execution without a supported error-handling mechanism.

When a useful answer is ready, do not put optional secondary AI calls or persistence ahead of its display unless the user's required ordering depends on them. Show Result is sequential and can wait for dismissal. Follow-up work after it is not a background task and may not run if the user stops the shortcut. If persistence must complete before display, retain that order and explain the delay/failure tradeoff. Never silently drop required memory behavior to make an answer appear sooner.

For replacement memory, enforce nonempty and maximum-length checks, preserve existing memory when a proposal is invalid, and choose any truncation/rejection policy explicitly. Do not silently clip structured data or facts mid-sentence. Keep read/write keys and scopes consistent. A compiled storage action proves neither durable storage nor that a write completed. Confirm forget/update behavior separately from merely asking a model to produce replacement text. Review valid/blank/oversized output, blank user input, optional-step failure, dialog cancellation, and required ordering. Compiler tests do not execute these scenarios on a device.


## Context efficiency and provider caching

Core language guides are supplied once in the agent's stable instructions. A later read points to that complete guide rather than repeating it. Exact duplicate read-only results refer to a retained full result in the same run; changed source revisions, errors, writes and compiler feedback are not silently substituted. User requests, answers, constraints and authoritative source remain intact. Overlapping action searches and exact lookups retain each identical full action contract once, with later references identifying its earlier result and canonical call. Large-project previews keep the entry first, then prefer exact filenames mentioned in the request within the same preview budget; all files remain available through the manifest and source tools.

For the supported OpenAI models, Studio uses an explicit cache breakpoint after the shared instructions and fixed format instruction, with the documented 30-minute TTL. Requests, prior conversation, source and tool results remain after the last breakpoint and are not included in these explicit cache writes. The routing key is opaque and owner-scoped; it contains no account identifier, API key or source. It rotates when the job store restarts. No prewarming calls or longer retention are enabled, and `store: false` is retained. This does not remove ordinary OpenAI API retention policies.

Claude uses a five-minute explicit cache breakpoint on the same public system instructions. Private requests, source and tool results remain outside that breakpoint. It does not enable automatic conversation caching or one-hour writes. Claude isolates caches at its provider workspace boundary; Studio does not maintain a shared private response cache. Cache writes cost more than uncached input, so a one-turn or expired-cache run can cost more, while repeated prefix hits can reduce cost. See [Claude prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).

Gemini keeps the stable system instructions first for its automatic implicit cache. Cache hits are not guaranteed. Carbon does not support explicit cache resources; Studio creates no explicit cache resources for Flash either, avoiding extra storage charges and cleanup calls. Its implicit cache is provider-managed and may include conversation content under Google's data policies; it has no Studio-configured public-only breakpoint or TTL. See [Gemini caching](https://aistudio.google.com/docs/caching?generate-content=true).

For all three providers, terminal-response usage is normalized to numeric input, cached-input, cache-write, output and total-token counts plus a cache-hit ratio. Claude input totals include its separate uncached, cache-read and cache-write fields. Gemini output totals include reported candidate and thinking tokens; unreported values, including cache writes, remain unknown. Partial runs never invent complete totals. Ratios are not measured monetary savings. No extra paid requests, prewarming or lower quality/reasoning limits are introduced. See [OpenAI caching](https://developers.openai.com/api/docs/guides/prompt-caching), [OpenAI data controls](https://developers.openai.com/api/docs/guides/your-data) and [Gemini usage fields](https://aistudio.google.com/api-reference/generate-content).

## HTTP conversation state and typed JSON

Match the provider's request schema and inspect exported JSON field types, not just source spelling. Text, Number, Boolean, Dictionary and List are distinct; a one-item list is not a scalar. Do not wrap text in a list to satisfy an uncertain action signature. OpenAI Responses `input` accepts a string or typed input items, not an array of bare strings. For a text turn, use `input: submitted`; for structured input use objects with the documented roles/content. Keep token limits numeric, flags Boolean, and omit absent optional fields. [Responses contract](https://developers.openai.com/api/reference/resources/responses/methods/create).

Validate the returned envelope before interpreting missing answer text. Capture the response ID, status, error and incomplete reason first. For raw HTTP Responses, traverse `output` message items and their `output_text` content; an SDK's aggregated `output_text` helper is not a guaranteed HTTP field. Keep refusals, tool-only output, missing/malformed data and service errors distinct. [Response items](https://developers.openai.com/api/docs/guides/migrate-to-responses).

Handle `status: incomplete` and `incomplete_details.reason: max_output_tokens` before the empty-answer exit. Reasoning uses the output-token allowance and may exhaust it without visible text. Retain a usable response ID for an explicit recovery path even when text is blank; label any text partial. Other incomplete reasons need their own explanation. Never silently repeat a paid call or increase every token limit: choose bounded, model-supported settings and explain retry costs. [Reasoning limits](https://developers.openai.com/api/docs/guides/reasoning).

Treat a new conversation as a proposed replacement. Reset its active cursor in memory, but keep the last saved conversation until the replacement meets the workflow's usable-state policy and its write completes. An incomplete recovery cursor can use a separate key so it cannot destroy the last good resume slot. User input cancellation, blank input and request failures must not delete it. Store related state together when possible; multiple writes are not a transaction. Explicit Forget is different from Start new. Do not claim an ID guarantees future server retention or successful resume.

Bounded loops need a terminal path before the next-turn menu. On the last iteration, offer only actions that can actually run; do not offer Follow up or New chat when no turn remains. A menu choice cannot restart an exhausted repeat. Final messages must reflect the retained cursor, not imply every exit saved a conversation. Review both the first and last turn, new-chat cancellation/failure, incomplete output with/without an ID, and empty completed output.

Save and Cancel labels must match ordering. If resumability requires saving before Show Result or a menu, disclose that dismissing it does not undo the save. If the workflow saves after an optional dialog, cancellation can prevent it. Announce Saved or Deleted only after the corresponding action returns; compiler success is not storage or native runtime evidence.


## Generated media
Use create_image_asset for simple geometric PNG graphics and create_sound_asset for short WAV tones/chimes. These are bounded built-in tools, not image diffusion, speech generation or code execution. Write a draft first. They return portable asset manifests, never base64 bytes. Reuse the exact returned asset path with `asset("Assets/…shortcutyasset")`, which produces base64 text, then decode with the appropriate native action. Inspect action definitions before using the decoded value. Media remains part of the saved project snapshot, not conversation memory. Portable project export depends on the available interface; Download shortcut is not project export. Do not promise photos, voices, or realistic sound effects.

## Targeted reference lookup

The stable prompt includes core language, type and variable-identity rules. Use `read_reference` with `mode: "index"` to see available guides, or `mode: "search"` and a short query to locate relevant sections. Read the matching topic and section (or exact offset) before relying on an excerpt. Reads are bounded; follow `nextOffset` until the needed contract is complete. Action signatures remain authoritative through `get_action`. Reference lookup searches installed guides only, not user histories.

Each tool result carries app-computed run state: research, validate, repair, or review. Use it to choose the next necessary step, not to repeat work. After a successful check, review the request and finish. The finish tool can include four ideas for new shortcuts alongside its separate suggestions for improving the current one. New ideas replace the account’s previous set only when a successful build supplies a valid batch and server saving is enabled. Opening the Create page only reads that set; it does not start another AI request. A retained draft without a check is not a completed shortcut. Recovery and compaction do not remove hard execution budgets.

## Designing native shortcut interfaces

For polished native UI, dashboards, managers, and Snapper-style menus, retrieve the **Native UI design playbook** section in `recipes` with `read_reference`. It distinguishes native menu sheets from pictured `vcard_menu` choices and custom web interfaces, includes compilable source, and covers accessible labels, dynamic status, navigation and destructive confirmation. Decide the smallest interaction that serves the task. Do not add a home screen, updater, image assets or persistent storage just to imitate a reference. Check the generated UI actions and request device validation separately when exact appearance matters.
