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/dist/routes-v2.js CHANGED
@@ -19,6 +19,7 @@ import { SHELL_CANCELLATION_KEY } from "./omo-shells.js";
19
19
  import { WorkStatusError } from "./work-status.js";
20
20
  import { FileWatchError } from "./file-watch.js";
21
21
  import { agentDescriptors, modelRefFromBody, numberParam, OPENCODE_COMPAT_VERSION, promptAsync, runSessionShell, runSessionSlash, sessionDirectory, sessionMetadata, } from "./route-services.js";
22
+ import { errorMessage } from "./guards.js";
22
23
  async function v2Agents(services) {
23
24
  return (await agentDescriptors(services)).map(({ model, variant, ...agent }) => ({
24
25
  id: agent.name,
@@ -785,8 +786,8 @@ export async function handleV2(services, req, res, url, path, method, directory)
785
786
  delete managed.compactionID;
786
787
  })
787
788
  .catch((error) => {
788
- fail(error instanceof Error ? error.message : String(error));
789
- announceSessionError({ sessions: services.sessions, session: managed, emit: services.broadcast }, error instanceof Error ? error.name : "UnknownError", error instanceof Error ? error.message : String(error));
789
+ fail(errorMessage(error));
790
+ announceSessionError({ sessions: services.sessions, session: managed, emit: services.broadcast }, error instanceof Error ? error.name : "UnknownError", errorMessage(error));
790
791
  });
791
792
  json(res, 200, { data: admission.item });
792
793
  return;
@@ -988,7 +989,7 @@ export async function handleV2(services, req, res, url, path, method, directory)
988
989
  }
989
990
  }
990
991
  catch (error) {
991
- json(res, 400, errorBody("SessionTreeError", error instanceof Error ? error.message : String(error)));
992
+ json(res, 400, errorBody("SessionTreeError", errorMessage(error)));
992
993
  }
993
994
  return;
994
995
  }
@@ -1025,7 +1026,7 @@ export async function handleV2(services, req, res, url, path, method, directory)
1025
1026
  res.writeHead(204).end();
1026
1027
  }
1027
1028
  catch (err) {
1028
- const message = err instanceof Error ? err.message : String(err);
1029
+ const message = errorMessage(err);
1029
1030
  console.error(`[model] session ${sessionId} → ${ref.providerID}/${ref.modelID} failed:`, message);
1030
1031
  json(res, message.startsWith("unknown session:") ? 404 : 400, errorBody(message.startsWith("unknown session:") ? "NotFoundError" : "BadRequestError", message));
1031
1032
  }
@@ -4,7 +4,7 @@
4
4
  * OpenChamber relaunches the adapter, and auto-update only installs it for the next launch.
5
5
  */
6
6
  import type * as fs from "node:fs";
7
- export interface RunningServer {
7
+ interface RunningServer {
8
8
  readonly pid: number;
9
9
  readonly version: string;
10
10
  readonly url: string;
@@ -2,7 +2,7 @@ export type InstallMethod = "npm" | "bun";
2
2
  export declare class SelfUpdateUnsupportedError extends Error {
3
3
  readonly name = "SelfUpdateUnsupportedError";
4
4
  }
5
- export interface InstallLocation {
5
+ interface InstallLocation {
6
6
  readonly packageRoot: string;
7
7
  readonly env: NodeJS.ProcessEnv;
8
8
  readonly home: string;
@@ -22,12 +22,11 @@ export interface SelfUpdateResult {
22
22
  readonly to: string;
23
23
  readonly method: InstallMethod;
24
24
  }
25
- export declare const MANAGED_UPDATE_HINT = "antechamber is managed by its OpenChamber extension: update the extension in Settings -> Extensions";
26
25
  export declare function installMethod(location: InstallLocation, npmRoot: () => string): InstallMethod;
27
26
  export declare function isNewerVersion(a: string, b: string): boolean;
28
27
  export declare function fetchLatestVersion(env?: NodeJS.ProcessEnv): Promise<string>;
29
28
  /** Prefers an npm beside the running runtime (bun or node): service PATHs often lack the user's tool directories. */
30
29
  export declare function npmBinaryFor(execPath?: string): string;
31
- export declare function defaultSelfUpdateDeps(env?: NodeJS.ProcessEnv, home?: string): SelfUpdateDeps;
32
30
  /** Installs the latest release when it is newer; concurrent callers in this process share one attempt. */
33
31
  export declare function selfUpdate(deps?: SelfUpdateDeps): Promise<SelfUpdateResult>;
32
+ export {};
@@ -6,6 +6,7 @@ import { basename, dirname, join } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { managedByExtension } from "./config.js";
8
8
  import { ADAPTER_VERSION } from "./version.js";
9
+ import { errorMessage } from "./guards.js";
9
10
  export class SelfUpdateUnsupportedError extends Error {
10
11
  name = "SelfUpdateUnsupportedError";
11
12
  }
@@ -22,7 +23,7 @@ function tryRealpath(path, location) {
22
23
  function bunInstallDir(location) {
23
24
  return location.env.BUN_INSTALL ?? join(location.home, ".bun");
24
25
  }
25
- export const MANAGED_UPDATE_HINT = "antechamber is managed by its OpenChamber extension: update the extension in Settings -> Extensions";
26
+ const MANAGED_UPDATE_HINT = "antechamber is managed by its OpenChamber extension: update the extension in Settings -> Extensions";
26
27
  function locate(location) {
27
28
  if (managedByExtension(location.env))
28
29
  throw new SelfUpdateUnsupportedError(MANAGED_UPDATE_HINT);
@@ -42,7 +43,7 @@ function npmOwns(location, root, npmGlobal) {
42
43
  throw notGlobal(root);
43
44
  }
44
45
  function npmUnavailable(error) {
45
- const reason = error instanceof Error ? error.message : String(error);
46
+ const reason = errorMessage(error);
46
47
  return new SelfUpdateUnsupportedError(`cannot run npm root -g to confirm a global npm install (${reason})`);
47
48
  }
48
49
  export function installMethod(location, npmRoot) {
@@ -152,7 +153,7 @@ function bunBinaryFor(env, home) {
152
153
  const installed = join(bunInstallDir({ env, home }), "bin", "bun");
153
154
  return existsSync(installed) ? installed : "bun";
154
155
  }
155
- export function defaultSelfUpdateDeps(env = process.env, home = homedir()) {
156
+ function defaultSelfUpdateDeps(env = process.env, home = homedir()) {
156
157
  const npmBinary = npmBinaryFor();
157
158
  return {
158
159
  // src/self-update.ts (tsx) and dist/self-update.js both sit one level below the package root.
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { PiRpcClient, UpstreamProtocolError } from "./pi-rpc.js";
3
3
  import { getAgentName } from "./agent-name.js";
4
4
  import { nativePromptInput, parsePromptParts } from "./prompt-parts.js";
5
+ import { errorMessage, isRecord } from "./guards.js";
5
6
  /**
6
7
  * Live output kept on a running shell card: the newest part. Every snapshot carries all of it, so it is kept small;
7
8
  * the finished card gets OmO's full output.
@@ -23,9 +24,6 @@ export const unsupportedShare = {
23
24
  name: "UnsupportedError",
24
25
  data: { message: "Sharing is not available with OmO" },
25
26
  };
26
- function isRecord(value) {
27
- return typeof value === "object" && value !== null && !Array.isArray(value);
28
- }
29
27
  function id(prefix) {
30
28
  return `${prefix}_${randomUUID().replaceAll("-", "")}`;
31
29
  }
@@ -407,7 +405,7 @@ export async function runShellCommand(context) {
407
405
  emitShellMessage(context, message);
408
406
  return { kind: "completed", message };
409
407
  }
410
- failShellMessage(message, command, error instanceof Error ? error.message : String(error));
408
+ failShellMessage(message, command, errorMessage(error));
411
409
  emitShellMessage(context, message);
412
410
  throw error;
413
411
  }
@@ -20,6 +20,7 @@ import { DatabaseSync } from "node:sqlite";
20
20
  import { piAgentDir } from "./agent-dir.js";
21
21
  import { isPromptPart } from "./prompt-parts.js";
22
22
  import { defaultStateDir, envSetting } from "./config.js";
23
+ import { errorMessage, isRecord } from "./guards.js";
23
24
  /** pi's session directory for a given cwd (see pi docs/session-format.md). */
24
25
  export function piSessionDir(cwd) {
25
26
  const sanitized = cwd.replace(/^[/\\]+/, "").replace(/[\\/:\u0000]/g, "-");
@@ -41,7 +42,7 @@ export function sameUsage(saved, info) {
41
42
  }
42
43
  export class SessionPersistenceError extends Error {
43
44
  constructor(file, cause) {
44
- super(`Failed to persist session registry ${file}: ${cause instanceof Error ? cause.message : String(cause)}`, {
45
+ super(`Failed to persist session registry ${file}: ${errorMessage(cause)}`, {
45
46
  cause,
46
47
  });
47
48
  this.name = "SessionPersistenceError";
@@ -369,31 +370,28 @@ export function scanPiSessions(directory) {
369
370
  * Persistent oc-session-id → metadata registry (title overrides, known pi
370
371
  * paths). Legacy JSON records are validated at migration; SQLite writes are atomic.
371
372
  */
372
- function record(value) {
373
- return value !== null && typeof value === "object" && !Array.isArray(value);
374
- }
375
373
  function stringRecord(value) {
376
- return record(value) && Object.values(value).every((entry) => typeof entry === "string");
374
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
377
375
  }
378
376
  function booleanRecord(value) {
379
- return record(value) && Object.values(value).every((entry) => typeof entry === "boolean");
377
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "boolean");
380
378
  }
381
379
  function persistedMessage(value) {
382
- return (record(value) &&
383
- record(value.info) &&
380
+ return (isRecord(value) &&
381
+ isRecord(value.info) &&
384
382
  typeof value.info.id === "string" &&
385
383
  typeof value.info.role === "string" &&
386
384
  Array.isArray(value.parts));
387
385
  }
388
386
  function sessionTreeState(value) {
389
- if (!record(value) || !stringRecord(value.messageEntries))
387
+ if (!isRecord(value) || !stringRecord(value.messageEntries))
390
388
  return false;
391
389
  if (value.promptParts !== undefined &&
392
- (!record(value.promptParts) ||
390
+ (!isRecord(value.promptParts) ||
393
391
  !Object.values(value.promptParts).every((parts) => Array.isArray(parts) && parts.every(isPromptPart))))
394
392
  return false;
395
393
  if (value.promptMetadata !== undefined &&
396
- (!record(value.promptMetadata) || !Object.values(value.promptMetadata).every((metadata) => record(metadata))))
394
+ (!isRecord(value.promptMetadata) || !Object.values(value.promptMetadata).every((metadata) => isRecord(metadata))))
397
395
  return false;
398
396
  if (value.promptDescriptions !== undefined && !stringRecord(value.promptDescriptions))
399
397
  return false;
@@ -402,7 +400,7 @@ function sessionTreeState(value) {
402
400
  !Object.values(value.compactionReasons).every((reason) => reason === "manual" || reason === "auto")))
403
401
  return false;
404
402
  if (value.messageParts !== undefined &&
405
- (!record(value.messageParts) ||
403
+ (!isRecord(value.messageParts) ||
406
404
  !Object.values(value.messageParts).every((parts) => Array.isArray(parts) && parts.every((part) => typeof part === "string"))))
407
405
  return false;
408
406
  if (value.shellDispatch !== undefined && !booleanRecord(value.shellDispatch))
@@ -411,21 +409,21 @@ function sessionTreeState(value) {
411
409
  if (value.lastIdle !== undefined && !finite(value.lastIdle))
412
410
  return false;
413
411
  if (value.compactionAdmissions !== undefined &&
414
- (!record(value.compactionAdmissions) || !Object.values(value.compactionAdmissions).every(finite)))
412
+ (!isRecord(value.compactionAdmissions) || !Object.values(value.compactionAdmissions).every(finite)))
415
413
  return false;
416
414
  if (value.idleBoundaries !== undefined &&
417
- (!record(value.idleBoundaries) ||
418
- !Object.values(value.idleBoundaries).every((boundary) => record(boundary) &&
415
+ (!isRecord(value.idleBoundaries) ||
416
+ !Object.values(value.idleBoundaries).every((boundary) => isRecord(boundary) &&
419
417
  finite(boundary.at) &&
420
418
  ["succeeded", "failed", "interrupted"].includes(boundary.outcome) &&
421
- (boundary.error === undefined || record(boundary.error)))))
419
+ (boundary.error === undefined || isRecord(boundary.error)))))
422
420
  return false;
423
421
  if (value.leafId !== undefined && value.leafId !== null && typeof value.leafId !== "string")
424
422
  return false;
425
423
  if (value.fileSize !== undefined && (typeof value.fileSize !== "number" || !Number.isFinite(value.fileSize)))
426
424
  return false;
427
425
  if (value.revert !== undefined) {
428
- if (!record(value.revert) ||
426
+ if (!isRecord(value.revert) ||
429
427
  typeof value.revert.messageID !== "string" ||
430
428
  (value.revert.previousLeafId !== null && typeof value.revert.previousLeafId !== "string") ||
431
429
  (value.revert.targetId !== null && typeof value.revert.targetId !== "string"))
@@ -433,7 +431,7 @@ function sessionTreeState(value) {
433
431
  }
434
432
  return (value.localShellTurns === undefined ||
435
433
  (Array.isArray(value.localShellTurns) &&
436
- value.localShellTurns.every((turn) => record(turn) &&
434
+ value.localShellTurns.every((turn) => isRecord(turn) &&
437
435
  (turn.afterEntryId === null || typeof turn.afterEntryId === "string") &&
438
436
  Array.isArray(turn.messages) &&
439
437
  turn.messages.length === 2 &&
@@ -441,24 +439,24 @@ function sessionTreeState(value) {
441
439
  persistedMessage(turn.messages[1]))));
442
440
  }
443
441
  function childTask(value) {
444
- return (record(value) &&
442
+ return (isRecord(value) &&
445
443
  typeof value.id === "string" &&
446
444
  typeof value.parentPiId === "string" &&
447
- record(value.input) &&
448
- record(value.details) &&
445
+ isRecord(value.input) &&
446
+ isRecord(value.details) &&
449
447
  (value.terminalAt === undefined || (typeof value.terminalAt === "number" && Number.isFinite(value.terminalAt))));
450
448
  }
451
449
  function finite(value) {
452
450
  return typeof value === "number" && Number.isFinite(value);
453
451
  }
454
452
  function sessionUsage(value) {
455
- if (!record(value) || !finite(value.cost) || !record(value.tokens))
453
+ if (!isRecord(value) || !finite(value.cost) || !isRecord(value.tokens))
456
454
  return false;
457
455
  const { tokens } = value;
458
456
  return (finite(tokens.input) &&
459
457
  finite(tokens.output) &&
460
458
  finite(tokens.reasoning) &&
461
- record(tokens.cache) &&
459
+ isRecord(tokens.cache) &&
462
460
  finite(tokens.cache.read) &&
463
461
  finite(tokens.cache.write));
464
462
  }
@@ -466,7 +464,7 @@ function titleSource(value) {
466
464
  return value === "user" || value === "native" || value === "fallback" || value === "generated";
467
465
  }
468
466
  function registryEntry(value) {
469
- if (!record(value) ||
467
+ if (!isRecord(value) ||
470
468
  typeof value.piPath !== "string" ||
471
469
  typeof value.piSessionId !== "string" ||
472
470
  typeof value.directory !== "string" ||
@@ -487,12 +485,12 @@ function registryEntry(value) {
487
485
  return false;
488
486
  if (value.agent !== undefined && typeof value.agent !== "string")
489
487
  return false;
490
- if (value.metadata !== undefined && !record(value.metadata))
488
+ if (value.metadata !== undefined && !isRecord(value.metadata))
491
489
  return false;
492
490
  if (value.instructions !== undefined &&
493
- (!record(value.instructions) ||
491
+ (!isRecord(value.instructions) ||
494
492
  !Object.entries(value.instructions).every(([key, entry]) => /^[a-z0-9][a-z0-9._-]*$/.test(key) &&
495
- record(entry) &&
493
+ isRecord(entry) &&
496
494
  "value" in entry &&
497
495
  (entry.removed === undefined || entry.removed === true))))
498
496
  return false;
@@ -507,10 +505,10 @@ function registryEntry(value) {
507
505
  if (value.viewed !== undefined && (typeof value.viewed !== "number" || !Number.isFinite(value.viewed)))
508
506
  return false;
509
507
  if (value.model !== undefined &&
510
- (!record(value.model) || typeof value.model.providerID !== "string" || typeof value.model.modelID !== "string"))
508
+ (!isRecord(value.model) || typeof value.model.providerID !== "string" || typeof value.model.modelID !== "string"))
511
509
  return false;
512
510
  if (value.lastStop !== undefined &&
513
- (!record(value.lastStop) ||
511
+ (!isRecord(value.lastStop) ||
514
512
  typeof value.lastStop.message !== "string" ||
515
513
  typeof value.lastStop.at !== "number" ||
516
514
  !Number.isFinite(value.lastStop.at)))
@@ -623,7 +621,7 @@ export class SessionStore {
623
621
  const parse = () => {
624
622
  try {
625
623
  const parsed = JSON.parse(readFileSync(legacy, "utf8"));
626
- return record(parsed) ? parsed : undefined;
624
+ return isRecord(parsed) ? parsed : undefined;
627
625
  }
628
626
  catch (error) {
629
627
  // Another process imported it and renamed it away after this one checked it was there.
@@ -14,7 +14,6 @@ import { WorkStatusBridge } from "./work-status.js";
14
14
  import { OmoShells } from "./omo-shells.js";
15
15
  import { SessionStore, type InstructionEntryState, type TitleSource } from "./session-store.js";
16
16
  import type { OCAssistantMessage, OCEvent, OCMessageWithParts, OCModelRef, OCPart, OCPromptPart, OCSession, OCSessionStatus, OCToolPart } from "./types.js";
17
- export { ADAPTER_VERSION } from "./version.js";
18
17
  interface StreamingState {
19
18
  message: OCAssistantMessage;
20
19
  /** contentIndex → part; pi addresses streaming content by index. */
@@ -340,8 +339,12 @@ export declare class SessionManager {
340
339
  private resolveRestored;
341
340
  /** Registry write for adapter-owned metadata (title override, pi path). */
342
341
  private persistMeta;
342
+ /** Take back a user message OmO did not admit: drop its stored parts and metadata and remove its card. */
343
+ private withdrawUserMessage;
344
+ private emitUnknownError;
343
345
  /** Async event callbacks cannot reject an HTTP operation; report save failures through SSE. */
344
346
  private reportPersistenceError;
345
347
  /** Keep the existing event entry point for RPC wiring and test harnesses. */
346
348
  private onPiEvent;
347
349
  }
350
+ export {};
package/dist/sessions.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { id, PiEventTranslator, syncSessionCost } from "./pi-event-translation.js";
6
6
  import { parsePiSessionFile, parsePiSessionText } from "./session-history.js";
7
7
  import { CONTEXT_MESSAGE_TYPE, nativePromptInput, v2PromptAttachments } from "./prompt-parts.js";
8
+ import { deliveredInstructions, INSTRUCTIONS_CUSTOM_TYPE, instructionDelivery } from "./instructions.js";
8
9
  import { existsSync, readdirSync, statSync, unlinkSync } from "node:fs";
9
10
  import { join } from "node:path";
10
11
  import { COMPACT_RPC_TIMEOUT_MS, describeStop, PiRpcClient, PiStoppedError, RPC_COMMAND_TIMEOUT_MS, } from "./pi-rpc.js";
@@ -24,7 +25,7 @@ import { waitForMcpServers } from "./mcp.js";
24
25
  import { announceSessionNotice, noticeMessage, skillCommandText, slashTitlePrompt } from "./session-commands.js";
25
26
  import { emptyTokens, ocIdFor, piSessionDir, piSessionsRootMtime, sameUsage, sessionUsageEntry, scanAllPiSessions, scanPiSessions, SessionStore, readSessionFileMeta, } from "./session-store.js";
26
27
  import { ADAPTER_VERSION } from "./version.js";
27
- export { ADAPTER_VERSION } from "./version.js";
28
+ import { errorMessage } from "./guards.js";
28
29
  const SESSION_SCAN_CACHE_TTL_MS = 5_000;
29
30
  const PI_FILE_RESOLVE_ATTEMPTS = 10;
30
31
  const PI_FILE_RESOLVE_RETRY_MS = 200;
@@ -82,7 +83,7 @@ export class SessionManager {
82
83
  this.defaultDirectory = defaultDirectory;
83
84
  this.store = store ?? new SessionStore();
84
85
  this.lifecycle = new SessionLifecycle(() => this.sessions.values(), lifecycleOptions);
85
- this.subagents = new SubagentBridge(this.store, this.sessions, this.emit, (session, raw) => parsePiSessionText(session, getAgentName(), raw));
86
+ this.subagents = new SubagentBridge(this.store, this.sessions, this.emit, (session, raw) => parsePiSessionText(session, getAgentName(), raw), (directory) => this.ensureScanned(directory));
86
87
  this.monitors = new MonitorSessions(this.sessions, this.emit);
87
88
  this.workStatus = new WorkStatusBridge(this.monitors);
88
89
  this.shells = new OmoShells(this.sessions, this.monitors, this.workStatus, this.emit);
@@ -890,13 +891,7 @@ export class SessionManager {
890
891
  this.emit(s.info.directory, { type: "session.diff", properties: { sessionID: s.info.id, diff } });
891
892
  })
892
893
  .catch((error) => {
893
- this.emit(s.info.directory, {
894
- type: "session.error",
895
- properties: {
896
- sessionID: s.info.id,
897
- error: { name: "UnknownError", data: { message: error instanceof Error ? error.message : String(error) } },
898
- },
899
- });
894
+ this.emitUnknownError(s, errorMessage(error));
900
895
  })
901
896
  .finally(() => {
902
897
  if (this.diffEmissions.get(s.info.id) === pending)
@@ -1133,16 +1128,7 @@ export class SessionManager {
1133
1128
  await this.setModelLive(s, model);
1134
1129
  }
1135
1130
  catch (error) {
1136
- this.emit(s.info.directory, {
1137
- type: "session.error",
1138
- properties: {
1139
- sessionID: s.info.id,
1140
- error: {
1141
- name: "UnknownError",
1142
- data: { message: error instanceof Error ? error.message : String(error) },
1143
- },
1144
- },
1145
- });
1131
+ this.emitUnknownError(s, errorMessage(error));
1146
1132
  throw error;
1147
1133
  }
1148
1134
  }
@@ -1235,40 +1221,18 @@ export class SessionManager {
1235
1221
  * (OpenCode rewinds its instruction state the same way, core/session/projector.ts).
1236
1222
  */
1237
1223
  async deliverInstructions(s, pi) {
1238
- const instructions = Object.entries(s.instructions ?? {});
1239
- if (instructions.length === 0)
1224
+ const instructions = s.instructions ?? {};
1225
+ if (Object.keys(instructions).length === 0)
1240
1226
  return;
1241
- const delivered = deliveredInstructions(branchEntries(await getEntries(pi)));
1242
- const pending = instructions
1243
- .filter(([key, entry]) => entry.removed
1244
- ? key in delivered
1245
- : !(key in delivered) || JSON.stringify(entry.value) !== JSON.stringify(delivered[key]))
1246
- .sort(([left], [right]) => left.localeCompare(right));
1247
- if (pending.length === 0)
1227
+ const delivery = instructionDelivery(instructions, deliveredInstructions(branchEntries(await getEntries(pi))));
1228
+ if (delivery === undefined)
1248
1229
  return;
1249
- const text = pending
1250
- .map(([key, entry]) => {
1251
- if (entry.removed)
1252
- return `The context under "${key}" no longer applies. Disregard it.`;
1253
- const block = `<context key="${key}">\n${typeof entry.value === "string" ? entry.value : JSON.stringify(entry.value, null, 2)}\n</context>`;
1254
- return key in delivered
1255
- ? `The context under "${key}" changed and supersedes the previous value:\n${block}`
1256
- : block;
1257
- })
1258
- .join("\n\n");
1259
- const snapshot = { ...delivered };
1260
- for (const [key, entry] of pending) {
1261
- if (entry.removed)
1262
- delete snapshot[key];
1263
- else
1264
- snapshot[key] = entry.value;
1265
- }
1266
1230
  const result = await pi.command({
1267
1231
  type: "send_custom_message",
1268
1232
  customType: INSTRUCTIONS_CUSTOM_TYPE,
1269
- content: [{ type: "text", text }],
1233
+ content: [{ type: "text", text: delivery.text }],
1270
1234
  display: false,
1271
- details: { instructions: snapshot },
1235
+ details: { instructions: delivery.snapshot },
1272
1236
  triggerTurn: false,
1273
1237
  });
1274
1238
  if (!result.success)
@@ -1289,15 +1253,7 @@ export class SessionManager {
1289
1253
  triggerTurn: false,
1290
1254
  });
1291
1255
  if (!res.success) {
1292
- if (s.tree.promptParts)
1293
- delete s.tree.promptParts[userMsg.id];
1294
- if (s.tree.promptMetadata)
1295
- delete s.tree.promptMetadata[userMsg.id];
1296
- s.messages = s.messages?.filter((message) => message.info.id !== userMsg.id);
1297
- this.emit(s.info.directory, {
1298
- type: "message.removed",
1299
- properties: { sessionID: s.info.id, messageID: userMsg.id },
1300
- });
1256
+ this.withdrawUserMessage(s, userMsg.id);
1301
1257
  throw new Error(res.error ?? "context admission rejected");
1302
1258
  }
1303
1259
  // Bind the appended entry and persist the new leaf before announcing delivery, or a restart
@@ -1323,15 +1279,7 @@ export class SessionManager {
1323
1279
  (s.inputs ??= new Map()).set(userMsg.id, input);
1324
1280
  const rejectInput = () => {
1325
1281
  s.inputs?.delete(userMsg.id);
1326
- if (s.tree.promptParts)
1327
- delete s.tree.promptParts[userMsg.id];
1328
- if (s.tree.promptMetadata)
1329
- delete s.tree.promptMetadata[userMsg.id];
1330
- s.messages = s.messages?.filter((message) => message.info.id !== userMsg.id);
1331
- this.emit(s.info.directory, {
1332
- type: "message.removed",
1333
- properties: { sessionID: s.info.id, messageID: userMsg.id },
1334
- });
1282
+ this.withdrawUserMessage(s, userMsg.id);
1335
1283
  if (wasIdle)
1336
1284
  this.events.setStatus(s, { type: "idle" });
1337
1285
  };
@@ -1371,13 +1319,7 @@ export class SessionManager {
1371
1319
  });
1372
1320
  if (!res.success) {
1373
1321
  rejectInput();
1374
- this.emit(s.info.directory, {
1375
- type: "session.error",
1376
- properties: {
1377
- sessionID: s.info.id,
1378
- error: { name: "UnknownError", data: { message: res.error ?? "prompt rejected" } },
1379
- },
1380
- });
1322
+ this.emitUnknownError(s, res.error ?? "prompt rejected");
1381
1323
  return false;
1382
1324
  }
1383
1325
  input.accepted = true;
@@ -1764,7 +1706,8 @@ export class SessionManager {
1764
1706
  /** Resolve a bare session id (e.g. deep link after restart) via known directories. */
1765
1707
  resolveRestored(sessionId) {
1766
1708
  const reg = this.store.get(sessionId);
1767
- if (reg?.deleted)
1709
+ // A child row's piPath is the adapter's own archive; only the subagent bridge may restore it.
1710
+ if (reg?.deleted || reg?.task)
1768
1711
  return undefined;
1769
1712
  if (reg && existsSync(reg.piPath)) {
1770
1713
  return this.adopt({
@@ -1830,10 +1773,25 @@ export class SessionManager {
1830
1773
  updated: s.info.time.updated,
1831
1774
  });
1832
1775
  }
1776
+ /** Take back a user message OmO did not admit: drop its stored parts and metadata and remove its card. */
1777
+ withdrawUserMessage(s, messageID) {
1778
+ if (s.tree.promptParts)
1779
+ delete s.tree.promptParts[messageID];
1780
+ if (s.tree.promptMetadata)
1781
+ delete s.tree.promptMetadata[messageID];
1782
+ s.messages = s.messages?.filter((message) => message.info.id !== messageID);
1783
+ this.emit(s.info.directory, { type: "message.removed", properties: { sessionID: s.info.id, messageID } });
1784
+ }
1785
+ emitUnknownError(s, message) {
1786
+ this.emit(s.info.directory, {
1787
+ type: "session.error",
1788
+ properties: { sessionID: s.info.id, error: { name: "UnknownError", data: { message } } },
1789
+ });
1790
+ }
1833
1791
  /** Async event callbacks cannot reject an HTTP operation; report save failures through SSE. */
1834
1792
  reportPersistenceError(s, error) {
1835
1793
  const name = error instanceof Error ? error.name : "UnknownError";
1836
- const message = error instanceof Error ? error.message : String(error);
1794
+ const message = errorMessage(error);
1837
1795
  this.emit(s.info.directory, {
1838
1796
  type: "session.error",
1839
1797
  properties: { sessionID: s.info.id, error: { name, data: { message } } },
@@ -1863,25 +1821,3 @@ export class SessionManager {
1863
1821
  }
1864
1822
  }
1865
1823
  }
1866
- const INSTRUCTIONS_CUSTOM_TYPE = "antechamber.instructions";
1867
- /** The instruction map the model holds on this branch: the last delivery inside the newest compaction's kept range. */
1868
- function deliveredInstructions(branch) {
1869
- let start = 0;
1870
- for (let index = branch.length - 1; index >= 0; index--) {
1871
- const entry = branch[index];
1872
- if (entry.type !== "compaction")
1873
- continue;
1874
- const kept = branch.findIndex((candidate) => candidate.id === entry.firstKeptEntryId);
1875
- start = kept >= 0 ? kept : index + 1;
1876
- break;
1877
- }
1878
- for (let index = branch.length - 1; index >= start; index--) {
1879
- const entry = branch[index];
1880
- if (entry?.type !== "custom_message" || entry.customType !== INSTRUCTIONS_CUSTOM_TYPE)
1881
- continue;
1882
- const details = entry.details;
1883
- if (details?.instructions !== null && typeof details?.instructions === "object")
1884
- return { ...details.instructions };
1885
- }
1886
- return {};
1887
- }
package/dist/sse.d.ts CHANGED
@@ -5,8 +5,6 @@ import type { TodoUpdated } from "./todo-bridge.js";
5
5
  export type SSESubscriber = {
6
6
  directory?: string;
7
7
  };
8
- /** The session an event belongs to, when it names one. */
9
- export declare function eventSessionID(event: OCEvent | TodoUpdated): string | undefined;
10
8
  export declare class SSE {
11
9
  private options;
12
10
  /** SSE subscribers tagged by protocol flavor and explicit directory scope. */
package/dist/sse.js CHANGED
@@ -6,7 +6,7 @@ const MAX_SSE_SUBSCRIBERS = 64;
6
6
  const MAX_SSE_PENDING_BYTES = 8 * 1024 * 1024;
7
7
  const MAX_SSE_REPLAY_RECORDS = 1024;
8
8
  /** The session an event belongs to, when it names one. */
9
- export function eventSessionID(event) {
9
+ function eventSessionID(event) {
10
10
  const properties = event.properties;
11
11
  const nested = (key) => {
12
12
  const value = properties[key];
@@ -48,10 +48,14 @@ export declare class SubagentBridge {
48
48
  private readonly sessions;
49
49
  private readonly emit;
50
50
  private readonly parse;
51
+ /** Adopts the pi sessions on disk for a directory, so an unscanned root parent is found before a child is hidden. */
52
+ private readonly scanDirectory;
51
53
  private readonly children;
52
54
  private readonly calls;
53
55
  private readonly removed;
54
- constructor(store: SessionStore, sessions: Map<string, ManagedSession>, emit: (directory: string, event: OCEvent) => void, parse: ParseHistory);
56
+ constructor(store: SessionStore, sessions: Map<string, ManagedSession>, emit: (directory: string, event: OCEvent) => void, parse: ParseHistory,
57
+ /** Adopts the pi sessions on disk for a directory, so an unscanned root parent is found before a child is hidden. */
58
+ scanDirectory?: (directory: string) => void);
55
59
  private archive;
56
60
  private sessionId;
57
61
  wire(parent: ManagedSession): void;
@@ -75,6 +79,12 @@ export declare class SubagentBridge {
75
79
  private discoverParts;
76
80
  private create;
77
81
  restore(id: string): ManagedSession | undefined;
82
+ /**
83
+ * A registry child outlives a parent that was deleted or never saved, and OpenChamber would then list it as a
84
+ * root holding only the "Full transcript is unavailable" fallback. A parent exists when it is loaded, registered
85
+ * and not deleted (a nested child's own parent chain counts the same way), or a pi session on disk.
86
+ */
87
+ private parentExists;
78
88
  /**
79
89
  * Tasks spawned outside a `task` tool call (e.g. `agent()` inside an `eval`
80
90
  * cell) never produce a card, so their session is built from the task record.