akanjs 3.3.0-rc.37 → 3.3.0-rc.38

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
@@ -4,6 +4,24 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
+ - 800f3ef: fix(agent): a write's change report carries a changed value the way the screen block does
8
+
9
+ After a tool call that changed something, its result lists the resources that changed. Each entry held the whole
10
+ new value, so free text published with `st.expose`, `st.useState` or `useAgentResource`, which the screen block
11
+ leaves out and `readState` answers as page content, reached the model as the app's own data on the first write. An
12
+ entry now keeps what the screen block keeps (a token, a number, a boolean, an ISO timestamp, a short list or object
13
+ of those, and a list scope's ids and token labels) and is marked `withheld: true` when anything was left out;
14
+ `readState(name)` answers the rest. The in-page agent and an MCP App view both report this way.
15
+
16
+ - `AgentContext.reported(view)` returns a surface view whose change report follows the rule.
17
+ - `ResourceDiff` gains the optional `withheld` field.
18
+
19
+ **Upgrading.** No code change is needed: both additions are optional. A model that read a sentence from a tool
20
+ result's `changes` now finds the entry marked `withheld` and reads it with `readState`, which makes the next change
21
+ ask for approval. Where an agent should act on a changed value without that ask, publish an id, a count or an enum
22
+ member, or return the value from the tool itself. A host that builds its own `ToolRunner` over the store surface
23
+ wraps the surface with `AgentContext.reported` to report the same way.
24
+
7
25
  - 4a568b2: What an agent turn carries beside the conversation reaches the model as marked data in a user turn, outside the system prompt.
8
26
 
9
27
  - **A turn's `context` is no longer written into the system prompt.** `OpenaiDialect` and `AnthropicLlm` send it as a `<turn-context …>` block that ends the turn's last user-role content, after that turn's tool results: a text block on the Messages API, and on the chat-completions wire the end of the user message the turn closes on, or a user message of its own after tool messages. The block closes on a delimiter chosen so that its content cannot contain it, in any case or width or with characters that do not show between its letters. The delimiter is keyed with a secret of the process: the same text gets the same one in every request a process sends, and another process gives it another. The system prompt is the instructions alone, so it is the same text on every turn of a conversation and a provider's prefix cache keeps it.
@@ -526,6 +544,14 @@
526
544
  Such a server handed its own start code on to the worker's command, so the child ran the server's code again with the worker file as an argument, exited with 1 and was started again every second: the worker never ran, and the log showed `[Worker:<name>] WARN exited 1; restarting in 1000ms` over and over. A server started from its file (`bun main.js` with no backends of its own) was not affected. The same command builds the `ops snapshot` and `ops migrate` children, which now leave the start code out as well.
527
545
 
528
546
  - f678e80: The `akanjs` package no longer ships `ARCHITECTURE.md`. The map of the framework's processes and messages is for contributors and stays in the repository (`pkgs/akanjs/ARCHITECTURE.md`); a coding agent building an app read its 11.9 KB from the unpacked package before scaffolding. Verifying a built `akanjs` dist now fails if the file is back in it.
547
+ - cda53a8: fix(signal): a bare value for an array argument is refused over HTTP and WebSocket
548
+
549
+ An endpoint declaring `tags: [String]` and sent `"a"` handed its handler the string `"a"` where it expects a list: the
550
+ primitive parser read the lone value as one item and returned it unwrapped. It now answers 400 `invalidArgument`,
551
+ as a model argument and a filter already did. A repeated query string (`?tags=a`) is always read as a list, so
552
+ `fetch` and the generated client are unaffected; a hand-written body must send `["a"]`. MCP still lifts a lone value
553
+ into a one-item list, since models send a bare value for an array.
554
+
529
555
  - af09c4f: `router.backOrFallback()` and `Link.Back` with a `fallback` close a browser tab the app itself opened instead of replacing to the fallback, when there is nothing to go back to. The tab counts as opened by the app when it holds one history entry and has an opener or a same-origin referrer, so a `window.open(href, "_blank", "noopener")` or `target="_blank"` link qualifies. A tab the person opened (a bookmark, a typed URL), one another site opened, and an iOS, Android or desktop shell keep going to the fallback, as does a tab the browser refuses to close.
530
556
  - 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.
531
557
  - 7c4143e: `akanjs/client` exports `nativeKeyboardEasing()`, the curve the keyboard of the shell a page runs in moves on: Android's (`ANDROID_KEYBOARD_ANIMATION_EASING`) in an Android app, iOS's (`IOS_KEYBOARD_ANIMATION_EASING`) anywhere else. `KeyboardRide` already used it; with the name on the barrel, a page's browser code holds the device and keyboard files once, where a build would otherwise have shipped them in two bundles.
@@ -597,6 +623,11 @@
597
623
 
598
624
  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.
599
625
 
626
+ - 040c561: Two cases where a room id did not match the arguments it was built from are fixed.
627
+
628
+ - A publish to a pubsub room whose required `String` argument is `""` now reaches its subscribers. The publisher's side spelled that argument as "no value" while the subscriber had joined with the empty string, so the message went to a room nobody was in. The publisher now reads each argument with the argument's own nullability, the way the client serializes it and the server parses it.
629
+ - An own `__proto__` key in an `Any` room argument or in a live query is part of the room id. It used to be dropped, so two subscriptions whose arguments differed only by that key shared a room.
630
+
600
631
  - 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.
601
632
  An existing zero-byte `.br` or `.gz` sibling is skipped, because an empty body is not valid brotli or gzip.
602
633
  - b30db27: A signal test's fetch opens its socket at the first subscribe or message, so a pubsub test needs no clone.
@@ -616,6 +647,11 @@
616
647
  In development (`NODE_ENV=development`, as under `akan start`), `st.use`, `st.do` and `st.slice` throw on a key no loaded store declares, naming it (`st.do.initMemo is not registered: …`), where they answered `undefined` and the call failed later with `… is not a function`. `in`, `Object.keys` and a symbol key still answer as before, and a production build and a test run are unchanged.
617
648
 
618
649
  - 8f9d432: A page no longer shows a broken character where React's output buffer ends. React writes a page's HTML in 4 KB pieces cut by bytes; when the piece that carried the document's head ended inside a character of more than one byte (Korean, Japanese, an accented letter, an emoji), that character arrived as replacement marks and a stray one closed the document. It depended on where the text fell, so the same page could be right on one request and wrong on the next.
650
+ - fb46b5d: Three malformed requests now get the refusal a well-formed mistake gets, instead of a 500 or a stray answer.
651
+
652
+ - A WebSocket frame whose `key` names a member of `Object.prototype` (`constructor`, `toString`, `valueOf`, `hasOwnProperty`, `__proto__`) answers 404 `routeNotFound`, like any other unregistered key. It used to find that member in the route table and answer 500 with an error log line, `{}` or `"[object Undefined]"`.
653
+ - A WebSocket frame whose `data` is not an array answers 400 `invalidMessage`. A missing or `null` `data` used to answer 500 with an error log line, and a string had its characters read as the arguments.
654
+ - An MCP `POST` whose JSON body is `null` answers 400 with a JSON-RPC `invalidRequest` error instead of throwing.
619
655
 
620
656
  ## 3.2.0
621
657
 
@@ -68,7 +68,8 @@ const canonicalOf = (value: unknown, holding: Set<object>): unknown => {
68
68
  if (value instanceof Set) return { "%set": [...value].map((item) => canonicalOf(item, holding)) };
69
69
  if (value instanceof RegExp) return { "%regexp": [value.source, value.flags] };
70
70
  if (Array.isArray(value)) return value.map((item) => canonicalOf(item, holding) ?? null);
71
- const record: Record<string, unknown> = {};
71
+
72
+ const record: Record<string, unknown> = Object.create(null);
72
73
  for (const key of Object.keys(value).sort()) {
73
74
  const item = canonicalOf((value as Record<string, unknown>)[key], holding);
74
75
  if (item !== undefined) record[key] = item;
@@ -52,6 +52,7 @@ export class InputParser {
52
52
  throw new InvalidInputError(key, null);
53
53
  }
54
54
  if (PrimitiveRegistry.has(argRef)) {
55
+ InputParser.#requireArrays(value, arrDepth, key);
55
56
  const parsed = deserialize(argRef, arrDepth, value, option);
56
57
  RequestValue.admit(parsed, key);
57
58
  return parsed;
@@ -59,6 +60,12 @@ export class InputParser {
59
60
  return InputParser.#walk(value, arrDepth, key, (item, path) => InputParser.#value(argRef, item, path));
60
61
  }
61
62
 
63
+ static #requireArrays(value: unknown, arrDepth: number, path: string) {
64
+ if (!arrDepth) return;
65
+ if (!Array.isArray(value)) throw new InvalidInputError(path, "array");
66
+ for (const [idx, item] of value.entries()) InputParser.#requireArrays(item, arrDepth - 1, `${path}.${idx}`);
67
+ }
68
+
62
69
  static #walk(value: unknown, arrDepth: number, path: string, parse: Parse): unknown {
63
70
  if (!arrDepth) return parse(value, path);
64
71
  if (!Array.isArray(value)) throw new InvalidInputError(path, "array");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.3.0-rc.37",
3
+ "version": "3.3.0-rc.38",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -257,6 +257,8 @@ export class McpRouter {
257
257
  } catch {
258
258
  return McpRouter.#error(null, McpErrorCode.parse, "Invalid JSON body.", { status: 400 });
259
259
  }
260
+ if (body === null)
261
+ return McpRouter.#error(null, McpErrorCode.invalidRequest, "A JSON-RPC request is an object.", { status: 400 });
260
262
  const id = body.id ?? null;
261
263
  const method = body.method;
262
264
  if (typeof method !== "string")
@@ -213,7 +213,8 @@ export class ApiRouter {
213
213
  ws.send(JSON.stringify(websocketHeartbeatContract.makeAck()));
214
214
  return;
215
215
  }
216
- const wsRoute = wsRoutes[msg.key];
216
+
217
+ const wsRoute = Object.hasOwn(wsRoutes, msg.key) ? wsRoutes[msg.key] : undefined;
217
218
  if (!wsRoute) {
218
219
 
219
220
  logger.warn(`WebSocket route "${msg.key}" is not registered`);
@@ -221,6 +222,8 @@ export class ApiRouter {
221
222
  statusCode: 404,
222
223
  });
223
224
  }
225
+ if (!Array.isArray(msg.data))
226
+ throw new AkanError("invalidMessage", "Message data is not an array", { statusCode: 400 });
224
227
  const eventType =
225
228
  typeof msg.subscribe === "boolean" ? (msg.subscribe ? "subscribe" : "unsubscribe") : "message";
226
229
  const call = () => wsRoute(ws, msg.data, eventType, { since: msg.since });
package/signal/roomKey.ts CHANGED
@@ -25,15 +25,12 @@ export class RoomKey {
25
25
 
26
26
  static #asReceived(arg: ArgInfo, value: unknown): unknown {
27
27
  try {
28
+ const nullable = arg.option?.nullable;
28
29
  const sent = serialize(arg.argRef as ConstantModelRef | PrimitiveScalar, arg.arrDepth, value, "input", {
29
- nullable: true,
30
+ nullable,
30
31
  });
31
32
  const wire: unknown = JSON.parse(JSON.stringify(sent) ?? "null");
32
- return InputParser.parse(arg.argRef as Cls, arg.arrDepth, wire, {
33
- key: arg.name,
34
- nullable: true,
35
- enum: arg.enum,
36
- });
33
+ return InputParser.parse(arg.argRef as Cls, arg.arrDepth, wire, { key: arg.name, nullable, enum: arg.enum });
37
34
  } catch {
38
35
  return value;
39
36
  }
@@ -1,5 +1,5 @@
1
1
  import { STATE_DERIVED_META } from "akanjs/base";
2
- import type { ContextBlock, PublishedResource, PublishedScope, SurfaceView } from "../../vendor/use-agentic";
2
+ import type { ContextBlock, PublishedResource, PublishedScope, ResourceDiff, SurfaceView } from "../../vendor/use-agentic";
3
3
  import { InlineToken } from "../../common/inlineToken";
4
4
  import type { StoreInstance } from "../storeInstance";
5
5
  import { StoreRegistry } from "../storeRegistry";
@@ -24,6 +24,17 @@ export class AgentContext {
24
24
  return AgentInline.path(pathname);
25
25
  }
26
26
 
27
+ static reported(view: SurfaceView): SurfaceView {
28
+ return {
29
+ snapshot: () => view.snapshot(),
30
+ tool: (name) => view.tool(name),
31
+ call: (name, args) => view.call(name, args),
32
+ read: (name) => view.read(name),
33
+ diffSince: (before) => AgentContext.#changes(view.diffSince(before), view.snapshot().scopes),
34
+ subscribe: (listener) => view.subscribe(listener),
35
+ };
36
+ }
37
+
27
38
  readonly #instance: StoreInstance;
28
39
  readonly #bridge: AgentBridge;
29
40
 
@@ -83,21 +94,35 @@ export class AgentContext {
83
94
  if (!rows.whole) labelled = false;
84
95
  return { ...resource, value: rows.value };
85
96
  }
86
- const { value, error, ...named } = resource;
87
- const inline = AgentInline.value(value);
88
- const failed = error !== undefined && !InlineToken.is(error);
89
- if (!inline.whole || failed) valued = false;
90
- return {
91
- ...named,
92
- ...(inline.value !== undefined ? { value: inline.value } : {}),
93
- ...(error !== undefined && !failed ? { error } : {}),
94
- ...(inline.whole && !failed ? {} : { withheld: true }),
95
- };
97
+ const inlined = AgentContext.#inlined(resource);
98
+ if (inlined.withheld) valued = false;
99
+ return inlined;
96
100
  });
97
101
  const notes = [...(labelled ? [] : [AgentContext.screenNote]), ...(valued ? [] : [AgentContext.resourceNote])];
98
102
  return [{ kind: "screen", scopes: shown, resources: listed, ...(notes.length ? { note: notes.join(" ") } : {}) }];
99
103
  }
100
104
 
105
+ static #changes(diffs: ResourceDiff[], scopes: PublishedScope[]): ResourceDiff[] {
106
+ const lists = new Set(scopes.map((scope) => `${scope.path}.items`));
107
+ return diffs.map((diff) => {
108
+ const rows = lists.has(diff.name) ? AgentContext.#rowsOf(diff.value) : null;
109
+ if (!rows) return AgentContext.#inlined(diff);
110
+ return { ...diff, value: rows.value, ...(rows.whole ? {} : { withheld: true }) };
111
+ });
112
+ }
113
+
114
+ static #inlined<Named extends { name: string; value?: unknown; error?: string }>(resource: Named) {
115
+ const { value, error, ...named } = resource;
116
+ const inline = AgentInline.value(value);
117
+ const failed = error !== undefined && !InlineToken.is(error);
118
+ return {
119
+ ...named,
120
+ ...(inline.value !== undefined ? { value: inline.value } : {}),
121
+ ...(error !== undefined && !failed ? { error } : {}),
122
+ ...(inline.whole && !failed ? {} : { withheld: true }),
123
+ };
124
+ }
125
+
101
126
  static #rowsOf(value: unknown): { value: unknown; whole: boolean } | null {
102
127
  if (!value || typeof value !== "object" || !("items" in value) || !Array.isArray(value.items)) return null;
103
128
  const items: unknown[] = value.items;
@@ -247,7 +247,7 @@ export class StoreSurfaceSource implements SurfaceSource {
247
247
  return {
248
248
  name: "readState",
249
249
  description:
250
- "Read one store state key of this page, or one resource by its name. Keys are listed in the state context block and in `withheld` of the route block; a resource the screen block marks `withheld` is read by its name.",
250
+ "Read one store state key of this page, or one resource by its name. Keys are listed in the state context block and in `withheld` of the route block; a resource the screen block or a tool result's `changes` marks `withheld` is read by its name.",
251
251
  parameters: {
252
252
  type: "object",
253
253
  properties: { key: { type: "string" } },
@@ -10,6 +10,7 @@ export declare class AgentContext {
10
10
  static of(): AgentContext;
11
11
  /** A pathname as the route block carries it: a segment of free text, or one past twelve words, reads `…`. */
12
12
  static routePath(pathname: string): string;
13
+ static reported(view: SurfaceView): SurfaceView;
13
14
  constructor(instance: StoreInstance, bridge: AgentBridge);
14
15
  blocks(surface: SurfaceView, view?: string[]): ContextBlock[];
15
16
  }
@@ -131,6 +131,8 @@ export interface ResourceDiff {
131
131
  value?: unknown;
132
132
  error?: string;
133
133
  removed?: boolean;
134
+ /** Set by a host that reports less than the whole value, so the model reads the rest through a tool. */
135
+ withheld?: boolean;
134
136
  }
135
137
  export type ChatRole = "user" | "assistant" | "tool";
136
138
  export interface ToolCallRequest {
@@ -66,7 +66,8 @@ export const agentSessionOf = ({
66
66
  const { surface } = ensureStoreSurface();
67
67
  const history = sessionHistoryOf(persist, view.join("."));
68
68
  const drawing = AgentVisual.sink(visual);
69
- const session = new AgentSession(sessionView(surface, view, builtins), runner ?? fetchRunner(), {
69
+ const shown = AgentContext.reported(sessionView(surface, view, builtins));
70
+ const session = new AgentSession(shown, runner ?? fetchRunner(), {
70
71
  buildContext: (scoped) => AgentContext.of().blocks(scoped, view),
71
72
  settle: () => ScreenSettle.wait(),
72
73
  continueAsk: () => ({ question: l("base.agentContinue"), keep: l("base.agentKeepGoing") }),
@@ -14,6 +14,26 @@
14
14
 
15
15
  **Upgrading.** A host that stages references (`session.stage`, `session.refer`) must render `pendingApproval`, as a host that publishes a `taint: "source"` tool already must: the first change after a mention now waits on it. To keep such changes running as each tool's own `confirm` decides, pass `askAfterUntrusted: false`. Nothing else changes for a host whose context blocks carry no `untrusted` field. A host that already used a field named `untrusted` on a context block for something else must rename it: any value but `false` or `undefined` now marks the block.
16
16
 
17
+ ### Patch Changes
18
+
19
+ - 800f3ef: fix(agent): a write's change report carries a changed value the way the screen block does
20
+
21
+ After a tool call that changed something, its result lists the resources that changed. Each entry held the whole
22
+ new value, so free text published with `st.expose`, `st.useState` or `useAgentResource`, which the screen block
23
+ leaves out and `readState` answers as page content, reached the model as the app's own data on the first write. An
24
+ entry now keeps what the screen block keeps (a token, a number, a boolean, an ISO timestamp, a short list or object
25
+ of those, and a list scope's ids and token labels) and is marked `withheld: true` when anything was left out;
26
+ `readState(name)` answers the rest. The in-page agent and an MCP App view both report this way.
27
+
28
+ - `AgentContext.reported(view)` returns a surface view whose change report follows the rule.
29
+ - `ResourceDiff` gains the optional `withheld` field.
30
+
31
+ **Upgrading.** No code change is needed: both additions are optional. A model that read a sentence from a tool
32
+ result's `changes` now finds the entry marked `withheld` and reads it with `readState`, which makes the next change
33
+ ask for approval. Where an agent should act on a changed value without that ask, publish an id, a count or an enum
34
+ member, or return the value from the tool itself. A host that builds its own `ToolRunner` over the store surface
35
+ wraps the surface with `AgentContext.reported` to report the same way.
36
+
17
37
  ## 0.3.0
18
38
 
19
39
  ### Minor Changes
@@ -151,6 +151,8 @@ export interface ResourceDiff {
151
151
  value?: unknown;
152
152
  error?: string;
153
153
  removed?: boolean;
154
+ /** Set by a host that reports less than the whole value, so the model reads the rest through a tool. */
155
+ withheld?: boolean;
154
156
  }
155
157
 
156
158
  export type ChatRole = "user" | "assistant" | "tool";
@@ -34,7 +34,7 @@ export class McpAppAgent {
34
34
  constructor(bridge: McpAppBridge, surface = ensureStoreSurface().surface, approvals = McpAppApprovals.shared) {
35
35
  this.#bridge = bridge;
36
36
  this.#surface = surface;
37
- this.#runner = new ToolRunner(surface, {
37
+ this.#runner = new ToolRunner(AgentContext.reported(surface), {
38
38
  approve: (request, signal) => McpAppAgent.#ask(approvals, request, signal),
39
39
  ...(AgentConfirm.policy.afterScreenRead ? {} : { askAfterUntrusted: false }),
40
40
  settle: () => ScreenSettle.wait(),