antechamber 2.0.13 → 2.0.15

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 (50) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/approvals.js +2 -3
  3. package/dist/background-results.d.ts +0 -17
  4. package/dist/background-results.js +4 -4
  5. package/dist/cli.js +2 -1
  6. package/dist/commands/doctor.js +5 -4
  7. package/dist/commands/serve.js +3 -2
  8. package/dist/guards.d.ts +5 -0
  9. package/dist/guards.js +9 -0
  10. package/dist/http.d.ts +0 -2
  11. package/dist/http.js +3 -2
  12. package/dist/instructions.d.ts +17 -0
  13. package/dist/instructions.js +53 -0
  14. package/dist/mcp.d.ts +0 -4
  15. package/dist/mcp.js +3 -8
  16. package/dist/misc-routes.d.ts +1 -1
  17. package/dist/misc-routes.js +2 -2
  18. package/dist/monitor-sessions.d.ts +0 -2
  19. package/dist/monitor-sessions.js +7 -9
  20. package/dist/omo-shells.d.ts +0 -1
  21. package/dist/pi-rpc.d.ts +2 -2
  22. package/dist/pi-rpc.js +2 -1
  23. package/dist/proc-table-darwin.d.ts +2 -1
  24. package/dist/prompt-parts.js +7 -11
  25. package/dist/route-services.d.ts +3 -2
  26. package/dist/route-services.js +2 -1
  27. package/dist/routes-v2.js +5 -4
  28. package/dist/running-servers.d.ts +1 -1
  29. package/dist/self-update.d.ts +2 -3
  30. package/dist/self-update.js +4 -3
  31. package/dist/session-commands.js +2 -4
  32. package/dist/session-store.js +28 -30
  33. package/dist/sessions.d.ts +4 -1
  34. package/dist/sessions.js +32 -96
  35. package/dist/sse.d.ts +0 -2
  36. package/dist/sse.js +1 -1
  37. package/dist/subagents.d.ts +11 -1
  38. package/dist/subagents.js +46 -22
  39. package/dist/todo-bridge.d.ts +0 -2
  40. package/dist/todo-bridge.js +11 -13
  41. package/dist/tool-map.d.ts +1 -1
  42. package/dist/tool-map.js +19 -21
  43. package/dist/types.d.ts +8 -32
  44. package/dist/v2.d.ts +2 -7
  45. package/dist/v2.js +1 -1
  46. package/dist/vcs.js +2 -1
  47. package/dist/work-status.d.ts +2 -8
  48. package/dist/work-status.js +18 -20
  49. package/extensions/antechamber/package.json +1 -1
  50. package/package.json +4 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,18 @@ and this project uses [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.0.15] - 2026-11-23
11
+
12
+ ### Fixed
13
+
14
+ - Subagent sessions whose parent session was deleted or never saved no longer show up in OpenChamber as top-level
15
+ sessions that only say "Full transcript is unavailable". The registry kept their rows, and every session list
16
+ rebuilt them without checking that the parent still existed.
17
+
18
+ ## [2.0.14] - 2026-11-23
19
+
20
+ - refactor: consolidate shared guards, extract instruction delivery, gate dead code with knip (#107)
21
+
10
22
  ## [2.0.13] - 2026-11-23
11
23
 
12
24
  ### Changed
package/dist/approvals.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { isRecord } from "./guards.js";
2
3
  export class ApprovalInputError extends Error {
3
4
  }
4
5
  const MAX_SETTLED_STRUCTURED_QUESTIONS = 256;
5
6
  function record(value) {
6
- return typeof value === "object" && value !== null && !Array.isArray(value)
7
- ? value
8
- : undefined;
7
+ return isRecord(value) ? value : undefined;
9
8
  }
10
9
  export function extensionUiRequestFrom(value) {
11
10
  const { id, method, title, options, toolCallId, timeout } = value;
@@ -12,22 +12,6 @@ export interface BackgroundResult {
12
12
  }
13
13
  /** Raw RPC capture of installed omo-ai 5.1.33 / senpi runtime, 2026-10-17. */
14
14
  export declare function backgroundResult(customType: unknown, content: unknown): BackgroundResult | undefined;
15
- /** Retain only the command needed to label a later terminal completion. */
16
- export declare function backgroundCommands(result: ToolResult): {
17
- backgroundCommands?: Record<string, string>;
18
- };
19
- export declare function launchedShells(text: string): string[];
20
- /**
21
- * What a tool result leaves running: the background shells it started, and the eval cell
22
- * itself when it detached. The card keeps running until each one reports finishing.
23
- */
24
- export declare function backgroundWaits(callID: string, text: string, commands?: Record<string, unknown>): string[];
25
- interface Final {
26
- output: string;
27
- failed: boolean;
28
- }
29
- /** Keep a finished card running, with its result already shown, until `waits` report finishing. */
30
- export declare function holdForBackground(part: OCToolPart, waits: string[], final: Final, agentStartedAtMs?: number): void;
31
15
  /** `id` finished at `at`: drop it from every card waiting on it; cards left with nothing to wait on end. */
32
16
  export declare function releaseBackground(messages: readonly OCMessageWithParts[], id: string, at: number): OCToolPart[];
33
17
  /** Nothing can still be running (the agent exited, or history is rebuilt): end every waiting card. */
@@ -48,4 +32,3 @@ export declare function backgroundMessage(s: Pick<ManagedSession, "info" | "mess
48
32
  model: OCModelRef;
49
33
  agent: string;
50
34
  }): OCMessageWithParts;
51
- export {};
@@ -37,7 +37,7 @@ export function backgroundResult(customType, content) {
37
37
  };
38
38
  }
39
39
  /** Retain only the command needed to label a later terminal completion. */
40
- export function backgroundCommands(result) {
40
+ function backgroundCommands(result) {
41
41
  const details = result.details;
42
42
  if (details === null || typeof details !== "object" || !("toolCalls" in details))
43
43
  return {};
@@ -57,14 +57,14 @@ export function backgroundCommands(result) {
57
57
  * trimmed to its tail, which can cut the "with ID" line and leave only the bash_output hint.
58
58
  */
59
59
  const LAUNCHED = /\b(?:running in background|auto-detached to background) with ID:\s*(bash_\d+)\b|Use bash_output\(\{ bash_id: "(bash_\d+)" \}\) only to peek/g;
60
- export function launchedShells(text) {
60
+ function launchedShells(text) {
61
61
  return [...new Set([...text.matchAll(LAUNCHED)].map((match) => match[1] ?? match[2] ?? "").filter(Boolean))];
62
62
  }
63
63
  /**
64
64
  * What a tool result leaves running: the background shells it started, and the eval cell
65
65
  * itself when it detached. The card keeps running until each one reports finishing.
66
66
  */
67
- export function backgroundWaits(callID, text, commands = {}) {
67
+ function backgroundWaits(callID, text, commands = {}) {
68
68
  const waits = new Set();
69
69
  for (const id of launchedShells(text))
70
70
  waits.add(id);
@@ -89,7 +89,7 @@ function backgroundShellID(callID, waits, agentStartedAtMs) {
89
89
  return shell !== undefined && agentStartedAtMs !== undefined ? terminalShellId(agentStartedAtMs, shell) : undefined;
90
90
  }
91
91
  /** Keep a finished card running, with its result already shown, until `waits` report finishing. */
92
- export function holdForBackground(part, waits, final, agentStartedAtMs) {
92
+ function holdForBackground(part, waits, final, agentStartedAtMs) {
93
93
  const state = part.state;
94
94
  if (state.status === "pending" || waits.length === 0)
95
95
  return;
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@
2
2
  /** CLI parsing and dispatch. Server code is loaded only for serve/default mode. */
3
3
  import { parseArgs } from "node:util";
4
4
  import { ADAPTER_VERSION, OPENCODE_API_VERSION } from "./version.js";
5
+ import { errorMessage } from "./guards.js";
5
6
  try {
6
7
  const argv = process.argv.slice(2);
7
8
  // Keep this probe byte-identical: OpenChamber expects an OpenCode 2.x version.
@@ -92,6 +93,6 @@ try {
92
93
  }
93
94
  }
94
95
  catch (error) {
95
- console.error(`antechamber: ${error instanceof Error ? error.message : String(error)}`);
96
+ console.error(`antechamber: ${errorMessage(error)}`);
96
97
  process.exitCode = 1;
97
98
  }
@@ -7,6 +7,7 @@ import { readRunningServers } from "../running-servers.js";
7
7
  import { isNewerVersion } from "../self-update.js";
8
8
  import { ADAPTER_VERSION } from "../version.js";
9
9
  import { autoUpdateLauncherPath, autoUpdateLauncherTarget, createContext, isPackageBinary, readSettings, resolveBinary, settingsPath, } from "./context.js";
10
+ import { errorMessage } from "../guards.js";
10
11
  /** EPERM means the process exists under another user. */
11
12
  function processAlive(pid) {
12
13
  try {
@@ -34,7 +35,7 @@ export function doctor(options = {}, ctx = createContext(), latestVersion) {
34
35
  add("backend", "PASS", `${binary}: ${ctx.exec(binary, ["--version"]) || "version command succeeded"}`);
35
36
  }
36
37
  catch (error) {
37
- add("backend", "FAIL", `${binary}: ${error instanceof Error ? error.message : String(error)}`);
38
+ add("backend", "FAIL", `${binary}: ${errorMessage(error)}`);
38
39
  }
39
40
  }
40
41
  add("backend-kind", isPlainPi(ctx.env) ? "WARN" : "PASS", isPlainPi(ctx.env)
@@ -54,7 +55,7 @@ export function doctor(options = {}, ctx = createContext(), latestVersion) {
54
55
  add("state-dir", "PASS", `${stateDir}${ancestor === stateDir ? " is writable" : ` can be created under writable ${ancestor}`}`);
55
56
  }
56
57
  catch (error) {
57
- add("state-dir", "FAIL", `${stateDir}: ${error instanceof Error ? error.message : String(error)}`);
58
+ add("state-dir", "FAIL", `${stateDir}: ${errorMessage(error)}`);
58
59
  }
59
60
  const latest = typeof latestVersion === "string" ? latestVersion : undefined;
60
61
  if (latestVersion instanceof Error)
@@ -102,7 +103,7 @@ export function doctor(options = {}, ctx = createContext(), latestVersion) {
102
103
  add("openchamber", "PASS", `${openchamber}: ${ctx.exec(openchamber, ["--version"]) || "version not reported"}`);
103
104
  }
104
105
  catch (error) {
105
- add("openchamber", "WARN", `${openchamber}: version not determinable (${error instanceof Error ? error.message : String(error)})`);
106
+ add("openchamber", "WARN", `${openchamber}: version not determinable (${errorMessage(error)})`);
106
107
  }
107
108
  }
108
109
  const settings = settingsPath(options, ctx);
@@ -120,7 +121,7 @@ export function doctor(options = {}, ctx = createContext(), latestVersion) {
120
121
  add("openchamber-settings", matches ? "PASS" : "WARN", `${settings}: opencodeBinary=${JSON.stringify(configured ?? null)}${viaLauncher ? ` (auto-update launcher for ${launcherTarget})` : matches ? "" : "; does not point at this antechamber installation"}`);
121
122
  }
122
123
  catch (error) {
123
- add("openchamber-settings", "WARN", error instanceof Error ? error.message : String(error));
124
+ add("openchamber-settings", "WARN", errorMessage(error));
124
125
  }
125
126
  }
126
127
  add("auth", "INFO", `OPENCODE_SERVER_PASSWORD is ${ctx.env.OPENCODE_SERVER_PASSWORD ? "set" : "not set"}`);
@@ -5,6 +5,7 @@ import { recordRunningServer } from "../running-servers.js";
5
5
  import { selfUpdate } from "../self-update.js";
6
6
  import { AdapterServer, isLoopbackHost, serverPassword } from "../server.js";
7
7
  import { ADAPTER_VERSION } from "../version.js";
8
+ import { errorMessage } from "../guards.js";
8
9
  export async function serve(options) {
9
10
  const { port, host, directory, insecureNoAuth, compatible } = options;
10
11
  if (!isLoopbackHost(host) &&
@@ -38,7 +39,7 @@ export async function serve(options) {
38
39
  }
39
40
  catch (error) {
40
41
  // Doctor and the OmO Work extension read the record; serving must not depend on it.
41
- console.error(`antechamber: cannot record the running version: ${error instanceof Error ? error.message : String(error)}`);
42
+ console.error(`antechamber: cannot record the running version: ${errorMessage(error)}`);
42
43
  }
43
44
  if (compatible)
44
45
  console.log(`opencode server listening on ${server.url}`);
@@ -57,6 +58,6 @@ async function autoUpdate() {
57
58
  console.error(`antechamber: auto-update installed ${result.to} (running ${result.from}); it starts next time`);
58
59
  }
59
60
  catch (error) {
60
- console.error(`antechamber: auto-update skipped: ${error instanceof Error ? error.message : String(error)}`);
61
+ console.error(`antechamber: auto-update skipped: ${errorMessage(error)}`);
61
62
  }
62
63
  }
@@ -0,0 +1,5 @@
1
+ /** Small type guards shared across modules that parse untrusted JSON (RPC frames, request bodies, JSONL). */
2
+ /** A plain object: not null and not an array. */
3
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
4
+ /** The message of a thrown value, which may not be an `Error`. */
5
+ export declare function errorMessage(error: unknown): string;
package/dist/guards.js ADDED
@@ -0,0 +1,9 @@
1
+ /** Small type guards shared across modules that parse untrusted JSON (RPC frames, request bodies, JSONL). */
2
+ /** A plain object: not null and not an array. */
3
+ export function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /** The message of a thrown value, which may not be an `Error`. */
7
+ export function errorMessage(error) {
8
+ return error instanceof Error ? error.message : String(error);
9
+ }
package/dist/http.d.ts CHANGED
@@ -13,8 +13,6 @@ export declare function errorBody(name: string, message: string): {
13
13
  };
14
14
  };
15
15
  export declare function json(res: ServerResponse, status: number, body: unknown): void;
16
- /** Routes the OmO Work extension service calls with the run-record token instead of the server password. */
17
- export declare const EXTENSION_ROUTE_PREFIX = "/antechamber/work-status/";
18
16
  export declare class Http {
19
17
  private serverOrigin?;
20
18
  private readonly credentials;
package/dist/http.js CHANGED
@@ -3,6 +3,7 @@ import { createHash, timingSafeEqual } from "node:crypto";
3
3
  import { ApprovalInputError } from "./approvals.js";
4
4
  import { envSetting } from "./config.js";
5
5
  import { UpstreamProtocolError } from "./pi-rpc.js";
6
+ import { errorMessage } from "./guards.js";
6
7
  const DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024;
7
8
  export class RequestBodyError extends Error {
8
9
  status;
@@ -46,7 +47,7 @@ export function json(res, status, body) {
46
47
  res.writeHead(status, { "Content-Type": "application/json" }).end(payload);
47
48
  }
48
49
  /** Routes the OmO Work extension service calls with the run-record token instead of the server password. */
49
- export const EXTENSION_ROUTE_PREFIX = "/antechamber/work-status/";
50
+ const EXTENSION_ROUTE_PREFIX = "/antechamber/work-status/";
50
51
  export class Http {
51
52
  serverOrigin;
52
53
  credentials;
@@ -104,7 +105,7 @@ export class Http {
104
105
  await handle();
105
106
  }
106
107
  catch (err) {
107
- const message = err instanceof Error ? err.message : String(err);
108
+ const message = errorMessage(err);
108
109
  if (err instanceof RequestBodyError && err.status === 413) {
109
110
  res.setHeader("Connection", "close");
110
111
  res.once("finish", () => req.destroy());
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Session instructions (`PUT /api/session/:id/instructions/:key`) reach the model as hidden
3
+ * `antechamber.instructions` custom messages appended to the native conversation.
4
+ */
5
+ import type { InstructionEntryState } from "./session-store.js";
6
+ import type { TreeEntry } from "./session-tree.js";
7
+ export declare const INSTRUCTIONS_CUSTOM_TYPE = "antechamber.instructions";
8
+ /** The instruction map the model holds on this branch: the last delivery inside the newest compaction's kept range. */
9
+ export declare function deliveredInstructions(branch: TreeEntry[]): Record<string, unknown>;
10
+ /**
11
+ * The message that brings the model from `delivered` to `instructions`, with the full map it then holds, or
12
+ * undefined when nothing changed. Keys are sent in sorted order so the text is deterministic.
13
+ */
14
+ export declare function instructionDelivery(instructions: Record<string, InstructionEntryState>, delivered: Record<string, unknown>): {
15
+ text: string;
16
+ snapshot: Record<string, unknown>;
17
+ } | undefined;
@@ -0,0 +1,53 @@
1
+ export const INSTRUCTIONS_CUSTOM_TYPE = "antechamber.instructions";
2
+ /** The instruction map the model holds on this branch: the last delivery inside the newest compaction's kept range. */
3
+ export function deliveredInstructions(branch) {
4
+ let start = 0;
5
+ for (let index = branch.length - 1; index >= 0; index--) {
6
+ const entry = branch[index];
7
+ if (entry.type !== "compaction")
8
+ continue;
9
+ const kept = branch.findIndex((candidate) => candidate.id === entry.firstKeptEntryId);
10
+ start = kept >= 0 ? kept : index + 1;
11
+ break;
12
+ }
13
+ for (let index = branch.length - 1; index >= start; index--) {
14
+ const entry = branch[index];
15
+ if (entry?.type !== "custom_message" || entry.customType !== INSTRUCTIONS_CUSTOM_TYPE)
16
+ continue;
17
+ const details = entry.details;
18
+ if (details?.instructions !== null && typeof details?.instructions === "object")
19
+ return { ...details.instructions };
20
+ }
21
+ return {};
22
+ }
23
+ /**
24
+ * The message that brings the model from `delivered` to `instructions`, with the full map it then holds, or
25
+ * undefined when nothing changed. Keys are sent in sorted order so the text is deterministic.
26
+ */
27
+ export function instructionDelivery(instructions, delivered) {
28
+ const pending = Object.entries(instructions)
29
+ .filter(([key, entry]) => entry.removed
30
+ ? key in delivered
31
+ : !(key in delivered) || JSON.stringify(entry.value) !== JSON.stringify(delivered[key]))
32
+ .sort(([left], [right]) => left.localeCompare(right));
33
+ if (pending.length === 0)
34
+ return undefined;
35
+ const text = pending
36
+ .map(([key, entry]) => {
37
+ if (entry.removed)
38
+ return `The context under "${key}" no longer applies. Disregard it.`;
39
+ const block = `<context key="${key}">\n${typeof entry.value === "string" ? entry.value : JSON.stringify(entry.value, null, 2)}\n</context>`;
40
+ return key in delivered
41
+ ? `The context under "${key}" changed and supersedes the previous value:\n${block}`
42
+ : block;
43
+ })
44
+ .join("\n\n");
45
+ const snapshot = { ...delivered };
46
+ for (const [key, entry] of pending) {
47
+ if (entry.removed)
48
+ delete snapshot[key];
49
+ else
50
+ snapshot[key] = entry.value;
51
+ }
52
+ return { text, snapshot };
53
+ }
package/dist/mcp.d.ts CHANGED
@@ -60,8 +60,6 @@ interface RouteResult {
60
60
  status: number;
61
61
  body?: unknown;
62
62
  }
63
- /** OmO's loopback listener gives up after 5 minutes; leave room for the reconnect that follows. */
64
- export declare const MCP_AUTH_COMMAND_TIMEOUT_MS: number;
65
63
  /** OmO's runtime states fold onto OpenCode's; lazy servers are usable, so they read as connected. */
66
64
  export declare function openCodeMcpStatus(server: OmoMcpServer): OCMcpStatus;
67
65
  export declare function v2McpStatus(server: OmoMcpServer): V2McpStatus;
@@ -77,8 +75,6 @@ export declare function waitForMcpServers(pi: PiRpcClient, budgetMs: number, sig
77
75
  * again: with the cross-directory fallback, one agent can change the answer for all of them.
78
76
  */
79
77
  export declare function mcpSurfacesChanged(broadcast: RouteServices["broadcast"]): void;
80
- /** The URL OmO prints on its own line after naming the server (`auth` and `auth-start` both do). */
81
- export declare function authorizationUrl(text: string, name: string): string | undefined;
82
78
  /**
83
79
  * The redirect `/mcp auth-complete` expects. OpenChamber sends either the bare code (callback
84
80
  * page, v1 paste box) or the whole redirect address; a bare code is rebuilt from the
package/dist/mcp.js CHANGED
@@ -26,12 +26,13 @@
26
26
  import { randomUUID } from "node:crypto";
27
27
  import { errorBody } from "./http.js";
28
28
  import { PiRpcClient } from "./pi-rpc.js";
29
+ import { errorMessage, isRecord } from "./guards.js";
29
30
  /** Bounds how long an HTTP caller waits on a read-only RPC; the transport keeps its own budget. */
30
31
  const MCP_READ_WAIT_MS = 5_000;
31
32
  /** OmO announces the authorization URL before it waits for the browser. */
32
33
  const MCP_AUTH_URL_WAIT_MS = 30_000;
33
34
  /** OmO's loopback listener gives up after 5 minutes; leave room for the reconnect that follows. */
34
- export const MCP_AUTH_COMMAND_TIMEOUT_MS = 10 * 60_000;
35
+ const MCP_AUTH_COMMAND_TIMEOUT_MS = 10 * 60_000;
35
36
  /** A pending paste flow is forgotten after this; OmO's own state is replaced by the next start. */
36
37
  const MCP_AUTH_ATTEMPT_TTL_MS = 10 * 60_000;
37
38
  /** Names are passed as one slash-command argument, so they must not split or quote. */
@@ -51,12 +52,6 @@ const watchedDirectories = new Set();
51
52
  const inventories = new Map();
52
53
  const inventoryAgents = new Set();
53
54
  let changeTimer;
54
- function isRecord(value) {
55
- return typeof value === "object" && value !== null && !Array.isArray(value);
56
- }
57
- function errorMessage(error) {
58
- return error instanceof Error ? error.message : String(error);
59
- }
60
55
  const flowKey = (directory, name) => `${directory}\0${name}`;
61
56
  /** OmO's runtime states fold onto OpenCode's; lazy servers are usable, so they read as connected. */
62
57
  export function openCodeMcpStatus(server) {
@@ -215,7 +210,7 @@ async function mcpCommandName(pi) {
215
210
  return (commands.find((command) => command.builtin) ?? commands.find((command) => command.name === "mcp"))?.name;
216
211
  }
217
212
  /** The URL OmO prints on its own line after naming the server (`auth` and `auth-start` both do). */
218
- export function authorizationUrl(text, name) {
213
+ function authorizationUrl(text, name) {
219
214
  if (!text.includes(name))
220
215
  return undefined;
221
216
  const candidate = /(?:^|\n)(https?:\/\/\S+)/.exec(text)?.[1];
@@ -1,4 +1,3 @@
1
- export { errorBody } from "./http.js";
2
1
  /** One shared failure latch for HTTP and agent-event diagnostics. */
3
2
  export declare function debugLog(line: string): void;
4
3
  interface RouteResult {
@@ -6,3 +5,4 @@ interface RouteResult {
6
5
  body: unknown;
7
6
  }
8
7
  export declare function miscRoute(method: string, path: string, url: URL, directory: string): Promise<RouteResult | undefined>;
8
+ export {};
@@ -3,8 +3,8 @@ import { opendir, realpath } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { envSetting } from "./config.js";
6
+ import { errorMessage } from "./guards.js";
6
7
  import { errorBody } from "./http.js";
7
- export { errorBody } from "./http.js";
8
8
  let loggingDisabled = false;
9
9
  const MAX_DIRECTORY_ENTRIES = 1000;
10
10
  const MAX_SEARCH_DIRECTORIES = 1024;
@@ -19,7 +19,7 @@ export function debugLog(line) {
19
19
  }
20
20
  catch (error) {
21
21
  loggingDisabled = true;
22
- console.error(`[debug] logging disabled: ${error instanceof Error ? error.message : String(error)}`);
22
+ console.error(`[debug] logging disabled: ${errorMessage(error)}`);
23
23
  }
24
24
  }
25
25
  function unsupported(message) {
@@ -30,8 +30,6 @@ export interface MonitorView {
30
30
  };
31
31
  lines: string[];
32
32
  }
33
- export declare function parseMonitor(value: unknown): MonitorSnapshot | undefined;
34
- export declare function monitorSummary(monitor: MonitorSnapshot, ending?: MonitorEnding): string;
35
33
  export declare class MonitorSessions {
36
34
  private readonly sessions;
37
35
  private readonly emit;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { getAgentName } from "./agent-name.js";
7
7
  import { ocIdFor } from "./session-store.js";
8
+ import { isRecord } from "./guards.js";
8
9
  /** Names OmO's terminal extension passes to `pi.rpc.emit` (core/extensions/builtin/monitor-state-event.js). */
9
10
  export const MONITOR_STATE_EVENT = "terminal_monitor_state";
10
11
  export const MONITOR_ENDED_EVENT = "terminal_monitor_ended";
@@ -12,17 +13,14 @@ export const MONITOR_ENDED_EVENT = "terminal_monitor_ended";
12
13
  export const MONITOR_NOTIFICATION = "senpi-monitor:notification";
13
14
  /** Matched lines kept per watch; older lines are dropped. */
14
15
  const MAX_EVENT_LINES = 200;
15
- function record(value) {
16
- return value !== null && typeof value === "object" && !Array.isArray(value);
17
- }
18
16
  function finite(value) {
19
17
  return typeof value === "number" && Number.isFinite(value) ? value : null;
20
18
  }
21
19
  function text(value) {
22
20
  return typeof value === "string" && value !== "" ? value : null;
23
21
  }
24
- export function parseMonitor(value) {
25
- if (!record(value) || typeof value.id !== "string" || value.id === "")
22
+ function parseMonitor(value) {
23
+ if (!isRecord(value) || typeof value.id !== "string" || value.id === "")
26
24
  return undefined;
27
25
  const startedAtMs = finite(value.startedAtMs);
28
26
  if (startedAtMs === null)
@@ -59,7 +57,7 @@ function endingLabel(ending) {
59
57
  function iso(ms) {
60
58
  return ms === null ? undefined : new Date(ms).toISOString();
61
59
  }
62
- export function monitorSummary(monitor, ending) {
60
+ function monitorSummary(monitor, ending) {
63
61
  const deadline = monitor.persistent ? "none (persistent)" : iso(monitor.deadlineMs);
64
62
  return [
65
63
  `Status: ${ending ? endingLabel(ending) : monitor.paused ? "paused" : "watching"}`,
@@ -119,7 +117,7 @@ export class MonitorSessions {
119
117
  return this.watches.get(id)?.session.messages ?? [];
120
118
  }
121
119
  observe(parent, ev) {
122
- if (!record(ev.data))
120
+ if (!isRecord(ev.data))
123
121
  return;
124
122
  if (ev.name === MONITOR_STATE_EVENT && Array.isArray(ev.data.monitors))
125
123
  this.applyState(parent, ev.data.monitors);
@@ -128,7 +126,7 @@ export class MonitorSessions {
128
126
  }
129
127
  /** A hidden `senpi-monitor:notification` custom message: append its lines to each watch it names. */
130
128
  notify(parent, message) {
131
- if (typeof message.content !== "string" || !record(message.details) || !Array.isArray(message.details.monitors))
129
+ if (typeof message.content !== "string" || !isRecord(message.details) || !Array.isArray(message.details.monitors))
132
130
  return;
133
131
  const lines = message.content
134
132
  .replaceAll(/<\/?system-reminder>/g, "")
@@ -138,7 +136,7 @@ export class MonitorSessions {
138
136
  if (lines.length === 0)
139
137
  return;
140
138
  for (const entry of message.details.monitors) {
141
- if (!record(entry) || typeof entry.id !== "string")
139
+ if (!isRecord(entry) || typeof entry.id !== "string")
142
140
  continue;
143
141
  const watch = this.watches.get(this.childID(parent, entry.id));
144
142
  if (!watch)
@@ -23,7 +23,6 @@ import type { OCEvent, OCShellInfo } from "./types.js";
23
23
  import { type WorkStatusBridge } from "./work-status.js";
24
24
  /** Metadata key OpenChamber puts on the note it sends before stopping commands (background-shell.ts). */
25
25
  export declare const SHELL_CANCELLATION_KEY = "openchamberShellCancellation";
26
- export type OmoShellKind = "monitor" | "background" | "eval";
27
26
  export declare function terminalShellId(agentStartedAtMs: number, bashId: string): string;
28
27
  export declare function evalShellId(cellId: string): string;
29
28
  export interface ShellOutputPage {
package/dist/pi-rpc.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  import { EventEmitter } from "node:events";
11
11
  import { type LifecycleClock } from "./lifecycle.js";
12
12
  import { type ProcessTable } from "./proc-table.js";
13
- export type { ProcessIdentity, ProcessTable } from "./proc-table.js";
13
+ export type { ProcessTable } from "./proc-table.js";
14
14
  export interface PiRpcCommand {
15
15
  id?: string;
16
16
  type: string;
@@ -33,7 +33,7 @@ export declare class UpstreamProtocolError extends Error {
33
33
  */
34
34
  export declare const AGENT_OOM_SCORE_ADJ_MARGIN = 300;
35
35
  /** Why the agent stopped without antechamber disposing it on purpose (eviction, delete, shutdown). */
36
- export type PiStopReason = {
36
+ type PiStopReason = {
37
37
  readonly kind: "timeout";
38
38
  readonly command: string;
39
39
  readonly ms: number;
package/dist/pi-rpc.js CHANGED
@@ -16,6 +16,7 @@ import { constants as osConstants } from "node:os";
16
16
  import { systemClock } from "./lifecycle.js";
17
17
  import { agentBinary, envSetting } from "./config.js";
18
18
  import { createProcessTable } from "./proc-table.js";
19
+ import { errorMessage } from "./guards.js";
19
20
  export const RPC_COMMAND_TIMEOUT_MS = 60_000;
20
21
  /**
21
22
  * `compact` answers only when the summary is written. OmO bounds one compaction by
@@ -253,7 +254,7 @@ export class PiRpcClient extends EventEmitter {
253
254
  this.stopped ??= reason;
254
255
  this.failAll(new PiStoppedError(reason, cause));
255
256
  void this.dispose().catch((disposeError) => {
256
- const message = disposeError instanceof Error ? disposeError.message : String(disposeError);
257
+ const message = errorMessage(disposeError);
257
258
  console.error(`[pi-rpc] failed to dispose after transport failure: ${message}`);
258
259
  });
259
260
  }
@@ -14,10 +14,11 @@ export type PsRunner = (args: readonly string[]) => string;
14
14
  */
15
15
  export declare function runPs(args: readonly string[]): string;
16
16
  /** One `ps -A` row with its state and argv, for callers that match processes by command line. */
17
- export interface PsProcess extends ProcessIdentity {
17
+ interface PsProcess extends ProcessIdentity {
18
18
  readonly state: string;
19
19
  readonly args: string;
20
20
  }
21
21
  /** Every live (non-zombie) process with its argv. Throws when `ps` fails, so the caller decides. */
22
22
  export declare function listDarwinProcesses(run?: PsRunner): PsProcess[];
23
23
  export declare function createDarwinProcTable(run?: PsRunner): ProcessTable;
24
+ export {};
@@ -5,6 +5,7 @@ import { basename, join, resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { defaultStateDir, envSetting } from "./config.js";
7
7
  import { RequestBodyError } from "./http.js";
8
+ import { isRecord } from "./guards.js";
8
9
  export function isPromptPart(value) {
9
10
  if (typeof value !== "object" || value === null || !("type" in value))
10
11
  return false;
@@ -44,9 +45,6 @@ export function parsePromptParts(value) {
44
45
  throw new RequestBodyError(400, "parts must contain supported text, file, or agent inputs");
45
46
  return value;
46
47
  }
47
- function plainRecord(value) {
48
- return typeof value === "object" && value !== null && !Array.isArray(value);
49
- }
50
48
  /** OpenChamber 2.x attachments (`files: [{uri, name?}]`, `agents: [{name, mention?}]`) as prompt parts. */
51
49
  export function v2PromptParts(text, files, agents) {
52
50
  const parts = text === "" ? [] : [{ type: "text", text }];
@@ -54,9 +52,7 @@ export function v2PromptParts(text, files, agents) {
54
52
  if (!Array.isArray(files))
55
53
  throw new RequestBodyError(400, "files must be an array");
56
54
  for (const file of files) {
57
- if (!plainRecord(file) ||
58
- typeof file.uri !== "string" ||
59
- (file.name !== undefined && typeof file.name !== "string"))
55
+ if (!isRecord(file) || typeof file.uri !== "string" || (file.name !== undefined && typeof file.name !== "string"))
60
56
  throw new RequestBodyError(400, "files must contain {uri, name?} attachments");
61
57
  // v2 carries no MIME type; an inline data URI still names its own.
62
58
  const mime = /^data:([^;,]+)/.exec(file.uri)?.[1] ?? "application/octet-stream";
@@ -72,11 +68,11 @@ export function v2PromptParts(text, files, agents) {
72
68
  if (!Array.isArray(agents))
73
69
  throw new RequestBodyError(400, "agents must be an array");
74
70
  for (const agent of agents) {
75
- const mention = plainRecord(agent) ? agent.mention : undefined;
76
- if (!plainRecord(agent) ||
71
+ const mention = isRecord(agent) ? agent.mention : undefined;
72
+ if (!isRecord(agent) ||
77
73
  typeof agent.name !== "string" ||
78
74
  (mention !== undefined &&
79
- (!plainRecord(mention) ||
75
+ (!isRecord(mention) ||
80
76
  typeof mention.start !== "number" ||
81
77
  typeof mention.end !== "number" ||
82
78
  typeof mention.text !== "string")))
@@ -84,7 +80,7 @@ export function v2PromptParts(text, files, agents) {
84
80
  parts.push({
85
81
  type: "agent",
86
82
  name: agent.name,
87
- ...(plainRecord(mention) &&
83
+ ...(isRecord(mention) &&
88
84
  typeof mention.text === "string" &&
89
85
  typeof mention.start === "number" &&
90
86
  typeof mention.end === "number"
@@ -122,7 +118,7 @@ export function v2PromptAttachments(parts) {
122
118
  export const CONTEXT_MESSAGE_TYPE = "antechamber.context";
123
119
  /** The OpenChamber message id of a native context entry, if the entry is one. */
124
120
  export function contextMessageID(entry) {
125
- if (entry.type !== "custom_message" || entry.customType !== CONTEXT_MESSAGE_TYPE || !plainRecord(entry.details))
121
+ if (entry.type !== "custom_message" || entry.customType !== CONTEXT_MESSAGE_TYPE || !isRecord(entry.details))
126
122
  return undefined;
127
123
  return typeof entry.details.messageID === "string" ? entry.details.messageID : undefined;
128
124
  }
@@ -33,7 +33,7 @@ export declare function modelRefFromBody(model: {
33
33
  } | undefined, variant?: string): ModelSelection | undefined;
34
34
  /** Both async APIs acknowledge admission; failures must reach SSE and history. */
35
35
  export declare function promptAsync(services: RouteServices, session: ManagedSession, text: string, model?: ModelSelection, noReply?: boolean, messageID?: string, delivery?: "steer" | "queue", parts?: readonly OCPromptPart[], metadata?: Record<string, unknown>): void;
36
- export type ShellRouteResult = {
36
+ type ShellRouteResult = {
37
37
  kind: "input";
38
38
  } | {
39
39
  kind: "busy";
@@ -46,7 +46,7 @@ export type ShellRouteResult = {
46
46
  };
47
47
  /** Run a shell command consistently while leaving each API version to shape its response envelope. */
48
48
  export declare function runSessionShell(services: RouteServices, session: ManagedSession, body: unknown): Promise<ShellRouteResult>;
49
- export type SlashRouteResult = {
49
+ type SlashRouteResult = {
50
50
  kind: "input";
51
51
  } | {
52
52
  kind: "success";
@@ -74,3 +74,4 @@ export declare function agentDescriptors(services: RouteServices): Promise<{
74
74
  prompt: string;
75
75
  temperature: number;
76
76
  }[]>;
77
+ export {};
@@ -6,6 +6,7 @@ import { agentDefaults } from "./catalog.js";
6
6
  import { announceSessionError, parseShellCommand, parseSlashCommand, runShellCommand, runSlashCommand, } from "./session-commands.js";
7
7
  import { envSetting } from "./config.js";
8
8
  import { PiStoppedError } from "./pi-rpc.js";
9
+ import { errorMessage } from "./guards.js";
9
10
  // This connector is not opencode — it only implements an OpenCode API subset.
10
11
  // OpenChamber reads /global/health's `version` as the installed opencode version
11
12
  // and offers an update when it trails the latest release. Advertising the SDK
@@ -62,7 +63,7 @@ export function promptAsync(services, session, text, model, noReply = false, mes
62
63
  // The agent stopped: the session's exit handler already shows why, once.
63
64
  if (error instanceof PiStoppedError)
64
65
  return;
65
- announceSessionError({ sessions: services.sessions, session, emit: services.broadcast }, error instanceof Error ? error.name : "UnknownError", error instanceof Error ? error.message : String(error));
66
+ announceSessionError({ sessions: services.sessions, session, emit: services.broadcast }, error instanceof Error ? error.name : "UnknownError", errorMessage(error));
66
67
  });
67
68
  }
68
69
  /** Run a shell command consistently while leaving each API version to shape its response envelope. */