Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/cli-runs-as-the-apps-principal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@flow-state-dev/engine": minor
"@flow-state-dev/fsdev": minor
---

`fsdev run` and `fsdev chat` now run as whoever the app's resolver names (new `FlowState.resolveInProcessPrincipal`, with `source: "cli"` reserved for it), stop with exit 2 before writing anything when that resolver or a seat's pin refuses the terminal (a `--session` owned by another user or organization now also exits 2 instead of 1), and take `--org`/`--user` to name the identity locally (FIX-1551).
9 changes: 7 additions & 2 deletions apps/docs/docs/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ The first argument is the flow **instance** id — see [Flows](/docs/fundamental
| `-f, --input-file <path>` | JSON input from file |
| `-m, --model <model>` | Override model for generator blocks that run in this process. See [Model overrides](/docs/cli/overview#model-overrides) |
| `-s, --session <id>` | Session ID for reuse across invocations |
| `--org <id>` | Run in this organization and skip the app's resolver. See [Who a run is](/docs/cli/configuration#who-a-run-is) |
| `-u, --user <id>` | Run as this user. The organization comes from the app's resolver unless you also pass `--org`. Default: the user your app's resolver returns, or `cli-user` if the app has none or you pass `--org` |
| `--seed-session <json\|path>` | Seed session-level state (JSON or file path) |
| `--flow-dir <path>` | Override flow discovery root (repeatable). Errors if a config is loaded. |
| `--config <path>` | Load an explicit `fsdev.config` file instead of searching the cwd |
Expand All @@ -36,6 +38,8 @@ The first argument is the flow **instance** id — see [Flows](/docs/fundamental

When a config is loaded, `fsdev run` looks up the flow by instance id in the config's registry and uses its stores. `--model <id>` still applies, routed through the config's own resolver (your gateways and providers stay in effect), and it covers the generators that run in this process but not [background work handed to a queue](/docs/cli/overview#model-overrides). `--flow-dir` together with a config is an error; the message suggests `--no-config` if directory discovery is what you want. The config's FlowState is disposed on exit, and disposal waits for any background work the run started in this process. See [App Configuration](/docs/cli/configuration) and [Background work](/docs/cli/overview#background-work).

Without `--org`, the run is whoever your app's resolver says it is. See [Who a run is](/docs/cli/configuration#who-a-run-is).

**NDJSON events:**

Each line of stdout is a JSON object with a `type` field:
Expand Down Expand Up @@ -143,7 +147,8 @@ fsdev chat hello-chat chat
|------|-------------|
| `-s, --session <id>` | Resume an engine session for the initially bound flow. Requires a bound target. |
| `-m, --model <model>` | Override model for generator blocks that run in this process. See [Model overrides](/docs/cli/overview#model-overrides) |
| `-u, --user <id>` | Engine identity for sessions and turns (default: `cli-user`) |
| `-u, --user <id>` | Run turns as this user. The organization comes from the app's resolver unless you also pass `--org`. Default: the user your app's resolver returns, or `cli-user` if the app has none or you pass `--org` |
| `--org <id>` | Run turns in this organization and skip the app's resolver. See [Who a run is](/docs/cli/configuration#who-a-run-is) |
| `--flow-dir <path>` | Override flow discovery root (repeatable). Errors if a config is loaded. |
| `--config <path>` | Load an explicit `fsdev.config` file instead of searching the cwd |
| `--no-config` | Ignore any config and force directory discovery |
Expand Down Expand Up @@ -345,7 +350,7 @@ import type {
|------|---------|
| 0 | Success |
| 1 | Execution error (flow or block failed at runtime) |
| 2 | Invalid arguments (bad JSON input, missing required flags) |
| 2 | Invalid arguments (bad JSON input, missing required flags), or a run whose identity was refused. See [Who a run is](/docs/cli/configuration#who-a-run-is) |
| 3 | Configuration error (invalid port, missing devtool assets) |
| 4 | Discovery error (flow or block not found, import failed) |
| 10 | Internal error (unhandled exception) |
78 changes: 78 additions & 0 deletions apps/docs/docs/cli/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,84 @@ Three caveats follow from running your real wiring from the terminal:
- **A colocated queue worker starts for the run.** If your config declares a queue worker alongside the stores (a BullMQ worker, say), a `fsdev run` starts that worker for the duration of the run and drains it on dispose.
- **Concurrent writes can lose an update.** The app and the CLI can write the same `.fsdev/data` at once. Filesystem writes are torn-write-safe across processes, so you won't read a half-written record. But two processes updating the same record can still race, and one update can be lost.

## Who a run is

Every run executes as a user in an organization, like a request to your server. `fsdev run` and
`fsdev chat` ask your app's resolver for both. That is the flow's own resolver,
`defineFlow({ authentication: { resolvePrincipal } })`, when it has one, and otherwise the
`resolvePrincipal` you passed to `createFlowState`. Whatever the resolver returns is who the run is.

Your resolver sees `source: "cli"`, with no `request` and no credential. Only `fsdev run` and
`fsdev chat` produce that source. A request from any transport that claims it, including a custom
adapter you wrote, is refused before your resolver runs. So it's safe to branch on:

```ts title="fsdev.config.ts"
resolvePrincipal: async (ctx) =>
ctx.source === "cli"
? { userId: "local-dev", orgId: "acme" }
: readSession(ctx.request),
```

With no resolver configured anywhere, a run is `cli-user` in the development organization,
`DEFAULT_ORG_ID` (`__fsd_default_org__` in output). That is also who a run is with no config at all, when flows come from directory
discovery or you pass `--no-config`. A configured resolver can't claim that organization: one that
returns `DEFAULT_ORG_ID` is refused, from the terminal as over HTTP. See
[Every request runs in an organization](/docs/server/authentication#every-request-runs-in-an-organization).

**When the resolver wants a credential.** A resolver that checks a bearer token or a signature
has nothing to check. It either throws its own error or returns `null`, and a `null` is refused
because it names no user or organization. Either way, `fsdev run` stops before it writes anything and exits
with code `2`. The error names the flow and carries the refusal's message. Here the flow's resolver
is `createBearerSecretPrincipalResolver`, which returns `null` when there's no bearer header:

```text
Flow "admin" refused this terminal: Action request requires non-empty userId
The CLI carries no credential, so a resolver that checks one refuses it. Pass --org <id> to name the organization yourself. Nothing was written.
```

Pass `--org` to say which organization to run in yourself:

```bash
fsdev run billing refund -i '{"id":"r_1"}' --org acme --user support-bot
```

`--org` skips your resolver entirely and runs as `--user`, or `cli-user` without it. It can't be
blank or `DEFAULT_ORG_ID`. `fsdev serve` and `fsdev dev` have no such flag, so requests that arrive
over the network always go through your resolver.

`--user` on its own asks your resolver as usual, keeps the organization it returns, and replaces
only the user. A resolver that refuses the terminal refuses it with `--user` too.

**Identities a run can't take.** `fsdev run` refuses each of these with exit code `2` before
anything is written:

- A session belongs to the user and organization it was created with. Resuming one with
`--session` as anyone else is refused, as it would be over HTTP. Use a new session id.
- A [hired seat](/docs/workforce/durable-hire#who-can-reach-a-hired-seat) runs only for the owner
it's pinned to. A run whose user or organization falls outside that pin is refused, whether the
identity came from your resolver or from `--user` and `--org`. Name the owner with `--org`, plus
`--user` for a seat one member owns.
- A session with no organization recorded on it is refused and left unchanged. The message points
to the upgrade steps in
[Which organization a record belongs to](/docs/persistence/overview#which-organization-a-record-belongs-to).

**Seeing who a run was.** Unless you pass `--quiet`, `fsdev run` prints one line to stderr before
the action runs:

```text
[fsdev] running as bob (named by --user) in organization acme-dev (from the app's resolver)
```

`--capture <path>` records the same identity under `command.principal`:

```json
{ "userId": "bob", "orgId": "acme-dev", "from": "resolver" }
```

`from` says where the organization came from: `resolver`, `flag` (`--org`), or
`development-default` (no resolver configured). It doesn't describe the user. Whether `--user`
named the user shows only on the stderr line.

## Runtime requirements

A `.ts` config needs a runtime that can load TypeScript. Inside the framework monorepo, tsx handles that. In a consumer repo, you need one of:
Expand Down
3 changes: 2 additions & 1 deletion apps/docs/docs/cli/interactive-chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Anything after `/` that no built-in claims is sent to the flow unchanged. That's

Each flow kind gets its own session within a run, so conversation history and state don't bleed across a `/use` switch. Switch away and back, and the first flow's session resumes where it left off. History persists in the engine's stores — the same SQLite database (`.fsdev/data/fsdev.db`) the DevTool reads in the discovery path — so a conversation survives restarts of the session.

Turns and the engine identity that owns them default to `cli-user`. The DevTool defaults to `devuser`. If you want a chat session to show up in the DevTool's session list, or to resume a session across the two surfaces, align them — pass `--user devuser` to `fsdev chat`, or set the DevTool's user to `cli-user`.
Turns run as whoever your app's resolver says, asked once per turn for that turn's flow. With no resolver, that is `cli-user` in the development organization, `DEFAULT_ORG_ID` (`__fsd_default_org__` in output), while the DevTool defaults to the user `devuser`. To see a chat session in the DevTool's session list, or resume one across the two, align them with `--user devuser`. If a flow's resolver refuses the CLI, that turn fails and the chat keeps going. Pass `--org` to get past it. `/status` shows the organization the current flow's last turn ran in. See [Who a run is](./configuration.md#who-a-run-is) for how the resolver is asked and what `--org` and `--user` change.

`--session <id>` resumes a specific session for the initially bound flow. A session that belongs to a different flow is rejected rather than silently reused, since the engine routes state by the session's flow.

Expand All @@ -76,6 +76,7 @@ Your name is Ada.
Target: hello-chat · chat
Session: sess_a1b2c3
Turns: 2
Org: __fsd_default_org__ (user cli-user, development-default)
Source: config (fsdev.config.ts)
Store: app-configured stores
❯ /exit
Expand Down
7 changes: 6 additions & 1 deletion apps/docs/docs/server/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ defineFlow({
kind: "billing",
authentication: {
resolvePrincipal: async (ctx) => {
// ctx.source: 'http' | 'mcp' | 'webhook' | 'scheduled' | ...
// ctx.source: 'http' | 'mcp' | 'webhook' | 'scheduled' | 'cli' | ...
// ctx.request — present for HTTP-shaped transports
// ctx.envelope — flowKind, action, sessionId, metadata, input
// ctx.rawBody — preserved by HTTP for signature verification
Expand Down Expand Up @@ -338,6 +338,11 @@ export const flowstate = createFlowState({

Per-flow `defineFlow({ authentication })` always wins over this fallback.

`fsdev run` and `fsdev chat` ask these resolvers too, with `source: "cli"` and no `request`.
Only those two commands produce that source. A request from any transport that claims it,
including a custom adapter, is refused with 401 before your resolver runs, so a resolver can
branch on it. See [Who a run is](/docs/cli/configuration#who-a-run-is).

## What a resolver protects

Configuring `resolvePrincipal` covers the whole flow API, not just action
Expand Down
4 changes: 2 additions & 2 deletions apps/kitchen-sink/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ curl -X POST localhost:3000/api/flows/workforce-admin/actions/hire \
-d '{"userId":"you","input":{"seatId":"support.bo","flow":"desk-clerk","settings":{"desk":"back"},"instructions":"You work the back desk."}}'
```

Over HTTP rather than through `fsdev run`, because the CLI sends a fixed user and no organization, and this action needs one.
Over HTTP, because the admin flow checks a token and the CLI carries none.

The admin action has a credential of its own, but not an organization of its own. Every token has to name `kitchen-sink`. An entry naming any other organization is refused when the app starts, and the refusal is logged, so a token can never quietly administer an organization this app doesn't serve. A seat the admin action hires belongs to the operator who hired it.

Expand Down Expand Up @@ -144,7 +144,7 @@ A hire names a kind this app already carries (`agent`, `desk-clerk` or `followup

Firing releases the address, and `discover` stops listing the seat. The seat's row in the live inventory stays, because that list records what was ever registered.

**From the CLI, mara can't hire.** A hired seat's address starts with its organization. In the app she runs as `kitchen-sink`, like every seat, so a hire through the app lands there. `fsdev run` doesn't use the app's resolver: it runs every seat under the framework's development organization, and that name is deliberately not a legal address, so the hire is refused and nothing is written. Ask her from the CLI anyway and she tells you the hire was refused, quoting the refusal, which names the organization:
**From the CLI, mara hires too.** A hired seat's address starts with its organization. In the app she runs as `kitchen-sink`, like every seat, and `fsdev run` asks the app's resolver the same question, so it runs as the same `devuser` in `kitchen-sink` and the hire lands where the app's pages see it:

```bash
pnpm fsdev run support.mara run -i '{"message":"Hire support.pat, an agent seat that takes refunds."}'
Expand Down
8 changes: 4 additions & 4 deletions apps/kitchen-sink/test/hired-seat-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ describe("a seat hired over workforce-admin, reached with the hiring credential"
it("is listed in the catalog for the operator who hired it", async () => {
const app = await bootWithHire();

const listed = await app.catalog(ACME);
const listed = await app.catalog(TOKEN);

expect(listed.status).toBe(200);
expect(listed.ids).toContain(SEAT);
Expand Down Expand Up @@ -212,11 +212,11 @@ describe("a seat hired over workforce-admin stays closed to everyone else", () =
it("is left out of the catalog for another organization and for a caller with no credential", async () => {
const app = await bootWithHire();

const bravo = await app.catalog(BRAVO);
const elsewhere = await app.catalog(OTHER_ORG_TOKEN);
const anonymous = await app.catalog(undefined);

expect(bravo.status).toBe(200);
expect(bravo.ids).not.toContain(SEAT);
expect(elsewhere.status).toBe(200);
expect(elsewhere.ids).not.toContain(SEAT);
// The catalog route stays exempt: no credential is a shorter list, not a 401.
expect(anonymous.status).toBe(200);
expect(anonymous.ids).not.toContain(SEAT);
Expand Down
Loading
Loading