@av-pi-studio/server 0.0.106 → 0.0.108

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.
@@ -218,13 +218,13 @@ class PiAgentSession {
218
218
  });
219
219
  }
220
220
  /**
221
- * Send a `/command` prompt *correlated* (`request`, not `notify`) so Pi's own ack is observable:
222
- * Pi acks on preflight (dist/modes/rpc/rpc-mode.js `case "prompt"`), then `get_state.isStreaming`
223
- * — set synchronously as `_runAgentPrompt`'s first statement, hence already `true` for a real
224
- * turn by the time the ack reaches us — says whether a turn is actually running. Not streaming ⇒
225
- * the command was handled inline (extension command) and this turn is already over. A rejected
226
- * ack (no model, no auth, "Agent is already processing") now surfaces as a failed turn instead of
227
- * being silently dropped the way an unmatched `notify` response is (rpc-transport.ts `handleLine`).
221
+ * Send a `/command` prompt *correlated* (`request`, not `notify`) so Pi's own ack is observable.
222
+ * Pi acks on preflight with `data.disposition` (dist/modes/rpc/rpc-mode.js `case "prompt"`,
223
+ * Pi ≥ 0.99.0): `"handled"` ⇒ an extension command ran inline, no run started and no
224
+ * `agent_settled` will follow, so this turn is already over; `"started"`/`"queued"` ⇒ a run is
225
+ * (or will be) in flight, so await its terminal event. A rejected ack (no model, no auth, "Agent
226
+ * is already processing") surfaces as a failed turn instead of being silently dropped the way an
227
+ * unmatched `notify` response is (rpc-transport.ts `handleLine`).
228
228
  */
229
229
  async runSlashPrompt(prompt, opts) {
230
230
  let terminated = false;
@@ -242,14 +242,11 @@ class PiAgentSession {
242
242
  });
243
243
  try {
244
244
  const images = this.toPiImages(opts?.images);
245
- await this.transport.request("prompt", {
245
+ const ack = (await this.transport.request("prompt", {
246
246
  message: prompt,
247
247
  ...(images ? { images } : {}),
248
- });
249
- if (terminated)
250
- return;
251
- const state = (await this.transport.request("get_state"));
252
- if (state.isStreaming === false)
248
+ }));
249
+ if (terminated || ack?.disposition === "handled")
253
250
  return;
254
251
  await terminal;
255
252
  }
@@ -135,12 +135,15 @@ export function createPiEventMapper() {
135
135
  return null;
136
136
  }
137
137
  case "agent_settled": {
138
- // The true terminal (docs/rpc.md § agent_settled: Pi will not continue automatically
139
- // through retry, compaction retry, or queued follow-up messages past this point).
140
- const result = disposition === "failed"
141
- ? { kind: "turn_failed", error: error ?? "error" }
142
- : disposition === "canceled"
143
- ? { kind: "turn_canceled" }
138
+ // The true terminal (docs/json.md § Agent and turn events: Pi will not continue
139
+ // automatically through retry, compaction retry, or queued follow-up messages past this).
140
+ // `aborted` (Pi ≥ 1.1.0) is authoritative for a user abort and wins over the latch: an
141
+ // abort landing between runs — during an auto-retry backoff or a compaction — produces
142
+ // no `stopReason: "aborted"` message to latch, so the latch alone would misreport it.
143
+ const result = event.aborted === true || disposition === "canceled"
144
+ ? { kind: "turn_canceled" }
145
+ : disposition === "failed"
146
+ ? { kind: "turn_failed", error: error ?? "error" }
144
147
  : { kind: "turn_completed" };
145
148
  latch("completed");
146
149
  return result;
@@ -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) => ({
@@ -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.106",
3
+ "version": "0.0.108",
4
4
  "bin": {
5
5
  "pi-studio-daemon": "dist/daemon/main.js"
6
6
  },
@@ -24,9 +24,9 @@
24
24
  "clean": "rm -rf dist *.tsbuildinfo"
25
25
  },
26
26
  "dependencies": {
27
- "@av-pi-studio/protocol": "^0.0.106",
28
- "@av-pi-studio/relay": "^0.0.106",
29
- "@earendil-works/pi-coding-agent": ">=0.85.1 <1.0.0",
27
+ "@av-pi-studio/protocol": "^0.0.108",
28
+ "@av-pi-studio/relay": "^0.0.108",
29
+ "@earendil-works/pi-coding-agent": "^1.1.0",
30
30
  "@xterm/addon-serialize": "^0.14.0",
31
31
  "@xterm/headless": "^6.0.0",
32
32
  "bcryptjs": "^3.0.3",