@xopcai/xopc 0.0.195 → 0.0.197

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 (154) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/telegram/xopc.extension.json +1 -1
  3. package/dist/gateway/static/root/assets/{agent-avatar-dicebear-DkYgzssq.js → agent-avatar-dicebear-C5st7lt5.js} +1 -1
  4. package/dist/gateway/static/root/assets/agents-Baxfj44y.js +68 -0
  5. package/dist/gateway/static/root/assets/{app-management-settings-panel-DVXLietl.js → app-management-settings-panel-S8LhoD6G.js} +1 -1
  6. package/dist/gateway/static/root/assets/{appearance-settings-D7oohrYf.js → appearance-settings-D8Cd5vDP.js} +1 -1
  7. package/dist/gateway/static/root/assets/apps-page-0uCxKyE5.js +1 -0
  8. package/dist/gateway/static/root/assets/{archive-plugin-CpBzHKzI.js → archive-plugin-qL07mwnY.js} +1 -1
  9. package/dist/gateway/static/root/assets/{attachment-load-DMWXe12h.js → attachment-load-CqSobpdi.js} +1 -1
  10. package/dist/gateway/static/root/assets/automations-page-XyDat125.js +6 -0
  11. package/dist/gateway/static/root/assets/{binary-plugins-BM0MgsHB.js → binary-plugins-DBRPyLYE.js} +1 -1
  12. package/dist/gateway/static/root/assets/{block-editor-C2MT7mG3.js → block-editor-6wG1LU7t.js} +47 -47
  13. package/dist/gateway/static/root/assets/browser-settings-page-CrYNMR4w.js +8 -0
  14. package/dist/gateway/static/root/assets/{browser-workflow-inputs-V01qhcZc.js → browser-workflow-inputs-Abil4puY.js} +1 -1
  15. package/dist/gateway/static/root/assets/{browser-workflows-page-DPmSKVWx.js → browser-workflows-page-BEu3E0et.js} +2 -2
  16. package/dist/gateway/static/root/assets/capabilities-settings-panel-CvMcDhGf.js +7 -0
  17. package/dist/gateway/static/root/assets/capability-presets-settings-panel-CHJDY-Ih.js +3 -0
  18. package/dist/gateway/static/root/assets/channels-settings-Ds9BJbcY.js +1 -0
  19. package/dist/gateway/static/root/assets/connectors-api-CgWjgPSI.js +1 -0
  20. package/dist/gateway/static/root/assets/connectors-page-NUs-Zf7F.js +2 -0
  21. package/dist/gateway/static/root/assets/{cron-expression-5SqAw4UD.js → cron-expression-ZdDBAoqA.js} +1 -1
  22. package/dist/gateway/static/root/assets/{dependency-picker-eiaYMDYI.js → dependency-picker-BGeB1jpn.js} +1 -1
  23. package/dist/gateway/static/root/assets/{desktop-pet-BtfzkmnU.js → desktop-pet-CsLR4pWB.js} +1 -1
  24. package/dist/gateway/static/root/assets/{desktop-pet-settings-Dn3hnBOU.js → desktop-pet-settings-CCjT1bdo.js} +1 -1
  25. package/dist/gateway/static/root/assets/directory-picker-path-field-C-Te1QN3.js +1 -0
  26. package/dist/gateway/static/root/assets/{extension-debug-page-EWu0uOpw.js → extension-debug-page-CD73euAM.js} +1 -1
  27. package/dist/gateway/static/root/assets/{extension-page-2qZ7ngqL.js → extension-page-DAKjpNwd.js} +1 -1
  28. package/dist/gateway/static/root/assets/{extension-settings-page-4MOAwYPT.js → extension-settings-page-BLSNdlgd.js} +1 -1
  29. package/dist/gateway/static/root/assets/{gateway-config-api-aqPj1HAI.js → gateway-config-api-CQrf0k3D.js} +1 -1
  30. package/dist/gateway/static/root/assets/{gateway-settings-BbQBgKWH.js → gateway-settings-CvgH8IJI.js} +1 -1
  31. package/dist/gateway/static/root/assets/{heartbeat-settings-DXtG-Sy0.js → heartbeat-settings-SPpnqbjl.js} +1 -1
  32. package/dist/gateway/static/root/assets/home-page-BFoD6047.js +3 -0
  33. package/dist/gateway/static/root/assets/index-84ys9u-K.js +152 -0
  34. package/dist/gateway/static/root/assets/index-D-srnucP.css +1 -0
  35. package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-WKmsr5WD.js → keyboard-shortcuts-settings-HMhxgOuD.js} +1 -1
  36. package/dist/gateway/static/root/assets/local-app-workbench-page-D5uL2_Fd.js +2 -0
  37. package/dist/gateway/static/root/assets/{local-apps-page-3-aNfJwB.js → local-apps-page-DIWkFa3g.js} +1 -1
  38. package/dist/gateway/static/root/assets/logs-page--6v8qq6y.js +2 -0
  39. package/dist/gateway/static/root/assets/{management-settings-D8vbsfLm.js → management-settings-DtEuS-kR.js} +1 -1
  40. package/dist/gateway/static/root/assets/{markdown-split-DRFl6Vfw.js → markdown-split-DvVBewS4.js} +1 -1
  41. package/dist/gateway/static/root/assets/{media-plugins-C5J46ROp.js → media-plugins-YVj7NVzD.js} +1 -1
  42. package/dist/gateway/static/root/assets/{notes-page-Z0lEBC-X.js → notes-page-BDzuL2I9.js} +1 -1
  43. package/dist/gateway/static/root/assets/notes-workbench-IdjuNXvH.js +4 -0
  44. package/dist/gateway/static/root/assets/{page-tabs-Dyj6Snbu.js → page-tabs-7bSEWfSX.js} +1 -1
  45. package/dist/gateway/static/root/assets/{preview-open-alternatives-CPDM4F7n.js → preview-open-alternatives-tgLbHgcV.js} +1 -1
  46. package/dist/gateway/static/root/assets/{product-open-page-8RFhWmcU.js → product-open-page-Bwx_CQht.js} +1 -1
  47. package/dist/gateway/static/root/assets/project-detail-page-DnJXSuM4.js +1 -0
  48. package/dist/gateway/static/root/assets/projects-page-DckZKlBI.js +1 -0
  49. package/dist/gateway/static/root/assets/remote-access-hub-CfbUHBUH.js +1 -0
  50. package/dist/gateway/static/root/assets/{runtime-tools-settings-panel-BBgWkYk0.js → runtime-tools-settings-panel-Fe05Nus6.js} +2 -2
  51. package/dist/gateway/static/root/assets/{schema-form-BJqF0l7i.js → schema-form-CFfyC4CB.js} +1 -1
  52. package/dist/gateway/static/root/assets/sessions-page-BCfCh4My.js +1 -0
  53. package/dist/gateway/static/root/assets/settings-advanced-gate-Cbi4FvzO.js +1 -0
  54. package/dist/gateway/static/root/assets/{settings-form-section-CYL5uBzc.js → settings-form-section-gEnEYT_3.js} +1 -1
  55. package/dist/gateway/static/root/assets/{settings-loading-skeleton-BabbixC0.js → settings-loading-skeleton-BRE_-7Da.js} +1 -1
  56. package/dist/gateway/static/root/assets/{settings-page-B7OH9I8A.js → settings-page-C1zxCpqB.js} +1 -1
  57. package/dist/gateway/static/root/assets/{settings-page-layout-D9X3eVDo.js → settings-page-layout-CRpXF_05.js} +1 -1
  58. package/dist/gateway/static/root/assets/{setup-status-panel-BHdz-BO7.js → setup-status-panel-BcHdpmFf.js} +1 -1
  59. package/dist/gateway/static/root/assets/{share-preview-page-CMuJZ5Qq.js → share-preview-page-DU8L68A5.js} +1 -1
  60. package/dist/gateway/static/root/assets/shares-settings-kjTqH9yY.js +1 -0
  61. package/dist/gateway/static/root/assets/skill-reload-api-QAGpwzIM.js +1 -0
  62. package/dist/gateway/static/root/assets/{skills-page-C9U1pIT-.js → skills-page-lE1-YRdK.js} +1 -1
  63. package/dist/gateway/static/root/assets/{skills-page.utils-C3iaLgk9.js → skills-page.utils-CYwFWTso.js} +1 -1
  64. package/dist/gateway/static/root/assets/{system-settings-panel-CAN01aY0.js → system-settings-panel-CVDsiPKn.js} +1 -1
  65. package/dist/gateway/static/root/assets/task-detail-page-DsM13-cy.js +1 -0
  66. package/dist/gateway/static/root/assets/{typed-models-lib-C9FMLeH2.js → typed-models-lib-DelyYgoc.js} +1 -1
  67. package/dist/gateway/static/root/assets/{use-autosave-AAZNoD6t.js → use-autosave-C50Mq5yQ.js} +1 -1
  68. package/dist/gateway/static/root/assets/user-context-page-D-VEOt2A.js +1 -0
  69. package/dist/gateway/static/root/assets/{voice-api-key-field-yLXEYgwV.js → voice-api-key-field-DYfgTe3Y.js} +1 -1
  70. package/dist/gateway/static/root/assets/{work-discovery-overlay-tbkbg-8l.js → work-discovery-overlay-DPbujsp3.js} +1 -1
  71. package/dist/gateway/static/root/assets/work-discovery-page-D77opady.js +1 -0
  72. package/dist/gateway/static/root/assets/{workflow-run-setup-panel-BJHOxj4Z.js → workflow-run-setup-panel-DqIb1oBB.js} +2 -2
  73. package/dist/gateway/static/root/assets/workflows-page-B9-PLmlX.js +5 -0
  74. package/dist/gateway/static/root/index.html +2 -2
  75. package/dist/package.js +1 -1
  76. package/dist/src/agent/embedded/execution-context.d.ts +2 -0
  77. package/dist/src/agent/embedded/execution-context.js +11 -0
  78. package/dist/src/agent/embedded/index.d.ts +3 -1
  79. package/dist/src/agent/embedded/index.js +5 -3
  80. package/dist/src/agent/embedded/run-turn.js +15 -9
  81. package/dist/src/agent/embedded/session-runner.d.ts +6 -11
  82. package/dist/src/agent/embedded/session-runner.js +25 -36
  83. package/dist/src/agent/embedded/transcript-runtime.d.ts +35 -0
  84. package/dist/src/agent/embedded/transcript-runtime.js +66 -0
  85. package/dist/src/agent/embedded/types.d.ts +3 -1
  86. package/dist/src/agent/service.d.ts +15 -0
  87. package/dist/src/agent/service.js +30 -0
  88. package/dist/src/config/agent-profile.js +1 -1
  89. package/dist/src/gateway/agents-admin.js +1 -1
  90. package/dist/src/gateway/heartbeat/service.js +1 -1
  91. package/dist/src/gateway/hono/routes/home.d.ts +1 -1
  92. package/dist/src/gateway/hono/routes/home.js +2 -2
  93. package/dist/src/gateway/hono/routes/index.js +2 -0
  94. package/dist/src/gateway/hono/routes/projects.js +12 -1
  95. package/dist/src/gateway/hono/routes/side-chats.d.ts +3 -0
  96. package/dist/src/gateway/hono/routes/side-chats.js +173 -0
  97. package/dist/src/gateway/hono/routes/understanding-sources.js +5 -1
  98. package/dist/src/gateway/service/agent-runner.d.ts +4 -0
  99. package/dist/src/gateway/service/agent-runner.js +15 -1
  100. package/dist/src/gateway/service/run-gateway-agent.js +1 -1
  101. package/dist/src/gateway/service.d.ts +4 -0
  102. package/dist/src/gateway/service.js +33 -7
  103. package/dist/src/gateway/side-chat/context-snapshot.d.ts +11 -0
  104. package/dist/src/gateway/side-chat/context-snapshot.js +108 -0
  105. package/dist/src/gateway/side-chat/index.d.ts +5 -0
  106. package/dist/src/gateway/side-chat/index.js +4 -0
  107. package/dist/src/gateway/side-chat/manager.d.ts +45 -0
  108. package/dist/src/gateway/side-chat/manager.js +198 -0
  109. package/dist/src/gateway/side-chat/run-service.d.ts +22 -0
  110. package/dist/src/gateway/side-chat/run-service.js +110 -0
  111. package/dist/src/gateway/side-chat/types.d.ts +61 -0
  112. package/dist/src/gateway/side-chat/types.js +1 -0
  113. package/dist/src/heartbeat/index.js +1 -1
  114. package/dist/src/routing/session-key-utils.d.ts +0 -1
  115. package/dist/src/routing/session-key-utils.js +1 -6
  116. package/dist/src/routing/session-key.js +2 -2
  117. package/dist/src/tasks/home-query-service.d.ts +24 -0
  118. package/dist/src/tasks/home-query-service.js +284 -5
  119. package/dist/src/tasks/index.js +3 -3
  120. package/dist/src/tasks/project-operating-view-service.d.ts +2 -1
  121. package/dist/src/tasks/project-operating-view-service.js +27 -4
  122. package/dist/src/user-context/sources/activity-clustering.js +1 -1
  123. package/dist/src/user-context/sources/index.js +2 -2
  124. package/dist/src/user-context/sources/repository.d.ts +1 -0
  125. package/dist/src/user-context/sources/repository.js +4 -1
  126. package/dist/src/work-discovery/analyzer.js +8 -8
  127. package/package.json +3 -3
  128. package/dist/gateway/static/root/assets/agents-COX-ZLtY.js +0 -68
  129. package/dist/gateway/static/root/assets/apps-page-S52mdBX_.js +0 -1
  130. package/dist/gateway/static/root/assets/automations-page-DGGJQO9B.js +0 -6
  131. package/dist/gateway/static/root/assets/browser-settings-page-C_tkW-L_.js +0 -8
  132. package/dist/gateway/static/root/assets/capabilities-settings-panel-CPu6MIHF.js +0 -7
  133. package/dist/gateway/static/root/assets/capability-presets-settings-panel-ttuWLoiJ.js +0 -3
  134. package/dist/gateway/static/root/assets/channels-settings-DrWWVQjj.js +0 -1
  135. package/dist/gateway/static/root/assets/connectors-api-CG0UqhPN.js +0 -1
  136. package/dist/gateway/static/root/assets/connectors-page-CyfIrY2l.js +0 -2
  137. package/dist/gateway/static/root/assets/directory-picker-path-field-Wa5zFvbb.js +0 -1
  138. package/dist/gateway/static/root/assets/home-page-k21J7B1q.js +0 -3
  139. package/dist/gateway/static/root/assets/index-DtEVsSU1.css +0 -1
  140. package/dist/gateway/static/root/assets/index-peR_-O6U.js +0 -150
  141. package/dist/gateway/static/root/assets/local-app-workbench-page-r8wlEj3A.js +0 -2
  142. package/dist/gateway/static/root/assets/logs-page-OU3uRCoz.js +0 -2
  143. package/dist/gateway/static/root/assets/notes-workbench-B74ylIVP.js +0 -4
  144. package/dist/gateway/static/root/assets/project-detail-page-3ugVthse.js +0 -1
  145. package/dist/gateway/static/root/assets/projects-page-VVAyOeRA.js +0 -1
  146. package/dist/gateway/static/root/assets/remote-access-hub-C6XqOPzA.js +0 -1
  147. package/dist/gateway/static/root/assets/sessions-page-BMj-t4hX.js +0 -1
  148. package/dist/gateway/static/root/assets/settings-advanced-gate-B7WvJXGJ.js +0 -1
  149. package/dist/gateway/static/root/assets/shares-settings-B0F1jbhj.js +0 -1
  150. package/dist/gateway/static/root/assets/skill-reload-api-Dnpq03tO.js +0 -1
  151. package/dist/gateway/static/root/assets/task-detail-page-Bs5oS-wN.js +0 -1
  152. package/dist/gateway/static/root/assets/user-context-page-CRY8IE-7.js +0 -1
  153. package/dist/gateway/static/root/assets/work-discovery-page-Dtqgvs_0.js +0 -1
  154. package/dist/gateway/static/root/assets/workflows-page-BBjCNaXn.js +0 -5
@@ -1,7 +1,7 @@
1
1
  import { deleteUnderstanding, listUnderstandingEvidence, listUnderstandings } from "../../../storage/sqlite/user-context-repository.js";
2
2
  import { getConnectorAccount } from "../../../storage/sqlite/connector-account-repository.js";
3
3
  import "../../../storage/sqlite/index.js";
4
- import { getUnderstandingSourceGrant, listUnderstandingSourceGrants, listUserFocuses, revokeUnderstandingSourceGrant, setUserFocusStatus } from "../../../user-context/sources/repository.js";
4
+ import { deleteUserFocus, getUnderstandingSourceGrant, listUnderstandingSourceGrants, listUserFocuses, revokeUnderstandingSourceGrant, setUserFocusStatus } from "../../../user-context/sources/repository.js";
5
5
  import { getWorkDiscoveryService } from "./work-discovery.js";
6
6
  import { listUnderstandingSourceDefinitions } from "../../../user-context/sources/catalog.js";
7
7
  //#region src/gateway/hono/routes/understanding-sources.ts
@@ -199,6 +199,10 @@ function registerUnderstandingSourceRoutes(authenticated, deps) {
199
199
  error: "Focus not found"
200
200
  }, 404);
201
201
  });
202
+ authenticated.delete("/api/understanding/focuses/:focusId", limited, (c) => deleteUserFocus(c.req.param("focusId")) ? c.json({ ok: true }) : c.json({
203
+ ok: false,
204
+ error: "Focus not found"
205
+ }, 404));
202
206
  }
203
207
  //#endregion
204
208
  export { registerUnderstandingSourceRoutes };
@@ -49,6 +49,7 @@ export declare class GatewayAgentRunner {
49
49
  private readonly clarifyBridge;
50
50
  /** Maps webchat session key → active `runId` for `clarify` tool routing. */
51
51
  private readonly activeWebchatRunBySession;
52
+ private readonly externalStreamBySession;
52
53
  readonly inputs: SessionInputCoordinator;
53
54
  constructor(opts: GatewayAgentRunnerOptions);
54
55
  /** True when a webchat agent run is currently in-flight for `sessionKey`. */
@@ -57,6 +58,9 @@ export declare class GatewayAgentRunner {
57
58
  getClarifyBridge(): ClarifyBridge;
58
59
  /** Called from `GatewayService.stop()` so the bridge gets cleaned up. */
59
60
  disposeClarifyBridge(): void;
61
+ registerExternalWebchatRun(sessionKey: string, runId: string, publish: (event: ClarifyStreamEvent) => void): void;
62
+ unregisterExternalWebchatRun(sessionKey: string, runId: string): void;
63
+ cancelClarificationForRun(runId: string): void;
60
64
  runAgent(message: string, channel: string, chatId: string, origin: TurnOrigin, attachments?: UserTurnAttachment[], thinking?: string, runOptions?: {
61
65
  signal?: AbortSignal;
62
66
  runId?: string;
@@ -16,6 +16,7 @@ var GatewayAgentRunner = class {
16
16
  clarifyBridge = new ClarifyBridge();
17
17
  /** Maps webchat session key → active `runId` for `clarify` tool routing. */
18
18
  activeWebchatRunBySession = /* @__PURE__ */ new Map();
19
+ externalStreamBySession = /* @__PURE__ */ new Map();
19
20
  inputs;
20
21
  constructor(opts) {
21
22
  this.opts = opts;
@@ -63,6 +64,19 @@ var GatewayAgentRunner = class {
63
64
  disposeClarifyBridge() {
64
65
  this.clarifyBridge.dispose();
65
66
  }
67
+ registerExternalWebchatRun(sessionKey, runId, publish) {
68
+ this.activeWebchatRunBySession.set(sessionKey, runId);
69
+ this.externalStreamBySession.set(sessionKey, publish);
70
+ }
71
+ unregisterExternalWebchatRun(sessionKey, runId) {
72
+ if (this.activeWebchatRunBySession.get(sessionKey) === runId) {
73
+ this.activeWebchatRunBySession.delete(sessionKey);
74
+ this.externalStreamBySession.delete(sessionKey);
75
+ }
76
+ }
77
+ cancelClarificationForRun(runId) {
78
+ this.clarifyBridge.cancelForRun(runId);
79
+ }
66
80
  async *runAgent(message, channel, chatId, origin, attachments, thinking, runOptions) {
67
81
  const trackedRunId = runOptions?.runId;
68
82
  if (trackedRunId) {
@@ -184,7 +198,7 @@ var GatewayAgentRunner = class {
184
198
  async requestClarification(opts) {
185
199
  const { sessionKey, request, publishStreamFor } = opts;
186
200
  const runId = this.activeWebchatRunBySession.get(sessionKey);
187
- const publishStream = runId ? publishStreamFor(runId) : void 0;
201
+ const publishStream = this.externalStreamBySession.get(sessionKey) ?? (runId ? publishStreamFor(runId) : void 0);
188
202
  const deliver = ((await this.opts.sessionIndex.getSessionMetadata(sessionKey).catch(() => null))?.routing)?.source === "telegram" ? async (ctx) => {
189
203
  await this.deliverTelegramClarify(ctx);
190
204
  } : void 0;
@@ -9,9 +9,9 @@ import { TaskRunCoordinator } from "../../tasks/task-run-coordinator.js";
9
9
  import { formatAgentRunErrorForClient } from "../../agent/client-error-format.js";
10
10
  import { prependEnvelopeTimestamp } from "../../channels/envelope-timestamp.js";
11
11
  import "../chat-limits.js";
12
+ import { ChatStreamMapper } from "../chat-stream/mapper.js";
12
13
  import { resolveWebchatSessionKey } from "../resolve-webchat-session-key.js";
13
14
  import { recordExplicitRelationshipFollowUp } from "../../user-context/relationship-continuity.js";
14
- import { ChatStreamMapper } from "../chat-stream/mapper.js";
15
15
  import { coalesceThinkingDeltas } from "../chat-stream/thinking-delta-coalescer.js";
16
16
  import crypto from "crypto";
17
17
  //#region src/gateway/service/run-gateway-agent.ts
@@ -6,6 +6,7 @@ import { NotesService } from '../notes/index.js';
6
6
  import { WorkflowRunService } from '../workflows/service/workflow-run-service.js';
7
7
  import { ExtensionLoader } from '../extensions/index.js';
8
8
  import { SessionIndex } from '../session/index.js';
9
+ import { EphemeralSideChatManager, SideChatRunService } from './side-chat/index.js';
9
10
  import type { Config } from '../config/schema.js';
10
11
  import { type ResolvedGatewayAuth } from './auth.js';
11
12
  import { ModelCatalogSyncService } from '../providers/model-catalog-sync-service.js';
@@ -79,6 +80,9 @@ export declare class GatewayService {
79
80
  * `activeWebchatRunBySession` + `runAbortControllers` maps.
80
81
  */
81
82
  readonly agentRunner: GatewayAgentRunner;
83
+ /** Process-local, non-persistent side conversations forked from durable sessions. */
84
+ readonly sideChats: EphemeralSideChatManager;
85
+ readonly sideChatRuns: SideChatRunService;
82
86
  /**
83
87
  * Session CRUD / search / compaction / tag-archive-pin / stats — the gateway
84
88
  * REST surface for sessions. Routes should depend on this narrow service
@@ -44,6 +44,7 @@ import { SessionIndex } from "../session/manager.js";
44
44
  import "../session/index.js";
45
45
  import { ExtensionLoader } from "../extensions/loader.js";
46
46
  import "../extensions/index.js";
47
+ import { getEmbeddedExecutionSession } from "../agent/embedded/execution-context.js";
47
48
  import { MessageBus, MessageBusShutdownError } from "../infra/bus/queue.js";
48
49
  import "../infra/bus/index.js";
49
50
  import { AgentService } from "../agent/service.js";
@@ -77,6 +78,9 @@ import { WorkflowRunService } from "../workflows/service/workflow-run-service.js
77
78
  import { WorkflowSessionBridge } from "../workflows/service/workflow-session-bridge.js";
78
79
  import { HeartbeatService, heartbeatRunnerConfigFromConfig } from "./heartbeat/service.js";
79
80
  import "./heartbeat/index.js";
81
+ import { EphemeralSideChatManager } from "./side-chat/manager.js";
82
+ import { SideChatRunService } from "./side-chat/run-service.js";
83
+ import "./side-chat/index.js";
80
84
  import { stopTailscaleExposure } from "./tailscale-lifecycle.js";
81
85
  import { getExposureManager } from "../remote-access/exposure-manager.js";
82
86
  import { assertGatewayAuthNotKnownWeak } from "./security/known-weak-secrets.js";
@@ -190,6 +194,9 @@ var GatewayService = class {
190
194
  * `activeWebchatRunBySession` + `runAbortControllers` maps.
191
195
  */
192
196
  agentRunner;
197
+ /** Process-local, non-persistent side conversations forked from durable sessions. */
198
+ sideChats;
199
+ sideChatRuns;
193
200
  /**
194
201
  * Session CRUD / search / compaction / tag-archive-pin / stats — the gateway
195
202
  * REST surface for sessions. Routes should depend on this narrow service
@@ -363,6 +370,21 @@ var GatewayService = class {
363
370
  },
364
371
  completeRealtimeTopic: (topic) => this.realtime.completeTopic(topic)
365
372
  });
373
+ let sideChatRuns;
374
+ this.sideChats = new EphemeralSideChatManager({
375
+ getParentMetadata: (sessionKey) => this.sessionIndex.getSessionMetadata(sessionKey),
376
+ loadParentMessages: (sessionKey) => this.sessionIndex.getStore().load(sessionKey),
377
+ getDefaultModelRef: (sessionKey) => this.ensureAgentService().getModelForSession(sessionKey),
378
+ getWorkspacePath: (metadata) => metadata.cwd || this.currentWorkspacePath,
379
+ onBeforeDispose: (sideChatId, clientInstanceId) => sideChatRuns?.abort(sideChatId, clientInstanceId).then(() => void 0)
380
+ });
381
+ this.sideChatRuns = sideChatRuns = new SideChatRunService({
382
+ manager: this.sideChats,
383
+ getAgentService: () => this.ensureAgentService(),
384
+ agentRunner: this.agentRunner,
385
+ publishRealtime: (topic, event, data) => this.realtime.broker.publish(topic, event, data),
386
+ completeRealtimeTopic: (topic) => this.realtime.completeTopic(topic)
387
+ });
366
388
  this.sessions = new GatewaySessionsApi({
367
389
  sessionIndex: this.sessionIndex,
368
390
  getAgentService: () => this.ensureAgentService(),
@@ -452,13 +474,16 @@ var GatewayService = class {
452
474
  }
453
475
  return null;
454
476
  },
455
- gatewayClarify: { requestClarification: (sessionKey, request) => this.agentRunner.requestClarification({
456
- sessionKey,
457
- request,
458
- publishStreamFor: (_runId) => (event) => {
459
- this._agentService.turnDispatcher.enqueueWebchatStreamEvent(sessionKey, event);
460
- }
461
- }) }
477
+ gatewayClarify: { requestClarification: (sessionKey, request) => {
478
+ const executionSessionKey = getEmbeddedExecutionSession() ?? sessionKey;
479
+ return this.agentRunner.requestClarification({
480
+ sessionKey: executionSessionKey,
481
+ request,
482
+ publishStreamFor: (_runId) => (event) => {
483
+ this._agentService.turnDispatcher.enqueueWebchatStreamEvent(executionSessionKey, event);
484
+ }
485
+ });
486
+ } }
462
487
  });
463
488
  this._agentService.setChannelManager(this.channelManager);
464
489
  this.channelManager.setSessionModelHooks({
@@ -988,6 +1013,7 @@ var GatewayService = class {
988
1013
  log.debug("Stopping gateway service...");
989
1014
  this.readiness.markStarting();
990
1015
  this.endpointTools.close();
1016
+ await this.sideChats.disposeAll();
991
1017
  this.realtime.close();
992
1018
  await this.proactiveWorker.stop();
993
1019
  await this.discussionWorker.stop();
@@ -0,0 +1,11 @@
1
+ import type { AgentMessage } from '@earendil-works/pi-agent-core';
2
+ import type { SideChatContextSnapshot, SideChatSelection } from './types.js';
3
+ export declare function validateSideChatSelections(value: unknown): SideChatSelection[];
4
+ export declare function createSideChatContextSnapshot(params: {
5
+ parentSessionKey: string;
6
+ parentSessionId: string;
7
+ parentMessages: readonly AgentMessage[];
8
+ selections: readonly SideChatSelection[];
9
+ createdAt: string;
10
+ }): SideChatContextSnapshot;
11
+ export declare function formatSideChatSelections(selections: readonly SideChatSelection[]): string | null;
@@ -0,0 +1,108 @@
1
+ import { createHash } from "node:crypto";
2
+ //#region src/gateway/side-chat/context-snapshot.ts
3
+ const MAX_SELECTIONS = 20;
4
+ const MAX_SELECTION_CHARS = 32e3;
5
+ const MAX_TOTAL_SELECTION_CHARS = 128e3;
6
+ function selectionText(selection) {
7
+ switch (selection.type) {
8
+ case "message": return selection.content;
9
+ case "text": return selection.text;
10
+ case "file-range": return selection.text;
11
+ case "diff": return selection.diff;
12
+ }
13
+ }
14
+ function validateSideChatSelections(value) {
15
+ if (value === void 0) return [];
16
+ if (!Array.isArray(value)) throw new Error("selections must be an array");
17
+ if (value.length > MAX_SELECTIONS) throw new Error(`selections cannot exceed ${MAX_SELECTIONS} items`);
18
+ let totalChars = 0;
19
+ const selections = value.map((candidate, index) => {
20
+ if (!candidate || typeof candidate !== "object") throw new Error(`selection ${index} must be an object`);
21
+ const selection = candidate;
22
+ const id = typeof selection.id === "string" ? selection.id.trim() : "";
23
+ const type = selection.type;
24
+ if (!id) throw new Error(`selection ${index} requires id`);
25
+ let normalized;
26
+ if (type === "message") normalized = {
27
+ id,
28
+ type,
29
+ messageId: requiredString(selection.messageId, `selection ${index} messageId`),
30
+ role: requiredString(selection.role, `selection ${index} role`),
31
+ content: requiredString(selection.content, `selection ${index} content`),
32
+ label: optionalString(selection.label)
33
+ };
34
+ else if (type === "text") normalized = {
35
+ id,
36
+ type,
37
+ text: requiredString(selection.text, `selection ${index} text`),
38
+ sourceMessageId: optionalString(selection.sourceMessageId),
39
+ label: optionalString(selection.label)
40
+ };
41
+ else if (type === "file-range") {
42
+ const startLine = positiveInteger(selection.startLine, `selection ${index} startLine`);
43
+ const endLine = positiveInteger(selection.endLine, `selection ${index} endLine`);
44
+ if (endLine < startLine) throw new Error(`selection ${index} endLine must be >= startLine`);
45
+ normalized = {
46
+ id,
47
+ type,
48
+ path: requiredString(selection.path, `selection ${index} path`),
49
+ startLine,
50
+ endLine,
51
+ text: requiredString(selection.text, `selection ${index} text`),
52
+ contentHash: optionalString(selection.contentHash),
53
+ label: optionalString(selection.label)
54
+ };
55
+ } else if (type === "diff") normalized = {
56
+ id,
57
+ type,
58
+ diff: requiredString(selection.diff, `selection ${index} diff`),
59
+ path: optionalString(selection.path),
60
+ label: optionalString(selection.label)
61
+ };
62
+ else throw new Error(`selection ${index} has unsupported type`);
63
+ const chars = selectionText(normalized).length;
64
+ if (chars > MAX_SELECTION_CHARS) throw new Error(`selection ${index} exceeds ${MAX_SELECTION_CHARS} characters`);
65
+ totalChars += chars;
66
+ return normalized;
67
+ });
68
+ if (totalChars > MAX_TOTAL_SELECTION_CHARS) throw new Error(`selection content exceeds ${MAX_TOTAL_SELECTION_CHARS} characters`);
69
+ return selections;
70
+ }
71
+ function createSideChatContextSnapshot(params) {
72
+ const selections = structuredClone(params.selections);
73
+ const digest = createHash("sha256").update(JSON.stringify({
74
+ messages: params.parentMessages,
75
+ selections
76
+ })).digest("hex");
77
+ return {
78
+ parentSessionKey: params.parentSessionKey,
79
+ parentSessionId: params.parentSessionId,
80
+ parentMessageCount: params.parentMessages.length,
81
+ createdAt: params.createdAt,
82
+ selections,
83
+ contentHash: digest
84
+ };
85
+ }
86
+ function formatSideChatSelections(selections) {
87
+ if (selections.length === 0) return null;
88
+ return `The user attached the following immutable context snapshot to this side chat:\n\n${selections.map((selection, index) => {
89
+ const title = selection.label || `${selection.type} ${index + 1}`;
90
+ if (selection.type === "file-range") return `### ${title}\nSource: ${selection.path}:${selection.startLine}-${selection.endLine}\n\n${selection.text}`;
91
+ if (selection.type === "message") return `### ${title}\nSource message: ${selection.messageId} (${selection.role})\n\n${selection.content}`;
92
+ if (selection.type === "diff") return `### ${title}${selection.path ? `\nSource: ${selection.path}` : ""}\n\n${selection.diff}`;
93
+ return `### ${title}${selection.sourceMessageId ? `\nSource message: ${selection.sourceMessageId}` : ""}\n\n${selection.text}`;
94
+ }).join("\n\n")}`;
95
+ }
96
+ function requiredString(value, label) {
97
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${label} is required`);
98
+ return value;
99
+ }
100
+ function optionalString(value) {
101
+ return typeof value === "string" && value.trim() ? value : void 0;
102
+ }
103
+ function positiveInteger(value, label) {
104
+ if (!Number.isInteger(value) || Number(value) < 1) throw new Error(`${label} must be a positive integer`);
105
+ return Number(value);
106
+ }
107
+ //#endregion
108
+ export { createSideChatContextSnapshot, formatSideChatSelections, validateSideChatSelections };
@@ -0,0 +1,5 @@
1
+ export { EphemeralSideChatManager, SideChatError, parseThinkingLevel } from './manager.js';
2
+ export type { EphemeralSideChatManagerOptions } from './manager.js';
3
+ export { validateSideChatSelections } from './context-snapshot.js';
4
+ export { SideChatRunService } from './run-service.js';
5
+ export type { CreateSideChatInput, SideChatConfig, SideChatContextSnapshot, SideChatSelection, SideChatStatus, SideChatView, } from './types.js';
@@ -0,0 +1,4 @@
1
+ import { validateSideChatSelections } from "./context-snapshot.js";
2
+ import { EphemeralSideChatManager, SideChatError, parseThinkingLevel } from "./manager.js";
3
+ import { SideChatRunService } from "./run-service.js";
4
+ export { EphemeralSideChatManager, SideChatError, SideChatRunService, parseThinkingLevel, validateSideChatSelections };
@@ -0,0 +1,45 @@
1
+ import type { AgentMessage, ThinkingLevel } from '@earendil-works/pi-agent-core';
2
+ import { InMemoryTranscriptRuntime } from '../../agent/embedded/transcript-runtime.js';
3
+ import type { SessionMetadata } from '../../session/types.js';
4
+ import type { CreateSideChatInput, SideChatConfig, SideChatStatus, SideChatView } from './types.js';
5
+ export declare class SideChatError extends Error {
6
+ readonly code: 'INVALID_REQUEST' | 'NOT_FOUND' | 'LIMIT_REACHED' | 'CONFLICT';
7
+ constructor(message: string, code: 'INVALID_REQUEST' | 'NOT_FOUND' | 'LIMIT_REACHED' | 'CONFLICT');
8
+ }
9
+ export interface EphemeralSideChatManagerOptions {
10
+ getParentMetadata: (sessionKey: string) => Promise<SessionMetadata | null>;
11
+ loadParentMessages: (sessionKey: string) => Promise<AgentMessage[]>;
12
+ getDefaultModelRef: (sessionKey: string) => string;
13
+ getWorkspacePath: (metadata: SessionMetadata) => string;
14
+ idleTtlMs?: number;
15
+ maxPerClient?: number;
16
+ maxTotal?: number;
17
+ now?: () => number;
18
+ startSweepTimer?: boolean;
19
+ onBeforeDispose?: (sideChatId: string, clientInstanceId: string) => void | Promise<void>;
20
+ }
21
+ export declare class EphemeralSideChatManager {
22
+ private readonly options;
23
+ private readonly entries;
24
+ private readonly now;
25
+ private readonly idleTtlMs;
26
+ private readonly maxPerClient;
27
+ private readonly maxTotal;
28
+ private readonly sweepTimer;
29
+ constructor(options: EphemeralSideChatManagerOptions);
30
+ create(input: CreateSideChatInput): Promise<SideChatView>;
31
+ get(id: string, clientInstanceId: string): SideChatView;
32
+ getRuntime(id: string, clientInstanceId: string): InMemoryTranscriptRuntime;
33
+ getMessages(id: string, clientInstanceId: string): AgentMessage[];
34
+ updateConfig(id: string, clientInstanceId: string, patch: Partial<SideChatConfig>): SideChatView;
35
+ heartbeat(id: string, clientInstanceId: string): SideChatView;
36
+ setStatus(id: string, clientInstanceId: string, status: SideChatStatus): SideChatView;
37
+ dispose(id: string, clientInstanceId: string): Promise<boolean>;
38
+ disposeClient(clientInstanceId: string): Promise<number>;
39
+ sweepExpired(at?: number): Promise<number>;
40
+ disposeAll(): Promise<void>;
41
+ private requireEntry;
42
+ private touchEntry;
43
+ private runBeforeDispose;
44
+ }
45
+ export declare function parseThinkingLevel(value: unknown): ThinkingLevel | undefined;
@@ -0,0 +1,198 @@
1
+ import { createLogger } from "../../utils/logger/index.js";
2
+ import { init_logger } from "../../utils/logger.js";
3
+ import { evictEmbeddedSessionRunner } from "../../agent/embedded/session-runner.js";
4
+ import { InMemoryTranscriptRuntime } from "../../agent/embedded/transcript-runtime.js";
5
+ import { createSideChatContextSnapshot, formatSideChatSelections, validateSideChatSelections } from "./context-snapshot.js";
6
+ import { randomUUID } from "node:crypto";
7
+ //#region src/gateway/side-chat/manager.ts
8
+ init_logger();
9
+ const DEFAULT_IDLE_TTL_MS = 1800 * 1e3;
10
+ const DEFAULT_MAX_PER_CLIENT = 5;
11
+ const DEFAULT_MAX_TOTAL = 50;
12
+ const log = createLogger("Gateway:SideChat");
13
+ var SideChatError = class extends Error {
14
+ constructor(message, code) {
15
+ super(message);
16
+ this.code = code;
17
+ }
18
+ };
19
+ var EphemeralSideChatManager = class {
20
+ entries = /* @__PURE__ */ new Map();
21
+ now;
22
+ idleTtlMs;
23
+ maxPerClient;
24
+ maxTotal;
25
+ sweepTimer;
26
+ constructor(options) {
27
+ this.options = options;
28
+ this.now = options.now ?? Date.now;
29
+ this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
30
+ this.maxPerClient = options.maxPerClient ?? DEFAULT_MAX_PER_CLIENT;
31
+ this.maxTotal = options.maxTotal ?? DEFAULT_MAX_TOTAL;
32
+ this.sweepTimer = options.startSweepTimer === false ? null : setInterval(() => {
33
+ this.sweepExpired().catch((err) => {
34
+ log.warn({
35
+ err,
36
+ phase: "side_chat_sweep"
37
+ }, "Side chat expiry sweep failed");
38
+ });
39
+ }, Math.min(this.idleTtlMs, 6e4));
40
+ this.sweepTimer?.unref();
41
+ }
42
+ async create(input) {
43
+ const parentSessionKey = input.parentSessionKey.trim();
44
+ const clientInstanceId = input.clientInstanceId.trim();
45
+ if (!parentSessionKey || !clientInstanceId) throw new SideChatError("parentSessionKey and clientInstanceId are required", "INVALID_REQUEST");
46
+ if (this.entries.size >= this.maxTotal) throw new SideChatError("The side chat capacity has been reached", "LIMIT_REACHED");
47
+ if ([...this.entries.values()].filter((entry) => entry.clientInstanceId === clientInstanceId).length >= this.maxPerClient) throw new SideChatError(`A client can have at most ${this.maxPerClient} side chats`, "LIMIT_REACHED");
48
+ const metadata = await this.options.getParentMetadata(parentSessionKey);
49
+ if (!metadata || !metadata.sessionId) throw new SideChatError("Parent session not found", "NOT_FOUND");
50
+ const parentMessages = await this.options.loadParentMessages(parentSessionKey);
51
+ let selections;
52
+ try {
53
+ selections = validateSideChatSelections(input.selections);
54
+ } catch (error) {
55
+ throw new SideChatError(error instanceof Error ? error.message : "Invalid selections", "INVALID_REQUEST");
56
+ }
57
+ const now = this.now();
58
+ const createdAt = new Date(now).toISOString();
59
+ const id = randomUUID();
60
+ const runtime = new InMemoryTranscriptRuntime({
61
+ runtimeId: `${parentSessionKey}:side-chat:${id}`,
62
+ cwd: this.options.getWorkspacePath(metadata),
63
+ initialMessages: structuredClone(parentMessages)
64
+ });
65
+ const selectionContext = formatSideChatSelections(selections);
66
+ if (selectionContext) runtime.openSessionManager(this.options.getWorkspacePath(metadata)).appendCustomMessageEntry("side-chat-selection", selectionContext, false);
67
+ runtime.captureBaseline();
68
+ const config = {
69
+ modelRef: normalizeOptionalString(input.config?.modelRef) || this.options.getDefaultModelRef(parentSessionKey),
70
+ thinkingLevel: input.config?.thinkingLevel
71
+ };
72
+ const entry = {
73
+ id,
74
+ parentSessionKey,
75
+ clientInstanceId,
76
+ status: "idle",
77
+ createdAt,
78
+ lastActiveAt: createdAt,
79
+ expiresAt: new Date(now + this.idleTtlMs).toISOString(),
80
+ messageCount: 0,
81
+ context: createSideChatContextSnapshot({
82
+ parentSessionKey,
83
+ parentSessionId: metadata.sessionId,
84
+ parentMessages,
85
+ selections,
86
+ createdAt
87
+ }),
88
+ config,
89
+ runtime
90
+ };
91
+ this.entries.set(id, entry);
92
+ return toView(entry);
93
+ }
94
+ get(id, clientInstanceId) {
95
+ return toView(this.requireEntry(id, clientInstanceId));
96
+ }
97
+ getRuntime(id, clientInstanceId) {
98
+ return this.requireEntry(id, clientInstanceId).runtime;
99
+ }
100
+ getMessages(id, clientInstanceId) {
101
+ const entry = this.requireEntry(id, clientInstanceId);
102
+ const messages = entry.runtime.loadConversationMessages();
103
+ entry.messageCount = messages.length;
104
+ return structuredClone(messages);
105
+ }
106
+ updateConfig(id, clientInstanceId, patch) {
107
+ const entry = this.requireEntry(id, clientInstanceId);
108
+ if (entry.status === "running") throw new SideChatError("Cannot change config while a run is active", "CONFLICT");
109
+ const modelRef = patch.modelRef === void 0 ? entry.config.modelRef : normalizeOptionalString(patch.modelRef);
110
+ if (!modelRef) throw new SideChatError("modelRef cannot be empty", "INVALID_REQUEST");
111
+ entry.config = {
112
+ modelRef,
113
+ thinkingLevel: patch.thinkingLevel === void 0 ? entry.config.thinkingLevel : patch.thinkingLevel
114
+ };
115
+ this.touchEntry(entry);
116
+ return toView(entry);
117
+ }
118
+ heartbeat(id, clientInstanceId) {
119
+ const entry = this.requireEntry(id, clientInstanceId);
120
+ this.touchEntry(entry);
121
+ return toView(entry);
122
+ }
123
+ setStatus(id, clientInstanceId, status) {
124
+ const entry = this.requireEntry(id, clientInstanceId);
125
+ entry.status = status;
126
+ this.touchEntry(entry);
127
+ return toView(entry);
128
+ }
129
+ async dispose(id, clientInstanceId) {
130
+ const entry = this.entries.get(id);
131
+ if (!entry || entry.clientInstanceId !== clientInstanceId) return false;
132
+ entry.status = "closing";
133
+ await this.runBeforeDispose(id, clientInstanceId);
134
+ this.entries.delete(id);
135
+ await evictEmbeddedSessionRunner(entry.runtime.runtimeId, "side_chat_dispose");
136
+ return true;
137
+ }
138
+ async disposeClient(clientInstanceId) {
139
+ const ids = [...this.entries.values()].filter((entry) => entry.clientInstanceId === clientInstanceId).map((entry) => entry.id);
140
+ await Promise.all(ids.map((id) => this.dispose(id, clientInstanceId)));
141
+ return ids.length;
142
+ }
143
+ async sweepExpired(at = this.now()) {
144
+ const expired = [...this.entries.values()].filter((entry) => Date.parse(entry.expiresAt) <= at);
145
+ await Promise.all(expired.map((entry) => this.dispose(entry.id, entry.clientInstanceId)));
146
+ return expired.length;
147
+ }
148
+ async disposeAll() {
149
+ if (this.sweepTimer) clearInterval(this.sweepTimer);
150
+ const entries = [...this.entries.values()];
151
+ await Promise.all(entries.map((entry) => this.runBeforeDispose(entry.id, entry.clientInstanceId)));
152
+ this.entries.clear();
153
+ await Promise.all(entries.map((entry) => evictEmbeddedSessionRunner(entry.runtime.runtimeId, "side_chat_shutdown")));
154
+ }
155
+ requireEntry(id, clientInstanceId) {
156
+ const entry = this.entries.get(id);
157
+ if (!entry || entry.clientInstanceId !== clientInstanceId) throw new SideChatError("Side chat not found", "NOT_FOUND");
158
+ return entry;
159
+ }
160
+ touchEntry(entry) {
161
+ const now = this.now();
162
+ entry.lastActiveAt = new Date(now).toISOString();
163
+ entry.expiresAt = new Date(now + this.idleTtlMs).toISOString();
164
+ }
165
+ async runBeforeDispose(id, clientInstanceId) {
166
+ try {
167
+ await this.options.onBeforeDispose?.(id, clientInstanceId);
168
+ } catch (err) {
169
+ log.warn({
170
+ err,
171
+ sideChatId: id,
172
+ phase: "side_chat_abort"
173
+ }, "Side chat run cleanup failed");
174
+ }
175
+ }
176
+ };
177
+ function toView(entry) {
178
+ const { runtime: _runtime, ...view } = entry;
179
+ return structuredClone(view);
180
+ }
181
+ function normalizeOptionalString(value) {
182
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
183
+ }
184
+ function parseThinkingLevel(value) {
185
+ if (value === void 0 || value === null || value === "") return void 0;
186
+ if (typeof value !== "string" || !new Set([
187
+ "off",
188
+ "minimal",
189
+ "low",
190
+ "medium",
191
+ "high",
192
+ "xhigh",
193
+ "max"
194
+ ]).has(value)) throw new SideChatError("Invalid thinkingLevel", "INVALID_REQUEST");
195
+ return value;
196
+ }
197
+ //#endregion
198
+ export { EphemeralSideChatManager, SideChatError, parseThinkingLevel };
@@ -0,0 +1,22 @@
1
+ import type { AgentService } from '../../agent/service.js';
2
+ import type { GatewayAgentRunner } from '../service/agent-runner.js';
3
+ import { type EphemeralSideChatManager } from './manager.js';
4
+ export interface SideChatRunServiceOptions {
5
+ manager: EphemeralSideChatManager;
6
+ getAgentService: () => AgentService;
7
+ agentRunner: GatewayAgentRunner;
8
+ publishRealtime: (topic: string, event: string, data: unknown) => void;
9
+ completeRealtimeTopic: (topic: string) => void;
10
+ }
11
+ export declare class SideChatRunService {
12
+ private readonly options;
13
+ private readonly activeBySideChat;
14
+ constructor(options: SideChatRunServiceOptions);
15
+ submit(sideChatId: string, clientInstanceId: string, content: string): {
16
+ runId: string;
17
+ };
18
+ abort(sideChatId: string, clientInstanceId: string, runId?: string): Promise<boolean>;
19
+ dispose(sideChatId: string, clientInstanceId: string): Promise<boolean>;
20
+ submitClarification(sideChatId: string, clientInstanceId: string, requestId: string, answer: string): boolean;
21
+ private execute;
22
+ }