---
name: im-create-agent
description: Scaffold a runnable in·manas agent project from a plain-language prompt, against the current im-sdk. Use when the user wants to "create an in·manas agent/project", "scaffold a new agent", "build an agent from a prompt", or asks to go from an idea to a deployed agent (create in Portal, login/link/push, run + check progress). Runs an interview, generates main.py + pyproject.toml pinning the published SDK (code only, no .env — the CLI's link owns .im/), derives the org via `im-cli link` and reads the real grants off `im-cli agent services`/`im-cli agent models` BEFORE composing main.py (output type is always string), writes the `.im/io.json` contract that binds the Playground form to the agent's inputs, and emits a pre-filled login → create-in-Portal + grant → link → read grants → main.py + io.json → uv lock → push → execute checklist driven by the `im-cli` CLI. Self-contained: relies only on the installed im-sdk + im-cli, with bundled SDK + CLI references. For UPDATING an existing project to a newer SDK, use im-update-agent instead.
---

# in·manas — Create a project from a prompt

Take a plain-language description of what an agent should do and turn it into a
**runnable, pushable project** in a project directory, wired to the **current
`im-sdk`**, then walk the user from there to a live execution.

The generated project follows the standard in·manas agent anatomy and runner contract,
captured in this skill's bundled skeleton/snippets/references — generated from the user's
prompt. It is **self-contained**: it needs only the installed `im-sdk` package and the
`im-cli` CLI, never the monorepo. The SDK surface is in the bundled
[`references/sdk-reference.md`](references/sdk-reference.md); the CLI surface + install in
[`references/cli-reference.md`](references/cli-reference.md).

## When to use

- "Create an in·manas agent that does X" / "scaffold a new agent from this prompt"
- "I want a project I can `im-cli push`" / "go from idea to a running agent"
- The user describes an agent's behavior and wants it wired to the SDK + deployed

Not for: editing the SDK itself, debugging an existing execution, or Portal UI work.

**Prerequisites on the host** — check these before Phase 1 rather than failing at `push`:

| Tool | Needed for | Check |
|---|---|---|
| `im-cli` | login, link, push, run, reading the grants | `im-cli version` (install: [`references/cli-reference.md`](references/cli-reference.md) § Install) |
| `uv` | `uv lock` — mandatory before every push | `uv --version` (https://docs.astral.sh/uv/) |
| `python3` | `scripts/scaffold.sh` shells out to it for token substitution | `python3 -V` |

`im-sdk` itself is **not** a host prerequisite: the agent slot installs it from `uv.lock`.
Installing it locally only helps if you want to read an exact version number (Phase 0).

## The three phases

1. **Interview** — gather behavior + inputs from the prompt and the deploy target; have the
   user **log in to the CLI**, **create the agent in the Portal** and **grant its providers**
   there. Then the only ID you need is the **agent UUID**.
2. **Scaffold** — copy the skeleton, `im-cli link` (which derives the org and writes `.im/`),
   **read the real grants off the CLI**, then compose `main.py` and `.im/io.json` against
   them. The order matters: the service names and aliases `main.py` hardcodes are not free
   choices, so linking comes *before* the code, not after it.
3. **Deploy checklist** — `uv lock`, `push`, and run from the Portal. **Don't
   run/compile/smoke-test the agent locally** — treat it as deployed independently and rely
   on the Portal execution + trace.

---

## Phase 0 — SDK version (you usually don't choose one)

`im-cli push` installs with `uv sync --frozen`, so the **`uv.lock` is what pins the exact SDK**
— not a number you pick by hand. You therefore **don't need to know the version up front**:
scaffold *without* `--sdk-version`, and `uv lock` (Phase 3) resolves the latest published
`im-sdk` from the public in·manas index and pins it exactly.

- **Don't go hunting for a version** — no grepping a repo, no reading commit history, no
  "recent commits reference X". That's the non-agnostic trap. The lock is the source of truth.
- Optionally, if you also want an explicit `==` pin in `pyproject.toml` *and* `im-sdk` is
  installed locally, read it from the package (never hardcode):
  ```bash
  python -c "import importlib.metadata as m; print(m.version('im-sdk'))"
  ```
- **`--sdk-version` exists only to pin an *older* SDK deliberately.** Leave it off and the
  lock takes the latest published one; there is no mode that requires it.

The resource surface is in the bundled [`references/sdk-reference.md`](references/sdk-reference.md)
(plus the scaffolding-focused [`references/sdk-api.md`](references/sdk-api.md)); read it so
the generated `main.py` only calls methods that exist in this version. To bring an *existing*
project across SDK bumps, use the [`im-update-agent`](../im-update-agent/SKILL.md) skill.

---

## Phase 1 — Interview

Keep it short and concrete. Ask only what you can't infer from the prompt. Confirm a
compact spec before generating anything. Gather:

| Topic | What to capture | Notes |
|---|---|---|
| **Behavior** | One-paragraph description of what the agent does, end to end | This is the prompt; drives `main.py`. |
| **Inputs** | Each input `name` + `type` (`string` \| `multiline` \| `url` \| `email` \| `json_string` \| `file`) + an example value | Goes into `.im/io.json` (§ 2.4) — the `name` is literally the key `main.py` reads off `data`, so **agree it with the user now**. A `file` input takes no example value. |
| **Output** | An example output value | **Output type is always `string`** (see below) — don't ask. **stdout carries ONLY the JSON-encoded output** (`json.loads(stdout)` populates `execution.output`). |
| **Providers** | Which SDK capabilities it needs (see table below) | Determines imports, calls, and the grants the server agent must hold. |
| **Settings & credentials** | Configuration it must not hard-code (a base URL, a region, an ID) and any login / token / password a connected service needs **per call** | Settings become org **variables**, read with `core.vars["KEY"]`; credentials become org **secrets**, written as `core.secret("KEY")` placeholders the gateway substitutes — see the grant step below and `snippets/variables_and_secrets.py`. Agree the `UPPER_SNAKE_CASE` keys now. A connection's *own* API key is not one of these: the admin stores it on the connected service. Never ask the user to paste a secret's value to you. |
| **Human in the loop** | Whether the agent ever needs to stop and ask a *person* something mid-run | Usually no — ask only if the behavior implies an approval, a missing detail, or a judgement call. If yes, it changes `main.py`'s shape: see `references/sdk-api.md` ("Pausing for a human"). |
| **Deploy target** | Where the Portal API lives — **ask the user to choose**: | No hardcoded default; the user picks. Determines the host `<api-url>`. |
| **Agent UUID** | The **only** ID you ask for. The user logs in + creates the agent in the Portal (below), then pastes the UUID | After scaffolding, `im-cli link --agent <uuid>` derives + prints the **org** (the workspace is runner-injected) — you don't ask for those. |

> **Output type is always `string`.** The server's `IoSchemaValidator` accepts only
> `string` / `url` / `email` / `json_string` / `multiline` — **`json` is invalid (422)**.
> Standardize on `string`: `main.py` emits `print(json.dumps(output))` where `output` is a
> string, and `.im/io.json` declares `"output": {"type": "string"}`. If the agent produces
> structured data, serialize it to a string yourself before printing.

### Log in, create the agent, grant its providers (do this during the interview)

So you only need the agent UUID, walk the user through these three steps and wait for the UUID:

1. **Install the CLI (if needed), then log in.** The agent CLI is the `im-cli` binary — use it
   if it's already on `PATH`, else install it (see [`references/cli-reference.md`](references/cli-reference.md)
   § Install; in the monorepo, `make cli-build`). It runs **on the host**, not in Docker.
   Logging in stores a **single active login** (one server) — subsequent calls
   (`link`/`push`/`run`/`whoami`) don't repeat `--api-url`:
   - Local stack: `im-cli login` (defaults to `http://localhost/api`)
   - Remote: `im-cli login --api-url https://<host>`
   - Headless (CI / token): `echo "$PAT" | im-cli login --with-token - --api-url <api-url>`

   > **Loopback http is fine.** `http://localhost/api` is accepted without `IM_CLI_ALLOW_HTTP`.
   > For a non-loopback plaintext `http://` server, set `IM_CLI_ALLOW_HTTP=1`. Once logged in,
   > every `im-cli` command authenticates off the active login — no PAT needed; `im-cli whoami`
   > shows the current server/user/org.
2. **Create the agent in the Portal UI** (Agents → New) and copy its **UUID** from the
   agent page (which also prints the exact `login → link → push` commands).
3. **Grant its providers in the Portal** (agent → Access): the capabilities from the table
   below, plus the model alias / connected service each one needs. **A new agent holds
   nothing**, and an ungranted call fails authorization at run time. Do this *now*, not
   after the code: §2.2 reads the grants back off the CLI and `main.py` hardcodes their
   names, so the code cannot be written correctly until they exist.

   If the interview found **settings or credentials**, have an org admin also:
   - create each one in **Org Settings → Variables** — a `var` for a setting, a `secret` for a
     credential, with the agreed key, limited to the agent's workspace if it should be;
   - for each **secret**, set its **allowed services** to the connected service(s) the call
     sends it to (e.g. `apify`) — a secret with none cannot be used in any call. Only a service
     that pins its destination can be one: a custom-HTTP connection with an endpoint list, or an
     Apify connection whose **allowed actors** list the actor the agent runs;
   - grant them on the agent's **Manifest** tab → Variables & secrets.

   The user types the values into the Portal themselves; you only ever see the keys. Granting
   takes effect on the next run.

That's all you need from the user — the **UUID**. Don't ask for the org or workspace: once
you've scaffolded the project and run `im-cli link --agent <uuid>` (§2.2), the CLI
**derives + prints the org** from the agent (the workspace is runner-injected), and
`im-cli agent services` / `im-cli agent models` list the agent's granted services + aliases **live**
off the active login — that's how you confirm the grants and wire the `main.py` constants. No
PAT, no curl script, no manual IDs.

**Run `im-cli` on the host** (login/link/push/run) — it talks straight to the Portal API over
HTTPS (or loopback http for the local stack); there is no container hop. After the first
`im-cli login` you don't pass `--api-url` again; logging into another server replaces the
active login.

Deploy-target options:

| Target | API URL for `im-cli login` (host) |
|---|---|
| Local stack | `http://localhost/api` (loopback http, no `IM_CLI_ALLOW_HTTP` needed) |
| Remote | `https://<host>` (`IM_CLI_ALLOW_HTTP=1` only for non-loopback http) |

The **SDK source** is independent of the target, and there is only one: the published
`im-sdk` on the public in·manas index, which needs no credential anywhere (see Phase 2.5).

> **The host `im-cli` reaches the local stack at `http://localhost/api`.** Don't use
> `http://nginx/api` — that hostname only resolves *inside* the Compose network and was a
> relic of the old container-run CLI; on the host `curl` fails with
> `Could not resolve host: nginx`. The exact host port follows the published nginx mapping
> (`docker compose ps`); it's `:80` (i.e. plain `http://localhost/api`) on the default
> local stack.

### Provider → SDK capability map

**All twelve** resource clients on `core`, so the right one is offered rather than the
nearest of five. Full signatures in [`references/sdk-reference.md`](references/sdk-reference.md) § 4.

| User need | SDK call | Server grant needed |
|---|---|---|
| Call an LLM | `core.llm.call(messages, alias=…)` (also `stream`, `call_structured`) | `llm` + a model **alias** |
| Embed text for search/RAG | `core.embedding.embed(input, alias=…)` | `embedding` + an **alias** |
| **Read a web page / download bytes from a URL you chose** | `core.web_fetch.fetch(service, url, as_text=…)`, `.probe(service, url)` | `web_fetch` + a `ciu-fetch` service (e.g. `im-fetch`) |
| Web search / extract article text | `core.web_search.search(service, query)` / `.extract(service, urls)` | `web_search` + service (e.g. `tavily`, `serper`) |
| Crawl / run a scraper | `core.web_crawler.run_actor(service, actor_id)` / `.fetch_dataset(service, dataset_id)` | `web_crawler` + service (e.g. `apify`) |
| Parse a document into elements | `core.document_parse.partition(service, file=<b64>)` or `partition(service, file_ref=…)`; also `.extract`, `.ocr` | `document_parse` + service (e.g. `unstructured`) |
| Read a `"type": "file"` input's bytes | `core.file_store.get(file_ref)` | **none** — platform-routed, no service, no grant |
| Keep a file past the upload TTL | `core.object_store.put_from_upload(service, file_ref=…)`, `.get`, `.put`, `.list`, … | `object_store` + service; each of the seven actions granted separately |
| Store / search embeddings | `core.vector.upsert(service, points=…)`, `.search(service, vector=…)`, `.delete` | `vector` + service (one collection per service) |
| Row CRUD on a connected database | `core.data.read(service, table, …)`, `.create`, `.update`, `.delete` | `data` + service; each of the four actions granted separately |
| Call tools on a connected MCP server | `core.mcp.list_tools(service)`, `.call_tool(service, tool, arguments)`; `defs, names = mcp_tools(listing)` hands the tools to the model: pass `defs` to `core.llm.call` (whatever the model) and map its call back through `names` | `mcp` + service, **and each tool named in the agent's grant** (nothing named = no tool). Needs `im-sdk` 1.2.0 or newer; `im-cli agent services` shows the connection, not its tools — `list_tools` shows what was granted |
| Call one configured external HTTP host | `core.http_capability.request(service, path, verb, body=…)` | `http_capability` + service (e.g. `playwright`, `ciu-api`) |
| Read org configuration (URL, region, ID) | `core.vars["KEY"]`, `core.vars.get("KEY", default)` (strings); `core.vars.get_int` / `get_float` / `get_bool` / `get_json("KEY", default)` for a number, flag or JSON | the **variable** granted on the Manifest tab |
| Send a password / token to a connected service | `core.secret("KEY")` written into an `http_capability` or `web_crawler` call's params | the **secret** granted on the Manifest tab, with that service among its **allowed services** — a custom-HTTP service with an endpoint list, or an Apify connection listing the actor |

> **The agent process has no outbound network of its own.** The runner slot is
> egress-less by policy: every byte from the open web arrives through one of the calls
> above. A direct `httpx`/`requests`/`urllib` call from agent code works on a laptop and
> then fails in a deployed slot with a DNS error that mentions nothing about policy — so
> it passes every local check and breaks only in production. **Reach for
> `core.web_fetch`** whenever the agent needs a URL's contents; `web_search`/`web_crawler`
> cover *finding* pages, `web_fetch` covers *reading one you already have*.

Confirm the spec back to the user (inputs/outputs/providers/target) before scaffolding.

---

## Phase 2 — Scaffold the project

> **Everything you need is bundled in this skill folder** — the skeleton, snippets, scripts,
> and references below are the source of truth. Don't reach for the monorepo or other local
> projects to copy from. (In the monorepo, ignore the gitignored `data/projects/` reference
> projects — they are not inputs to this skill.)

Skill assets:
- `assets/skeleton/` — a code-only project skeleton with `{{TOKENS}}` (`main.py`,
  `pyproject.toml`, `README.md`). **No `.env`** (`from_env()` defaults the secret) and **no
  `.im/`** — `im-cli link` creates the latter.
- `snippets/` — copy-paste-ready provider functions (`llm.py`, `web_search.py`,
  `web_fetch.py`, `web_crawler.py`, `document_parse.py`, `http_capability.py`,
  `variables_and_secrets.py`) matching the current SDK signatures. The remaining six clients (`embedding`, `data`, `vector`,
  `object_store`, `file_store`, `mcp`) have no snippet — take their signatures from
  [`references/sdk-reference.md`](references/sdk-reference.md) § 4.
- `scripts/scaffold.sh` — copies the skeleton + substitutes tokens (no manual file reads).
  `--dest` is the **parent** dir (`--dest data/projects --id foo` → `data/projects/foo`);
  it won't double-nest if `--dest` already ends in `<id>`. **On a name collision it
  scaffolds into the next free `<id>-N`** (e.g. `foo` taken → `foo-2`) and prints the
  resolved path on stdout — so it never clobbers an existing (possibly already-linked)
  project; pass `--force` only when you mean to overwrite the exact dir.
- `references/sdk-reference.md` — bundled full `im-sdk` API reference (signatures, the
  `ResourceResult` envelope, errors, tracing); `references/sdk-api.md` — scaffolding-focused
  quick guide + runner contract.
- `references/cli-reference.md` — bundled `im-cli` CLI command surface + install.

> **Two scaffolders exist; this skill uses the bundled one.** `im-cli new <slug> <dir>`
> downloads a starter from the Portal's own catalog (`im-cli new --list` — typically
> `python-blank`, `python-llm`) and emits **five** files: `main.py`, `pyproject.toml`,
> `README.md`, a committed `uv.lock`, and a *pre-filled* `.im/io.json`. `scripts/scaffold.sh`
> emits **three** — code only, no lock, no `.im/` — because it also substitutes the agent's
> name/description/index URL and leaves `.im/` to `im-cli link`. Use `scaffold.sh` (below):
> it is version-stable and needs no server round trip. `im-cli new` is the right answer when
> the user wants the Portal's own starter verbatim, or has no `python3`/skill checkout — in
> which case skip §2.1, run `im-cli new python-llm <dir>`, and note that `link` will **not**
> overwrite the `io.json` it already wrote, so §2.4 still applies.

### 2.1 Scaffold from the bundled skeleton

Pick where the project should live. `--dest` is the **parent** directory (default `.`); the
project lands at `<dest>/<id>`. Run the bundled scaffold script — it copies `assets/skeleton/`
into the project dir and substitutes tokens. It emits **code only** (no `.env`) — `.im/` comes
later, from `im-cli link`:

```bash
bash .agents/skills/im-create-agent/scripts/scaffold.sh \
  --id <project-name> \
  --name "<agent name>" --description "<short description>" \
  --dest <parent-dir>     # e.g. --dest data/projects → data/projects/<project-name>; default parent: .
  # No --sdk-version needed: pyproject pins bare `im-sdk` and `uv lock` resolves the
  # latest published version. Pass it only to pin an older SDK on purpose.
```

This produces a runnable single-provider (LLM) base. Tokens substituted:
`{{PROJECT_ID}}`, `{{SDK_SPEC}}` (`im-sdk` or `im-sdk==<v>`), `{{AGENT_NAME}}`,
`{{DESCRIPTION}}`, and `{{SDK_SOURCE_BLOCK}}` (the `[[tool.uv.index]]` +
`[tool.uv.sources]` block naming the in·manas index).

**SDK source — one mode, no choice to make.** The generated `pyproject.toml` pins a
**published** `im-sdk` from the public PEP 503 index at
`https://downloads.mgt-platform.com/simple/`. The URL carries **no credential** and none is
needed at any point — nothing to export before `uv lock`, and nothing that could leak out of
a generated file the user is likely to commit. `explicit = true` in the generated block is
load-bearing: without it `uv` searches that index for *every* dependency, and a public
package sharing a name with something published there resolves from the wrong place.
Override the index with `--index-url <url>` for a mirror or an air-gapped copy (the script
refuses a URL carrying userinfo).

### 2.2 Link now — read the grants *before* writing `main.py`

`main.py` hardcodes an `llm` alias and one `*_SERVICE` constant per provider. Those strings
are **admin-defined in the Portal**, not free choices, and a wrong one fails authorization at
run time. So link first and read them back; composing the code against invented placeholders
and fixing it afterwards is a second edit pass with nothing to catch it if you forget.

`im-cli link` also scaffolds `.im/`: a local (gitignored) v2 `config.json`, an `io.json`
skeleton (tracked), and `.im/.gitignore`. Run it from the project dir, on the host. You're
already logged in from Phase 1, so no `--api-url`:

```bash
cd <project-dir>
im-cli link --agent <agent-uuid>   # derives + prints the org; add --org <uuid> only to disambiguate
im-cli agent services              # the connected services granted to THIS agent
im-cli agent models                # the llm/embedding aliases granted to THIS agent
im-cli agent variables             # the variables + secrets granted to THIS agent, with the line to use each
```

What they print (a TTY; see the note below). **The rows are one org's, not a fixed set** —
`tavily`, `mini`, `im-fetch` here are whatever that admin happened to configure, exactly
like the snippet placeholders. Read your own:

```
2 more service(s) exist in the organization but are not granted to this agent.
NAME       DRIVER      TYPE          STATE
im-fetch   ciu-fetch   external_api  active
openai     openai      cloud_ai      active
tavily     tavily      external_api  active
```

```
1 more alias(es) exist in the organization but are not granted to this agent.
ALIAS  RESOURCE TYPE  TARGETS       STRATEGY
mini   llm            gpt-5.4-nano  fallback
```

- **`NAME` is the string you pass as `service=`**; `ALIAS` is the string you pass as
  `alias=`. `DRIVER` / `TARGETS` are what the admin pointed them at — informational. Never
  copy a *target* model id (`gpt-5.4-nano`) into `alias=`.
- **Zero rows means zero grants**, not "unfiltered": the headers still print, followed by
  `(0 rows)`. That is Phase 1 step 3 not done — stop and have the user grant them.
- A `no linked agent — showing everything in the organization` line on **stderr** means the
  `link` didn't take or you're in the wrong directory. Those rows are the *org's* services,
  not the agent's; wiring `main.py` from them is how an ungranted name gets hardcoded.
- The count line ("*N* more … not granted") is also stderr, so it survives a pipe.
- **Piping changes the format.** `-o` is TTY-aware: a terminal gets the table above, a pipe
  gets JSON (`[{"name":"tavily","driver_id":"tavily",…}]`). Pass `-o table` to force it.

If the interview found settings or credentials, `im-cli agent variables` lists them with a
**`USE`** column — `core.vars["KEY"]` for a variable, `core.secret("KEY")` for a secret — and a
secret's **`USABLE WITH`** — the services the agent holds that the secret allows: the placeholder
only works in a call to one of those. Copy the `USE` cell as-is; never put a secret's value in
code (it is never shown anyway). A grant marked
`(not in this agent's workspace)` is not delivered — have the admin fix its scope.

Now fix the `LLM_MODEL_ALIAS` / `*_SERVICE` constants in `main.py` to the names above, and
compose the body around them.

### 2.3 Compose the real behavior

Edit `<project-dir>/main.py` to implement the user's prompt. **The skeleton uses
`@im_agent`** — an `async def main(core, data)` that *returns* the output. Most edits
are just filling in the function body:
- Add providers by pasting the matching function(s) from `snippets/` and calling them
  from `main`. Read the agent's inputs off `data` — **using the exact `name` strings that
  go into `.im/io.json` (§2.4)**, e.g. `data.get("prompt")` ↔ `{"name": "prompt", …}`.
  `return` the final output value. Delete the LLM demo if unused.
- **Wire service names + aliases to the agent's actual grants — don't invent them.** The
  `*_SERVICE` constants and the `llm` alias are **admin-defined in the Portal**, not free
  choices; a name the agent wasn't granted fails authorization at run time. The snippet
  defaults (`"tavily"`, `"apify"`, `"gpt-mini"`, …) are placeholders — replace them with the
  names §2.2 printed. For `llm`, remember the
  **alias name doesn't pick the driver** — its Portal target does (a provider-specific
  route, e.g. Azure vs plain OpenAI for a shared `gpt-*`, must be pinned on the alias's
  target, not chosen here).
- **Group multi-step work with `@observe`.** When a step makes more than one call (or
  you want a readable label), wrap it in `@observe(name="…")` so its resource calls
  nest under one named `NODE` span — the trace reads `RUN → gather_sources →
  {web_search.search, web_search.extract}` instead of a flat list of calls. Use
  `capture_input=False` when the first arg is `core`. See `references/sdk-api.md`
  ("Grouping calls into named nodes"). Each node + resource appears "running" as it
  starts and updates when it finishes, so the trace fills in live while the agent runs.
- **Fan independent calls out concurrently**: `await asyncio.gather(...)` over resource
  calls is supported — gathered calls parent under the enclosing span and render as
  concurrent siblings, so the step takes as long as the *slowest* call. Group the
  fan-out under one `@observe` node; keep data-dependent calls sequential. See
  `references/sdk-api.md` ("Concurrent fan-out").
- **What `@im_agent` handles for you** (don't re-implement): loads any `.env` (best-effort);
  builds + authorizes `core` (`ImCore.from_env()`, with the runner-injected per-run `AGENT_SECRET`); supplies `data` (`read_input() or example_input()` — runner `--input`, else
  the `.im/io.json` sample, else `{}`); opens the Langfuse trace (input = the real
  `--input`); records your **return value** as both the trace output *and* the stdout
  JSON (`print(json.dumps(...))`); maps a fatal `ImError` → stderr + exit 1. So: use
  `log(...)` for progress, **never `print` yourself**, and just `return` the output.
- **Need finer control?** A custom trace input, `set_output` mid-run, multiple outputs,
  or partial-failure handling → switch to the explicit `ImCore` + `async_trace_run`
  form (see `references/sdk-api.md` "Trace input / output — explicit form"). Then *you*
  own the rules: read `--input` with `read_input()` and pass `input=`; `log(...)` for
  progress with `print(json.dumps(output))` only at the very end; `trace.set_output(...)`
  before the block exits; and `print(..., file=sys.stderr)` on a fatal `ImError`.

> **Never add an HTTP client to `pyproject.toml`.** `httpx`, `requests`, `urllib`,
> `aiohttp` — none of them can reach anything from a deployed slot, which has no outbound
> egress. This is the failure that looks like success: the dependency resolves, `uv lock`
> is happy, the push is accepted, and the call dies at DNS resolution in production only.
> The two things agents reach for it for both have a capability:
> - **bytes at a URL** → `core.web_fetch.fetch(service, url, as_text=False)`, whose
>   `.output.content_base64` is already the shape `document_parse` wants;
> - **one configured upstream host** → `core.http_capability.request(service, path, …)`.

### 2.4 Write `.im/io.json` — the contract, and the one file that fails silently

`im-cli link` (§2.2) wrote a **skeleton with zero inputs**. Push it as-is and the agent runs,
exits 0, and returns whatever your `data.get(...)` fallback says — no traceback, no rejected
push, a wrong answer shaped exactly like a right one. This file is what binds the Playground
form to `data`, so every `name` here **must** match a key `main.py` reads.

Full contract, accepted keys, types and failure modes:
[`references/cli-reference.md`](references/cli-reference.md) § `.im/io.json`. The shape:

```json
{
  "inputs": [
    { "name": "company", "type": "string" },
    { "name": "focus",   "type": "multiline" }
  ],
  "output": { "type": "string" },
  "example": {
    "inputs": { "company": "Patagonia", "focus": "supply chain transparency" },
    "output": "Patagonia — recent coverage\n\n1. …"
  }
}
```

Non-negotiable, all enforced at `push` with a **422** that names the offending key:

- **All three top-level keys are required** — `inputs`, `output`, `example`. `inputs` may be
  `[]`; `example` is still required (`{"inputs": {}, "output": ""}`).
- **Each input is exactly `{name, type}`.** Any other key (`description`, `required`,
  `label`, `default`) **validates and is then silently dropped** before storage — it never
  reaches the Portal and never renders. There is no optional input: the Playground requires
  every declared field.
- **Input `type`**: `string` · `multiline` · `url` · `email` · `json_string` · `file`.
  **Output `type`**: the same minus `file`. `"json"` is not a type — it is a 422; use
  `json_string`, or serialize to `string` yourself.
- **`example.inputs` needs a value for every declared input** — except a `file` input, which
  must **not** appear there (a 422 of its own: the field is an uploader, and an example id
  would be offered as a default that no run can use).
- Duplicate `name`s are a 422. `example.output` must be present; its value can be anything.
- `.im/io.json` **must be in the push bundle** — a missing one is a 422 before any version
  row is created. So is a missing root `pyproject.toml` or `uv.lock`.

`example.inputs` is also what the SDK's `example_input()` returns, so it is the fallback a
hand-run uses — one more reason it should be a realistic value, not `"foo"`.

### 2.5 SDK delivery

`uv lock` resolves `im-sdk` from the public in·manas index. The lock happens in Phase 3,
once `pyproject.toml` is final.

The index is **public**: no credential, no `UV_INDEX_*` environment, nothing to export
before `uv lock`. That is also what removed the vendoring step — `uv sync --frozen` in the
agent slot fetches the exact URL in `uv.lock`, and the slot holds no credential, so a
*private* index could never install there however well the push went. A public one
resolves in the slot exactly as it does on a laptop. There is no vendored wheel and no
second mode (#464).

### 2.6 Do NOT run the agent locally

Treat the agent as **deployed independently** — the skill won't have the code at run time,
so verify by **pushing and running it in the Portal**, not locally. Concretely:

- **No `uv run` / `python main.py` / smoke test in the project dir.** A local run creates a
  `.venv/` (tens of MB) and `__pycache__/` in the project — these used to bloat the push
  zip (HTTP 413). The CLI now excludes them, but the cleanest path is to never create them.
- **No need to compile-check.** A quick read of `main.py` against `references/sdk-api.md` is
  enough; the real signal is the Portal execution + trace after push.

---

## Phase 3 — Deploy checklist

Emit these as a copy-pasteable checklist, **pre-filled** with the project dir. **Run
`im-cli` on the host**, from the project directory. You're already logged in from Phase 1, so
the per-command `--api-url` is gone — every command uses the stored active login.

Login, agent creation and the provider grants already happened in **Phase 1**; `link`, the
grant readback, `main.py` and `.im/io.json` in **Phase 2**. What is left is to lock and ship.

### Step 1 — Re-check before you lock

Three things, because each one is a push that succeeds and an agent that is wrong:

```bash
cd <project-dir>
im-cli whoami                 # right server, right agent
cat .im/io.json               # every `name` here is a key main.py reads — compare them
im-cli agent services         # every *_SERVICE constant in main.py appears in this list
im-cli agent models           # the LLM_MODEL_ALIAS appears in this list
```

### Step 2 — lock → push

```bash
# Lock before push (--upgrade-package re-resolves/re-hashes im-sdk so `uv sync --frozen` accepts it).
uv lock --upgrade-package im-sdk
im-cli push   # add --submit to chain submit-for-review
```

`push` zips the project (`.venv`/`__pycache__` excluded; the SDK is not in the zip — the
slot fetches it from the public index off `uv.lock`), validates `.im/io.json` and the root
`pyproject.toml` + `uv.lock` **before** creating anything, then uploads it as version
`v{n}` in `draft`; `--submit` transitions it to `pending_review`. A **422** naming an
`agents.version.io.*` key is the `io.json` contract in §2.4 — fix and re-push; nothing was
created. A **422** naming an `agents.version.install.*` code is the *bundle*:
`install_lockfile_missing` / `install_lockfile_stale` mean `uv sync --frozen` refused your
lock (re-lock and re-push), `install_project_invalid` an unparseable `pyproject.toml`,
`install_dependencies_unresolvable` a pin with no solution. All of them are yours to fix —
the API reserves 422 for exactly that, and answers the four retryable ones
(`install_slots_exhausted`, `install_timed_out`, `install_manager_unavailable`,
`install_dependency_download_failed`) with **503** instead — wait and re-push, unchanged.

> **Diagnosing a push 500 — `push -v` first, then read the message.** A 500 is *never* a
> lock or a bundle problem — those come back 422 with a code, above. What reaches 500:
> - *Forwarded agent-manager error* → the Portal API's 500 body wraps an inner message
>   from the agent-manager (`HttpAgentManagerClient`), e.g.
>   `HTTP request returned status code 400: … gosu-wrapper.sh: Permission denied`. That is
>   **remote infrastructure** (the deployed agent-manager can't provision a slot), **not**
>   the project or the zip — don't keep re-pushing. Report it for an ops fix; link/
>   io.json/lock all persist, so only the `push` needs re-running once the server is fixed.
>   Sanity-check the project itself by pushing to the **local stack** instead.

### Step 3 — Execute and check progress

Any of these runs the **deployed** version server-side (not a local run) and is the
verification:

- **CLI (`im-cli run`):** from the project dir, streams the console live and blocks to a
  terminal status. Inputs are **repeated `--input key=value`** pairs or a **`--input-file
  <file.json>`** — **not** a bare JSON blob (that errors `--input "..." must be key=value`).
  Quote the whole `key=value` when the value has spaces:
  ```bash
  # repeated --input k=v (good for short values):
  im-cli run --input company=Patagonia --input "focus=supply chain transparency"
  # or a JSON file (good for long/multiline values; --input k=v overrides individual keys):
  im-cli run --input-file inputs.json
  ```
  With no version it runs the latest runnable (the draft you just pushed). Add `--detach`
  for just the execution UUID; `im-cli logs <execution> --follow` to re-stream.
- **Portal UI:** open the agent → **Playground**, fill the inputs (from `.im/io.json`),
  run, and watch the execution + trace events live.
- **API:** `POST /organizations/{org}/agents/{agent}/playground` to start;
  `GET /organizations/{org}/agents/{agent}/executions` to list/poll status.

---

## Guardrails

- **Run `im-cli` on the host** (use it if on `PATH`, else install per
  [`references/cli-reference.md`](references/cli-reference.md); in the monorepo, `make cli-build`).
  `im-cli login` once with `--api-url` (loopback http for the local stack, `https://` or
  `IM_CLI_ALLOW_HTTP=1` for remote); after that every `im-cli` command (`link`/`push`/`run`/
  `whoami`/`agent …`) uses the stored active login — **no PAT, no per-command `--api-url`**.
- **stdout discipline:** only the final `json.dumps(output)` may hit stdout. Anything
  else corrupts `json.loads(stdout)` on the runner.
- **The slot has no outbound egress — never `httpx`/`requests`/`urllib`/`aiohttp`.** Every
  byte from the open web comes through a granted capability (`web_fetch` for a URL you
  chose, `web_search`/`web_crawler`/`http_capability` otherwise). This is the one mistake
  that survives every local check: a direct HTTP client resolves, locks, pushes and passes
  review, then fails in the deployed slot with a bare DNS error. `install`-time and
  `run`-time are different containers — `uv sync` reaching the index proves nothing about
  the runner.
- **`.im/io.json` is a contract, and getting it wrong fails silently.** Every input `name`
  must match a key `main.py` reads off `data`; a mismatch is not an error, it is the
  fallback value returned as if it were the answer. Inputs are exactly `{name, type}` —
  any other key is accepted and then dropped. Input types: `string`/`multiline`/`url`/
  `email`/`json_string`/`file`; `file` is input-only and must be **absent** from
  `example.inputs`. All three of `inputs`/`output`/`example` are required, and every
  non-`file` input needs an `example.inputs` value. See §2.4.
- **The `uv.lock` pins the SDK** — `im-cli push` installs with `uv sync --frozen`, so a committed,
  current lock is what guarantees the exact version (the pyproject `==` pin is optional —
  `uv lock` resolves and freezes the latest published `im-sdk`). Never point a **path source**
  into the monorepo (`apps/core-sdk`): the agent-manager slot has no monorepo checkout. A
  `vendor/` path source is no longer needed either — the index is public, so the slot resolves
  it directly. Always `uv lock` before push.
- **Lock before every push** when a `pyproject.toml` is present, or push is refused 422
  `install_lockfile_missing` / `install_lockfile_stale`. Use
  `uv lock --upgrade-package im-sdk` — `--locked` rejects a lock that drifted from the pin,
  and plain `uv lock` won't re-resolve/re-hash an unchanged-version `im-sdk`.
- **Read the canonical `ResourceResult`, not the old per-resource shapes.** Every
  resource call returns one envelope whose *answer* is a typed `output` variant: LLM/answer
  text on `.text`, search hits on `.citations` (= `output.results`), and the structured
  payload on the typed `.output` (`output.blocks` / `output.pages` / `output.elements` /
  `output.items` / `output.body`). There is **no `.content`**. Variant list items are typed models — read
  `hit.url` / `el.text` as attributes, not `["key"]`. Verify against the bundled
  [`references/sdk-reference.md`](references/sdk-reference.md) (or the installed package via
  `python -c "import im_sdk …"`) before composing `main.py`.
- **`im-cli link` owns `.im/`** — don't pre-create `config.json` **or `io.json`**. `link`
  writes a local (gitignored) v2 `config.json` + an `io.json` skeleton (tracked) +
  `.im/.gitignore`, and never overwrites an `io.json` that already exists. Edit it only
  *after* `link` (§2.4). There is no local manifest file — inspect grants live with
  `im-cli agent models` / `im-cli agent services`.
- **Link before you write `main.py`.** The `*_SERVICE` constants and the `llm` alias are
  Portal-defined strings; `im-cli agent services` / `im-cli agent models` only answer for an
  agent once the project is linked. Writing the code first guarantees a second edit pass.
  Empty output from either command means no grants, not "no filter".
- **Agent is created in the Portal UI**, not by a script. After `im-cli link`, inspect it
  (org via `im-cli whoami`, grants via `im-cli agent services` / `im-cli agent models`) off the
  active login — no token-bearing curl script needed.
- **Grants are server-side:** creating the agent doesn't grant providers; the user must
  grant them in the Portal or the run fails authorization.
- **Output type is always `string`.** `IoSchemaValidator` allows only
  `string`/`url`/`email`/`json_string`/`multiline` — **`json` is a 422**. Serialize any
  structured result to a string before `print(json.dumps(output))`.
- **Never run the agent locally** (`uv run` / `python main.py`). It creates `.venv/` +
  `__pycache__/` (zip bloat → historically 413) and isn't a faithful signal — the skill
  doesn't own the runtime. Verify via push + the Portal Playground/trace instead.
- **Ask for the agent UUID only.** Login + Portal-create happen in Phase 1; `im-cli link`
  derives + prints the org from the UUID (the workspace is runner-injected) — don't ask the
  user for those.
- **`im-cli run` inputs are `--input key=value` / `--input-file`, not a JSON blob.** A bare
  `--input '{...}'` errors `--input "..." must be key=value`. (This is distinct from the
  runner→agent contract, where the runner passes `--input '<json>'` that `read_input()`
  parses — that JSON form is correct *inside* the agent, not for the `im-cli run` CLI.)
- **The generated project is the user's** to keep/commit. Never commit `.venv/` /
  `__pycache__/` (the push zip excludes them). In the monorepo, scaffolding under the
  gitignored `data/projects/` keeps generated agents out of version control.
