@av-pi-studio/server 0.0.105 → 0.0.107

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/README.md CHANGED
@@ -69,7 +69,7 @@ From the monorepo root:
69
69
 
70
70
  ```bash
71
71
  npm install # install all workspace deps
72
- npm run build:server # build this package (compiles protocol + highlight first via project refs)
72
+ npm run build:server # build this package (compiles protocol first via project refs)
73
73
  ```
74
74
 
75
75
  Or build everything: `npm run build`.
@@ -214,6 +214,10 @@ export function createPiEventMapper() {
214
214
  case "error":
215
215
  return { kind: "error", message: str(event.message ?? event.error) };
216
216
  // ── Ignored (handled elsewhere / not surfaced as timeline events) ──
217
+ // `auto_retry_end` left Pi's *declared* session-event union in 0.85.0 but the shipped
218
+ // bundle still emits it, so the case stays. This switch is on a loose `string`, not Pi's
219
+ // union, so a `.d.ts` removal cannot break the build — verify against
220
+ // `dist/bundle/chunks/` before deleting a case here.
217
221
  case "turn_start":
218
222
  case "turn_end":
219
223
  case "message_start":
@@ -28,7 +28,7 @@ const PI_CLI_FALLBACKS = [join("dist", "bundle", "cli.js"), join("dist", "cli.js
28
28
  *
29
29
  * Reading the declared `bin` rather than hardcoding a path is deliberate: Pi moved it from
30
30
  * `dist/cli.js` to `dist/bundle/cli.js` in 0.84.4, and the dependency range intentionally accepts
31
- * future minor releases (`>=0.84.4 <1.0.0`), so a relocation must not silently fall back to a
31
+ * future minor releases (`>=0.85.1 <1.0.0`), so a relocation must not silently fall back to a
32
32
  * global `pi` — or to an entry upstream has stopped shipping.
33
33
  */
34
34
  function resolvePiCliInPackage(root) {
@@ -62,6 +62,7 @@ import { LoopService, } from "../orchestration/loop-service.js";
62
62
  import { registerOrchestrationHandlers } from "./orchestration-rpc.js";
63
63
  import { ExtensionsService } from "../extensions/extensions-service.js";
64
64
  import { registerExtensionsHandlers } from "../extensions/extensions-rpc.js";
65
+ import { registerViewerSettingsHandlers } from "../viewers/viewer-settings-rpc.js";
65
66
  import { SERVER_FEATURES, helloSchema, serverInfoPayloadSchema, statusSchema, } from "@av-pi-studio/protocol";
66
67
  import { connectRelay } from "./relay-transport.js";
67
68
  function resolveHome(opts) {
@@ -428,6 +429,12 @@ export function startDaemon(opts) {
428
429
  const fileWatchService = new FileWatchService({ logger });
429
430
  registerFileWatchHandlers(registry, { fileWatchService, subscriptions, logger });
430
431
  registerExtensionsHandlers(registry, { service: extensionsService, logger: extensionsLogger });
432
+ registerViewerSettingsHandlers(registry, {
433
+ home,
434
+ broadcast,
435
+ getActiveSessions,
436
+ logger: logger.child({ component: "viewer-settings" }),
437
+ });
431
438
  // ── Provider auth: remote-driven Pi login flows (sprint-055) ─────────────────
432
439
  const providerAuthLogger = logger.child({ component: "provider-auth" });
433
440
  const providerAuthRuntime = createPiAuthRuntime(resolvePiAuthPaths(config));
@@ -27,6 +27,7 @@ import { ProviderRegistry } from "../agent/provider-registry.js";
27
27
  import { FileExplorerService } from "../files/file-explorer.js";
28
28
  import { MAX_INLINE_FILE_READ_BYTES } from "../files/limits.js";
29
29
  import { createDaemonLogger } from "../logging/logger.js";
30
+ import { registerViewerSettingsHandlers } from "../viewers/viewer-settings-rpc.js";
30
31
  import { wrapSessionEnvelope } from "./bootstrap.js";
31
32
  /** Broadcast helper — see `bootstrap.ts`'s `wrapSessionEnvelope` for the full rationale. */
32
33
  function broadcast(sessions, message) {
@@ -108,6 +109,15 @@ export function startDevDaemon(opts) {
108
109
  const permissionService = new PermissionService({ manager, broadcast });
109
110
  permissionService.registerHandlers(registry, getActiveSessions);
110
111
  registerAgentUiHandlers(registry, { service: agentUiService, logger });
112
+ // Unlike extensions (production-only), this subsystem must exist in dev: the web client is
113
+ // developed against the dev daemon, and without it every dev session runs the
114
+ // capability-absent degrade path and can never exercise the toggle.
115
+ registerViewerSettingsHandlers(registry, {
116
+ home: "/tmp/pi-studio-dev",
117
+ broadcast,
118
+ getActiveSessions,
119
+ logger: logger.child({ component: "viewer-settings" }),
120
+ });
111
121
  // ── list_agents_request: minimal directory listing (not in scope elsewhere) ─
112
122
  registry.register("list_agents_request", (ctx) => {
113
123
  const agents = manager.list().map((m) => ({
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export declare const SERVER_PACKAGE: "@av-pi-studio/server";
2
- /** Proves the server consumes protocol + highlight emitted declarations. */
3
- export declare const SERVER_DEPS: readonly ["@av-pi-studio/protocol", "@av-pi-studio/highlight"];
2
+ /** Proves the server consumes protocol's emitted declarations. */
3
+ export declare const SERVER_DEPS: readonly ["@av-pi-studio/protocol"];
4
4
  export * from "./persistence/index.js";
5
5
  export * from "./config/index.js";
6
6
  export * from "./daemon/index.js";
package/dist/index.js CHANGED
@@ -1,9 +1,8 @@
1
1
  // @av-pi-studio/server — the daemon: WS API, agent supervision, stores, relay.
2
- import { HIGHLIGHT_PACKAGE } from "@av-pi-studio/highlight";
3
2
  import { PROTOCOL_PACKAGE } from "@av-pi-studio/protocol";
4
3
  export const SERVER_PACKAGE = "@av-pi-studio/server";
5
- /** Proves the server consumes protocol + highlight emitted declarations. */
6
- export const SERVER_DEPS = [PROTOCOL_PACKAGE, HIGHLIGHT_PACKAGE];
4
+ /** Proves the server consumes protocol's emitted declarations. */
5
+ export const SERVER_DEPS = [PROTOCOL_PACKAGE];
7
6
  // File-based JSON persistence (atomic store primitive + entity stores).
8
7
  export * from "./persistence/index.js";
9
8
  // Configuration (daemon config.json + per-project pi-studio.json).
@@ -0,0 +1,16 @@
1
+ import type { Logger } from "../logging/logger.js";
2
+ import type { HandlerRegistry } from "../ws/router.js";
3
+ import type { Session } from "../ws/session.js";
4
+ /**
5
+ * `viewer_settings_get`/`_set` RPCs + the `viewer_settings_update` broadcast
6
+ * (docs/MOLVIEWER_DECOUPLING.md § 4.4). Thin orchestration only — every decision (merge
7
+ * semantics, defaults, fallback direction) lives in `viewer-settings-state.ts`.
8
+ */
9
+ export interface ViewerSettingsRpcDeps {
10
+ home: string;
11
+ broadcast: (sessions: Iterable<Session>, message: unknown) => void;
12
+ getActiveSessions: () => Iterable<Session>;
13
+ logger?: Logger;
14
+ }
15
+ export declare function registerViewerSettingsHandlers(registry: HandlerRegistry, deps: ViewerSettingsRpcDeps): void;
16
+ //# sourceMappingURL=viewer-settings-rpc.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { applyViewerSettingsPatch, loadViewerSettings, saveViewerSettings, } from "./viewer-settings-state.js";
2
+ /** `ctx.message` is an unvalidated `Record<string, unknown>` (`ws/router.ts`), so the handler
3
+ * must check `patch`'s shape itself rather than trust the wire schema a conforming client used —
4
+ * same posture as `extensions-rpc.ts`'s `isSlugArray`. */
5
+ function isViewerSettingsPatch(value) {
6
+ if (typeof value !== "object" || value === null || Array.isArray(value))
7
+ return false;
8
+ return Object.values(value).every((entry) => {
9
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry))
10
+ return false;
11
+ const e = entry;
12
+ if ("enabled" in e && typeof e.enabled !== "boolean")
13
+ return false;
14
+ if ("config" in e &&
15
+ e.config !== undefined &&
16
+ (typeof e.config !== "object" || e.config === null || Array.isArray(e.config))) {
17
+ return false;
18
+ }
19
+ return true;
20
+ });
21
+ }
22
+ export function registerViewerSettingsHandlers(registry, deps) {
23
+ const { home, broadcast, getActiveSessions, logger } = deps;
24
+ // Serializes every successful `set`'s read-modify-write so two concurrent patches to two
25
+ // different viewer ids never race and lose one's update. "Last write wins" is the semantic
26
+ // rule for a single boolean; a lost update across two different ids is a bug wearing that
27
+ // semantic's clothes, not the semantic itself. A rejected link (a write failure) must not wedge
28
+ // the queue for later callers, so the chained promise always resolves regardless of outcome —
29
+ // only the caller's own awaited `run` promise carries the rejection.
30
+ let queue = Promise.resolve();
31
+ function enqueueSet(task) {
32
+ const run = queue.then(task, task);
33
+ queue = run.then(() => undefined, () => undefined);
34
+ return run;
35
+ }
36
+ registry.register("viewer_settings_get_request", async () => {
37
+ const settings = await loadViewerSettings(home, logger);
38
+ return { type: "viewer_settings_get_response", payload: { settings } };
39
+ });
40
+ registry.register("viewer_settings_set_request", async (ctx) => {
41
+ const patch = ctx.message.patch;
42
+ // A malformed `patch` is a domain failure, never a silent partial apply or a thrown
43
+ // `rpc_error` (transport-level only). The wire schema declares no `ok`/`error` channel on
44
+ // this response (unlike `provider_auth_*`/`extension_packs_*`), so the domain-failure
45
+ // answer is the current, unchanged document — a no-op the caller can observe by comparing
46
+ // it to the patch it sent. Only a client bypassing the protocol schema
47
+ // (`patch: Record<string, viewerSettingsPatchEntrySchema>`) can reach this path.
48
+ if (!isViewerSettingsPatch(patch)) {
49
+ logger?.warn({ patch }, "viewer_settings_set_request: rejecting malformed patch");
50
+ const settings = await loadViewerSettings(home, logger);
51
+ return { type: "viewer_settings_set_response", payload: { settings } };
52
+ }
53
+ const settings = await enqueueSet(async () => {
54
+ const current = await loadViewerSettings(home, logger);
55
+ const next = applyViewerSettingsPatch(current, patch);
56
+ await saveViewerSettings(home, next);
57
+ return next;
58
+ });
59
+ // Broadcast BEFORE answering (slash-command-operations.ts:216-221 ordering) — including the
60
+ // caller — so no session, not even this one, ever observes a success while its own cached
61
+ // copy is stale.
62
+ broadcast(getActiveSessions(), { type: "viewer_settings_update", settings });
63
+ return { type: "viewer_settings_set_response", payload: { settings } };
64
+ });
65
+ }
66
+ //# sourceMappingURL=viewer-settings-rpc.js.map
@@ -0,0 +1,37 @@
1
+ import { type ViewerSettings, type ViewerSettingsPatchEntry } from "@av-pi-studio/protocol";
2
+ import type { Logger } from "../logging/logger.js";
3
+ /**
4
+ * `$PI_STUDIO_HOME/viewer-settings.json` — the durable, per-viewer enable/disable document
5
+ * (docs/MOLVIEWER_DECOUPLING.md § 4.4). The daemon has zero plugin knowledge: rows are keyed by
6
+ * whatever id a client sends (no id enum, ever) and `config` is an opaque blob it never
7
+ * interprets — § 3's dependency rule (core never knows a specific plugin) applied to persistence.
8
+ */
9
+ export type ViewerSettingsPatch = Record<string, ViewerSettingsPatchEntry>;
10
+ export declare function viewerSettingsPath(home: string): string;
11
+ /**
12
+ * Load `viewer-settings.json`. Absent file, corrupt/partial JSON, or a schema mismatch → the
13
+ * all-enabled defaults (`{ version: 1, viewers: {} }`), with a `warn` log on a read failure
14
+ * (never on a merely-absent file — that is the ordinary first-boot state).
15
+ *
16
+ * Deliberately the **soft-fallback** contract, not `extensions-state.ts`'s `"unreadable"`
17
+ * sentinel: extensions must not silently re-offer a package after a corrupt read (an identity
18
+ * already offered must stay offered), whereas an unreadable viewer setting must degrade toward
19
+ * *offering* the viewer — the same direction every other viewer-settings degrade path takes
20
+ * (absent row, capability-free daemon, failed client fetch all mean "enabled";
21
+ * docs/MOLVIEWER_DECOUPLING.md § 4.4 rules). A corrupt file must never end up hiding a file
22
+ * behind a "which viewer can open this" decision.
23
+ *
24
+ * Hand-rolled (mirroring `extensions-state.ts`'s own manual read+parse) rather than the generic
25
+ * `loadStore` helper, which has no hook to log a distinct warning on a read failure versus an
26
+ * ordinary missing file.
27
+ */
28
+ export declare function loadViewerSettings(home: string, logger?: Logger): Promise<ViewerSettings>;
29
+ export declare function saveViewerSettings(home: string, settings: ViewerSettings): Promise<void>;
30
+ /**
31
+ * Pure per-viewer merge: a patch entry's present fields overwrite, absent fields are preserved
32
+ * from the current row. A viewer id not present in `current` is created, `enabled` defaulting to
33
+ * `true` when the patch omits it (absent-row-means-enabled applies to a brand new row too). No
34
+ * deletion semantics — a patch never removes a row.
35
+ */
36
+ export declare function applyViewerSettingsPatch(current: ViewerSettings, patch: ViewerSettingsPatch): ViewerSettings;
37
+ //# sourceMappingURL=viewer-settings-state.d.ts.map
@@ -0,0 +1,69 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { viewerSettingsSchema, } from "@av-pi-studio/protocol";
5
+ import { atomicWriteJson } from "../persistence/atomic-store.js";
6
+ const DEFAULT_SETTINGS = { version: 1, viewers: {} };
7
+ export function viewerSettingsPath(home) {
8
+ return join(home, "viewer-settings.json");
9
+ }
10
+ /**
11
+ * Load `viewer-settings.json`. Absent file, corrupt/partial JSON, or a schema mismatch → the
12
+ * all-enabled defaults (`{ version: 1, viewers: {} }`), with a `warn` log on a read failure
13
+ * (never on a merely-absent file — that is the ordinary first-boot state).
14
+ *
15
+ * Deliberately the **soft-fallback** contract, not `extensions-state.ts`'s `"unreadable"`
16
+ * sentinel: extensions must not silently re-offer a package after a corrupt read (an identity
17
+ * already offered must stay offered), whereas an unreadable viewer setting must degrade toward
18
+ * *offering* the viewer — the same direction every other viewer-settings degrade path takes
19
+ * (absent row, capability-free daemon, failed client fetch all mean "enabled";
20
+ * docs/MOLVIEWER_DECOUPLING.md § 4.4 rules). A corrupt file must never end up hiding a file
21
+ * behind a "which viewer can open this" decision.
22
+ *
23
+ * Hand-rolled (mirroring `extensions-state.ts`'s own manual read+parse) rather than the generic
24
+ * `loadStore` helper, which has no hook to log a distinct warning on a read failure versus an
25
+ * ordinary missing file.
26
+ */
27
+ export async function loadViewerSettings(home, logger) {
28
+ const path = viewerSettingsPath(home);
29
+ if (!existsSync(path))
30
+ return DEFAULT_SETTINGS;
31
+ let raw;
32
+ try {
33
+ raw = JSON.parse(await readFile(path, "utf8"));
34
+ }
35
+ catch (error) {
36
+ logger?.warn({ err: error?.message ?? String(error) }, "viewer-settings.json is corrupt JSON; degrading to all-enabled defaults");
37
+ return DEFAULT_SETTINGS;
38
+ }
39
+ const parsed = viewerSettingsSchema.safeParse(raw);
40
+ if (!parsed.success) {
41
+ logger?.warn({ issues: parsed.error.issues }, "viewer-settings.json failed schema validation; degrading to all-enabled defaults");
42
+ return DEFAULT_SETTINGS;
43
+ }
44
+ return parsed.data;
45
+ }
46
+ export async function saveViewerSettings(home, settings) {
47
+ await atomicWriteJson(viewerSettingsPath(home), settings, viewerSettingsSchema);
48
+ }
49
+ /**
50
+ * Pure per-viewer merge: a patch entry's present fields overwrite, absent fields are preserved
51
+ * from the current row. A viewer id not present in `current` is created, `enabled` defaulting to
52
+ * `true` when the patch omits it (absent-row-means-enabled applies to a brand new row too). No
53
+ * deletion semantics — a patch never removes a row.
54
+ */
55
+ export function applyViewerSettingsPatch(current, patch) {
56
+ const viewers = { ...current.viewers };
57
+ for (const [id, entryPatch] of Object.entries(patch)) {
58
+ const existing = viewers[id];
59
+ const entry = {
60
+ enabled: entryPatch.enabled ?? existing?.enabled ?? true,
61
+ };
62
+ const config = entryPatch.config ?? existing?.config;
63
+ if (config !== undefined)
64
+ entry.config = config;
65
+ viewers[id] = entry;
66
+ }
67
+ return { version: current.version, viewers };
68
+ }
69
+ //# sourceMappingURL=viewer-settings-state.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@av-pi-studio/server",
3
- "version": "0.0.105",
3
+ "version": "0.0.107",
4
4
  "bin": {
5
5
  "pi-studio-daemon": "dist/daemon/main.js"
6
6
  },
@@ -24,10 +24,9 @@
24
24
  "clean": "rm -rf dist *.tsbuildinfo"
25
25
  },
26
26
  "dependencies": {
27
- "@av-pi-studio/highlight": "^0.0.105",
28
- "@av-pi-studio/protocol": "^0.0.105",
29
- "@av-pi-studio/relay": "^0.0.105",
30
- "@earendil-works/pi-coding-agent": "^0.84.4",
27
+ "@av-pi-studio/protocol": "^0.0.107",
28
+ "@av-pi-studio/relay": "^0.0.107",
29
+ "@earendil-works/pi-coding-agent": ">=0.85.1 <1.0.0",
31
30
  "@xterm/addon-serialize": "^0.14.0",
32
31
  "@xterm/headless": "^6.0.0",
33
32
  "bcryptjs": "^3.0.3",