@native-sdk/cli 0.8.0 → 0.8.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.
Files changed (75) hide show
  1. package/README.md +4 -4
  2. package/build.zig +49 -23
  3. package/package.json +10 -10
  4. package/packages/core/compile-surface/core.ts +16 -0
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/sdk/core.d.ts +11 -0
  8. package/packages/core/sdk/core.ts +29 -2
  9. package/packages/core/sdk/events.d.ts +10 -0
  10. package/packages/core/sdk/events.ts +24 -4
  11. package/packages/core/src/checker.ts +1 -1
  12. package/packages/core/src/contract.ts +4 -1
  13. package/packages/core/src/devhost.ts +10 -1
  14. package/packages/core/src/diagnostics.ts +1 -1
  15. package/skill-data/core/SKILL.md +48 -20
  16. package/skill-data/core/references/app-model-runtime.md +2 -2
  17. package/skill-data/core/references/project-anatomy.md +22 -6
  18. package/skill-data/native-ui/SKILL.md +71 -29
  19. package/skill-data/ts-core/SKILL.md +13 -8
  20. package/skill-data/zig/SKILL.md +1 -1
  21. package/skills/native-sdk/SKILL.md +6 -5
  22. package/src/app_runner/ts_core_main.zig +2 -1
  23. package/src/embed/tests.zig +3 -1
  24. package/src/platform/macos/appkit_host.h +4 -4
  25. package/src/platform/macos/appkit_host.m +24 -4
  26. package/src/platform/macos/cef_host.mm +22 -6
  27. package/src/platform/macos/root.zig +2 -2
  28. package/src/primitives/canvas/events.zig +8 -0
  29. package/src/primitives/canvas/markdown.zig +2010 -57
  30. package/src/primitives/canvas/markdown_hostile_tests.zig +40 -0
  31. package/src/primitives/canvas/markdown_tests.zig +778 -3
  32. package/src/primitives/canvas/root.zig +2 -0
  33. package/src/primitives/canvas/test_support.zig +1 -0
  34. package/src/primitives/canvas/ui.zig +53 -8
  35. package/src/primitives/canvas/ui_markup.zig +10 -1
  36. package/src/primitives/canvas/ui_markup_compiled.zig +61 -3
  37. package/src/primitives/canvas/ui_markup_compiled_tests.zig +27 -0
  38. package/src/primitives/canvas/ui_markup_contract.zig +31 -3
  39. package/src/primitives/canvas/ui_markup_reflect.zig +41 -0
  40. package/src/primitives/canvas/ui_markup_view.zig +49 -3
  41. package/src/primitives/canvas/ui_markup_view_tests.zig +61 -2
  42. package/src/primitives/canvas/ui_schema.zig +8 -1
  43. package/src/primitives/canvas/ui_schema_tests.zig +7 -6
  44. package/src/primitives/canvas/ui_tests.zig +14 -0
  45. package/src/primitives/canvas/widget_access.zig +4 -3
  46. package/src/primitives/canvas/widget_invalidation.zig +11 -0
  47. package/src/primitives/canvas/widget_layout.zig +26 -3
  48. package/src/primitives/canvas/widget_metrics.zig +21 -3
  49. package/src/primitives/canvas/widget_render.zig +87 -1
  50. package/src/primitives/canvas/widget_routing.zig +12 -7
  51. package/src/primitives/canvas/widget_runtime_tests.zig +132 -0
  52. package/src/primitives/canvas/widgets.zig +40 -0
  53. package/src/root.zig +1 -0
  54. package/src/runtime/automation_widget_dispatch.zig +19 -0
  55. package/src/runtime/canvas_limits.zig +5 -0
  56. package/src/runtime/canvas_widget_event_tests.zig +424 -8
  57. package/src/runtime/canvas_widget_events.zig +254 -7
  58. package/src/runtime/canvas_widget_state.zig +123 -1
  59. package/src/runtime/core.zig +6 -0
  60. package/src/runtime/effects.zig +36 -1
  61. package/src/runtime/effects_fetch_tests.zig +21 -0
  62. package/src/runtime/effects_notification_tests.zig +65 -0
  63. package/src/runtime/gpu_surface_events.zig +60 -14
  64. package/src/runtime/tests.zig +1 -0
  65. package/src/runtime/ts_core_host.zig +16 -0
  66. package/src/runtime/ts_ui_app.zig +55 -2
  67. package/src/runtime/ui_app.zig +112 -0
  68. package/src/runtime/ui_app_tests.zig +356 -0
  69. package/src/runtime/view.zig +35 -0
  70. package/src/runtime/view_widget_tree.zig +12 -0
  71. package/tools/corewire/core_abi.zig +1 -0
  72. package/tools/corewire/emit.zig +55 -8
  73. package/tools/corewire/emit_facade.zig +63 -2
  74. package/tools/corewire/emit_profile.zig +4 -1
  75. package/tools/corewire/sidecar.zig +36 -6
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: ts-core
3
- description: Authoring guide for TypeScript app cores - Model, Msg, update, and the pure functions they call, written in the closed app-core subset, checked by the @native-sdk/core frontend, and compiled ahead-of-time to native code by the external core compiler. Use when writing or modifying a src/core.ts app core, fixing subset checker errors (NS1001-NS1060), or deciding how to express state, messages, text (bytes and the byte-text string methods), text input, continuous controls (sliders, scroll), effects (Cmd), subscriptions (Sub), the host-event wiring channels (frameMsg, keyMsg, appearanceMsg, chromeMsg, envMsgs, app.zon assets), derived values, the view_unbound lint opt-out, local mutation of owned arrays, or how to split a core into modules under src/ (relative imports, namespace imports, @native-sdk/core/text, @native-sdk/core/events).
3
+ description: Authoring guide for the primary Native SDK app-logic path: TypeScript app cores - Model, Msg, update, and the pure functions they call, written in the closed app-core subset, checked by the @native-sdk/core frontend, and compiled ahead-of-time to native code by the external core compiler. Use for new apps unless the user explicitly chose Zig, when writing or modifying a src/core.ts app core, fixing subset checker errors (NS1001-NS1060), or deciding how to express state, messages, text (bytes and the byte-text string methods), text input, continuous controls (sliders, scroll), effects (Cmd), subscriptions (Sub), the host-event wiring channels (frameMsg, keyMsg, pinchMsg, dropMsg, appearanceMsg, chromeMsg, envMsgs, app.zon assets), derived values, the view_unbound lint opt-out, local mutation of owned arrays, or how to split a core into modules under src/ (relative imports, namespace imports, @native-sdk/core/text, @native-sdk/core/events).
4
4
  ---
5
5
 
6
6
  # Author app cores in the TypeScript subset
7
7
 
8
- An app core is the logic tier of a Native SDK app: `Model` (the app state), `Msg` (a discriminated union of everything that can happen), `update(model, msg)` (the one pure transition function), and the pure helpers they call. You write it as a TypeScript module rooted at `src/core.ts` - splitting into more modules under `src/` when it grows (see "Splitting a core into modules") - and the build checks the whole import graph with the `@native-sdk/core` frontend and compiles it to native code with the external core compiler. No JS engine ships in the binary — the program either passes the subset checker and compiles to native, or you get a teaching error naming the rule, the fix, and the reason. The same file is executable TypeScript: it typechecks with stock tsc and runs unmodified under node, so you can poke behavior with plain node scripts before the native build.
8
+ TypeScript is the primary app-authoring language. An app core is the logic tier of a Native SDK app: `Model` (the app state), `Msg` (a discriminated union of everything that can happen), `update(model, msg)` (the one pure transition function), and the pure helpers they call. You write it as a TypeScript module rooted at `src/core.ts` - splitting into more modules under `src/` when it grows (see "Splitting a core into modules") - and the build checks the whole import graph with the `@native-sdk/core` frontend and compiles it to native code with the external core compiler. No JS engine ships in the binary — the program either passes the subset checker and compiles to native, or you get a teaching error naming the rule, the fix, and the reason. The same file is executable TypeScript: it typechecks with stock tsc and runs unmodified under node, so you can poke behavior with plain node scripts before the native build.
9
9
 
10
10
  A whole TS app is three files of truth and zero Zig: `src/core.ts` (this guide; plus any modules it imports under `src/`), `src/app.native` (the markup view over the core's model), and `app.zon` (windows, identity, permissions). `native init` scaffolds exactly that; the build detects `src/core.ts` in the tree (never a flag or config — a tree with both `src/core.ts` and `src/main.zig` is a teaching error) and generates the wiring outside the app. The loop:
11
11
 
@@ -133,13 +133,14 @@ The command set (Cmd wire format v3):
133
133
 
134
134
  ### The named engine ops
135
135
 
136
- These map directly onto the host's effect engine — files, HTTP, the clipboard, one-shot timers. Routing follows the `Cmd.request` rules (inline `{ key?, ok, err }`, string-literal arm names, arm shapes checked by tsc and taught by NS1027), with one difference from `request`: each op's `ok` arm has the op's OWN result shape. Keys follow the one keyed-effect rule everywhere: issuing an op whose key is already in flight REPLACES the old one (the superseded op's result is dropped — no message), and `Cmd.cancel(key)` drops it silently. Every `err` arm carries exactly one `Uint8Array` field and receives a machine-readable reason. Paths, URLs, and bodies are bytes (`asciiBytes` for literals); dynamic values the engine refuses at runtime surface through the `err` arm, while compile-time-knowable bound violations stop the build (NS1030).
136
+ These map directly onto the host's effect engine — files, HTTP, the clipboard, notifications, one-shot timers. Routed operations follow the `Cmd.request` rules (inline `{ key?, ok, err }`, string-literal arm names, arm shapes checked by tsc and taught by NS1027), with one difference from `request`: each op's `ok` arm has the op's OWN result shape. Keys follow the one keyed-effect rule everywhere: issuing a keyed op whose key is already in flight REPLACES the old one (the superseded op's result is dropped — no message), and `Cmd.cancel(key)` drops it silently. Every `err` arm carries exactly one `Uint8Array` field and receives a machine-readable reason; fire-and-forget writes and notifications have no routing arms. Paths, URLs, and bodies are bytes (`asciiBytes` for literals); dynamic values the engine refuses at runtime surface through the `err` arm, while compile-time-knowable bounds for routed operations stop the build (NS1030). Fire-and-forget operations fail closed under the host's validation instead.
137
137
 
138
138
  - `Cmd.readFile(path, { key?, ok, err })` — read a whole file. `ok` arm: one `Uint8Array` field with the content. `err` reasons: `not_found`, `io_failed`, `truncated` (the file exceeds the engine's 1 MiB read bound — a cut file never passes as whole), `rejected`. Paths are at most 1024 bytes.
139
139
  - `Cmd.writeFile(path, bytes, { key?, ok, err })` — write a whole file (parent directories created, an existing file replaced whole; at most 1 MiB). `ok` arm: NO payload fields (`{ kind: "wrote" }`) — a successful write has nothing to report. `err` reasons: `io_failed`, `rejected`.
140
140
  - `Cmd.fetch({ url, method?, headers?, body?, timeoutMs? }, { key?, ok, err })` — a buffered HTTP(S) exchange. `ok` arm: exactly two fields, one `number` and one `Uint8Array` (`{ kind: "fetched", status: number, body: Uint8Array }`) — matched by type, so the names are yours. The status is the real HTTP status: a 404 is still `ok` (an HTTP-level error is a delivered response). `err` reasons: `connect_failed`, `tls_failed`, `protocol_failed`, `timed_out`, `rejected`, and `truncated` (the body exceeded the engine's 256 KiB buffered bound — never delivered silently cut). The spec is an inline object: `url` bytes (≤ 2 KiB), `method` one of `"GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD"` (default GET), `headers` an inline flat record — names are compile-time ASCII, values are string literals OR runtime bytes (`{ authorization: bearerToken(model.apiKey), "content-type": "application/json" }` — how a launch-supplied key rides an `Authorization` header; ≤ 8 headers, ≤ 1 KiB total, NS1029/NS1030), `body` bytes (≤ 64 KiB), `timeoutMs` a positive integer literal (engine default when omitted). Buffered only — no streaming responses in v1.
141
141
  - `Cmd.clipboardWrite(bytes)` — put bytes on the system clipboard, fire-and-forget: there is no routing, and a refused or over-bound write is dropped by design.
142
142
  - `Cmd.clipboardRead({ key?, ok, err })` — read the clipboard. `ok` arm: one `Uint8Array` field with the text. `err` reasons: `failed` (no clipboard service, over-bound content, pasteboard error), `rejected`.
143
+ - `Cmd.showNotification({ title, subtitle?, body? })` — request a desktop notification, fire-and-forget: `title` is required bytes (1–128), `subtitle` optional bytes (up to 128), and `body` optional bytes (up to 1024). The host validates all fields before entering the platform service; invalid or unavailable requests fail closed, and Focus / Do Not Disturb and user settings remain authoritative after acceptance. Fake execution and session replay never display one.
143
144
  - `Cmd.delay(key, ms, "fired")` — a keyed ONE-SHOT timer: dispatches the named arm once, `ms` from now, with the fire time (ms) as its single number payload (the same arm shape `Cmd.now` and `Sub.timer` target). Re-issuing a live delay key re-arms it from now — that is the debounce discipline (`Cmd.delay("autosave", 800, "save_now")` on every keystroke, one fire after the pause). `Cmd.cancel(key)` drops it silently. The interval is 1ms to one year; a literal outside that stops the build (NS1030).
144
145
 
145
146
  One honesty note on `Cmd.persist()`: it compiles and encodes, but no shipping host implements the persist verb yet, so the checker teaches NS1028 as a WARNING (never failing the build). Persist real state with `Cmd.writeFile` and load it back with `Cmd.readFile` from `initialModel`'s boot command — the pattern every real app uses.
@@ -216,8 +217,8 @@ One caveat for node-side pokes: the build resolves the `@native-sdk/core*` speci
216
217
  - **`src/` is the boundary**: `../` escapes and absolute paths are taught (NS1034); bare npm specifiers are taught (NS1035 - vendor the code under `src/` or make the import `import type`). Only `@native-sdk/core` (the intrinsic Cmd/Sub/asciiBytes surface) and the SDK library modules below carry runtime meaning from outside.
217
218
  - **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the compile uniques them per module).
218
219
  - **No runtime import cycles** (NS1036). `import type` back-edges are legal and idiomatic: a helper module type-imports `Model` from `./core.ts` while `core.ts` runtime-imports the helpers - that is the expected shape, not a smell.
219
- - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
220
- - **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
220
+ - **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
221
+ - **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
221
222
 
222
223
  The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/ai-chat-ts` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
223
224
 
@@ -308,13 +309,17 @@ export type Msg = /* ... */ | { readonly kind: "library_scrolled"; readonly scro
308
309
  <scroll value="{libraryScrollTop}" on-scroll="library_scrolled"> ... </scroll>
309
310
  ```
310
311
 
312
+ - **Drag (`on-drag`, the live insertion event):** write a bound constructor such as `<row global-key="{card.id}" on-drag="card_dragged:{card.id}">`. Its Msg arm must be exactly `{ kind: "card_dragged"; sourceId: number; phase: number; x: number; y: number; viewWidth: number; viewHeight: number }`. Markup fills `sourceId`; the runtime fills view-local geometry and `phase` (`0` change, `1` end, `2` cancel). The renderer lifts the source appearance under the pointer at full opacity and leaves its in-flow rendering blank. For precise reordering, keep committed data unchanged during change and have derived array helpers move the same globally keyed source record to the candidate slot. That hidden row is the ONE reserved card-sized space: it starts at the source and moves to the candidate instead of duplicating. Keyed draggable neighbors ease between candidate poses; commit the array order on end and clear the candidate on cancel. A plain Escape during the drag is consumed and dispatches phase 2; the floating item continues from its pointer position into the committed slot (or back on cancel), and reduced-motion appearances snap the reflow.
313
+
311
314
  ## The host-event wiring channels
312
315
 
313
- The generated wiring detects each channel from an export (export exists → wired; a wrong shape is a taught NS1033). Event records are matched by field name, STRUCTURALLY: import them from `@native-sdk/core/events` (`FrameEvent`, `KeyEvent`, `ColorScheme`, `ChromeInsets`/`ChromeButtons`) or declare the same shapes in your core — both emit as your module's types and match identically. The `appearanceMsg`/`chromeMsg` arms themselves stay inline union members (`kind` plus the event's fields — the subset has no intersection arms); the SDK's `AppearanceEvent`/`ChromeEvent` records are those arms' canonical payload shapes, importable for helper signatures.
316
+ The generated wiring detects each channel from an export (export exists → wired; a wrong shape is a taught NS1033). Event records are matched by field name, STRUCTURALLY: import them from `@native-sdk/core/events` (`FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`, `ChromeInsets`/`ChromeButtons`) or declare the same shapes in your core — both emit as your module's types and match identically. The `appearanceMsg`/`chromeMsg` arms themselves stay inline union members (`kind` plus the event's fields — the subset has no intersection arms); the SDK's `AppearanceEvent`/`ChromeEvent` records are those arms' canonical payload shapes, importable for helper signatures.
314
317
 
315
318
  - **`commandMsg(name: string): Msg | null`** — menus, shortcuts, and chrome tabs, by command id (string equality works on `string` values).
316
319
  - **`frameMsg(model: Model, frame: FrameEvent): Msg | null`** — presented frames. `FrameEvent` is exactly `{ width, height, timestampMs, intervalMs }` numbers (canvas points; fractional milliseconds). Return null for frames that change nothing — the idle law holds exactly when an idle app dispatches nothing (a frame arm that always returns a Msg would spin the loop at full frame rate). The installing frame is excluded; the first PRESENTED frame corrects any seeded value.
317
320
  - **`keyMsg(key: KeyEvent): Msg | null`** — the app-level key FALLBACK (a focused widget's own keys and editable text always win first). `KeyEvent` is exactly `{ key: string; shift: boolean; control: boolean; alt: boolean; super: boolean }`; the key NAME arrives lowercased (`key.key === "space"`).
321
+ - **`pinchMsg(pinch: PinchEvent): Msg | null`** — the view-global trackpad pinch channel. `PinchEvent` carries `windowId`, `label`, begin/change/end `phase`, multiplicative `scale` delta, and the view-local `x`/`y` anchor.
322
+ - **`dropMsg(drop: FileDropEvent): Msg | null`** — native file drops after widget routing. `FileDropEvent` is exactly `{ windowId; viewLabel; point; paths }`: `point` is `{ x; y } | null`, and `paths` is `readonly Uint8Array[]` so arbitrary UTF-8 filesystem names remain byte text. Return null to ignore the drop or map it to any ordinary Msg.
318
323
  - **`export const appearanceMsg = "<arm>"`** — system appearance changes dispatch the named arm, a record of exactly `{ colorScheme: ColorScheme; reduceMotion: boolean; highContrast: boolean }` where `ColorScheme` is a NAMED `"light" | "dark"` alias (routing is data: a string-literal arm name, the effects rule applied to the app shell).
319
324
  - **`export const chromeMsg = "<arm>"`** — window-chrome geometry (the hidden-titlebar channel), a record of exactly `{ insets: { top; right; bottom; left }; buttons: { x; y; width; height }; tabsProjected: boolean }` (numbers/boolean). Delivered before the first view build and again on changes.
320
325
  - **`export const envMsgs = [{ env: "NAME", msg: "<arm>" }] as const`** — each named environment variable present at launch dispatches its value through the arm (exactly one `Uint8Array` field, `BytesKind` — annotate with `readonly EnvMsg<Msg>[]` from the SDK for tsc checking) as one journaled Msg right after the boot command. The core never reads the environment (NS1005), and neither does replay: the deliveries are journaled at record time and fed back from the journal, so a recording replays byte-identically even when the variables are unset or changed at replay launch.
@@ -356,7 +361,7 @@ Every diagnostic carries one of these IDs plus the fix and the why. Write to the
356
361
  - **NS1031 exported model helpers join the model's binding surface.** An exported single-Model-parameter helper becomes a Model declaration markup binds (`doneCount` → `{doneCount}`); two members with one binding name would be ambiguous — rename one.
357
362
  - **NS1032 viewUnbound names update-only model state.** `export const viewUnbound = [...] as const` entries must be string literals naming Model fields, exported model helpers, or Msg kinds — by their TypeScript spellings (`"nextId"`); anything else would silence nothing and hide a typo.
358
363
  - **NS1030 effect arguments respect the engine's limits.** A compile-time-knowable value outside an engine bound (a path literal over 1024 bytes, a URL literal over 2 KiB, more than 8 headers, a header block over 1 KiB, a delay literal outside 1ms..one year) stops the build instead of shipping a guaranteed runtime rejection. Dynamic values stay the engine's to validate — they surface through the `err` arm.
359
- - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm. The generated wiring builds these host events structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
364
+ - **NS1033 wiring channel exports match their host event shapes.** `frameMsg`/`keyMsg`/`pinchMsg`/`dropMsg` take their exact event records and return `Msg | null`; `appearanceMsg`/`chromeMsg` are string literals naming arms with those channels' record shapes; `envMsgs` entries carry `env` and a one-`Uint8Array`-field `msg` arm. The generated wiring builds these host events structurally from your declarations, so a wrong shape is taught here instead of surfacing as a Zig error inside generated code.
360
365
  - **NS1034 core imports stay inside src/.** `../` escapes and absolute paths are rejected: the entry module's directory is the core's whole world - the build ships exactly that tree.
361
366
  - **NS1035 npm packages do not run inside a core.** No JS engine ships in the binary; vendor the logic under `src/` or make the import type-only.
362
367
  - **NS1036 core modules do not import in a cycle.** Runtime cycles only work through JS live-binding indirection; hoist shared declarations, or make the back-edge `import type` (which is exempt and idiomatic).
@@ -481,7 +486,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
481
486
  });
482
487
  ```
483
488
 
484
- - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically (a wiring that also sets one of those seams is a teaching panic). Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
489
+ - `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically (a wiring that also sets one of those seams is a teaching panic). Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
485
490
  - Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the core's model keeps the TS spellings). Record arrays iterate with `<for each="tasks" as="t" key="id">` and items bind their fields (`{t.title}`); optional scalars gate with `<if test="{selected}">` (null is falsy); string-literal unions bind as their member name (`{filter}` renders `all` — compare against a quoted literal, `selected="{sortKey == 'cpu'}"`); exported single-model helpers bind as derived values (`{doneCount}`) and slice-returning ones drive `for each`. Markup `<chart>` series bind number arrays too — `<series kind="bar" values="{cpuSpark}" />` over a field or helper returning `readonly number[]` (f64, narrowed per sample into the chart pipeline); pad a filling window's leading gap with `NaN` samples, which draw nothing.
486
491
  - `Options.sync` does not exist for TS apps (a committed model cannot be mutated in place): keep continuous controls model-driven — bind the widget's value and echo `on-change`/`on-scroll` Msgs back into the model.
487
492
  - One live app per core module per process: two apps over the SAME core would share one committed root — and a process carries ONE compiled core (the archive owns a fixed-prefix C ABI symbol set).
@@ -38,7 +38,7 @@ pub fn main(init: std.process.Init) !void {
38
38
  }
39
39
  ```
40
40
 
41
- The CLI's own entry point is the live reference: `tools/native-sdk/main.zig`. Generated apps already have this shape — `main(init: std.process.Init)` passes `init` through to `runner.runWithOptions(app, options, init)` and `init.io` to the markup hot-reload watcher (see any `examples/*/src/main.zig`). `std.heap.page_allocator` still exists for allocations that live for the whole process. Library code that cannot take an `Init` builds its own `Io`: `var threaded = std.Io.Threaded.init(allocator, .{});` then `threaded.io()` (`src/platform/macos/root.zig`).
41
+ The CLI's own entry point is the live reference: `tools/native-sdk/main.zig`. Generated **Zig-core** apps have this shape — `main(init: std.process.Init)` passes `init` through to `runner.runWithOptions(app, options, init)` and `init.io` to the markup hot-reload watcher (see the older Zig-core examples' `src/main.zig`). Default TypeScript apps have no authored Zig entry point. `std.heap.page_allocator` still exists for allocations that live for the whole process. Library code that cannot take an `Init` builds its own `Io`: `var threaded = std.Io.Threaded.init(allocator, .{});` then `threaded.io()` (`src/platform/macos/root.zig`).
42
42
 
43
43
  ## error: struct 'fs' has no member named 'cwd' — file IO moved to `std.Io.Dir`
44
44
 
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: native-sdk
3
- description: Discovery skill for the Native SDK, the complete toolkit for building native desktop applications - views are declarative Native markup (.native), logic is plain Zig, and the toolkit's own engine renders every pixel, with WebView surfaces as the optional web-content path. Use when the user asks what the Native SDK is, how to build a Native SDK app, author native UI, scaffold an app, configure app.zon, add bridge commands, embed web content, package an app, test a running app, or automate a Native SDK app.
3
+ description: Discovery skill for the Native SDK, the complete toolkit for building native desktop applications. Apps are authored in TypeScript + declarative Native markup (.native) by default and compiled to native code with no JS runtime in the binary; Zig cores are an explicit alternative, and WebViews are the optional web-content path. Use when the user asks what the Native SDK is, how to build a Native SDK app, author native UI, scaffold an app, configure app.zon, add bridge commands, embed web content, package an app, test a running app, or automate a Native SDK app.
4
4
  allowed-tools: Bash(native:*), Bash(npx @native-sdk/cli:*)
5
5
  hidden: true
6
6
  ---
7
7
 
8
8
  # Native SDK
9
9
 
10
- The Native SDK is the complete toolkit for building native desktop applications. Views are declarative markup in `.native` files, logic is plain Zig, and the toolkit's own engine draws every pixel into real OS windows — no browser, no WebView, no interpreter in the binary. Every app embeds a deterministic automation server, so agents can snapshot, drive, and screenshot the running window. Desktop is the mature surface (macOS deepest, Linux and Windows exercised in CI); mobile embedding is experimental. WebView surfaces coexist as the optional path for embedding web content or hosting an existing web frontend.
10
+ The Native SDK is the complete toolkit for building native desktop applications. **The primary authoring path is TypeScript app logic in `src/core.ts` plus declarative Native markup in `.native` files.** The TypeScript core is checked and compiled ahead of time to native code, so the shipped binary contains no browser, WebView, JS runtime, or interpreter. Zig is how the toolkit itself works and is a first-class, explicitly chosen app-core alternative (`--template zig-core`); it is not the default inferred from the SDK's implementation. Every app embeds a deterministic automation server, so agents can snapshot, drive, and screenshot the running window. Desktop is the mature surface (macOS deepest, Linux and Windows exercised in CI); mobile embedding is experimental. WebView surfaces coexist as the optional path for embedding web content or hosting an existing web frontend.
11
11
 
12
12
  ## Start here
13
13
 
@@ -16,10 +16,11 @@ This file is a discovery stub for agents that installed the Native SDK once with
16
16
  ```bash
17
17
  native skills list
18
18
  native skills get core
19
- native skills get core --full
19
+ native skills get native-ui
20
+ native skills get ts-core
20
21
  ```
21
22
 
22
- Use `native skills get core` for initial orientation. Use `native skills get core --full` for implementation tasks because it includes the reference files for project anatomy, runtime, frontend assets, bridge/security/native capabilities, packaging, and debugging. Use `native skills get automation` when testing a running app, taking snapshots, requesting reloads, or using the built-in automation server. Use `native skills get zig` when `zig build` fails with "no member named" errors on std APIs — the SDK requires Zig 0.16.0, and that skill maps each pre-0.16 idiom's compile error to the current one.
23
+ Use `native skills get core` for initial orientation. For the default app-authoring path, load **both** `native-ui` (views, bindings, the app loop) and `ts-core` (the TypeScript subset, effects, subscriptions, and modules) before implementing. Use `native skills get core --full` when work reaches lower-level runtime wiring, WebViews, bridge/security, native capabilities, packaging, or debugging. Use `native skills get automation` when testing a running app, taking snapshots, requesting reloads, or using the built-in automation server. Use `native skills get zig` only for an existing Zig core, a toolkit extension, SDK implementation work, or a Zig 0.16 compile error.
23
24
 
24
25
  ## Quick orientation
25
26
 
@@ -30,4 +31,4 @@ cd my_app
30
31
  native dev
31
32
  ```
32
33
 
33
- Generated apps center on `app.zon`, `src/app.native` (the markup view), and `src/main.zig` (Model, Msg, update). Inspect those files before editing an existing app; web-frontend shells additionally carry `frontend/` and a `build.zig`.
34
+ `native init my_app` generates the primary three-file app: `app.zon`, `src/app.native` (the markup view), and `src/core.ts` (`Model`, `Msg`, `update`). Inspect the tree before editing an existing app and preserve the core language it already uses. `src/main.zig` means the app explicitly uses the Zig-core template; web-frontend shells additionally carry `frontend/` and usually owned build/runtime wiring.
@@ -31,7 +31,8 @@
31
31
  //! its exports (export exists -> wired): `frameMsg`
32
32
  //! (presented frames), `keyMsg` (the app-level key
33
33
  //! fallback), `appearanceMsg`/`chromeMsg` (Msg arms
34
- //! the host fills structurally).
34
+ //! the host fills structurally), and `dropMsg`
35
+ //! (native file drops with source, point, and paths).
35
36
  //! images app.zon's `.assets.images` entries (`.{ .id = 1,
36
37
  //! .path = "assets/..." }`) are read once at launch
37
38
  //! and registered on the installing frame — the ids
@@ -933,7 +933,9 @@ test "mobile C ABI dispatches GPU widget accessibility actions" {
933
933
  .text_len = drag_delta.len,
934
934
  };
935
935
  try std.testing.expectEqual(@as(c_int, 1), native_sdk_app_widget_action(app, &action));
936
- try std.testing.expectEqual(platform.GpuSurfaceInputKind.pointer_drag, self.last_input_kind);
936
+ // Drag automation is a complete gesture: the movement is followed by
937
+ // the release that lets markup `on-drag` handlers commit the drop.
938
+ try std.testing.expectEqual(platform.GpuSurfaceInputKind.pointer_up, self.last_input_kind);
937
939
  try std.testing.expectApproxEqAbs(@as(f32, 276), self.last_touch_x, 0.001);
938
940
  try std.testing.expectApproxEqAbs(@as(f32, 74), self.last_touch_y, 0.001);
939
941
 
@@ -612,13 +612,13 @@ int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size
612
612
  // already gone, which is the state the caller asked for. Returns 1 on
613
613
  // accept, 0 only for the invalid id 0.
614
614
  int native_sdk_appkit_unregister_font(uint64_t font_id, uint64_t token);
615
- /* Decode encoded image bytes (PNG, JPEG, ... — whatever ImageIO supports)
616
- * through CGImageSource into tightly packed, row-major, straight-alpha
615
+ /* Decode encoded image bytes (PNG, JPEG, ... through ImageIO; SVG through
616
+ * NSImage's system rasterizer) into tightly packed, row-major, straight-alpha
617
617
  * (non-premultiplied) RGBA8 written into `pixels`. Returns 1 on success
618
618
  * (with `out_width`/`out_height` set), 0 when the bytes cannot be decoded,
619
619
  * and -1 when the decoded pixels do not fit `pixels_len` (`out_width`/
620
- * `out_height` still report the decoded dimensions). Pure CoreGraphics —
621
- * no AppKit state — so it needs no host and is main-thread independent. */
620
+ * `out_height` still report the decoded dimensions). It retains no AppKit
621
+ * state, needs no host, and is main-thread independent. */
622
622
  int native_sdk_appkit_decode_image(const uint8_t *bytes, size_t bytes_len, uint8_t *pixels, size_t pixels_len, size_t *out_width, size_t *out_height);
623
623
  void native_sdk_appkit_clipboard_write(native_sdk_appkit_host_t *host, const char *text, size_t text_len);
624
624
  size_t native_sdk_appkit_clipboard_read_data(native_sdk_appkit_host_t *host, const char *mime_type, size_t mime_type_len, char *buffer, size_t buffer_len);
@@ -2454,7 +2454,9 @@ int native_sdk_appkit_measure_text_advances(uint64_t font_id, double size, const
2454
2454
  }
2455
2455
 
2456
2456
  // Platform image decoder: CGImageSource (ImageIO) handles PNG, JPEG, and
2457
- // every other codec the OS ships — the framework bundles none. The image
2457
+ // every other raster codec the OS ships. AppKit's NSImage adds the system SVG
2458
+ // representation/rasterizer when ImageIO cannot create a CGImage directly —
2459
+ // still an in-box codec, with no framework-bundled parser. The image
2458
2460
  // draws into a premultiplied RGBA8 bitmap context (the only RGBA layout
2459
2461
  // CGBitmapContext can render into) and is un-premultiplied in place,
2460
2462
  // because the canvas image pipeline — the reference renderer and the
@@ -2465,10 +2467,28 @@ int native_sdk_appkit_decode_image(const uint8_t *bytes, size_t bytes_len, uint8
2465
2467
  if (!bytes || bytes_len == 0 || !pixels) return 0;
2466
2468
  @autoreleasepool {
2467
2469
  NSData *data = [NSData dataWithBytesNoCopy:(void *)bytes length:bytes_len freeWhenDone:NO];
2470
+ CGImageRef image = NULL;
2468
2471
  CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
2469
- if (!source) return 0;
2470
- CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
2471
- CFRelease(source);
2472
+ if (source) {
2473
+ image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
2474
+ CFRelease(source);
2475
+ }
2476
+ if (!image) {
2477
+ NSImage *system_image = [[NSImage alloc] initWithData:data];
2478
+ NSSize size = system_image ? system_image.size : NSZeroSize;
2479
+ if (size.width > 0 && size.height > 0 && size.width <= 8192 && size.height <= 8192) {
2480
+ // SVG is resolution-independent, so cap the proposed point
2481
+ // extent before NSImage selects its Retina representation.
2482
+ // A 256pt square becomes at most the registry's 512px square
2483
+ // on macOS's 2x displays instead of materializing an
2484
+ // attacker-declared multi-hundred-megabyte bitmap first.
2485
+ const CGFloat max_raster_points = 256.0;
2486
+ const CGFloat raster_scale = MIN(1.0, MIN(max_raster_points / size.width, max_raster_points / size.height));
2487
+ NSRect proposed = NSMakeRect(0, 0, size.width * raster_scale, size.height * raster_scale);
2488
+ CGImageRef rendered = [system_image CGImageForProposedRect:&proposed context:nil hints:nil];
2489
+ if (rendered) image = CGImageRetain(rendered);
2490
+ }
2491
+ }
2472
2492
  if (!image) return 0;
2473
2493
 
2474
2494
  size_t width = CGImageGetWidth(image);
@@ -2909,19 +2909,35 @@ int native_sdk_appkit_measure_text_advances(uint64_t font_id, double size, const
2909
2909
  return 0;
2910
2910
  }
2911
2911
 
2912
- /* Mirror of the AppKit host's decoder: pure CoreGraphics/ImageIO with no
2913
- * host state, so both engines decode identically. See appkit_host.h for
2914
- * the pixel-format and return-value contract. */
2912
+ /* Mirror of the AppKit host's decoder: ImageIO raster codecs plus NSImage's
2913
+ * system SVG rasterizer, with no host state, so both engines decode
2914
+ * identically. See appkit_host.h for the pixel-format and return-value
2915
+ * contract. */
2915
2916
  int native_sdk_appkit_decode_image(const uint8_t *bytes, size_t bytes_len, uint8_t *pixels, size_t pixels_len, size_t *out_width, size_t *out_height) {
2916
2917
  if (out_width) *out_width = 0;
2917
2918
  if (out_height) *out_height = 0;
2918
2919
  if (!bytes || bytes_len == 0 || !pixels) return 0;
2919
2920
  @autoreleasepool {
2920
2921
  NSData *data = [NSData dataWithBytesNoCopy:(void *)bytes length:bytes_len freeWhenDone:NO];
2922
+ CGImageRef image = NULL;
2921
2923
  CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
2922
- if (!source) return 0;
2923
- CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
2924
- CFRelease(source);
2924
+ if (source) {
2925
+ image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
2926
+ CFRelease(source);
2927
+ }
2928
+ if (!image) {
2929
+ NSImage *system_image = [[NSImage alloc] initWithData:data];
2930
+ NSSize size = system_image ? system_image.size : NSZeroSize;
2931
+ if (size.width > 0 && size.height > 0 && size.width <= 8192 && size.height <= 8192) {
2932
+ // Bound SVG rasterization before NSImage materializes the
2933
+ // screen-scale representation; see the AppKit mirror.
2934
+ const CGFloat max_raster_points = 256.0;
2935
+ const CGFloat raster_scale = MIN(1.0, MIN(max_raster_points / size.width, max_raster_points / size.height));
2936
+ NSRect proposed = NSMakeRect(0, 0, size.width * raster_scale, size.height * raster_scale);
2937
+ CGImageRef rendered = [system_image CGImageForProposedRect:&proposed context:nil hints:nil];
2938
+ if (rendered) image = CGImageRetain(rendered);
2939
+ }
2940
+ }
2925
2941
  if (!image) return 0;
2926
2942
 
2927
2943
  size_t width = CGImageGetWidth(image);
@@ -1131,8 +1131,8 @@ fn measureTextAdvances(context: ?*anyopaque, font_id: u64, size: f32, text: []co
1131
1131
  return native_sdk_appkit_measure_text_advances(font_id, size, text.ptr, text.len, advances.ptr) == 1;
1132
1132
  }
1133
1133
 
1134
- /// CGImageSource-backed image decoding (PNG, JPEG, ... — every codec
1135
- /// ImageIO ships) into straight-alpha RGBA8.
1134
+ /// System image decoding (ImageIO raster codecs plus NSImage's SVG
1135
+ /// rasterizer) into straight-alpha RGBA8.
1136
1136
  fn decodeImage(context: ?*anyopaque, bytes: []const u8, buffer: []u8) anyerror!platform_mod.DecodedImage {
1137
1137
  _ = context;
1138
1138
  var width: usize = 0;
@@ -388,9 +388,17 @@ pub const WidgetFileDropEvent = struct {
388
388
  paths: []const []const u8 = &.{},
389
389
  };
390
390
 
391
+ pub const WidgetDragPhase = enum {
392
+ change,
393
+ end,
394
+ cancel,
395
+ };
396
+
391
397
  pub const WidgetDragEvent = struct {
392
398
  source_id: ObjectId = 0,
399
+ phase: WidgetDragPhase = .change,
393
400
  point: geometry.PointF,
401
+ /// Total displacement from the pointer-down that began the gesture.
394
402
  delta: geometry.OffsetF = .{},
395
403
  };
396
404