akanjs 3.2.1-rc.0 → 3.2.1-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,97 @@
1
1
  # akanjs
2
2
 
3
+ ## 3.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - c44d068: A coding agent reads less to build its first app: the `akanjs` README keeps the path to a first app and links the rest on akanjs.com (17 KB to 7 KB), the `akan-page` and `akan-service` skills ship the API reference one section at a time with every entry named in the skill's index (`Link` now lists the anchor attributes it takes and `Link.Back`, `Link.Close` and `Link.Lang`), the `akan-page` skill holds what a first page looks up while `pageRule` keeps the deeper contract, and each rule is stated once across AGENTS.md, the path rules and the skills. Run `akan agent install` in a workspace to pick up the new files.
8
+ - 24315d1: A page asks for its stylesheet before its client chunks. The preload tags for the chunks a page's first screen imports are written at the end of `<head>` instead of at its top, so the stylesheet link comes first; the bootstrap module, the dictionary and the import map stay at the top. On a throttled mobile connection (Lighthouse's slow 4G applied in the browser, over HTTP/2) a 56-chunk page first paints about 160 ms sooner (1.83 s to 1.67 s), and a page whose largest element is a small image shows it about 140 ms sooner; a large image still shares the connection with the chunks and arrives when it did. Every chunk still starts loading with the document, so the page hydrates when it did.
9
+ - bf582c1: A page stored in the HTML cache is kept as the bytes it streamed, instead of being decoded to text and encoded again before compression. Storing a 600 KB page takes about a fifth of the main-thread time it did, and the stored page and every response from it are unchanged.
10
+ - c10f7cf: A loader sends its store at most 500 distinct keys per query and splits a larger batch into several queries that run together. A `load<Model>Many` or a nested list with more ids than a database takes in one statement now loads instead of failing: Postgres refused more than 65,534 values, and SQLite refused a `byQuery` batch of about 1,000 keys.
11
+ - c10f7cf: A loader asks its store for each key once per batch: loads of the same key in one batch share one lookup, and each caller still gets its own document wherever the loader has `copy`, as every model and declared loader does. A `new DataLoader(...)` without `copy` now hands the callers of a repeated key one result object, where a batch function that built a fresh object per position gave each its own: pass `copy` to keep them apart. A batch function that throws, or resolves to something that is not an array, now rejects its callers instead of leaving them waiting.
12
+ - 045699c: The `create-akan-workspace` README shows how to run it on a host with only Node and npm (`npx -y bun@1.4.4 x create-akan-workspace@latest`) and the `npm run build` / `npm start` scripts it then writes, and `akanjs`, `@akanjs/cli` and `create-akan-workspace` each carry a one-line `description`, so `npm view` says what the package is and how to start.
13
+ - 5c7e083: Every page of a list is read with one SQL text: the page offset is a bound parameter, so paging no longer adds a prepared statement per page to the SQLite statement cache or to each Postgres connection. On Postgres a list of two or more values (`q.oneOf`, `q.notOneOf`, a raw table's `$in` and `$nin`) is bound as one array, so its length adds no prepared statement either, and a list past the 65,534 parameters one statement may bind is now read. An insight is read in one statement instead of one per field, so its counts and sums come from one snapshot and, with six fields, in about a third of the time.
14
+ - aead1aa: A page render no longer sends the whole client manifest to the RSC worker with every request. The worker process receives a manifest once and each render names it by revision, which takes a burst of cached pages from about 38 ms to about 7 ms at the median on the docs app.
15
+
16
+ A page the RSC worker has cached replays as one message instead of one message and one timer wait per chunk: a cached page of the docs app answers in about 0.3 ms instead of 4.7 ms.
17
+
18
+ A render that produces many small chunks at once sends them as a few messages of up to 32 KB. A page still waiting on data sends what it has rendered at once, as before.
19
+
20
+ The server still fails a render whose stream it has 256 messages of undrained, and since a message now holds up to 32 KB that is about 8 MB of a streamed page where it was about 1 MB; a cached page arrives as one message, so it is never counted.
21
+
22
+ - 5c6d039: A precompressed `.br` or `.gz` asset is now streamed from disk instead of being read whole and copied on every request, which cuts the server CPU per asset request to about a quarter. In production the answer of whether a sidecar exists is remembered per path.
23
+ An existing zero-byte `.br` or `.gz` sibling is skipped, because an empty body is not valid brotli or gzip.
24
+ - 0492e0b: The SQLite cache sweeps expired entries through an index on their expiry, a thousand at a time with a pause between, so a large backlog no longer stalls the server for hundreds of milliseconds, and `hkeys` and `hentries` no longer run a sweep on every call. They skip expired fields themselves, so they return the same fields as before. The index is built once, at the first start after upgrading.
25
+ - 0492e0b: On the SQLite cache, a value or hash field written by another process is no longer removed by a `get` or `hget` that saw the key's previous, expired entry.
26
+ - 5c7e083: On SQLite a read, count or write by a list of ids (`q.oneOf` on `id`, which is how a batched load by id reads) goes through the primary key. A model with an index that leads with `removedAt` had a list of five or more ids read every live row instead: at 20,000 rows a load of five ids took about 6 ms and now takes about 0.03 ms.
27
+ - 98931e4: `akan start` boots the backend while the first base build runs: the backend loads its server graph beside the build and mounts the web surface as soon as the build's artifact is on disk, so the dev server is ready sooner.
28
+
29
+ The port now answers from the start of the build. A request to `localhost` or an IP address, page or API, waits for the first artifact; a build longer than the 15 s the gateway holds a request ends the wait with a 503 "Backend is starting" page that reloads itself. A request to one of the app's own domains (a custom local domain) gets that 503 at once until the backend is ready, because the build has not written the app's hosts yet; after that it is served as before, and any other Host is refused as before.
30
+
31
+ ## 3.2.0
32
+
33
+ ### Minor Changes
34
+
35
+ - 038d918: Akan.js 3.2.0. Read **Upgrade notes** before deploying an app that runs 3.1.1: unguarded endpoints, log levels, the `Err` class, loaders, SQLite transactions, exit codes and a CLI version check change behaviour.
36
+
37
+ **Highlights**
38
+
39
+ - **`agentService.loop`.** A server-side agent run over the `/mcp` tool catalogue, in-process, with `toolkits`, `remotes` (other MCP servers), `clientTools` (a screen the member has open), `ask` (a question parked between runs), `answer`, overflow retry, and a read rule that counts what a run reads as untrusted. `plug(AgentToolsRole)` runs the catalogue as a given account; `mcp: "agent"` keeps an entry off `/mcp` for the in-process agent only.
40
+ - **Akan Graph and Akan Studio.** `get_graph` (MCP) returns the Akan Graph, read from source with no dev server: models, scalars, slices, endpoints with guards, services, jobs, adaptors, routes, layouts, the framework itself, and the Change Map for `since: <revision>`. `akan start` serves Studio at `/_akan/studio`, and it opens from the CLI and the editor.
41
+ - **Editor support.** `@akanjs/language` resolves names Akan.js derives (`fetch.initMemoInPublic`, `st.do.setNameOnMemo`, `this.memoService.listByName`) and ships `akan-language-server`. The VS Code / Cursor extension opens a module side by side, runs `akan verify` and workflows, and publishes from CI to the VS Marketplace and Open VSX.
42
+ - **Secure defaults.** Signals, websocket rooms, MCP, OAuth, the agent relay, the server edge, the ops channel, native builds, `akan code`, the CLI's tunnels and workflows, and the in-page agent each take the narrower default. Every change names how to get the old behaviour back.
43
+ - **Faster pages.** Every SSR page loads 72K less framework JS (22K less Brotli); client modules preload from `<head>`; Link prefetch; Flight rows share inline scripts; one preloaded font face per family; faster RSC decoding and store writes; a route JS budget (`akan build --check-budget`).
44
+ - **Realtime.** Per-socket, per-caller and per-model room limits, subscribe budgets, gateway subscribe acks, per-model live-sync routing, Redis room sharding, resync after a Redis outage, and an outbox limit for a down socket.
45
+ - **Native.** `external-view` on Linux (Wayland and X11) with `sendKey`; Android 12 launch crash fixed; AppImage relaunch; tighter CSP, external-link, temp-folder and update defaults.
46
+
47
+ **Upgrade notes**
48
+
49
+ - **Guards.** An endpoint, slice query or pubsub room that declares no guards is refused with 403; open it with `[Public]`. Outside local operation a server whose signals declare a guardless endpoint stops at boot and names each one. `AKAN_UNGUARDED_ENDPOINTS=open` answers them as before. A slice whose `guards` leaves out `root` mounts no root list or insight. `guard(name)` refuses until `canPass` is overridden.
50
+ - **`Err`.** Every `Err` is one class, `Err` from `akanjs/common`, and an `AkanError`. `err.code` is always set (a generalized failure's code, else its status's code), so `{ ...err }` now holds it. `Err.NotFound.is(error)` also requires status 404. Check across a page bundle and the framework with `Err.is`, not `instanceof`. `setErrorConstructor`, `HttpClientOptions.ErrorCls` and `FetchClient.build`'s `Err` option are deprecated.
51
+ - **Coded failures.** The signal, service, server, route-tree, RSC and client facets throw coded `AkanError`s instead of a bare `Error`; messages and statuses are unchanged. A production 500 shows the status reason and code only. `bun run error:codes` lists the codes. A failed tool call and a failed agent turn carry a `code`.
52
+ - **Log levels.** A failure under 500 logs at `warn`, a 5xx is one `error` record with `type` and `stack`, a declared error, a 429 and a by-id read of a missing id log at `debug`, and a crashed RSC worker logs at `warn`. Alerts and `--level error` filters see fewer lines. A page `redirect()` is `ok` at `info` with its 3xx status, and `notFound()` is `warn` with 404. Every log record reaches ndjson stdout, and a request line is never folded.
53
+ - **Loaders.** A loader no longer shares a batch between a transaction and the requests outside it, and each caller gets its own document. A loader that keeps its keys forgets them when the model is written; a write by query clears every kept key of the model, and `cache: true` keeps the 10,000 most recent keys. A custom `DatabaseAdaptor` can implement `transactionKey()`; a `batchScheduleFn` must run its callback in the caller's async context.
54
+ - **SQLite.** Work outside an open `this.transaction()` no longer sees its uncommitted rows, on `:memory:` or a non-WAL file either. `SqliteDatabase.getMeta` and `listMeta` return promises, so await them. A reader pays one database copy per transaction on `:memory:`; past a few tens of megabytes, put the database in a file.
55
+ - **Indexes.** A boot keeps an index the release no longer declares and warns about it. After every instance runs this release, run `akan migrate <app> prune-indexes` once. `migrationActions` gains `indexes` and `prune-indexes`, so code that switches over every action needs the two cases.
56
+ - **Websockets.** A socket holds at most 256 rooms, a caller 2,000 per process, a model 50,000 evaluated live rooms; a subscribe past a limit gets a 429 frame coded `liveRoomLimit`. Subscribes are budgeted at 1,000 a minute per socket and 10,000 per caller. A `pubsub` room's `onResync` also runs after Redis returns; a custom `WebsocketAdaptor.onRecovered` handler now takes the held rooms. A down socket keeps at most 100 emits.
57
+ - **Gateway.** `/_akan/app/ready` answers 503 while no replica's RSC worker can render. A subscribe is acknowledged once the gateway routes the room.
58
+ - **CLI.** A CLI whose major.minor differs from the workspace's `akanjs` refuses every command that writes, with exit 2; run `akan update`, or set `AKAN_ALLOW_VERSION_MISMATCH=1`. Exit codes: 2 for usage and unknown targets, 3 for failed checks (`verify`, `typecheck`), 130 for an interrupted prompt; a script that tested for exit 1 tests for non-zero. With `--json`, a failure ends stdout with `{"ok":false,"error":"<message>","code":"<code>"}`. `akan doctor` exits 1 on `"status": "failed"`; `akan workflow plan`, `apply` and `validate` exit non-zero on failure. A shell `AKAN_PUBLIC_ENV` now outranks the workspace `.env`, and `akan build --env <env>` builds another environment.
59
+ - **Package budget.** `akan lint` and `akan verify` hold each package under `pkgs/` to the file, function and class budget. Run `akan quality baseline` once in a workspace whose packages are over it. `akan verify` also typechecks every app and lib that uses a changed lib.
60
+ - **Secure defaults.**
61
+ - Write tools in the in-page agent confirm by default (`submit`, `create`, `update`, `send`, `export` and the rest, not only `remove`); opt out with `{ confirm: false }`. Page text reaches the model fenced as data, and a transcript belongs to one account.
62
+ - A `FetchClient` sends its session token only to its own origin; pass `clone({ origin, jwt })` to send one elsewhere.
63
+ - A connection idle for 120 s closes (`AKAN_IDLE_TIMEOUT`), a body is capped at 128 MiB (`AKAN_MAX_UPLOAD_BODY`) and 16 MiB for a non-multipart one (`AKAN_MAX_REQUEST_BODY`), `akan start` binds 127.0.0.1 (`AKAN_LISTEN_HOST=*` restores it), and HTML carries `Cache-Control`, HSTS and a `frame-ancestors` policy.
64
+ - The dev server answers only `localhost`, `*.localhost` and IP hosts unless `AKAN_ALLOWED_HOSTS` is set.
65
+ - A 500 shows its message and stack only under `akan start`, `NODE_ENV` `development` or `test`, or `AKAN_ERROR_DETAIL=1`.
66
+ - `ops snapshot` outside local operation needs `AKAN_BACKUP_RECIPIENT` or `--allow-plaintext`; the ops key must differ from `AKAN_MACHINE_PUBLIC_KEY`.
67
+ - `/__rsc/manifest` is dev-only (`AKAN_EXPOSE_RSC_MANIFEST=1`), and health detail, metrics and devtools need a local dev runtime.
68
+ - Filter arguments are parsed against their declared type and an `Any` filter argument throws at declaration; `q.search()` text is capped at 32 terms and 1000 characters.
69
+ - The image optimizer refuses non-public remote hosts (`images.dangerouslyAllowLocalIP`).
70
+ - The CLI's tunnels listen on loopback and check the SSH host key, workflow commands run without a shell, `akan download-env` copies only env and secret files, a Dockerfile built with `AKAN_PUBLIC_ENV=local` needs `--build-arg AKAN_ALLOW_LOCAL_IMAGE=1`, and `akan code` asks before network access and trusts a repository's MCP servers and extensions only after one terminal approval.
71
+ - MCP rate-limits an unverified bearer by address, checks the browser Origin, and bounds client registration; the agent relay refuses a request past fixed limits with `agent.error.requestRefused` (413) unless a policy sets its own.
72
+ - Native builds ship a Content-Security-Policy, open only `https:`, `mailto:` and `tel:` links, and recheck a downloaded desktop update before installing it; `updates.windowsSigners` and `updates.expiresIn` are new.
73
+ - **UI.** `Field.Switch`'s on position is `primary` (pass `variant="accent"` for the old look), and two `Data.Item` status tags change color. `useCamera` and `useGeoLocation` no longer send the user to Settings after a denial. A page `.head()` can set `theme-color`, and a level that writes an image no longer inherits the image tags above it. `--akan-theme-color` drives the browser's `theme-color`.
74
+ - **Libraries.** The `shared` and `util` libraries `akan install-library` copies are refreshed; compare your copy. In `util`, `security` and `security.jwtSecret` are optional in `ModulesOptions`. `libs/shared` keeps its SSO and refresh cookies on `__Host-` names outside local.
75
+ - **Other.** `LLM` stream endings are read more completely: a cut tool call ends as `length`, and unparseable arguments in a finished answer get `argsError` and the code `invalidArgument`. `ConformanceEnv.has` fails instead of skipping when `AKAN_TEST_REQUIRE_BACKENDS=1`. A new workspace has no `patches/` folder, no `agent:sample:*` scripts and one `setup:agent` script; `create-akan-workspace` no longer hangs when `akan` is not on PATH.
76
+
77
+ **Features**
78
+
79
+ - **Agent.** `Agent.Chat` modals and toasts stack above the panel and its header takes a node; the tool row is the `AgentToolRow` override slot; a restored transcript that ends on an unanswered `askUser` reopens on it; a turn its caller stops is billed at what the provider plausibly charged, and every turn the quota passes is billed.
80
+ - **Rendering and navigation.** `{ static: true }` page apps answer a host that asks for script-less HTML; `i18n.localePrefix: "as-needed"` serves the default locale unprefixed; a route guard receives `{ path }` and `signedIn({ path })` adds `?redirect=`; a failed route level or `Load.Stream` draws a notice with "Try again" in its own place; `router.refresh()` in CSR no longer reloads the document; a lazy chunk the server no longer serves reloads the page once; `forwardVisitor: false` keeps a render cacheable; a query takes `signal` and identical in-flight queries share one request.
81
+ - **Data.** `create<Model>Many(rows)` runs every row through `_preCreate`, `_postCreate` and the document hooks; `bulkWrite` runs in one transaction; a cascade removes a long array's documents 200 ids at a time; `Binary` arguments are typed `Uint8Array<ArrayBuffer>`; a hidden `.optional()` field is optional in create inputs; store form setters and writes cost about one copy of the state; `onError` on store writes receives the failed request's dictionary error.
82
+ - **Server and ops.** `/_akan/app/ready`; `RestartSchedule` shared by every child-restart loop; a single-flight `cache` endpoint; stopped or failed starts tear down what they brought up; the Redis WebSocket adaptor shards channels per room and model and flushes publishes on shutdown; a log stream stops growing for a client that stops reading; missing assets answer `no-store`.
83
+ - **CLI.** `akan test --parallel=<n>`, `--junit <path>` and `--coverage`; `akan build --env`; a `rename-key` workflow; `akan remove-module pokedex:_billing` removes a service module; `akan create-workspace` works in an existing folder, without sample code, and without a git identity; `akan preview` opens `/_akan/studio`, `/openapi.json` and `/mcp` as written and restarts a dead browser; `akan verify` reports step durations and gives a dictionary hint for a missing key; commands without a terminal take the workspace's only app, lib or package, and remove commands never pick a target themselves; release candidates publish from CI with npm provenance.
84
+ - **Native.** `external-view` and `sendKey` on Linux; Android 12 and 12L launch fix; AppImage relaunch; a `single-instance` pipe that another account cannot own on Windows.
85
+ - **Types and styling.** A new app's default style is Pretendard with -3% letter spacing, even sizes from 12px, 150% line height for wrapping text and `leading-auto` for one line.
86
+
87
+ **Fixes**
88
+
89
+ - A dev page keeps its styles after a stylesheet change arrives with a pages rebuild; idle-suspended dev servers apply every save, stay awake when work arrives, and stop cleanly; `[BarrelAnalyzer] ERROR scan failed` is gone; a backend replica's builder answer no longer reaches its replacement.
90
+ - A page that renders a string of 1024 characters or more renders and hydrates whatever its lines say; a page cut off by a disconnected client, or one that streamed an error, is no longer cached; partial RSC commit (`AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`) patches real pages, replays patches from cache and cancels overtaken navigations.
91
+ - In production, a render error no longer reaches the browser as its message; reading the client address from a crafted forwarded header no longer stalls the server; `happy-dom` peers ask for `^21.0.4`; the pi agent packages move to 1.5.2, dropping undici and minimatch advisories.
92
+ - The build lock records its host and survives a dead remover, a Windows antivirus hold and a devcontainer; `akan` no longer rebuilds the dev CLI from a command it runs; the typecheck behind `akan verify` and `akan build` uses its incremental cache.
93
+ - Internal: the largest classes and methods in `akanjs`, `@akanjs/devkit` and `@akanjs/cli` are split by concern with unchanged public members, and the `akanjs` facets import sibling files instead of their own barrel and list every export by name.
94
+
3
95
  ## 3.1.1
4
96
 
5
97
  ### Patch Changes
package/README.ko.md CHANGED
@@ -6,11 +6,9 @@
6
6
 
7
7
  **에이전트까지 들어 있는 TypeScript 프레임워크.** Bun으로 구동합니다.
8
8
 
9
- **화면을 만들면, 에이전트가 씁니다. 서버를 만들면, AI가 다룹니다.**
10
-
11
- 툴 스키마도, 따로 쓰는 MCP 서버도, 에이전트용 권한 모델도 없습니다. 사람을 위해 만든 앱이 그대로 AI가 쓰는 앱이
12
- 되고, 모델은 원하는 것을 고르면 됩니다. 비즈니스 코드 한 줄이 모든 레이어를 지나 여섯 플랫폼에 닿고, 쓰는 모두에게
13
- 이릅니다. 사람에게도, 에이전트에게도요.
9
+ Akan.js는 풀스택 TypeScript 프레임워크입니다. 필드 선언 한 줄이 스키마, 서비스, API, 클라이언트 상태, UI를 모두
10
+ 지나고, 같은 코드가 웹 앱, iOS·Android 앱, 데스크톱 앱으로 나갑니다. 가드를 단 엔드포인트는 그대로 MCP 툴이, 화면의
11
+ 컨트롤은 인페이지 에이전트 툴이 되고, 사람이 지나는 가드를 똑같이 지납니다.
14
12
 
15
13
  ## 빠른 시작
16
14
 
@@ -62,19 +60,10 @@ URL이라면, 코딩 에이전트는 묻지 않고 아래대로 진행하면 됩
62
60
  - **정해진 URL:** 페이지는 기본적으로 `/<locale>/…` 아래에 있습니다. 기본 로케일을 프리픽스 없는 경로
63
61
  (`/books/OL45804W`)로 내보내려면 `akan.config.ts`에 `i18n: { defaultLocale: "en", locales: ["en"], localePrefix:
64
62
  "as-needed" }`를 두세요. `<Link>`도 따라갑니다.
65
- - **Node와 npm만 있는 호스트:** 생성기를 npx로 실행하세요. 전역에 아무것도 쓰지 않습니다:
66
- `npx -y bun@1.4.4 x create-akan-workspace@latest . --app <app> --dir <folder> --sample false`. 그 Bun은 이후
67
- `PATH`에 없으므로 생성기가 워크스페이스의 `dependencies`에 `bun`을 넣고 아래 script를 씁니다. 다른 명령은
68
- `npx akan …`으로 실행하세요.
69
- - **Docker 없이 빌드하고 실행하기:** 아래 package script를 두고 `npm run build` 뒤 `PORT=3000 npm start`로 띄웁니다.
70
-
71
- ```json
72
- "build": "akan build <app>",
73
- "start": "cd dist/apps/<app> && bun main.js"
74
- ```
75
-
76
- 새로 clone한 사본도 그대로 빌드됩니다. env 파일은 gitignore된 채로 두면 `akan`이 없는 것을 만들어 주므로 커밋할
77
- 필요가 없습니다. 빌드에 필요한 env가 함께 들어 있고, 실행할 때 지정한 변수가 그 값을 덮어씁니다.
63
+ - **Node와 npm만 있는 호스트:** `npx -y bun@1.4.4 x create-akan-workspace@latest . --app <app> --dir <folder> --sample false`를
64
+ 실행한 뒤 `npm run build`, `PORT=3000 npm start`로 빌드하고 띄웁니다. 생성기가 쓰는 script와 새로 clone한 사본에
65
+ 필요한 것은 [`create-akan-workspace` README](https://github.com/akan-team/akanjs/blob/main/pkgs/create-akan-workspace/README.ko.md#node와-npm만-있을-때)에
66
+ 있습니다.
78
67
  - **실행할 곳에 맞게 빌드하기.** 셸이나 Bun이 읽는 `.env.local`에서 지정한 변수가 워크스페이스 `.env`보다 우선하고(빈
79
68
  값은 지정하지 않은 것으로 보며, 빌드는 그렇게 가져간 값을 하나씩 알려 줍니다), `AKAN_PUBLIC_ENV`는 `--env`가 둘보다
80
69
  우선합니다. 새 워크스페이스의 `.env`는 `local`이라 내 컴퓨터나 테스트 러너에서는 이대로 맞지만, 서버가
@@ -82,287 +71,42 @@ URL이라면, 코딩 에이전트는 묻지 않고 아래대로 진행하면 됩
82
71
  `AKAN_PUBLIC_REPO_NAME`과 `AKAN_PUBLIC_SERVE_DOMAIN`(서비스할 도메인)을 지정하고 `akan build <app> --env main`을
83
72
  실행하세요.
84
73
 
85
- ## 이 모든 게 한 줄입니다
86
-
87
- ```ts
88
- export class ProductInput extends via((field) => ({
89
- name: field(String),
90
- })) {}
91
- ```
92
-
93
- **한 줄 × 8 레이어 × 6 플랫폼 × 사람과 에이전트.**
94
-
95
- - **한 줄.** 필드를 더하는 일은 선언 한 줄, 이름과 타입이면 됩니다.
96
- - **× 8 레이어.** 그 한 줄이 스키마, 쿼리, 서비스, API, fetch, 클라이언트 타입, 상태, UI prop까지 뚫고 내려갑니다.
97
- 보통의 스택에서는 손으로 고쳐야 할 8곳이고, 하나라도 빠뜨리면 타입이 깨지거나 런타임에서 터집니다. 여기서는
98
- 함께 바뀝니다.
99
- - **× 6 플랫폼.** 같은 코드가 SEO 웹, iOS·Android 앱, macOS·Windows·Linux 데스크톱 앱으로 배포됩니다. 감싼
100
- 웹사이트가 아니라 네이티브 수준의 화면 전환까지 갖춘 채로요.
101
- - **× 사람과 에이전트.** 가드를 통과한 엔드포인트는 MCP 도구가, 화면의 컨트롤은 인페이지 에이전트 도구가 됩니다.
102
- 사람과 같은 가드를 거쳐서요.
103
-
104
- ## 당신이 만든 화면이 곧 에이전트의 인터페이스입니다
105
-
106
- ```tsx
107
- export const Order = () => {
108
- const { l } = usePage();
109
- const icecreamOrderForm = st.use.icecreamOrderForm();
110
- const order = st.tool("createIcecreamOrder", { confirm: true })
111
- .desc("Place the order in the form.")
112
- .exec(() => st.do.createIcecreamOrder());
113
- return (
114
- <>
115
- <Field.MultiToggleSelect
116
- label={l("icecreamOrder.toppings")}
117
- items={cnst.Topping}
118
- value={icecreamOrderForm.toppings}
119
- onChange={st.do.setToppingsOnIcecreamOrder}
120
- />
121
- <Button onClick={order}>{l("icecreamOrder.createIcecreamOrder")}</Button>
122
- </>
123
- );
124
- };
125
- ```
126
-
127
- - **원래 쓰려던 화면을 그대로 씁니다.** setter를 넘겨받은 필드는 그 setter를 공개합니다. 버튼 핸들러는 `st.tool`
128
- 한 줄로 툴이 되고, 버튼이 부르는 바로 그 함수가 됩니다.
129
- - **에이전트에게는 픽셀이 아니라 도구가 보입니다.** 연결한 컨트롤마다 자기 이름과 받는 인자로 공개됩니다. 화면에
130
- 없는 것은 목록에도 없습니다.
131
- - **사용자 자신의 탭에서, 그 사용자의 세션으로 화면을 다룹니다.** 클릭과 똑같습니다.
132
- - **중요한 일은 승인을 기다립니다.** `confirm`으로 선언한 툴은 승인 카드에서 멈춥니다.
133
-
134
- 설정은 레이아웃에 `<Agent.Chat />` 하나, 그리고 `option.ts`에 넣는 모델 키가 전부입니다. OpenAI 호환 호스트와
135
- Anthropic 모두 쓸 수 있습니다.
136
-
137
- ## 당신의 서버는 이미 MCP 서버입니다
138
-
139
- ```ts
140
- serveIcecreamOrder: mutation(cnst.IcecreamOrder, {
141
- guards: [Admin],
142
- })
143
- .param("icecreamOrderId", ID)
144
- .exec(async function (icecreamOrderId) {
145
- return await this.icecreamOrderService.serve(icecreamOrderId);
146
- }),
147
- refundIcecreamOrder: mutation(cnst.IcecreamOrder, {
148
- guards: [Every, Person],
149
- })
150
- .param("icecreamOrderId", ID)
151
- .with(Self)
152
- .exec(async function (icecreamOrderId, self) {
153
- return await this.icecreamOrderService.refund(icecreamOrderId, self.id);
154
- }),
155
- ```
156
-
157
- - **MCP 클라이언트에 앱 주소만 넣습니다.** `POST /mcp`는 기본으로 켜져 있습니다. 가드가 허용하는 엔드포인트는 모두
158
- 툴이 되고, 설명은 이미 쓰는 사전에서 옵니다.
159
- - **로그인과 동의는 당신의 앱에서 합니다.** OAuth 2.1은 `libs/shared`에 들어 있습니다. AI는 사용자 한 명의 토큰을
160
- 받고, 권한도 딱 그 사용자만큼이며, 언제든 해지할 수 있습니다.
161
- - **해서는 안 되는 일은 못 합니다.** `refundIcecreamOrder`에는 `Person` 가드가 걸려 있어 목록에 올라가지 않습니다.
162
- AI에게는 처음부터 없는 툴과 똑같아 보입니다.
163
- - **페이지가 프롬프트가 됩니다.** `page().prompt(name, description)`은 화면을 MCP 프롬프트로 공개합니다. 페이지의
164
- fetch가 호출자의 토큰으로 실행되고 에이전트는 그 데이터를 받습니다. 따로 맞춰 둘 두 번째 구현은 없습니다.
165
-
166
- ## 규칙은 하나, 사용자는 셋
167
-
168
- 가드는 엔드포인트마다 한 번 씁니다. 화면 앞의 사람, 그 사람 탭 안의 에이전트, MCP로 부르는 AI 모두를 같은 가드가
169
- 판단합니다.
170
-
171
- - **거절은 아무것도 드러내지 않습니다.** 에이전트가 쓸 수 없는 툴은 처음부터 없는 툴과 똑같이 답합니다.
172
- - **호출자마다 속도 제한.** MCP 호출은 호출자마다 분당 120번, 동시에 8개로 묶입니다.
173
- - **비밀은 밖으로 나가지 않습니다.** hidden·secret 필드는 모델에 닿기 전에 빠집니다.
174
- - **연결은 언제든 끝낼 수 있습니다.** 연결을 해지하면 다음 호출부터 거절됩니다. 채팅 릴레이는 세션도 대화도 남기지
175
- 않습니다.
176
-
177
- ## 만드는 일도 에이전트가
178
-
179
- AI 코딩은 일정 규모를 넘으면 스파게티가 됩니다. 에이전트가 코드를 빨리 뽑을수록 파일 위치, 이름, 구조, 선언 방식이
180
- 제각각이 되기 때문입니다. Akan은 엄격한 규칙으로 이 문제를 원천 차단합니다.
181
-
182
- - **config 파일 지옥은 그만.** `akan.config.ts` 하나로 모든 것을 설정하고, 비어 있어도 앱은 돌아갑니다.
183
- - **엄격한 규칙, 통일된 스타일.** 파일 위치, 이름, 구조, 선언 방식이 통일되고 lint가 이를 지킵니다. 누가 짰든 한
184
- 사람이 쓴 것처럼 읽힙니다.
185
- - **에이전트가 우회할 수 없는 규칙.** 모든 워크스페이스에 생성된 `AGENTS.md`, 번들 가이드라인, 계획 후 적용하는
186
- 워크플로 MCP, 그리고 이를 따라 일하는 터미널 코딩 에이전트 `akan code`가 들어 있습니다.
187
- - **정해진 블록.** 업로드, 로그인, 관리자, 채팅, 게시판, 알림이 미리 만들어진 블록이라, 에이전트는 그 위에서 일관된
188
- 코드만 생산합니다.
189
-
190
- ## 도메인 모듈
191
-
192
- 코드는 기술 계층보다 `user`, `product`, `ticket`, `project` 같은 비즈니스 도메인을 기준으로 묶입니다.
193
-
194
- ```text
195
- lib/product/
196
- ├── product.constant.ts # 모델, 스칼라, enum, 스키마 정의
197
- ├── product.dictionary.ts # i18n 라벨, 설명, 에러
198
- ├── product.signal.ts # 타입 안전한 엔드포인트 계약, 가드
199
- ├── product.document.ts # 영속성과 document 쿼리
200
- ├── product.service.ts # 비즈니스 로직
201
- ├── product.store.ts # 도메인 상태와 action
202
- ├── Product.Template.tsx # 폼 UI
203
- ├── Product.Unit.tsx # 목록 아이템 UI
204
- ├── Product.View.tsx # 상세 UI
205
- └── Product.Zone.tsx # 페이지 섹션 UI
206
- ```
207
-
208
- ```mermaid
209
- flowchart LR
210
- ConstantDictionarySignal["constant + dictionary + signal"] --> DocumentService["document + service"]
211
- ConstantDictionarySignal --> StoreComponents["store + UI components"]
212
- DocumentService --> ServerRuntime["server runtime + MCP"]
213
- StoreComponents --> ClientRuntime["client runtime + in-page agent"]
214
- ServerRuntime --> DeployArtifacts["deploy artifacts"]
215
- ClientRuntime --> DeployArtifacts
216
- ```
217
-
218
- ## v2보다 빠르게
219
-
220
- v3는 에이전트, MCP, 새 UI 시스템을 더하고도 측정한 모든 지표에서 v2보다 빠릅니다.
221
-
222
- | 지표 | v2 | v3 | 변화 |
223
- | --- | --- | --- | --- |
224
- | 초당 요청 수 | 112K | 123K | +10% |
225
- | 응답 시간 (p99) | 1.30 ms | 1.04 ms | −20% |
226
- | 시작 시간 | 204 ms | 102 ms | −50% |
227
- | 대기 메모리 | 84 MB | 57 MB | −32% |
228
- | 부하 중 메모리 | 105 MB | 85 MB | −19% |
74
+ ## 첫 앱 만들기
229
75
 
230
- - 클라이언트 빌드 결과물: 26MB → 8.1MB (청크 605개 → 258개).
231
- - 클라이언트에서 1,000행 하이드레이션: 3.5ms → 0.9ms.
232
- - 50행 목록 쿼리: 시간 −33%, 할당 85% 감소.
76
+ - **화면**은 `apps/<app>/page/` 아래 파일입니다. `<route>.tsx`나 `_index.tsx`, 그 바깥의 `_layout.tsx`, 경로
77
+ 세그먼트는 `[id]/`이고, `akanjs/client`의 `page()` 체인 하나를 export합니다. [라우팅](https://akanjs.com/docs/core/routing)
78
+ - **저장되는 모델**은 `lib/<model>/` 모듈이고 `akan create-module <model> <app>`으로 만듭니다. 외부 API처럼 저장할
79
+ 모델이 없는 서비스는 `akan create-service <service> <app>`으로 `lib/_<service>/`에 둡니다.
80
+ [파일 규칙](https://akanjs.com/docs/core/file-rule)
81
+ - 코딩 에이전트가 따르는 **규칙**은 워크스페이스 안에 있습니다. `AGENTS.md`, `.claude/rules/akan/`, 그리고
82
+ `.claude/skills/`와 `.agents/skills/`의 스킬입니다. `akan guideline show <name>`은 번들된 가이드라인을 출력합니다.
83
+ - **`akan.config.ts`**는 비워 둬도 됩니다. 라우트, 도메인, 로케일, 데이터베이스 모드, 네이티브 앱이 필요할 때만
84
+ 늘어납니다. [설정](https://akanjs.com/docs/core/config)
233
85
 
234
- Apple M4 Pro MacBook Pro에서 프로덕션 빌드, 동시 사용자 50명으로 측정했습니다. 측정 도구와 원본 데이터는
235
- [`benchmarks/api-benchmark`](https://github.com/akan-team/akanjs/tree/main/benchmarks/api-benchmark)에 있습니다.
236
-
237
- ## 빌드에서 라이브 URL까지
238
-
239
- [Akan Cloud](https://cloud.akanjs.com)는 Akan 앱을 위해 만든 배포 플랫폼입니다.
240
-
241
- ```bash
242
- akan login # 이 컴퓨터에서 Akan Cloud에 로그인
243
- akan tunnel <app> # 배포 전에 실행 중인 앱을 공개 URL로 공유
244
- akan build <app> # Akan Cloud가 돌릴 프로덕션 결과물 빌드
245
- ```
246
-
247
- ## 사람과 에이전트를 위한 문서
248
-
249
- - 문서는 [akanjs.com/docs](https://akanjs.com/docs)에 있습니다. 모든 문서 페이지에 인페이지 에이전트가 있어, 주제를
250
- 물으면 문서를 검색해 해당 페이지를 열어 줍니다.
251
- - Claude Code나 Cursor에 `https://akanjs.com/mcp`를 연결하면, AI가 코드를 쓰면서 이 문서를 읽습니다
252
- (`listDocPages`, `searchDocPages`, `readDocPage`).
253
- - [`llms.txt`](https://akanjs.com/llms.txt)는 어떤 모델이든 읽을 수 있는 문서 색인입니다.
254
-
255
- ## 하나의 패키지, 여러 경계
256
-
257
- Akan은 하나의 npm 패키지 `akanjs`로 배포됩니다. root import는 의도적으로 작게 두고, 서버 전용·클라이언트 전용·UI·
258
- 도구 표면은 subpath import로 나눕니다.
259
-
260
- ```ts
261
- import { Int, dayjs } from "akanjs/base";
262
- import { via } from "akanjs/constant";
263
- import { endpoint } from "akanjs/signal";
264
- import { Button, Layout } from "akanjs/ui";
265
- import { page } from "akanjs/client";
266
- import { AkanApp } from "akanjs/server/akanApp";
267
- ```
268
-
269
- ```css
270
- @import "akanjs/ui/styles.css";
271
- ```
272
-
273
- | Subpath | 역할 |
274
- | --- | --- |
275
- | `akanjs/base` | 핵심 primitive, 스칼라(`Int`, `Float`, `ID`, `Binary`, `enumOf`), `dayjs`, 환경 헬퍼. |
276
- | `akanjs/common` | 여러 런타임에서 함께 쓰는 헬퍼. |
277
- | `akanjs/constant` | 모델 선언, 스키마 구성, 직렬화, 기본값, `via` 빌더. |
278
- | `akanjs/dictionary` | 라벨, 설명, 에러를 위한 locale·번역·사전 헬퍼. |
279
- | `akanjs/document` | DB document, 필터, 쿼리 빌더, 전문 검색, 영속성 유틸리티. |
280
- | `akanjs/signal` | 엔드포인트, slice, 가드, 미들웨어, 타입 안전한 signal 계약. |
281
- | `akanjs/service` | 서비스, 어댑터, 의존성 주입, 비즈니스 로직 런타임. |
282
- | `akanjs/fetch` | 타입 안전한 fetch, HTTP, WebSocket 클라이언트. |
283
- | `akanjs/store` | 도메인 상태, action, 인페이지 에이전트의 `st.tool` / `st.use` 표면. |
284
- | `akanjs/ui` | React 컴포넌트, recipe, `_overrides.tsx` 슬롯: 레이아웃, 폼, 모달, 테이블, 로딩, 에이전트 채팅. |
285
- | `akanjs/client` | 라우트 체인(`page()`, `layout()`), 라우팅, 쿠키, 스토리지, locale, `cn`. |
286
- | `akanjs/client/native` | iOS·Android·데스크톱 앱을 위한 네이티브 브리지와 내장 플러그인. |
287
- | `akanjs/webkit` | `lazy`, SEO 페이지 같은 브라우저 쪽 헬퍼. |
288
- | `akanjs/server` | 서버 런타임, SSR/RSC, MCP, 로깅, 서버 타입. 엔트리포인트는 `akanjs/server/akanApp`입니다. |
289
- | `akanjs/native/desktop` | 네이티브 플러그인의 데스크톱 부분. |
290
- | `akanjs/test` | 테스트 헬퍼와 샘플 생성. |
291
-
292
- 도구는 별도 패키지로 배포됩니다. `@akanjs/cli`(`akan` 명령), `@akanjs/devkit`(빌드 러너, 코드 생성, lint 규칙),
293
- `create-akan-workspace`입니다.
294
-
295
- ## CLI 개요
86
+ ## 빌드와 실행
296
87
 
297
88
  ```bash
298
- akan create-workspace
299
- akan create-application <app>
300
- akan create-module
301
- akan start <app> --open # 여러 앱은 akan start a,b
302
- akan build <app>
303
- akan build-ios <app> # build-android, build-desktop도 있습니다
304
- akan lint <app>
305
- akan typecheck <app>
306
- akan test <app>
307
- akan logs <app>
308
- akan code
309
- akan update
89
+ akan start <app> # 개발 서버, http://localhost:8282
90
+ akan verify <app> # sync, lint, 타입체크, 빌드, SSR 검사
91
+ akan build <app> # dist/apps/<app>에 프로덕션 빌드
92
+ cd dist/apps/<app> && PORT=3000 bun main.js
310
93
  ```
311
94
 
312
- - **Workspace**: 워크스페이스 생성, lint, sync, `akan doctor`.
313
- - **Application**: 웹·모바일·데스크톱 앱의 start, build, typecheck, test, 패키징.
314
- - **Library**: 공유 라이브러리 생성, 설치, sync, push, pull.
315
- - **Module and scalar**: 도메인 모듈, 모델, view, unit, template, store 생성.
316
- - **Agents**: `akan code`, `akan mcp`, `akan mcp-install`, `akan workflow`, `akan guideline`.
317
- - **Cloud and release**: `akan login`, `akan tunnel`, 배포 자산, 패키지 업데이트.
318
-
319
- ## 애플리케이션 설정
320
-
321
- `akan.config.ts`는 앱 단위 설정을 모으는 단 하나의 파일입니다. 비워 둔 채 시작하고, routes, domains, base paths,
322
- database modes, native app settings가 필요해질 때만 늘려 가면 됩니다.
323
-
324
- ```ts
325
- import type { AppConfig } from "akanjs";
326
-
327
- const config: AppConfig = {
328
- routes: [
329
- { domains: { main: ["example.com", "www.example.com"] }, basePath: "web" },
330
- { domains: {}, basePath: "app" },
331
- ],
332
- database: { modes: ["single", "cluster"] },
333
- native: {
334
- basePath: "app",
335
- appName: "Example",
336
- appId: "com.example.app",
337
- version: "1.0.0",
338
- buildNum: 1,
339
- },
340
- };
341
-
342
- export default config;
343
- ```
344
-
345
- ## Contributor Notes
346
-
347
- 이 저장소는 Bun-first 모노레포입니다. 프레임워크 코드는 `pkgs/akanjs`, 도구는 `pkgs/@akanjs`, 애플리케이션은
348
- `apps`, 공유 라이브러리는 `libs`, 배포 자산은 `infra`에 있습니다. `apps/akan`이 [akanjs.com](https://akanjs.com)
349
- 그 자체입니다.
350
-
351
- 이 저장소 안에서는 `bun run akan`이 CLI를 소스에서 빌드해 실행합니다.
352
-
353
- ```bash
354
- bun run akan start <app>
355
- bun run akan lint <app>
356
- bun run akan typecheck <app>
357
- bun run akan test <app-or-lib-or-pkg>
358
- ```
359
-
360
- `AGENTS.md`는 코딩 에이전트와 기여자 모두를 위한 가이드입니다. 프레임워크 코드를 고칠 때는 기존 subpath를 우선
361
- 쓰고 root `akanjs` 엔트리포인트는 작게 유지하세요. 이 패키지 경계는 런타임 설계의 일부입니다.
362
-
363
- ## 오픈소스 메모
364
-
365
- - 라이선스: MIT. [`pkgs/akanjs/LICENSE`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/LICENSE)를 참고하세요.
366
- - 저장소: [akan-team/akanjs](https://github.com/akan-team/akanjs).
367
- - 기여 가이드: [`pkgs/akanjs/CONTRIBUTING.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CONTRIBUTING.md).
368
- - 행동 강령: [`pkgs/akanjs/CODE_OF_CONDUCT.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CODE_OF_CONDUCT.md).
95
+ [Akan Cloud](https://cloud.akanjs.com)는 Akan 앱을 실행하는 플랫폼입니다. `akan login`으로 로그인하고,
96
+ `akan tunnel <app>`으로 실행 중인 앱을 공개 URL로 공유합니다.
97
+
98
+ ## 더 보기
99
+
100
+ - [akanjs.com](https://akanjs.com): 코드 한 줄이 닿는 곳, 에이전트의 인터페이스가 되는 화면, MCP 서버가 되는 서버.
101
+ - [문서](https://akanjs.com/docs), [CLI 레퍼런스](https://akanjs.com/references/cli/overview),
102
+ [`llms.txt`](https://akanjs.com/llms.txt). 코딩 에이전트에 `https://akanjs.com/mcp`를 연결하면 코드를 쓰면서 문서를
103
+ 읽습니다.
104
+ - [MCP](https://akanjs.com/cheatsheet/interface/mcp)와 [인페이지 에이전트](https://akanjs.com/cheatsheet/interface/agent-chat):
105
+ 가드, 거절, rate limit, 모델 설정.
106
+ - [v3 성능](https://akanjs.com/blog/v3release#v3-performance): v2와 비교한 수치와 측정 방법.
107
+ - `akanjs`는 npm 패키지 하나입니다. subpath(`akanjs/base`, `akanjs/client`, `akanjs/signal`, `akanjs/ui`, …)가 서버
108
+ 전용, 클라이언트 전용, UI, 툴링 코드를 나누고([패키지 레퍼런스](https://akanjs.com/references/akanjs/base)), 툴링은
109
+ `@akanjs/cli`와 `@akanjs/devkit`으로 나옵니다.
110
+ - 기여: [`CONTRIBUTING.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CONTRIBUTING.md)와
111
+ [행동 강령](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CODE_OF_CONDUCT.md). 라이선스: MIT
112
+ ([`LICENSE`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/LICENSE)).
package/README.md CHANGED
@@ -6,11 +6,9 @@
6
6
 
7
7
  **The TypeScript framework, agents included.** Powered by Bun.
8
8
 
9
- **Build a screen — agents can use it. Build a server — any AI can run it.**
10
-
11
- No tool schemas, no MCP server to write, no second permission model. The app you build for people is already the
12
- one AI can use, on the model you choose. One line of business code runs through every layer, ships to six platforms,
13
- and reaches everyone who uses it — people and agents.
9
+ Akan.js is a full-stack TypeScript framework. One field declaration runs through the schema, service, API, client
10
+ state and UI, and the same code ships as a web app, iOS and Android apps, and desktop apps. Every guarded endpoint is
11
+ also an MCP tool and every control on screen an in-page agent tool, behind the guards people pass.
14
12
 
15
13
  ## Quick Start
16
14
 
@@ -61,307 +59,53 @@ Node and npm, or URLs given by a spec, a coding agent needs these, and nothing h
61
59
  - **Exact URLs:** pages live under `/<locale>/…`. To serve the default locale at the bare path (`/books/OL45804W`),
62
60
  set `i18n: { defaultLocale: "en", locales: ["en"], localePrefix: "as-needed" }` in `akan.config.ts`; `<Link>`
63
61
  follows.
64
- - **A host with only Node and npm:** run the creator through npx, which writes nothing global:
65
- `npx -y bun@1.4.4 x create-akan-workspace@latest . --app <app> --dir <folder> --sample false`. That Bun is not on
66
- `PATH` afterwards, so the creator lists `bun` in the workspace's `dependencies` and writes the scripts below; run
67
- any other command as `npx akan …`.
68
- - **Build and run without Docker** through these package scripts; `npm run build`, then `PORT=3000 npm start`:
69
-
70
- ```json
71
- "build": "akan build <app>",
72
- "start": "cd dist/apps/<app> && bun main.js"
73
- ```
74
-
75
- A fresh clone builds as is: the env files stay gitignored and `akan` writes the ones it lacks, so commit none. The
76
- build carries the env it needs, and a variable set at start overrides it.
62
+ - **A host with only Node and npm:** `npx -y bun@1.4.4 x create-akan-workspace@latest . --app <app> --dir <folder> --sample false`,
63
+ then `npm run build` and `PORT=3000 npm start`. The
64
+ [`create-akan-workspace` README](https://www.npmjs.com/package/create-akan-workspace#with-only-node-and-npm) has the
65
+ scripts it writes and what a fresh clone needs.
77
66
  - **Build for where it runs.** A variable set in the shell, or in a `.env.local` Bun loads, outranks the workspace `.env`
78
67
  (an empty one counts as unset, and the build names each one it took), and `--env` outranks both for `AKAN_PUBLIC_ENV`. A new workspace's `.env` says `local`, which suits your own machine or a test runner, but the
79
68
  server runs without endpoint rate limits and on local defaults. For a host others can reach, run
80
69
  `akan build <app> --env main` with `AKAN_PUBLIC_REPO_NAME` and `AKAN_PUBLIC_SERVE_DOMAIN` (the domain it serves) set
81
70
  in the shell or the workspace `.env`.
82
71
 
83
- ## All Of It Is One Line
84
-
85
- ```ts
86
- export class ProductInput extends via((field) => ({
87
- name: field(String),
88
- })) {}
89
- ```
90
-
91
- **1 line × 8 layers × 6 platforms × people & agents.**
92
-
93
- - **1 line.** Adding a field is one declaration: a name and a type.
94
- - **× 8 layers.** That line runs through the schema, query, service, API, fetch, client type, state and UI prop. In a
95
- usual stack those are eight places to change by hand, and missing one breaks a type or fails at runtime. Here they
96
- change together.
97
- - **× 6 platforms.** The same code ships as SEO-ready web, iOS and Android apps, and macOS, Windows and Linux desktop
98
- apps, with native-level screen transitions rather than a wrapped website.
99
- - **× people & agents.** Every guarded endpoint becomes an MCP tool and every control on screen an in-page agent
100
- tool, behind the same guards people pass.
101
-
102
- ## The Screen You Build Is The Agent's Interface
103
-
104
- ```tsx
105
- export const Order = () => {
106
- const { l } = usePage();
107
- const icecreamOrderForm = st.use.icecreamOrderForm();
108
- const order = st.tool("createIcecreamOrder", { confirm: true })
109
- .desc("Place the order in the form.")
110
- .exec(() => st.do.createIcecreamOrder());
111
- return (
112
- <>
113
- <Field.MultiToggleSelect
114
- label={l("icecreamOrder.toppings")}
115
- items={cnst.Topping}
116
- value={icecreamOrderForm.toppings}
117
- onChange={st.do.setToppingsOnIcecreamOrder}
118
- />
119
- <Button onClick={order}>{l("icecreamOrder.createIcecreamOrder")}</Button>
120
- </>
121
- );
122
- };
123
- ```
124
-
125
- - **Write the screen you were going to write.** A field handed its setter publishes it. A button's handler becomes a
126
- tool with one `st.tool` line — the same function the button calls.
127
- - **An agent sees tools, not pixels.** Every control you wired is published under its own name, with the arguments it
128
- takes. What isn't on the screen isn't on the list.
129
- - **It works the screen in the user's own tab**, with their session, exactly like a click.
130
- - **What matters waits for a yes.** A tool declared with `confirm` stops on an approval card.
131
-
132
- Setup is one `<Agent.Chat />` in a layout and your model's key in `option.ts`. OpenAI-compatible hosts and Anthropic
133
- both work.
134
-
135
- ## Your Server Is Already An MCP Server
136
-
137
- ```ts
138
- serveIcecreamOrder: mutation(cnst.IcecreamOrder, {
139
- guards: [Admin],
140
- })
141
- .param("icecreamOrderId", ID)
142
- .exec(async function (icecreamOrderId) {
143
- return await this.icecreamOrderService.serve(icecreamOrderId);
144
- }),
145
- refundIcecreamOrder: mutation(cnst.IcecreamOrder, {
146
- guards: [Every, Person],
147
- })
148
- .param("icecreamOrderId", ID)
149
- .with(Self)
150
- .exec(async function (icecreamOrderId, self) {
151
- return await this.icecreamOrderService.refund(icecreamOrderId, self.id);
152
- }),
153
- ```
154
-
155
- - **Point any MCP client at your app.** `POST /mcp` is on by default. Every endpoint whose guards admit the caller is
156
- a tool, described by the dictionary you already write.
157
- - **Sign-in and consent happen on your app.** OAuth 2.1 ships with `libs/shared`. The AI gets a token for one user —
158
- exactly their rights, revocable at any time.
159
- - **It can't do what it shouldn't.** `refundIcecreamOrder` is guarded by `Person`, so it never reaches the shelf. To
160
- the AI it looks exactly like a tool that doesn't exist.
161
- - **Pages become prompts.** `page().prompt(name, description)` publishes a screen as an MCP prompt: its fetches run
162
- under the caller's token and the agent receives the data, with no second implementation to keep in sync.
163
-
164
- ## One Rule, Three Kinds Of Users
165
-
166
- You write a guard once per endpoint. It decides for a person on the screen, for the agent in their tab, and for an AI
167
- calling over MCP.
168
-
169
- - **Refusals give nothing away.** A tool an agent may not use answers exactly like one that doesn't exist.
170
- - **Rate-limited per caller.** MCP calls are capped at 120 a minute and 8 at once for each caller.
171
- - **Secrets stay home.** Hidden and secret fields are stripped before anything reaches a model.
172
- - **Connections end when you say.** Revoke a connection and its next call is refused. The chat relay keeps no
173
- session and no transcript.
174
-
175
- ## Agents Build It, Too
176
-
177
- AI coding turns to spaghetti past a certain size: the faster an agent writes, the more file paths, names, structures
178
- and declaration styles drift apart. Akan stops this at the source with strict rules.
179
-
180
- - **Config hell ends.** Everything is configured in `akan.config.ts`, and an empty one still runs.
181
- - **Strict rules, unified style.** File paths, names, structures and declarations stay consistent, and lint enforces
182
- them, so code reads like one person wrote it.
183
- - **Rules agents can't route around.** Every workspace ships a generated `AGENTS.md`, bundled guidelines, a
184
- plan-then-apply workflow MCP, and `akan code`, a terminal coding agent that works through them.
185
- - **Fixed blocks.** Upload, login, admin, chat, boards and alerts are ready-made blocks, so agents produce
186
- consistent code on top of them.
187
-
188
- ## The Domain Module
189
-
190
- Code is organized around business domains such as `user`, `product`, `ticket` or `project`, not by technical layer
191
- first.
192
-
193
- ```text
194
- lib/product/
195
- ├── product.constant.ts # model, scalar, enum, schema definition
196
- ├── product.dictionary.ts # i18n labels, descriptions, errors
197
- ├── product.signal.ts # typed endpoint contract, guards
198
- ├── product.document.ts # persistence and document queries
199
- ├── product.service.ts # business logic
200
- ├── product.store.ts # domain state and actions
201
- ├── Product.Template.tsx # form UI
202
- ├── Product.Unit.tsx # list item UI
203
- ├── Product.View.tsx # detail UI
204
- └── Product.Zone.tsx # page section UI
205
- ```
206
-
207
- ```mermaid
208
- flowchart LR
209
- ConstantDictionarySignal["constant + dictionary + signal"] --> DocumentService["document + service"]
210
- ConstantDictionarySignal --> StoreComponents["store + UI components"]
211
- DocumentService --> ServerRuntime["server runtime + MCP"]
212
- StoreComponents --> ClientRuntime["client runtime + in-page agent"]
213
- ServerRuntime --> DeployArtifacts["deploy artifacts"]
214
- ClientRuntime --> DeployArtifacts
215
- ```
216
-
217
- ## Faster Than v2
218
-
219
- v3 adds agents, MCP and a new UI system, and it is still faster than v2 on every number we measured.
220
-
221
- | Metric | v2 | v3 | Change |
222
- | --- | --- | --- | --- |
223
- | Requests per second | 112K | 123K | +10% |
224
- | Response time (p99) | 1.30 ms | 1.04 ms | −20% |
225
- | Startup time | 204 ms | 102 ms | −50% |
226
- | Memory at rest | 84 MB | 57 MB | −32% |
227
- | Memory under load | 105 MB | 85 MB | −19% |
72
+ ## Your First App
228
73
 
229
- - Client build output: 26MB → 8.1MB (605 chunks down to 258).
230
- - Hydrating 1,000 rows on the client: 3.5ms → 0.9ms.
231
- - A 50-row list query: −33% time, with 85% fewer allocations.
74
+ - **A screen** is a file under `apps/<app>/page/`: `<route>.tsx` or `_index.tsx`, `_layout.tsx` around it, `[id]/`
75
+ for a segment. It exports one `page()` chain from `akanjs/client`. [Routing](https://akanjs.com/docs/core/routing)
76
+ - **A stored model** is a module under `lib/<model>/`, made by `akan create-module <model> <app>`. A service with no
77
+ stored model, such as an outside API, goes under `lib/_<service>/` with `akan create-service <service> <app>`.
78
+ [File rules](https://akanjs.com/docs/core/file-rule)
79
+ - **The rules** a coding agent follows are in the workspace: `AGENTS.md`, `.claude/rules/akan/`, and the skills in
80
+ `.claude/skills/` and `.agents/skills/`. `akan guideline show <name>` prints any bundled guideline.
81
+ - **`akan.config.ts`** may stay empty. It grows only for routes, domains, locales, database modes or native apps.
82
+ [Configuration](https://akanjs.com/docs/core/config)
232
83
 
233
- Measured on an Apple M4 Pro MacBook Pro with production builds and 50 concurrent users. The harness and raw data live
234
- in [`benchmarks/api-benchmark`](https://github.com/akan-team/akanjs/tree/main/benchmarks/api-benchmark).
235
-
236
- ## From Build To A Live URL
237
-
238
- [Akan Cloud](https://cloud.akanjs.com) is the deploy platform built for Akan apps.
239
-
240
- ```bash
241
- akan login # sign in to Akan Cloud from your machine
242
- akan tunnel <app> # share the app you are running on a public URL
243
- akan build <app> # build the production artifact Akan Cloud runs
244
- ```
245
-
246
- ## Docs For You And Your Agent
247
-
248
- - Read the docs at [akanjs.com/docs](https://akanjs.com/docs). Every docs page carries the in-page agent, so you can
249
- ask it about a topic and it opens the page.
250
- - Connect Claude Code or Cursor to `https://akanjs.com/mcp`, and your AI reads the docs (`listDocPages`,
251
- `searchDocPages`, `readDocPage`) while it writes your code.
252
- - [`llms.txt`](https://akanjs.com/llms.txt) indexes the docs for any model.
253
-
254
- ## One Package, Many Boundaries
255
-
256
- Akan is published as a single npm package, `akanjs`. The root import is intentionally small; subpath imports keep
257
- server-only, client-only, UI and tooling surfaces apart.
258
-
259
- ```ts
260
- import { Int, dayjs } from "akanjs/base";
261
- import { via } from "akanjs/constant";
262
- import { endpoint } from "akanjs/signal";
263
- import { Button, Layout } from "akanjs/ui";
264
- import { page } from "akanjs/client";
265
- import { AkanApp } from "akanjs/server/akanApp";
266
- ```
267
-
268
- ```css
269
- @import "akanjs/ui/styles.css";
270
- ```
271
-
272
- | Subpath | Purpose |
273
- | --- | --- |
274
- | `akanjs/base` | Core primitives, scalars (`Int`, `Float`, `ID`, `Binary`, `enumOf`), `dayjs`, environment helpers. |
275
- | `akanjs/common` | Shared cross-runtime helpers. |
276
- | `akanjs/constant` | Model declarations, schema shaping, serialization, defaults, and the `via` builder. |
277
- | `akanjs/dictionary` | Locale, translation, and dictionary helpers for labels, descriptions and errors. |
278
- | `akanjs/document` | Database documents, filters, query builders, full-text search, and persistence utilities. |
279
- | `akanjs/signal` | Endpoints, slices, guards, middleware, and typed signal contracts. |
280
- | `akanjs/service` | Services, adaptors, dependency injection, and the business logic runtime. |
281
- | `akanjs/fetch` | Typed fetch, HTTP and WebSocket clients. |
282
- | `akanjs/store` | Domain state, actions, and the in-page agent's `st.tool` / `st.use` surface. |
283
- | `akanjs/ui` | React components, recipes, and `_overrides.tsx` slots: layout, form, modal, table, loading, agent chat. |
284
- | `akanjs/client` | The route chain (`page()`, `layout()`), routing, cookies, storage, locale, and `cn`. |
285
- | `akanjs/client/native` | The native bridge and builtin plugins for iOS, Android and desktop apps. |
286
- | `akanjs/webkit` | Browser-side helpers such as `lazy` and SEO pages. |
287
- | `akanjs/server` | Server runtime, SSR/RSC, MCP, logging, and server types. `akanjs/server/akanApp` is the entrypoint. |
288
- | `akanjs/native/desktop` | Desktop parts of native plugins. |
289
- | `akanjs/test` | Test helpers and sample generation. |
290
-
291
- Tooling ships as separate packages: `@akanjs/cli` (the `akan` command), `@akanjs/devkit` (build runners, code
292
- generation, lint rules) and `create-akan-workspace`.
293
-
294
- ## CLI Overview
84
+ ## Build And Run
295
85
 
296
86
  ```bash
297
- akan create-workspace
298
- akan create-application <app>
299
- akan create-module
300
- akan start <app> --open # or several: akan start a,b
301
- akan build <app>
302
- akan build-ios <app> # also build-android, build-desktop
303
- akan lint <app>
304
- akan typecheck <app>
305
- akan test <app>
306
- akan logs <app>
307
- akan code
308
- akan update
87
+ akan start <app> # dev server, http://localhost:8282
88
+ akan verify <app> # sync, lint, typecheck, build and SSR check
89
+ akan build <app> # production build in dist/apps/<app>
90
+ cd dist/apps/<app> && PORT=3000 bun main.js
309
91
  ```
310
92
 
311
- - **Workspace**: create workspaces, lint, sync, and run `akan doctor`.
312
- - **Application**: start, build, typecheck, test, and package web, mobile and desktop apps.
313
- - **Library**: create, install, sync, push, and pull shared libraries.
314
- - **Module and scalar**: generate domain modules, models, views, units, templates, and stores.
315
- - **Agents**: `akan code`, `akan mcp`, `akan mcp-install`, `akan workflow`, `akan guideline`.
316
- - **Cloud and release**: `akan login`, `akan tunnel`, deployment assets, and package updates.
317
-
318
- ## Application Configuration
319
-
320
- `akan.config.ts` is the single place for app-level configuration. It can stay empty, then grow only when the app
321
- needs routes, domains, base paths, database modes, or native app settings.
322
-
323
- ```ts
324
- import type { AppConfig } from "akanjs";
325
-
326
- const config: AppConfig = {
327
- routes: [
328
- { domains: { main: ["example.com", "www.example.com"] }, basePath: "web" },
329
- { domains: {}, basePath: "app" },
330
- ],
331
- database: { modes: ["single", "cluster"] },
332
- native: {
333
- basePath: "app",
334
- appName: "Example",
335
- appId: "com.example.app",
336
- version: "1.0.0",
337
- buildNum: 1,
338
- },
339
- };
340
-
341
- export default config;
342
- ```
343
-
344
- ## Contributor Notes
345
-
346
- This repository is a Bun-first monorepo. Framework code lives under `pkgs/akanjs`, tooling under `pkgs/@akanjs`,
347
- applications under `apps`, shared libraries under `libs`, and deployment assets under `infra`. `apps/akan` is
348
- [akanjs.com](https://akanjs.com) itself.
349
-
350
- Inside this repository, `bun run akan` builds the CLI from source and runs it:
351
-
352
- ```bash
353
- bun run akan start <app>
354
- bun run akan lint <app>
355
- bun run akan typecheck <app>
356
- bun run akan test <app-or-lib-or-pkg>
357
- ```
358
-
359
- `AGENTS.md` is the guide for coding agents and contributors alike. When editing framework code, prefer established
360
- subpaths and keep the root `akanjs` entrypoint small. The package boundary is part of the runtime design.
361
-
362
- ## Open Source Notes
363
-
364
- - License: MIT. See [`pkgs/akanjs/LICENSE`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/LICENSE).
365
- - Repository: [akan-team/akanjs](https://github.com/akan-team/akanjs).
366
- - Contribution guide: [`pkgs/akanjs/CONTRIBUTING.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CONTRIBUTING.md).
367
- - Code of conduct: [`pkgs/akanjs/CODE_OF_CONDUCT.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CODE_OF_CONDUCT.md).
93
+ [Akan Cloud](https://cloud.akanjs.com) runs Akan apps: `akan login` signs in, and `akan tunnel <app>` shares the app
94
+ you are running on a public URL.
95
+
96
+ ## Learn More
97
+
98
+ - [akanjs.com](https://akanjs.com): what one line of code reaches, the screen as an agent's interface, and your server
99
+ as an MCP server.
100
+ - [Docs](https://akanjs.com/docs), the [CLI reference](https://akanjs.com/references/cli/overview), and
101
+ [`llms.txt`](https://akanjs.com/llms.txt). Connect a coding agent to `https://akanjs.com/mcp` to read the docs while
102
+ it writes code.
103
+ - [MCP](https://akanjs.com/cheatsheet/interface/mcp) and the [in-page agent](https://akanjs.com/cheatsheet/interface/agent-chat):
104
+ guards, refusals, rate limits and model setup.
105
+ - [v3 performance](https://akanjs.com/blog/v3release#v3-performance): the numbers against v2 and how they were measured.
106
+ - `akanjs` is one npm package. Its subpaths (`akanjs/base`, `akanjs/client`, `akanjs/signal`, `akanjs/ui`, …) keep
107
+ server-only, client-only, UI and tooling code apart, and the [package reference](https://akanjs.com/references/akanjs/base)
108
+ covers them; the tooling ships as `@akanjs/cli` and `@akanjs/devkit`.
109
+ - Contributing: [`CONTRIBUTING.md`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CONTRIBUTING.md) and
110
+ the [code of conduct](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/CODE_OF_CONDUCT.md). License: MIT
111
+ ([`LICENSE`](https://github.com/akan-team/akanjs/blob/main/pkgs/akanjs/LICENSE)).
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.1-rc.0",
3
+ "version": "3.2.1-rc.2",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
+ "description": "Akan.js, a full-stack TypeScript framework: business code written once reaches web, native apps, server, database and infrastructure. Start with: bunx create-akan-workspace@latest",
9
10
  "homepage": "https://akanjs.com",
10
11
  "license": "MIT",
11
12
  "repository": {
@@ -608,16 +608,12 @@ export class SsrFromRscRenderer {
608
608
  throw error;
609
609
  }
610
610
 
611
+ const headPreloads = [...new Set([...(input.bootstrapModules ?? []), ...(input.modulePreloads ?? [])])];
611
612
  const withHeadScripts = SsrFromRscRenderer.#injectHeadScriptsIntoHead(htmlStream, {
612
613
  importmap: input.importmap,
614
+ modulePreloads: headPreloads,
613
615
 
614
- modulePreloads: [
615
- ...new Set([
616
- ...(input.bootstrapModules ?? []),
617
- ...(chunkPreloads?.urls ?? []),
618
- ...(input.modulePreloads ?? []),
619
- ]),
620
- ],
616
+ chunkPreloads: (chunkPreloads?.urls ?? []).filter((src) => !headPreloads.includes(src)),
621
617
  theme: input.theme,
622
618
  injectThemeInitScript: input.injectThemeInitScript,
623
619
  });
@@ -747,6 +743,7 @@ export class SsrFromRscRenderer {
747
743
  options: {
748
744
  importmap?: Record<string, string>;
749
745
  modulePreloads: string[];
746
+ chunkPreloads: string[];
750
747
  theme?: AkanTheme;
751
748
  injectThemeInitScript?: boolean;
752
749
  },
@@ -754,6 +751,8 @@ export class SsrFromRscRenderer {
754
751
  const encoder = new TextEncoder();
755
752
  const decoder = new TextDecoder();
756
753
  const { importmap, modulePreloads, theme, injectThemeInitScript } = options;
754
+
755
+ const chunkTags = SsrFromRscRenderer.#createModulePreloadTags(options.chunkPreloads);
757
756
  const htmlTheme = theme && theme !== "css" && theme !== "system" ? theme : undefined;
758
757
  const importmapTag =
759
758
  importmap && Object.keys(importmap).length > 0
@@ -763,11 +762,11 @@ export class SsrFromRscRenderer {
763
762
  const shouldInjectThemeScript = theme === "system" || (theme === undefined && injectThemeInitScript);
764
763
  const themeInitTag = shouldInjectThemeScript ? SsrFromRscRenderer.#themeInitScript : "";
765
764
  const tags = `${themeInitTag}${importmapTag}${modulePreloadTags}`;
766
- if (!tags && !htmlTheme) return stream;
765
+ if (!tags && !chunkTags && !htmlTheme) return stream;
767
766
  const htmlOpenRe = /<html(\s[^>]*)?>/i;
768
767
  const headOpenRe = /<head(\s[^>]*)?>/i;
769
768
  let buffered = "";
770
- let injected = false;
769
+ let awaiting: "<head>" | "</head>" | undefined = "<head>";
771
770
 
772
771
  const withHtmlTheme = (html: string): string => {
773
772
  if (!htmlTheme) return html;
@@ -780,30 +779,31 @@ export class SsrFromRscRenderer {
780
779
  return stream.pipeThrough(
781
780
  new TransformStream<Uint8Array, Uint8Array>({
782
781
  transform(chunk, controller) {
783
- if (injected) {
782
+ if (!awaiting) {
784
783
  controller.enqueue(chunk);
785
784
  return;
786
785
  }
787
786
  buffered += decoder.decode(chunk, { stream: true });
788
- const m = headOpenRe.exec(buffered);
789
- if (!m) return;
790
- const end = m.index + m[0].length;
791
- const before = withHtmlTheme(buffered.slice(0, end));
792
- const after = buffered.slice(end);
793
- controller.enqueue(encoder.encode(before + tags + after));
794
- buffered = "";
795
- injected = true;
787
+ let out = "";
788
+ if (awaiting === "<head>") {
789
+ const m = headOpenRe.exec(buffered);
790
+ if (!m) return;
791
+ const end = m.index + m[0].length;
792
+ out = withHtmlTheme(buffered.slice(0, end)) + tags;
793
+ buffered = buffered.slice(end);
794
+ awaiting = "</head>";
795
+ }
796
+ const close = chunkTags ? buffered.indexOf(awaiting) : 0;
797
+ const cut = close >= 0 ? close : Math.max(0, buffered.length - awaiting.length + 1);
798
+ out += buffered.slice(0, cut) + (close >= 0 ? chunkTags + buffered.slice(cut) : "");
799
+ buffered = close >= 0 ? "" : buffered.slice(cut);
800
+ if (close >= 0) awaiting = undefined;
801
+ if (out) controller.enqueue(encoder.encode(out));
796
802
  },
797
803
  flush(controller) {
798
- if (injected) {
799
- const tail = decoder.decode();
800
- if (tail) controller.enqueue(encoder.encode(tail));
801
- return;
802
- }
803
804
 
804
- const tail = decoder.decode();
805
- const rest = withHtmlTheme(buffered + tail);
806
- if (rest) controller.enqueue(encoder.encode(rest));
805
+ const rest = buffered + decoder.decode();
806
+ if (rest) controller.enqueue(encoder.encode(awaiting === "<head>" ? withHtmlTheme(rest) : rest));
807
807
  },
808
808
  }),
809
809
  );