akanjs 3.2.0-rc.23 → 3.2.0-rc.25

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 (54) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/client/route/RouteHead.ts +4 -1
  3. package/client/viewportMeta.ts +54 -4
  4. package/package.json +1 -1
  5. package/server/index.ts +1 -0
  6. package/server/migration/migrationCommand.ts +31 -2
  7. package/server/migration/migrationRunner.ts +36 -1
  8. package/server/ops/migrateJobs.ts +2 -2
  9. package/server/ops/opsCommand.ts +1 -1
  10. package/server/rscDocumentHead.tsx +19 -12
  11. package/server/rscRouteDocument.tsx +20 -3
  12. package/service/agentLoop/agentLoop.ts +33 -9
  13. package/service/agentLoop/agentLoopTypes.ts +5 -1
  14. package/service/agentLoop/loopCompaction.ts +5 -1
  15. package/service/predefinedAdaptor/database.adaptor.ts +2 -0
  16. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +10 -0
  17. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +54 -16
  18. package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
  19. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
  20. package/service/predefinedAdaptor/sql/types.ts +12 -2
  21. package/signal/agentTurnStream.ts +7 -2
  22. package/types/client/viewportMeta.d.ts +2 -1
  23. package/types/server/index.d.ts +1 -1
  24. package/types/server/migration/migrationCommand.d.ts +1 -1
  25. package/types/server/migration/migrationRunner.d.ts +9 -1
  26. package/types/server/rscDocumentHead.d.ts +4 -3
  27. package/types/service/agentLoop/agentLoopTypes.d.ts +5 -1
  28. package/types/service/agentLoop/loopCompaction.d.ts +2 -1
  29. package/types/service/predefinedAdaptor/database.adaptor.d.ts +1 -1
  30. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +3 -1
  31. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +3 -1
  32. package/types/service/predefinedAdaptor/sql/types.d.ts +10 -2
  33. package/types/signal/agentTurnStream.d.ts +1 -0
  34. package/types/ui/overlayLayer.d.ts +2 -1
  35. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +2 -2
  36. package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
  37. package/types/vendor/use-agentic/Compaction.d.ts +3 -1
  38. package/types/vendor/use-agentic/types.d.ts +6 -3
  39. package/ui/Agent/Chat.tsx +12 -2
  40. package/ui/overlayLayer.ts +4 -2
  41. package/vendor/@akanjs/native/CHANGELOG.md +3 -0
  42. package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
  43. package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
  44. package/vendor/@akanjs/native/native/desktop/src/external.rs +27 -3
  45. package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
  46. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +107 -7
  47. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +2 -2
  48. package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
  49. package/vendor/use-agentic/AgentSession.ts +6 -8
  50. package/vendor/use-agentic/CHANGELOG.md +11 -0
  51. package/vendor/use-agentic/Compaction.ts +10 -1
  52. package/vendor/use-agentic/WIRE.md +4 -2
  53. package/vendor/use-agentic/httpRunner.ts +7 -4
  54. package/vendor/use-agentic/types.ts +7 -1
package/CHANGELOG.md CHANGED
@@ -45,6 +45,17 @@
45
45
 
46
46
  Both are new and optional, so no upgrade step is needed.
47
47
 
48
+ - 3ebf990: `agentService.loop` now recovers from a model call refused for length, the way the in-page chat does, instead of ending the run. Both now read a refusal's `limit` in the refusal's own unit when it also gives `requested`.
49
+
50
+ - With `compact` set, a round whose call fails as `agent.error.contextOverflow` compacts at once, whatever `at` says, emits `compacted` as usual, and asks again.
51
+ - The retry is part of the same round. A second refusal, a transcript with nothing to cut, or a summary that fails ends the run with the original error, as before.
52
+ - The refused attempt is metered as a `failed` turn with what the provider counted, which is nothing for a refusal an adaptor makes before any network call.
53
+ - When the refusal's data carries `limit` and `requested`, the run lowers `at` for its remaining rounds to where that request would have fit, so the next one compacts ahead instead of being refused.
54
+ - The relay now forwards `requested` beside `limit` on the wire's `overflow` (`TurnOverflow`). Given both, the chat scales its own estimate of the refused prompt by `limit / requested` to get the window it adopts. Given `limit` alone, the chat still takes it as the window in tokens.
55
+ - The two numbers may be in any unit, as long as it is the same one. An adaptor that caps the request body in bytes can throw `new Err("agent.error.contextOverflow", { limit, requested })` with its own byte counts, and neither the loop nor the chat mistakes them for tokens.
56
+
57
+ A run without `compact` ends on the refusal as before. With `compact` set, a refused round now costs up to two more model calls (the summary and the retry) before the run ends. `AgentTurnStream.failure(...).overflow` and `RunnerEvent`'s error `overflow` gain an optional `requested`; code reading only `limit` needs no change.
58
+
48
59
  - 2da2adc: `agentService.loop` takes `toolkits`, so a run over a large catalogue no longer sends every tool definition every round.
49
60
 
50
61
  - **Shape.** `toolkits: { calendar: { description: "Read and edit the org calendar", tools: ["eventListInOrg", "updateEvent"] } }` groups names of `allow`. A tool in no toolkit is the core and is listed every round. `allow` still caps every toolkit.
@@ -194,6 +205,14 @@
194
205
  No upgrade step is needed: `AkanIpcMessage` only gains the `pubsub.subscribed` message and an optional `ack` on `pubsub.subscribe`, and `SolidPubSub` an injected `behindGateway` flag it reads from the env.
195
206
 
196
207
  - f314eba: A route guard gets a second argument, `{ path }`: the requested in-app path with its search, in the form `router.push` takes, on the server and in CSR (`undefined` while MCP lists a screen). `signedIn({ path })` from `@libs/shared/webkit` adds `?redirect=<path>` to the sign-in URL, and `signedIn("/login")` still works. Use `path` to build a redirect target only. It must never decide admission: CSR asks a guard again only when the route or an argument it declared changes.
208
+ - 4a4c62b: A boot no longer drops an index akan built that the release no longer declares. Since 3.1.0 the first instance of a new release to boot, `akan migrate` included, dropped those indexes while instances of the previous release were still serving queries from them. An older instance that restarted during the rollout, or after a rollback, built the index again (on SQLite a blocking build inside its boot), and the next new boot dropped it again.
209
+
210
+ - Each boot keeps such an index and warns about each one. A unique one is named as unique, because it keeps refusing a duplicate of its key that the new release would write.
211
+ - `akan migrate <app> indexes` (`bun main.js ops migrate indexes` in a built image) lists them. `akan migrate <app> prune-indexes` drops them, concurrently on Postgres. Run it once no instance of an earlier release is serving. An index made by hand, outside akan, is never listed or dropped.
212
+ - Through the ops channel, `prune-indexes` needs a token with a `sub`, like `apply` and `rollback`.
213
+
214
+ Upgrade step: after every instance runs this release, run `prune-indexes` once to drop what earlier releases left; until then the warnings at boot list those indexes. `migrationActions` and `MigrationAction` gain `indexes` and `prune-indexes`, so code that switches over every action needs the two new cases; nothing else changes for a caller.
215
+
197
216
  - d6b3619: Every `Err` is now one class, `Err` from `akanjs/common`. That covers the one an app's or lib's `lib/dict` builds, the one `useClient` returns, `akanjs/dictionary`'s own, and an error restored off the wire. Each is that class typed with its own dictionary's keys, so `Err.is` and the status classes behave the same in the browser and on the server. `instanceof Err` holds within one copy of the module. A page bundle and the framework each carry one, so check across them with `Err.is`.
198
217
 
199
218
  - **`Err` is an `AkanError`.** `AkanError.is(err)` is true for every `Err`, and `err.forwarded` is true unless it was restored with a `code`, so the request path still sends its `toJSON()` as it is.
@@ -225,6 +244,14 @@
225
244
 
226
245
  Upgrading: `WebsocketAdaptor.onRecovered` now hands its handler the rooms held on the server, `(rooms: string[]) => void`. A custom adaptor that implements `onRecovered` must call the handler with every room a socket on the server is still in, live rooms included, and only once events published to those rooms reach the server again, since each room refetches on it. Code that only reads `WebsocketResData` needs no change beyond handling, or ignoring, `type: "resync"`.
227
246
 
247
+ - ce90ad0: A page's `.head()` can now set its own `theme-color`, and a level that writes an image no longer inherits the image tags of the one above it.
248
+
249
+ - A `<meta name="theme-color">` a `.head()` writes replaces the root `.viewport({ themeColor })`'s tags, in the server render, after hydration and across client navigation. A page without its own gets the root's back.
250
+ - A level that writes `og:image` drops the `og:image:*` tags (`width`, `height`, `alt`, `type`) it inherits and keeps its own. `twitter:image` and its `twitter:image:*` tags merge the same way.
251
+ - Only `.head()` merges. A `<title>` or `<meta>` written inside a component renders beside the merged head, so a second `<title>` can reach the document. The `pageRule` guideline now says so.
252
+
253
+ Behaviour is unchanged for a page that sets neither a theme-color nor an image. The api report lists one new `ViewportMeta` static; no upgrade step is needed.
254
+
228
255
  - bc5fdb0: `--akan-theme-color` on the root now drives the browser's `theme-color`, and a native app's status bar icons when the app names the `appearance` plugin.
229
256
 
230
257
  - **The variable outranks the root layout's `.viewport({ themeColor })`.** Set it per theme beside the tokens (`--akan-theme-color: var(--background)`), or at run time on `document.documentElement.style`. The page reads it again when the root's `style`, `class` or `data-theme` changes, or the OS scheme flips. With neither the variable nor a `themeColor`, no tag is written, as before.
@@ -270,6 +297,12 @@
270
297
  - **The `akan-service` skill** carries a recipe for pages backed by an external HTTP API: an `adapt()` adapter in `srvkit/` that reads its base URL at boot, a `lib/_<service>` service, a `Public` `query(Any, { nullable: true })` endpoint and its dictionary label, and the page that calls it.
271
298
  - **The README's "Inside an existing repository"** runs the creator through `npx -y bun@1.4.4 x …` on a host with only Node and npm, so nothing global is written. It also gives copy-ready `build` and `start` scripts, says a fresh clone builds without a committed env file, and says which environment a `.env`-less build is for and what a deployed host sets instead.
272
299
 
300
+ - 6fc8a60: A toast now shows above a modal the floating `Agent.Chat` opened, and a question from the agent leaves focus and Escape to that modal.
301
+
302
+ - **Toasts top every overlay but Reconnect.** `overlayZ.toast` moves from 140 to 180, above the agent panel (150), a modal the panel opened (160) and one a card opened (170), so a toast reporting what that modal's controls did is no longer hidden behind it.
303
+ - **A question no longer pulls focus out of an overlay.** When `askUser` puts a question up while focus sits in a modal, sheet, menu or popconfirm, focus stays there, so typing meant for the modal no longer lands in the composer and Enter no longer sends it as the answer. Opening the panel still focuses the composer.
304
+ - **Escape closes one layer at a time.** With a modal, sheet or popconfirm open from the panel or from a card, Escape in the composer closes that overlay through its own close, `confirmClose` included, and only the next Escape closes the panel. It used to close the panel and the modal together, skipping `confirmClose`.
305
+
273
306
  - f5d1e63: A restored chat transcript that ends on an unanswered `askUser` call now opens on that question instead of closing it. This covers a server run that parked on a question while no chat was open, and a page reloaded mid-question.
274
307
 
275
308
  - The session's `pendingQuestion` holds the question, so `Agent.Chat` draws its card and the composer answers it as usual.
@@ -16,6 +16,7 @@ export class RouteHead {
16
16
  ]);
17
17
 
18
18
  static readonly #pageIdentityKeys = new Set(["link:canonical", "meta:property:og:url"]);
19
+ static readonly #imageKeys = ["meta:property:og:image", "meta:name:twitter:image", "meta:property:twitter:image"];
19
20
 
20
21
  static merge(levels: ResolveHeadResult[]): ResolveHeadResult {
21
22
  const present = levels.filter((level) => RouteHead.#nodeOf(level) != null || RouteHead.#snapshotOf(level));
@@ -179,7 +180,9 @@ export class RouteHead {
179
180
  .map((item, idx) => ({ item, level, idx }))
180
181
  .filter(({ item }) => {
181
182
  const key = keyOf(item);
182
- return !key || owner.get(key) === level;
183
+ if (!key) return true;
184
+ const imageOwner = RouteHead.#imageKeys.find((imageKey) => key.startsWith(`${imageKey}:`));
185
+ return owner.get(key) === level && (!imageOwner || (owner.get(imageOwner) ?? level) <= level);
183
186
  }),
184
187
  );
185
188
  }
@@ -1,4 +1,4 @@
1
- import type { RouteViewport } from "./csrTypes";
1
+ import type { AkanHeadSnapshotNode, RouteViewport } from "./csrTypes";
2
2
 
3
3
  export interface ThemeColorTag {
4
4
  content: string;
@@ -9,6 +9,8 @@ export interface ThemeColorTag {
9
9
  export class ViewportMeta {
10
10
  static readonly #offMedia = "not all";
11
11
  static readonly #ownAttr = "data-akan-theme-color";
12
+ static readonly #mutedAttr = "data-akan-media";
13
+ static readonly #viewportAttr = "data-akan-viewport";
12
14
  static readonly #themeColorVar = "--akan-theme-color";
13
15
 
14
16
  static content(viewport: RouteViewport | undefined, { native = false }: { native?: boolean } = {}): string {
@@ -33,6 +35,13 @@ export class ViewportMeta {
33
35
  return first ? [{ content: first }] : [];
34
36
  }
35
37
 
38
+ static themeColorNodes(viewport: RouteViewport | undefined, theme?: string): AkanHeadSnapshotNode[] {
39
+ return ViewportMeta.themeColors(viewport, theme).map(({ content, media }) => ({
40
+ tag: "meta",
41
+ attrs: { name: "theme-color", content, ...(media ? { media } : {}), [ViewportMeta.#viewportAttr]: "" },
42
+ }));
43
+ }
44
+
36
45
  static applyContent(viewport: RouteViewport | undefined, { native = false }: { native?: boolean } = {}) {
37
46
  const meta = ViewportMeta.#ensureMeta("viewport");
38
47
  const content = ViewportMeta.content(viewport, { native });
@@ -45,13 +54,26 @@ export class ViewportMeta {
45
54
 
46
55
  static applyThemeColor(viewport: RouteViewport | undefined, theme?: string): string | null {
47
56
  const runtime = ViewportMeta.runtimeThemeColor();
48
- const tags = runtime ? [{ content: runtime }] : ViewportMeta.themeColors(viewport, theme);
49
57
  const existing = [...document.head.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]')];
58
+ const authored = existing.filter(
59
+ (meta) => !meta.hasAttribute(ViewportMeta.#ownAttr) && !meta.hasAttribute(ViewportMeta.#viewportAttr),
60
+ );
61
+ if (!runtime && authored.length) {
62
+ for (const meta of existing) {
63
+ if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
64
+ else if (meta.hasAttribute(ViewportMeta.#viewportAttr)) ViewportMeta.#mute(meta);
65
+ else ViewportMeta.#unmute(meta);
66
+ }
67
+ return ViewportMeta.#inEffect(
68
+ authored.map((meta) => ({ content: meta.content, media: meta.getAttribute("media") })),
69
+ );
70
+ }
71
+ const tags = runtime ? [{ content: runtime }] : ViewportMeta.themeColors(viewport, theme);
50
72
  if (!tags.length) {
51
73
  for (const meta of existing) if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
52
74
  return null;
53
75
  }
54
- const inEffect = tags.find((tag) => !tag.media || window.matchMedia(tag.media).matches)?.content ?? null;
76
+ const inEffect = ViewportMeta.#inEffect(tags);
55
77
  const live = existing.filter((meta) => meta.getAttribute("media") !== ViewportMeta.#offMedia);
56
78
  const isCurrent =
57
79
  live.length === tags.length &&
@@ -62,7 +84,7 @@ export class ViewportMeta {
62
84
 
63
85
  for (const meta of existing) {
64
86
  if (meta.hasAttribute(ViewportMeta.#ownAttr)) meta.remove();
65
- else meta.setAttribute("media", ViewportMeta.#offMedia);
87
+ else ViewportMeta.#mute(meta);
66
88
  }
67
89
  for (const tag of tags) {
68
90
  const meta = document.createElement("meta");
@@ -75,6 +97,26 @@ export class ViewportMeta {
75
97
  return inEffect;
76
98
  }
77
99
 
100
+ static #inEffect(tags: { content: string; media?: string | null }[]): string | null {
101
+ return tags.find((tag) => !tag.media || window.matchMedia(tag.media).matches)?.content ?? null;
102
+ }
103
+
104
+ static #mute(meta: HTMLMetaElement) {
105
+
106
+ if (meta.getAttribute("media") === ViewportMeta.#offMedia) return;
107
+ if (!meta.hasAttribute(ViewportMeta.#mutedAttr))
108
+ meta.setAttribute(ViewportMeta.#mutedAttr, meta.getAttribute("media") ?? "");
109
+ meta.setAttribute("media", ViewportMeta.#offMedia);
110
+ }
111
+
112
+ static #unmute(meta: HTMLMetaElement) {
113
+ const media = meta.getAttribute(ViewportMeta.#mutedAttr);
114
+ if (media === null) return;
115
+ if (media) meta.setAttribute("media", media);
116
+ else meta.removeAttribute("media");
117
+ meta.removeAttribute(ViewportMeta.#mutedAttr);
118
+ }
119
+
78
120
  static watchThemeColor(apply: () => void): () => void {
79
121
  let frame = 0;
80
122
  const schedule = () => {
@@ -85,10 +127,18 @@ export class ViewportMeta {
85
127
  };
86
128
  const observer = new MutationObserver(schedule);
87
129
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style", "class", "data-theme"] });
130
+ const headObserver = new MutationObserver(schedule);
131
+ headObserver.observe(document.head, {
132
+ childList: true,
133
+ subtree: true,
134
+ attributes: true,
135
+ attributeFilter: ["content", "media", "name"],
136
+ });
88
137
  const scheme = window.matchMedia("(prefers-color-scheme: dark)");
89
138
  scheme.addEventListener("change", schedule);
90
139
  return () => {
91
140
  observer.disconnect();
141
+ headObserver.disconnect();
92
142
  scheme.removeEventListener("change", schedule);
93
143
  if (frame) cancelAnimationFrame(frame);
94
144
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.23",
3
+ "version": "3.2.0-rc.25",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/server/index.ts CHANGED
@@ -150,6 +150,7 @@ export {
150
150
  type MigrationPatch,
151
151
  type MigrationPlan,
152
152
  type MigrationPlanResult,
153
+ type MigrationPruneResult,
153
154
  MigrationPulse,
154
155
  type MigrationRevertOutcome,
155
156
  type MigrationRewriteOption,
@@ -1,8 +1,9 @@
1
1
  import { parseArgs } from "node:util";
2
+ import type { UndeclaredIndex } from "akanjs/service";
2
3
  import { MigrationError, type MigrationErrorCode } from "./migrationError";
3
4
  import type { MigrationListItem, MigrationRunner } from "./migrationRunner";
4
5
 
5
- export const migrationActions = ["list", "plan", "apply", "verify", "rollback"] as const;
6
+ export const migrationActions = ["list", "plan", "apply", "verify", "rollback", "indexes", "prune-indexes"] as const;
6
7
  export type MigrationAction = (typeof migrationActions)[number];
7
8
  const migrationOptions = ["param", "expect", "actor", "items"] as const;
8
9
  type MigrationOption = (typeof migrationOptions)[number];
@@ -35,7 +36,10 @@ export class MigrationCommand {
35
36
  apply: ["param", "expect", "actor"],
36
37
  verify: ["param", "actor"],
37
38
  rollback: ["actor"],
39
+ indexes: [],
40
+ "prune-indexes": ["actor"],
38
41
  };
42
+ static readonly #untargeted = new Set<MigrationAction>(["list", "indexes", "prune-indexes"]);
39
43
 
40
44
  static usageOf(invokedAs = "ops migrate") {
41
45
  return [
@@ -45,6 +49,8 @@ export class MigrationCommand {
45
49
  ` ${invokedAs} apply <id> [--param <name>=<value>]... [--expect <planHash>] [--actor <id>] [--json]`,
46
50
  ` ${invokedAs} verify <id> [--param <name>=<value>]... [--actor <id>] [--json]`,
47
51
  ` ${invokedAs} rollback <applyRunId|id> [--actor <id>] [--json]`,
52
+ ` ${invokedAs} indexes [--json]`,
53
+ ` ${invokedAs} prune-indexes [--actor <id>] [--json]`,
48
54
  ].join("\n");
49
55
  }
50
56
 
@@ -59,7 +65,7 @@ export class MigrationCommand {
59
65
  if (!migrationActions.includes(name as MigrationAction))
60
66
  throw new MigrationError("usage", `Unknown action "${name}"\n${usage}`);
61
67
  const action = name as MigrationAction;
62
- if (action === "list" ? target : !target)
68
+ if (MigrationCommand.#untargeted.has(action) ? target : !target)
63
69
  throw new MigrationError("usage", `${action} ${target ? "takes no id" : "needs an id"}\n${usage}`);
64
70
  if (extra.length) throw new MigrationError("usage", `Unexpected arguments: ${extra.join(" ")}`);
65
71
  const refused = migrationOptions.find(
@@ -85,6 +91,19 @@ export class MigrationCommand {
85
91
  if (action === "list") return { ok: true, action, migrations: await runner.list() };
86
92
  if (action === "plan") return { ok: true, action, ...(await runner.plan(target, params, { actor, items })) };
87
93
  if (action === "rollback") return { ok: true, action, ...(await runner.rollback(target, { actor })) };
94
+ if (action === "indexes") return { ok: true, action, indexes: await runner.undeclaredIndexes() };
95
+ if (action === "prune-indexes") {
96
+ const { dropped, failed } = await runner.pruneIndexes({ actor });
97
+ if (!failed.length) return { ok: true, action, dropped, failed };
98
+ return {
99
+ ok: false,
100
+ action,
101
+ code: "failed",
102
+ error: `${failed.length} of the indexes could not be dropped`,
103
+ dropped,
104
+ failed,
105
+ };
106
+ }
88
107
  const result =
89
108
  action === "apply"
90
109
  ? await runner.apply(target, params, { expect, actor })
@@ -128,6 +147,8 @@ export class MigrationCommand {
128
147
  if (json) return JSON.stringify(result);
129
148
  if (result.ok && result.action === "list")
130
149
  return MigrationCommand.#renderList(result.migrations as MigrationListItem[]);
150
+ if (result.ok && result.action === "indexes")
151
+ return MigrationCommand.#renderIndexes(result.indexes as UndeclaredIndex[]);
131
152
  return JSON.stringify(result, null, 2);
132
153
  }
133
154
 
@@ -146,6 +167,14 @@ export class MigrationCommand {
146
167
  .join("\n");
147
168
  }
148
169
 
170
+ static #renderIndexes(indexes: UndeclaredIndex[]) {
171
+ if (!indexes.length) return "This release declares every index an earlier one built";
172
+ return [
173
+ "Kept for an earlier release; drop them with prune-indexes once no instance runs one:",
174
+ ...indexes.map(({ table, name, unique }) => `${unique ? "unique" : " "} ${table} ${name}`),
175
+ ].join("\n");
176
+ }
177
+
149
178
  static #parseArgs(argv: string[], usage: string) {
150
179
  try {
151
180
  return parseArgs({
@@ -1,6 +1,13 @@
1
1
  import { Logger } from "akanjs/common";
2
2
  import { createDocumentId, sanitizeJson } from "akanjs/document";
3
- import { type DatabaseAdaptor, descriptorHash, stableJson } from "akanjs/service";
3
+ import {
4
+ type DatabaseAdaptor,
5
+ descriptorHash,
6
+ type PrunedIndex,
7
+ type SqlDocumentStore,
8
+ stableJson,
9
+ type UndeclaredIndex,
10
+ } from "akanjs/service";
4
11
  import { MigrationChangeLog } from "./migrationChangeLog";
5
12
  import { MigrationChanges, type MigrationSkip } from "./migrationChanges";
6
13
  import { MigrationContext, type MigrationGet } from "./migrationContext";
@@ -79,6 +86,11 @@ export interface MigrationRollbackResult {
79
86
  runs: MigrationRollbackRun[];
80
87
  }
81
88
 
89
+ export interface MigrationPruneResult {
90
+ dropped: UndeclaredIndex[];
91
+ failed: PrunedIndex[];
92
+ }
93
+
82
94
  export class MigrationRunner {
83
95
  static readonly defaultItemNum = 100;
84
96
  readonly #entries: MigrationEntry[];
@@ -129,6 +141,29 @@ export class MigrationRunner {
129
141
  );
130
142
  }
131
143
 
144
+ async undeclaredIndexes(): Promise<UndeclaredIndex[]> {
145
+ const indexes: UndeclaredIndex[] = [];
146
+ for (const store of this.#stores()) indexes.push(...(await store.undeclaredIndexes()));
147
+ return indexes;
148
+ }
149
+
150
+ async pruneIndexes({ actor = null }: { actor?: string | null } = {}): Promise<MigrationPruneResult> {
151
+ const pruned: PrunedIndex[] = [];
152
+ for (const store of this.#stores()) pruned.push(...(await store.pruneUndeclaredIndexes()));
153
+ const failed = pruned.filter(({ error }) => error !== undefined);
154
+ const dropped = pruned.filter(({ error }) => error === undefined);
155
+ this.#logger.info(
156
+ `prune-indexes${actor ? ` for ${actor}` : ""}: ${dropped.length} dropped, ${failed.length} failed to drop`,
157
+ );
158
+ return { dropped, failed };
159
+ }
160
+
161
+ #stores(): SqlDocumentStore[] {
162
+ const stores = this.#database.stores?.();
163
+ if (!stores) throw new MigrationError("failed", "This database adaptor keeps no model stores to read indexes from");
164
+ return stores;
165
+ }
166
+
132
167
  async plan(
133
168
  id: string,
134
169
  raw: Record<string, string> = {},
@@ -54,7 +54,7 @@ export class MigrateJobs {
54
54
  return `id must match ${MigrateJobs.idPattern.source}`;
55
55
  if (typeof action !== "string" || !migrationActions.includes(action as MigrationAction))
56
56
  return `action must be one of ${migrationActions.join(", ")}`;
57
- if ((action === "apply" || action === "rollback") && !actor)
57
+ if ((action === "apply" || action === "rollback" || action === "prune-indexes") && !actor)
58
58
  return `${action} needs the token's sub, the person it runs for`;
59
59
  if (target !== undefined && (typeof target !== "string" || !MigrateJobs.targetPattern.test(target)))
60
60
  return `target must match ${MigrateJobs.targetPattern.source}`;
@@ -72,7 +72,7 @@ export class MigrateJobs {
72
72
  ...entries.map(([name, value]) => `--param=${name}=${value as string}`),
73
73
  ...(expect ? [`--expect=${expect}`] : []),
74
74
  ...(items === undefined ? [] : [`--items=${items}`]),
75
- ...(actor && action !== "list" ? [`--actor=${actor}`] : []),
75
+ ...(actor && action !== "list" && action !== "indexes" ? [`--actor=${actor}`] : []),
76
76
  "--json",
77
77
  ];
78
78
  return { id, action: action as MigrationAction, argv };
@@ -20,7 +20,7 @@ export class OpsCommand {
20
20
  "Usage:",
21
21
  " bun main.js ops snapshot [--id <id>] [--out <dir>] [--include-solid] [--db <file>] [--solid-db <file>] [--allow-plaintext] [--json]",
22
22
  " bun main.js ops restore <manifest.json> [--identity <file>] [--db <file>] [--solid-db <file>] [--allow-plaintext] [--force]",
23
- " bun main.js ops migrate [list|plan|apply|verify|rollback] [<id>] [--param <name>=<value>]... [--expect <planHash>] [--items <n>] [--actor <id>] [--json]",
23
+ " bun main.js ops migrate [list|plan|apply|verify|rollback|indexes|prune-indexes] [<id>] [--param <name>=<value>]... [--expect <planHash>] [--items <n>] [--actor <id>] [--json]",
24
24
  ].join("\n");
25
25
 
26
26
  static async run(argv: string[], host?: OpsHost): Promise<number> {
@@ -1,4 +1,4 @@
1
- import type { ResolvedHead, RouteRender, RouteViewport } from "akanjs/client";
1
+ import type { AkanHeadSnapshotNode, ResolvedHead, RouteRender, RouteViewport } from "akanjs/client";
2
2
  import { type AkanI18nConfig, getBasePathFromPathname, LocalePath } from "akanjs/common";
3
3
  import { untrackedRequest } from "akanjs/fetch";
4
4
  import type { ReactNode } from "react";
@@ -41,15 +41,8 @@ export class RscDocumentHead {
41
41
  return values.find((value) => value !== undefined);
42
42
  }
43
43
 
44
- renderViewport(viewport: RouteViewport | undefined, theme?: string): ReactNode {
45
- return (
46
- <>
47
- <meta key="viewport" name="viewport" content={ViewportMeta.content(viewport)} />
48
- {ViewportMeta.themeColors(viewport, theme).map(({ content, media }) => (
49
- <meta key={`theme-color:${media ?? ""}`} name="theme-color" content={content} media={media} />
50
- ))}
51
- </>
52
- );
44
+ renderViewport(viewport: RouteViewport | undefined): ReactNode {
45
+ return <meta key="viewport" name="viewport" content={ViewportMeta.content(viewport)} />;
53
46
  }
54
47
 
55
48
  async renderManifestLink(url: URL, renderRootLayouts: RouteRender[]): Promise<ReactNode> {
@@ -68,9 +61,11 @@ export class RscDocumentHead {
68
61
  snapshots,
69
62
  noindex = false,
70
63
  tags = null,
64
+ themeColors = [],
71
65
  }: {
72
66
  manifestLink: ReactNode;
73
67
  routeHead: ResolvedHead;
68
+ themeColors?: AkanHeadSnapshotNode[];
74
69
  snapshots?: RouteHeadSnapshots;
75
70
  noindex?: boolean;
76
71
  tags?: ReactNode[] | null;
@@ -83,14 +78,26 @@ export class RscDocumentHead {
83
78
  return (
84
79
  <>
85
80
  {ownsManifest ? null : manifestLink}
86
- <AkanRouteHeadReference layouts={snapshots.layouts} page={snapshots.page} />
81
+ <AkanRouteHeadReference
82
+ layouts={{
83
+ ...snapshots.layouts,
84
+ nodes: RouteHead.mergeSnapshots([themeColors, snapshots.layouts.nodes]).nodes,
85
+ }}
86
+ page={snapshots.page}
87
+ />
87
88
  </>
88
89
  );
89
90
  }
90
91
  const head = routeHead.node ?? this.renderDefaultHead();
91
92
  return (
92
93
  <>
93
- {RouteHead.mergeNodes([manifestLink, head, noindex ? RouteHead.noindexOver(head) : null, tags])}
94
+ {RouteHead.mergeNodes([
95
+ themeColors.map((node, idx) => <meta key={`theme-color:${idx}`} {...node.attrs} />),
96
+ manifestLink,
97
+ head,
98
+ noindex ? RouteHead.noindexOver(head) : null,
99
+ tags,
100
+ ])}
94
101
  {this.#renderLocaleAlternates(url)}
95
102
  </>
96
103
  );
@@ -3,6 +3,7 @@ import type { AkanI18nConfig, Logger } from "akanjs/common";
3
3
  import { setRequestFrameState, setRequestTheme, untrackedCookies, untrackedRequest } from "akanjs/fetch";
4
4
  import type { ReactNode } from "react";
5
5
  import { RouteHead } from "../client/route/RouteHead";
6
+ import { ViewportMeta } from "../client/viewportMeta";
6
7
  import { FallbackHead } from "./fallbackHead";
7
8
  import { resolveHeadResult } from "./head";
8
9
  import { type AdmittedNotFoundFallback, RouteElementComposer, type RouteNotFoundInPlace } from "./routeElementComposer";
@@ -100,7 +101,15 @@ export class RscRouteDocument {
100
101
  key="route-head"
101
102
  head={fallbackHead}
102
103
  until={gate?.opened ?? Promise.resolve()}
103
- render={(tags) => this.#head.renderHeadTags(url, { manifestLink, routeHead, noindex: true, tags })}
104
+ render={(tags) =>
105
+ this.#head.renderHeadTags(url, {
106
+ manifestLink,
107
+ routeHead,
108
+ noindex: true,
109
+ tags,
110
+ themeColors: ViewportMeta.themeColorNodes(viewport),
111
+ })
112
+ }
104
113
  />
105
114
  {this.#head.renderStylesheet(pathname)}
106
115
  </head>
@@ -173,12 +182,14 @@ export class RscRouteDocument {
173
182
  notFound: { ...notFound, head: fallbackHead },
174
183
  gate,
175
184
  });
185
+ const themeColors = ViewportMeta.themeColorNodes(viewport, themeColorTheme);
176
186
  const renderHead = async (tags: ReactNode[] | null) => {
177
187
  if (!tags)
178
188
  return this.#head.renderHeadTags(url, {
179
189
  manifestLink,
180
190
  routeHead: routeHead.layers.head,
181
191
  snapshots: routeHead.snapshots,
192
+ themeColors,
182
193
  });
183
194
  const layoutsHead = await RscRouteDocument.#resolveFallbackHead({
184
195
  kind: "not-found",
@@ -186,14 +197,20 @@ export class RscRouteDocument {
186
197
  params: match.params,
187
198
  searchParams,
188
199
  });
189
- return this.#head.renderHeadTags(url, { manifestLink, routeHead: layoutsHead, noindex: true, tags });
200
+ return this.#head.renderHeadTags(url, {
201
+ manifestLink,
202
+ routeHead: layoutsHead,
203
+ noindex: true,
204
+ tags,
205
+ themeColors,
206
+ });
190
207
  };
191
208
 
192
209
  const element = (
193
210
  <html lang={match.params.lang ?? this.#i18n.defaultLocale} suppressHydrationWarning>
194
211
  <head key="head">
195
212
  <meta key="charset" charSet="utf-8" />
196
- {this.#head.renderViewport(viewport, themeColorTheme)}
213
+ {this.#head.renderViewport(viewport)}
197
214
  <FallbackHead.Settled
198
215
  key="route-head"
199
216
  head={fallbackHead}
@@ -70,6 +70,7 @@ export class AgentLoop {
70
70
  #toolCalls = 0;
71
71
  #tainted: boolean = false;
72
72
  #compactFloor = 0;
73
+ #overflowAt = Number.POSITIVE_INFINITY;
73
74
 
74
75
  constructor(port: AgentLoopPort, request: AgentLoopRequest) {
75
76
  this.#port = port;
@@ -178,16 +179,37 @@ export class AgentLoop {
178
179
  }
179
180
 
180
181
  async *#ask(tools: AgentTool[]): Events<AgentLoopAnswer> {
182
+ const preamble = this.#request.preamble ?? false;
183
+ const request = this.#turnOf(tools);
184
+ try {
185
+ return yield* this.#metered(request, preamble, true);
186
+ } catch (error) {
187
+ if (!this.#request.compact || !Err.is(error, "agent.error.contextOverflow")) throw error;
188
+ this.#learnOverflow(error.data, request);
189
+
190
+ if (!(yield* this.#compact(true))) throw error;
191
+ }
192
+ return yield* this.#metered(this.#turnOf(tools), preamble, true);
193
+ }
194
+
195
+ #turnOf(tools: AgentTool[]): LlmTurnRequest {
181
196
  const { context = [], model, preamble } = this.#request;
182
197
  const instructions = this.#request.instructions || (preamble ? "" : AgentLoop.noInstructions);
183
- const request: LlmTurnRequest = {
198
+ return {
184
199
  messages: LoopTranscript.wire(this.#messages),
185
200
  tools: tools.map(({ readOnly: _readOnly, ...tool }) => tool),
186
201
  context,
187
202
  ...(instructions ? { instructions } : {}),
188
203
  ...(model ? { model } : {}),
189
204
  };
190
- return yield* this.#metered(request, preamble ?? false, true);
205
+ }
206
+
207
+ #learnOverflow(data: Record<string, unknown> | undefined, request: LlmTurnRequest) {
208
+ const { limit, requested } = data ?? {};
209
+ if (typeof limit !== "number" || typeof requested !== "number" || !(limit > 0 && requested > limit)) return;
210
+ const frame = LoopCompaction.frameTokensOf(request);
211
+ const fits = Math.floor(((LoopCompaction.tokensOf(this.#messages) + frame) * limit) / requested) - frame;
212
+ if (fits > 0) this.#overflowAt = Math.min(this.#overflowAt, fits);
191
213
  }
192
214
 
193
215
  async *#metered(request: LlmTurnRequest, preamble: string | false, streamed: boolean): Events<AgentLoopAnswer> {
@@ -221,12 +243,13 @@ export class AgentLoop {
221
243
  return answer;
222
244
  }
223
245
 
224
- async *#compact(): Events<void> {
246
+ async *#compact(forced = false): Events<boolean> {
225
247
  const { compact, model, untrusted } = this.#request;
226
- if (!compact) return;
227
- if (LoopCompaction.tokensOf(this.#messages) < Math.max(compact.at, this.#compactFloor)) return;
248
+ if (!compact) return false;
249
+ const threshold = Math.min(compact.at, this.#overflowAt);
250
+ if (!forced && LoopCompaction.tokensOf(this.#messages) < Math.max(threshold, this.#compactFloor)) return false;
228
251
  const at = LoopCompaction.cutAt(this.#messages, compact.keep ?? LoopCompaction.keep);
229
- if (at <= 0) return;
252
+ if (at <= 0) return false;
230
253
  const digest = LoopCompaction.digest(this.#messages.slice(0, at));
231
254
  let text = "";
232
255
  try {
@@ -242,9 +265,9 @@ export class AgentLoop {
242
265
  if (this.#haltedBy(error)) throw error;
243
266
 
244
267
  AgentLoop.#logger.warn(`agent loop compaction failed: ${error instanceof Error ? error.message : String(error)}`);
245
- return;
268
+ return false;
246
269
  }
247
- if (!text) return;
270
+ if (!text) return false;
248
271
  const summary = LoopCompaction.message(
249
272
  text,
250
273
  this.#tainted || untrusted ? this.#tainted : undefined,
@@ -253,8 +276,9 @@ export class AgentLoop {
253
276
  this.#messages.splice(0, at, summary);
254
277
  const after = LoopCompaction.tokensOf(this.#messages);
255
278
 
256
- this.#compactFloor = after >= compact.at ? after + compact.at : 0;
279
+ this.#compactFloor = after >= threshold ? after + threshold : 0;
257
280
  yield { type: "compacted", replaced: at, summary };
281
+ return true;
258
282
  }
259
283
 
260
284
  async *#runCalls(calls: AgentWireToolCall[], tools: AgentTool[]): Events<AgentLoopStop | null> {
@@ -81,7 +81,11 @@ export interface AgentLoopOptions {
81
81
  * no question is answered with an error instead. A `clientTools` entry by that name is dropped.
82
82
  */
83
83
  ask?: boolean;
84
- /** Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens. */
84
+ /**
85
+ * Summarizes all but the last `keep` messages (6) once the transcript is estimated at `at` tokens, and also when a
86
+ * round's call fails as `agent.error.contextOverflow`, which is then asked again once. A refusal whose data carries
87
+ * `limit` and `requested`, in any one unit, lowers `at` for the rest of the run to where the request would fit.
88
+ */
85
89
  compact?: { at: number; keep?: number };
86
90
  /** Asked before every call; without it a `needsConfirm` tool is refused, and so is any write once tainted. */
87
91
  approve?: AgentLoopApprove;
@@ -1,4 +1,4 @@
1
- import type { AgentWireAttachment, AgentWireMessage } from "../predefinedAdaptor/llm.adaptor";
1
+ import type { AgentWireAttachment, AgentWireMessage, LlmTurnRequest } from "../predefinedAdaptor/llm.adaptor";
2
2
  import { LoopTranscript } from "./loopTranscript";
3
3
 
4
4
  export class LoopCompaction {
@@ -20,6 +20,10 @@ export class LoopCompaction {
20
20
  return Math.ceil(chars / 4);
21
21
  }
22
22
 
23
+ static frameTokensOf({ messages: _messages, ...frame }: LlmTurnRequest): number {
24
+ return Math.ceil(JSON.stringify(frame).length / 4);
25
+ }
26
+
23
27
  static #charsOf(message: AgentWireMessage): number {
24
28
  const own = LoopCompaction.#blanked(message.attachments);
25
29
  let images = own.images;
@@ -65,11 +65,13 @@ export type {
65
65
  DocumentStore,
66
66
  InsightSession,
67
67
  PostgresDatabaseConfig,
68
+ PrunedIndex,
68
69
  SearchConfig,
69
70
  SqlDialect,
70
71
  SqliteDatabaseConfig,
71
72
  SqlResultRows,
72
73
  TransferRow,
74
+ UndeclaredIndex,
73
75
  UpsertByIdOptions,
74
76
  } from "./sql/types";
75
77
  export { descriptorHash, stableJson } from "./sql/values";