@memberjunction/ng-conversations 6.2.0 → 6.3.0-edge.0

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 (49) hide show
  1. package/README.md +2 -2
  2. package/dist/lib/components/collection/artifact-create-modal.component.js +4 -4
  3. package/dist/lib/components/collection/artifact-create-modal.component.js.map +1 -1
  4. package/dist/lib/components/collection/collection-form-modal.component.js +3 -3
  5. package/dist/lib/components/collection/collection-form-modal.component.js.map +1 -1
  6. package/dist/lib/components/collection/collections-full-view.component.js +1 -1
  7. package/dist/lib/components/collection/collections-full-view.component.js.map +1 -1
  8. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +42 -3
  9. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
  10. package/dist/lib/components/conversation/conversation-chat-area.component.js +145 -23
  11. package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
  12. package/dist/lib/components/conversation/conversation-list.component.d.ts +35 -1
  13. package/dist/lib/components/conversation/conversation-list.component.d.ts.map +1 -1
  14. package/dist/lib/components/conversation/conversation-list.component.js +65 -6
  15. package/dist/lib/components/conversation/conversation-list.component.js.map +1 -1
  16. package/dist/lib/components/conversation/conversation-remote-browser-controller.d.ts +11 -3
  17. package/dist/lib/components/conversation/conversation-remote-browser-controller.d.ts.map +1 -1
  18. package/dist/lib/components/conversation/conversation-remote-browser-controller.js +40 -4
  19. package/dist/lib/components/conversation/conversation-remote-browser-controller.js.map +1 -1
  20. package/dist/lib/components/realtime/channels/client-context-channel.d.ts +20 -4
  21. package/dist/lib/components/realtime/channels/client-context-channel.d.ts.map +1 -1
  22. package/dist/lib/components/realtime/channels/client-context-channel.js +62 -8
  23. package/dist/lib/components/realtime/channels/client-context-channel.js.map +1 -1
  24. package/dist/lib/components/realtime/remote-browser/remote-browser-tools.d.ts.map +1 -1
  25. package/dist/lib/components/realtime/remote-browser/remote-browser-tools.js +2 -2
  26. package/dist/lib/components/realtime/remote-browser/remote-browser-tools.js.map +1 -1
  27. package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts +28 -1
  28. package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts.map +1 -1
  29. package/dist/lib/components/sidebar/conversation-sidebar.component.js +51 -6
  30. package/dist/lib/components/sidebar/conversation-sidebar.component.js.map +1 -1
  31. package/dist/lib/events/chat-events.d.ts +45 -0
  32. package/dist/lib/events/chat-events.d.ts.map +1 -1
  33. package/dist/lib/events/chat-events.js +64 -0
  34. package/dist/lib/events/chat-events.js.map +1 -1
  35. package/dist/lib/services/realtime-audio-recorder.d.ts +10 -8
  36. package/dist/lib/services/realtime-audio-recorder.d.ts.map +1 -1
  37. package/dist/lib/services/realtime-audio-recorder.js +28 -12
  38. package/dist/lib/services/realtime-audio-recorder.js.map +1 -1
  39. package/dist/lib/services/realtime-session.service.d.ts +10 -3
  40. package/dist/lib/services/realtime-session.service.d.ts.map +1 -1
  41. package/dist/lib/services/realtime-session.service.js +8 -3
  42. package/dist/lib/services/realtime-session.service.js.map +1 -1
  43. package/dist/lib/services/search.service.js +1 -1
  44. package/dist/lib/services/search.service.js.map +1 -1
  45. package/dist/lib/utils/agent-artifact-summary.d.ts +1 -1
  46. package/dist/lib/utils/agent-artifact-summary.d.ts.map +1 -1
  47. package/dist/lib/utils/agent-artifact-summary.js +1 -1
  48. package/dist/lib/utils/agent-artifact-summary.js.map +1 -1
  49. package/package.json +36 -36
@@ -43,6 +43,7 @@ export declare class ConversationRemoteBrowserController {
43
43
  private provider;
44
44
  private pushSub;
45
45
  private conversationId;
46
+ private standbyConversationId;
46
47
  private currentUrl;
47
48
  private stateVersion;
48
49
  private disposed;
@@ -57,6 +58,13 @@ export declare class ConversationRemoteBrowserController {
57
58
  get OwnsTools(): boolean;
58
59
  /** Connects the controller to the agent client (tool dispatch) and the provider (server calls, pushed frames). */
59
60
  Initialize(agentClient: AgentClientService, provider: GraphQLDataProvider | null): void;
61
+ /**
62
+ * Registers the `browser_*` tools for `conversationId` in standby mode when `AllowRemoteBrowser` is enabled,
63
+ * so an agent turn can call `browser_OpenUrl` (auto-opening the browser drawer) before the user manually
64
+ * opens the drawer. Does not start a server browser or light the header button until {@link Open} or
65
+ * {@link ExecuteBrowserTool} runs.
66
+ */
67
+ SetConversation(conversationId: string | null): void;
60
68
  /**
61
69
  * Opens the browser for `conversationId` and claims the `browser_*` tools. A browser this controller
62
70
  * held for a different conversation is ended first.
@@ -85,10 +93,10 @@ export declare class ConversationRemoteBrowserController {
85
93
  /** What the agent is told about the browser. */
86
94
  GetAppContextSnapshot(): ConversationRemoteBrowserContextSnapshot;
87
95
  /**
88
- * Adds the browser to an app context while it is open: its state under
89
- * `AdditionalContext.RemoteBrowser`, and, while this controller owns them, the `browser_*` tools
96
+ * Adds the browser to an app context while it is open or in standby for an allowed conversation: its state
97
+ * under `AdditionalContext.RemoteBrowser`, and, while this controller owns them, the `browser_*` tools
90
98
  * under `Capabilities.Tools`, the tier an agent run reads a surface's tools from. Returns `base`
91
- * unchanged while no browser is open.
99
+ * unchanged while no browser is open or in standby.
92
100
  */
93
101
  WithBrowserContext(base: Record<string, unknown> | null): Record<string, unknown> | null;
94
102
  /** Ends the browser and releases the tools, push subscription and channel. */
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-remote-browser-controller.d.ts","sourceRoot":"","sources":["../../../../src/lib/components/conversation/conversation-remote-browser-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG3D,OAAO,EAAE,mBAAmB,EAAoB,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAGrE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6DAA6D,CAAC;AAG5G,mHAAmH;AACnH,MAAM,WAAW,wCAAwC;IACvD,IAAI,EAAE,OAAO,CAAC;IACd,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED;;GAEG;AACH,MA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AWzC;;;OAGG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAcnC,yFAAyF;IAClF,WAAW,CAAC,OAAO,EAAE,6BAA6B,GAAG,IAAI;IAOhE,oFAAoF;IAC7E,aAAa,IAAI,IAAI;IAI5B,gHAAgH;IACnG,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAKxF,qEAAqE;IACxD,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,IAAI,CAAC,EAAE,SAAS,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAkB1J,gDAAgD;IACzC,qBAAqB,IAAI,wCAAwC;IAIxE;;;;;OAKG;IACI,kBAAkB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAe/F,8EAA8E;IACvE,OAAO,IAAI,IAAI;IAQtB;;;OAGG;IACI,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAwClD,8FAA8F;IAC9F,OAAO,CAAC,MAAM;IAQd,OAAO,CAAC,OAAO;IAOf,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,sBAAsB;YAShB,mBAAmB;IAqBjC,OAAO,CAAC,oBAAoB;CAqB7B"}
1
+ {"version":3,"file":"conversation-remote-browser-controller.d.ts","sourceRoot":"","sources":["../../../../src/lib/components/conversation/conversation-remote-browser-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG3D,OAAO,EAAE,mBAAmB,EAAoB,MAAM,sCAAs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8FAA8F;IAC9F,OAAO,CAAC,MAAM;IAQd,OAAO,CAAC,OAAO;IAOf,OAAO,CAAC,oBAAoB;IAmB5B,OAAO,CAAC,sBAAsB;YAShB,mBAAmB;IAqBjC,OAAO,CAAC,oBAAoB;CAqB7B"}
@@ -43,6 +43,7 @@ export class ConversationRemoteBrowserController {
43
43
  provider = null;
44
44
  pushSub = null;
45
45
  conversationId = null;
46
+ standbyConversationId = null;
46
47
  currentUrl = null;
47
48
  stateVersion = 0;
48
49
  disposed = false;
@@ -74,6 +75,32 @@ export class ConversationRemoteBrowserController {
74
75
  this.pushSub?.unsubscribe();
75
76
  this.pushSub = provider?.PushStatusUpdates().subscribe((raw) => this.HandlePushMessage(raw)) ?? null;
76
77
  }
78
+ /**
79
+ * Registers the `browser_*` tools for `conversationId` in standby mode when `AllowRemoteBrowser` is enabled,
80
+ * so an agent turn can call `browser_OpenUrl` (auto-opening the browser drawer) before the user manually
81
+ * opens the drawer. Does not start a server browser or light the header button until {@link Open} or
82
+ * {@link ExecuteBrowserTool} runs.
83
+ */
84
+ SetConversation(conversationId) {
85
+ const nextId = conversationId?.trim() || null;
86
+ if (!nextId) {
87
+ if (!this.standbyConversationId) {
88
+ return;
89
+ }
90
+ this.standbyConversationId = null;
91
+ if (!this.conversationId) {
92
+ this.unregisterBrowserTools();
93
+ }
94
+ this.changed();
95
+ return;
96
+ }
97
+ if (this.standbyConversationId && UUIDsEqual(this.standbyConversationId, nextId) && this.OwnsTools) {
98
+ return;
99
+ }
100
+ this.standbyConversationId = nextId;
101
+ this.registerBrowserTools();
102
+ this.changed();
103
+ }
77
104
  /**
78
105
  * Opens the browser for `conversationId` and claims the `browser_*` tools. A browser this controller
79
106
  * held for a different conversation is ended first.
@@ -94,7 +121,13 @@ export class ConversationRemoteBrowserController {
94
121
  */
95
122
  async Close() {
96
123
  const conversationId = this.conversationId;
124
+ const hadStandby = this.standbyConversationId !== null;
125
+ this.standbyConversationId = null;
97
126
  if (!conversationId) {
127
+ if (hadStandby) {
128
+ this.unregisterBrowserTools();
129
+ this.changed();
130
+ }
98
131
  return;
99
132
  }
100
133
  // Unbinding reads the session ID synchronously, so it must run before the ID is cleared.
@@ -123,6 +156,9 @@ export class ConversationRemoteBrowserController {
123
156
  }
124
157
  /** Runs one `browser_*` tool against this conversation's browser. */
125
158
  async ExecuteBrowserTool(toolName, params) {
159
+ if (!this.conversationId && this.standbyConversationId) {
160
+ this.Open(this.standbyConversationId);
161
+ }
126
162
  if (!this.conversationId) {
127
163
  return { Success: false, ErrorMessage: 'No browser is open for this conversation.' };
128
164
  }
@@ -145,13 +181,13 @@ export class ConversationRemoteBrowserController {
145
181
  return { Open: this.conversationId !== null, CurrentUrl: this.currentUrl };
146
182
  }
147
183
  /**
148
- * Adds the browser to an app context while it is open: its state under
149
- * `AdditionalContext.RemoteBrowser`, and, while this controller owns them, the `browser_*` tools
184
+ * Adds the browser to an app context while it is open or in standby for an allowed conversation: its state
185
+ * under `AdditionalContext.RemoteBrowser`, and, while this controller owns them, the `browser_*` tools
150
186
  * under `Capabilities.Tools`, the tier an agent run reads a surface's tools from. Returns `base`
151
- * unchanged while no browser is open.
187
+ * unchanged while no browser is open or in standby.
152
188
  */
153
189
  WithBrowserContext(base) {
154
- if (!this.conversationId) {
190
+ if (!this.conversationId && !this.standbyConversationId) {
155
191
  return base;
156
192
  }
157
193
  const context = base ?? {};
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-remote-browser-controller.js","sourceRoot":"","sources":["../../../../src/lib/components/conversation/conversation-remote-browser-controller.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAuB,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAG7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,mDAAmD,CAAC;AAEzF,OAAO,EAAE,+BAA+B,EAAE,yBAAyB,EAAE,MAAM,iDAAiD,CAAC;AAyB7H;;;GAGG;AACH,MAAM,sBAAsB,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YACL,SAAS,EAAE,mBAAmB;YAC9B,IAAI,QAAQ;gBACV,OAAO,IAAI,CAAC,QAAQ,CAAC;YACvB,CAAC;YACD,IAAI,cAAc;gBAChB,OAAO,IAAI,CAAC,cAAc,CAAC;YAC7B,CAAC;YACD,kGAAkG;YAClG,eAAe,EAAE,CAAC,IAAY,EAAE,EAAE;gBAChC,MAAM,KAAK,GAAG,0DAA0D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACpF,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,CAAC;YACD,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;YAC5B,YAAY,EAAE,GAAG,EAAE,CAAC,SAAS;YAC7B,cAAc,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;YAChC,mBAAmB,EAAE,CAAI,KAAa,EAAE,SAAoC,EAAE,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAI,KAAK,EAAE,SAAS,CAAC;SAC/H,CAAC;IACJ,CAAC;CACF;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAAiC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/G,CAAC","sourcesContent":["import { Subscription } from 'rxjs';\nimport { JSONObject, JSONValue } from '@memberjunction/ai';\nimport { ClientToolMetadata } from '@memberjunction/ai-core-plus';\nimport { UUIDsEqual } from '@memberjunction/global';\nimport { GraphQLDataProvider, SafeGraphQLError } from '@memberjunction/graphql-dataprovider';\nimport { AgentClientService } from '@memberjunction/ng-agent-client';\nimport { RealtimeChannelContext } from '@memberjunction/realtime-runtime';\nimport { RemoteBrowserChannel } from '../realtime/remote-browser/remote-browser-channel';\nimport { RemoteBrowserSurfaceComponent } from '../realtime/remote-browser/remote-browser-surface.component';\nimport { REMOTE_BROWSER_TOOL_DEFINITIONS, REMOTE_BROWSER_TOOL_NAMES } from '../realtime/remote-browser/remote-browser-tools';\n\n/** What a text agent is told about the conversation's browser, as `appContext.AdditionalContext.RemoteBrowser`. */\nexport interface ConversationRemoteBrowserContextSnapshot {\n Open: boolean;\n CurrentUrl: string | null;\n}\n\n/**\n * Options for constructing a {@link ConversationRemoteBrowserController}.\n */\nexport interface ConversationRemoteBrowserControllerOptions {\n /** Invoked when an agent's `browser_*` tool runs, so the UI can show the browser drawer. */\n OnAutoOpenSurface?: () => void;\n /** Invoked when the browser opens or closes, or its URL changes. */\n OnStateChange?: () => void;\n /**\n * Invoked once when the server refuses this conversation a browser (not enabled, not the caller's, over\n * the cap). The controller has already closed it, which stops the live view's polling.\n */\n OnSessionRefused?: (message: string) => void;\n /** Optional custom GraphQL executor (used by unit tests; defaults to the provider's `ExecuteGQL`). */\n ExecuteServerAction?: <T>(query: string, variables: Record<string, JSONValue>) => Promise<T | null>;\n}\n\n/**\n * The `extensions.code` the server sets on a refusal that asking again cannot change (browsers not enabled,\n * not the caller's, over a cap): MJServer's `RemoteBrowserRefusedError`.\n */\nconst REMOTE_BROWSER_REFUSED = 'REMOTE_BROWSER_REFUSED';\n\nconst END_REMOTE_BROWSER_SESSION_MUTATION = `\n mutation EndRemoteBrowserSession($agentSessionID: String!) {\n EndRemoteBrowserSession(agentSessionID: $agentSessionID)\n }\n`;\n\n/**\n * The `browser_*` tools a text conversation's agents get: all but AchieveGoal, whose goal loop clicks\n * and navigates on its own, past the click guard (the server refuses goal runs for a conversation too).\n */\nconst TEXT_BROWSER_TOOLS = REMOTE_BROWSER_TOOL_DEFINITIONS.filter((def) => def.Name !== REMOTE_BROWSER_TOOL_NAMES.AchieveGoal);\n\n/** The text browser tools in the shape an agent run reads from `appContext.Capabilities.Tools`. */\nconst BROWSER_TOOL_METADATA: ClientToolMetadata[] = TEXT_BROWSER_TOOLS.map((def) => ({\n Name: def.Name,\n Description: def.Description,\n InputSchema: (def.ParametersSchema ?? {}) as Record<string, unknown>,\n}));\n\ntype ClientToolHandler = ReturnType<AgentClientService['GetRegisteredTools']>[number]['Handler'];\n\n/**\n * Gives one text conversation (`MJ: Conversations`) a live Remote Browser its agents can drive.\n *\n * The browser belongs to the conversation that opened it ({@link Open}); the controller captures that\n * ID, so a later conversation switch still stops and ends the right browser ({@link Close}).\n *\n * Agents reach the browser through the `browser_*` client tools. Their handlers live in\n * `AgentClientService`, whose registry is app-wide, so they are registered only while this\n * controller's browser is open, and removed on close only if this controller still owns them (a chat\n * area that opened a browser later takes them over). The tools are advertised to this conversation's\n * agent runs alone, through `appContext.Capabilities.Tools` ({@link WithBrowserContext}).\n */\nexport class ConversationRemoteBrowserController {\n private readonly channel = new RemoteBrowserChannel();\n private readonly options: ConversationRemoteBrowserControllerOptions;\n private readonly handlers = new Map<string, ClientToolHandler>();\n private agentClient: AgentClientService | null = null;\n private provider: GraphQLDataProvider | null = null;\n private pushSub: Subscription | null = null;\n private conversationId: string | null = null;\n private currentUrl: string | null = null;\n private stateVersion = 0;\n private disposed = false;\n\n constructor(options: ConversationRemoteBrowserControllerOptions = {}) {\n this.options = options;\n this.channel.Initialize(this.createChannelContext());\n }\n\n /** The conversation whose browser is open, or `null` when none is. */\n public get ConversationId(): string | null {\n return this.conversationId;\n }\n\n /** The browser's last known URL. */\n public get CurrentUrl(): string | null {\n return this.currentUrl;\n }\n\n /** Bumps on every open, close and URL change, so a host can cache what it derives from the state. */\n public get StateVersion(): number {\n return this.stateVersion;\n }\n\n /** Whether the app-wide registry holds THIS controller's `browser_*` handlers. */\n public get OwnsTools(): boolean {\n const registered = this.agentClient?.GetRegisteredTools() ?? [];\n return this.handlers.size > 0 && Array.from(this.handlers).every(([name, handler]) => registered.find((t) => t.Name === name)?.Handler === handler);\n }\n\n /** Connects the controller to the agent client (tool dispatch) and the provider (server calls, pushed frames). */\n public Initialize(agentClient: AgentClientService, provider: GraphQLDataProvider | null): void {\n this.agentClient = agentClient;\n this.provider = provider;\n this.pushSub?.unsubscribe();\n this.pushSub = provider?.PushStatusUpdates().subscribe((raw: string) => this.HandlePushMessage(raw)) ?? null;\n }\n\n /**\n * Opens the browser for `conversationId` and claims the `browser_*` tools. A browser this controller\n * held for a different conversation is ended first.\n */\n public Open(conversationId: string): void {\n if (this.conversationId && UUIDsEqual(this.conversationId, conversationId)) {\n this.registerBrowserTools();\n return;\n }\n void this.Close();\n this.conversationId = conversationId;\n this.registerBrowserTools();\n this.changed();\n }\n\n /**\n * Ends the conversation's browser: stops its streams, gives up the tools this controller still owns,\n * and ends the server browser so no Chromium process (or billed hosted browser) is left running.\n */\n public async Close(): Promise<void> {\n const conversationId = this.conversationId;\n if (!conversationId) {\n return;\n }\n // Unbinding reads the session ID synchronously, so it must run before the ID is cleared.\n this.channel.UnbindSurface();\n this.unregisterBrowserTools();\n this.conversationId = null;\n this.currentUrl = null;\n this.changed();\n await this.executeServerAction(END_REMOTE_BROWSER_SESSION_MUTATION, { agentSessionID: conversationId });\n }\n\n /** Binds the drawer's live surface (starts the screencast, audio and human takeover). */\n public BindSurface(surface: RemoteBrowserSurfaceComponent): void {\n this.channel.BindSurface(surface);\n if (this.currentUrl) {\n surface.SetCurrentUrl(this.currentUrl);\n }\n }\n\n /** Unbinds the surface when the drawer is hidden; the browser itself stays open. */\n public UnbindSurface(): void {\n this.channel.UnbindSurface();\n }\n\n /** Navigates the browser, e.g. from the drawer's URL bar; a refusal or failure comes back in `ErrorMessage`. */\n public async Navigate(url: string): Promise<{ Success: boolean; ErrorMessage?: string }> {\n const result = await this.ExecuteBrowserTool(REMOTE_BROWSER_TOOL_NAMES.OpenUrl, { url });\n return { Success: result.Success, ErrorMessage: result.ErrorMessage };\n }\n\n /** Runs one `browser_*` tool against this conversation's browser. */\n public async ExecuteBrowserTool(toolName: string, params: Record<string, unknown>): Promise<{ Success: boolean; Data?: JSONValue; ErrorMessage?: string }> {\n if (!this.conversationId) {\n return { Success: false, ErrorMessage: 'No browser is open for this conversation.' };\n }\n this.options.OnAutoOpenSurface?.();\n const raw = await this.channel.ApplyAgentTool(toolName, JSON.stringify(params ?? {}));\n let result: { success?: boolean; currentUrl?: string; detail?: string; error?: string };\n try {\n result = JSON.parse(raw);\n } catch {\n return { Success: true, Data: { raw } };\n }\n this.setUrl(result.currentUrl);\n return result.success === false\n ? { Success: false, Data: result as JSONObject, ErrorMessage: result.error ?? result.detail ?? 'Browser tool execution failed.' }\n : { Success: true, Data: result as JSONObject };\n }\n\n /** What the agent is told about the browser. */\n public GetAppContextSnapshot(): ConversationRemoteBrowserContextSnapshot {\n return { Open: this.conversationId !== null, CurrentUrl: this.currentUrl };\n }\n\n /**\n * Adds the browser to an app context while it is open: its state under\n * `AdditionalContext.RemoteBrowser`, and, while this controller owns them, the `browser_*` tools\n * under `Capabilities.Tools`, the tier an agent run reads a surface's tools from. Returns `base`\n * unchanged while no browser is open.\n */\n public WithBrowserContext(base: Record<string, unknown> | null): Record<string, unknown> | null {\n if (!this.conversationId) {\n return base;\n }\n const context = base ?? {};\n const additional = asRecord(context['AdditionalContext']);\n const capabilities = asRecord(context['Capabilities']);\n const tools = Array.isArray(capabilities['Tools']) ? (capabilities['Tools'] as ClientToolMetadata[]) : [];\n return {\n ...context,\n AdditionalContext: { ...additional, RemoteBrowser: this.GetAppContextSnapshot() },\n ...(this.OwnsTools ? { Capabilities: { ...capabilities, Tools: [...tools, ...BROWSER_TOOL_METADATA] } } : {}),\n };\n }\n\n /** Ends the browser and releases the tools, push subscription and channel. */\n public Dispose(): void {\n this.disposed = true;\n void this.Close();\n this.pushSub?.unsubscribe();\n this.pushSub = null;\n this.channel.Dispose();\n }\n\n /**\n * Routes a pushed `RemoteBrowserScreencastFrame` or `RemoteBrowserAudioChunk` to the channel when it\n * belongs to this controller's browser.\n */\n public HandlePushMessage(rawMessage: string): void {\n if (!this.conversationId || !rawMessage) {\n return;\n }\n let message: {\n resolver?: string;\n type?: string;\n agentSessionID?: string;\n currentUrl?: string | null;\n dataBase64?: string;\n sampleRate?: number;\n channels?: number;\n seq?: number;\n };\n try {\n const outer = JSON.parse(rawMessage) as Record<string, unknown>;\n message = typeof outer['message'] === 'string' ? JSON.parse(outer['message']) : outer;\n } catch {\n return; // Not JSON: an unrelated status update.\n }\n if (message.resolver !== 'RemoteBrowserActionResolver' || !message.agentSessionID || !UUIDsEqual(message.agentSessionID, this.conversationId)) {\n return;\n }\n if (typeof message.dataBase64 !== 'string') {\n return;\n }\n if (message.type === 'RemoteBrowserScreencastFrame') {\n this.channel.OnScreencastFrame(message.dataBase64, message.currentUrl ?? null);\n this.setUrl(message.currentUrl);\n } else if (message.type === 'RemoteBrowserAudioChunk') {\n this.channel.OnAudioChunk({\n dataBase64: message.dataBase64,\n codec: 'webm-opus',\n sampleRate: message.sampleRate ?? 48000,\n channels: message.channels ?? 2,\n seq: message.seq ?? 0,\n });\n }\n }\n\n /** Records a new URL; frames repeat the same one, so only a real change notifies the host. */\n private setUrl(url: string | null | undefined): void {\n const next = url?.trim();\n if (next && next !== this.currentUrl) {\n this.currentUrl = next;\n this.changed();\n }\n }\n\n private changed(): void {\n this.stateVersion++;\n if (!this.disposed) {\n this.options.OnStateChange?.();\n }\n }\n\n private registerBrowserTools(): void {\n const agentClient = this.agentClient;\n if (!agentClient) {\n return;\n }\n for (const def of TEXT_BROWSER_TOOLS) {\n let handler = this.handlers.get(def.Name);\n if (!handler) {\n handler = (params: Record<string, unknown>) => this.ExecuteBrowserTool(def.Name, params);\n this.handlers.set(def.Name, handler);\n }\n agentClient.RegisterTool({ Name: def.Name, Description: def.Description, ParameterSchema: (def.ParametersSchema ?? {}) as JSONObject, Handler: handler });\n }\n const sessionId = this.provider?.sessionId;\n if (sessionId && (!agentClient.IsActive || agentClient.SessionId !== sessionId)) {\n agentClient.StartSession(sessionId);\n }\n }\n\n private unregisterBrowserTools(): void {\n const registered = this.agentClient?.GetRegisteredTools() ?? [];\n for (const [name, handler] of this.handlers) {\n if (registered.find((t) => t.Name === name)?.Handler === handler) {\n this.agentClient?.UnregisterTool(name);\n }\n }\n }\n\n private async executeServerAction<T>(query: string, variables: Record<string, JSONValue>): Promise<T | null> {\n try {\n if (this.options.ExecuteServerAction) {\n return await this.options.ExecuteServerAction<T>(query, variables);\n }\n return this.provider ? (((await this.provider.ExecuteGQL(query, variables)) as T) ?? null) : null;\n } catch (err) {\n if (err instanceof SafeGraphQLError && err.Code === REMOTE_BROWSER_REFUSED) {\n // Asking again gets the same answer: close, so the live view stops polling, and say why once. Only\n // for the browser still open: a refusal for one already left (its End, after a switch) changes nothing.\n if (UUIDsEqual(variables['agentSessionID'] as string | null, this.conversationId)) {\n void this.Close();\n this.options.OnSessionRefused?.(err.message);\n }\n } else {\n console.warn('[ConversationRemoteBrowserController] GraphQL execution failed:', err);\n }\n return null;\n }\n }\n\n private createChannelContext(): RealtimeChannelContext {\n const self = this;\n return {\n AgentName: 'ConversationAgent',\n get Provider(): GraphQLDataProvider | null {\n return self.provider;\n },\n get AgentSessionID(): string | null {\n return self.conversationId;\n },\n // The channel narrates page changes as notes; a text conversation only needs the URL out of them.\n SendContextNote: (text: string) => {\n const match = /^\\[browser\\] (?:current page|the page changed to): (\\S+)/.exec(text);\n self.setUrl(match?.[1]);\n },\n RequestSave: () => undefined,\n SetFocusMode: () => undefined,\n SaveAsArtifact: async () => null,\n ExecuteServerAction: <T>(query: string, variables: Record<string, JSONValue>) => self.executeServerAction<T>(query, variables),\n };\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n"]}
1
+ {"version":3,"file":"conversation-remote-browser-controller.js","sourceRoot":"","sources":["../../../../src/lib/components/conversation/conversation-remote-browser-controller.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAuB,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAG7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,mDAAmD,CAAC;AA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OAAO;YACL,SAAS,EAAE,mBAAmB;YAC9B,IAAI,QAAQ;gBACV,OAAO,IAAI,CAAC,QAAQ,CAAC;YACvB,CAAC;YACD,IAAI,cAAc;gBAChB,OAAO,IAAI,CAAC,cAAc,CAAC;YAC7B,CAAC;YACD,kGAAkG;YAClG,eAAe,EAAE,CAAC,IAAY,EAAE,EAAE;gBAChC,MAAM,KAAK,GAAG,0DAA0D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACpF,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1B,CAAC;YACD,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;YAC5B,YAAY,EAAE,GAAG,EAAE,CAAC,SAAS;YAC7B,cAAc,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;YAChC,mBAAmB,EAAE,CAAI,KAAa,EAAE,SAAoC,EAAE,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAI,KAAK,EAAE,SAAS,CAAC;SAC/H,CAAC;IACJ,CAAC;CACF;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAAiC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/G,CAAC","sourcesContent":["import { Subscription } from 'rxjs';\nimport { JSONObject, JSONValue } from '@memberjunction/ai';\nimport { ClientToolMetadata } from '@memberjunction/ai-core-plus';\nimport { UUIDsEqual } from '@memberjunction/global';\nimport { GraphQLDataProvider, SafeGraphQLError } from '@memberjunction/graphql-dataprovider';\nimport { AgentClientService } from '@memberjunction/ng-agent-client';\nimport { RealtimeChannelContext } from '@memberjunction/realtime-runtime';\nimport { RemoteBrowserChannel } from '../realtime/remote-browser/remote-browser-channel';\nimport { RemoteBrowserSurfaceComponent } from '../realtime/remote-browser/remote-browser-surface.component';\nimport { REMOTE_BROWSER_TOOL_DEFINITIONS, REMOTE_BROWSER_TOOL_NAMES } from '../realtime/remote-browser/remote-browser-tools';\n\n/** What a text agent is told about the conversation's browser, as `appContext.AdditionalContext.RemoteBrowser`. */\nexport interface ConversationRemoteBrowserContextSnapshot {\n Open: boolean;\n CurrentUrl: string | null;\n}\n\n/**\n * Options for constructing a {@link ConversationRemoteBrowserController}.\n */\nexport interface ConversationRemoteBrowserControllerOptions {\n /** Invoked when an agent's `browser_*` tool runs, so the UI can show the browser drawer. */\n OnAutoOpenSurface?: () => void;\n /** Invoked when the browser opens or closes, or its URL changes. */\n OnStateChange?: () => void;\n /**\n * Invoked once when the server refuses this conversation a browser (not enabled, not the caller's, over\n * the cap). The controller has already closed it, which stops the live view's polling.\n */\n OnSessionRefused?: (message: string) => void;\n /** Optional custom GraphQL executor (used by unit tests; defaults to the provider's `ExecuteGQL`). */\n ExecuteServerAction?: <T>(query: string, variables: Record<string, JSONValue>) => Promise<T | null>;\n}\n\n/**\n * The `extensions.code` the server sets on a refusal that asking again cannot change (browsers not enabled,\n * not the caller's, over a cap): MJServer's `RemoteBrowserRefusedError`.\n */\nconst REMOTE_BROWSER_REFUSED = 'REMOTE_BROWSER_REFUSED';\n\nconst END_REMOTE_BROWSER_SESSION_MUTATION = `\n mutation EndRemoteBrowserSession($agentSessionID: String!) {\n EndRemoteBrowserSession(agentSessionID: $agentSessionID)\n }\n`;\n\n/**\n * The `browser_*` tools a text conversation's agents get: all but AchieveGoal, whose goal loop clicks\n * and navigates on its own, past the click guard (the server refuses goal runs for a conversation too).\n */\nconst TEXT_BROWSER_TOOLS = REMOTE_BROWSER_TOOL_DEFINITIONS.filter((def) => def.Name !== REMOTE_BROWSER_TOOL_NAMES.AchieveGoal);\n\n/** The text browser tools in the shape an agent run reads from `appContext.Capabilities.Tools`. */\nconst BROWSER_TOOL_METADATA: ClientToolMetadata[] = TEXT_BROWSER_TOOLS.map((def) => ({\n Name: def.Name,\n Description: def.Description,\n InputSchema: (def.ParametersSchema ?? {}) as Record<string, unknown>,\n}));\n\ntype ClientToolHandler = ReturnType<AgentClientService['GetRegisteredTools']>[number]['Handler'];\n\n/**\n * Gives one text conversation (`MJ: Conversations`) a live Remote Browser its agents can drive.\n *\n * The browser belongs to the conversation that opened it ({@link Open}); the controller captures that\n * ID, so a later conversation switch still stops and ends the right browser ({@link Close}).\n *\n * Agents reach the browser through the `browser_*` client tools. Their handlers live in\n * `AgentClientService`, whose registry is app-wide, so they are registered only while this\n * controller's browser is open, and removed on close only if this controller still owns them (a chat\n * area that opened a browser later takes them over). The tools are advertised to this conversation's\n * agent runs alone, through `appContext.Capabilities.Tools` ({@link WithBrowserContext}).\n */\nexport class ConversationRemoteBrowserController {\n private readonly channel = new RemoteBrowserChannel();\n private readonly options: ConversationRemoteBrowserControllerOptions;\n private readonly handlers = new Map<string, ClientToolHandler>();\n private agentClient: AgentClientService | null = null;\n private provider: GraphQLDataProvider | null = null;\n private pushSub: Subscription | null = null;\n private conversationId: string | null = null;\n private standbyConversationId: string | null = null;\n private currentUrl: string | null = null;\n private stateVersion = 0;\n private disposed = false;\n\n constructor(options: ConversationRemoteBrowserControllerOptions = {}) {\n this.options = options;\n this.channel.Initialize(this.createChannelContext());\n }\n\n /** The conversation whose browser is open, or `null` when none is. */\n public get ConversationId(): string | null {\n return this.conversationId;\n }\n\n /** The browser's last known URL. */\n public get CurrentUrl(): string | null {\n return this.currentUrl;\n }\n\n /** Bumps on every open, close and URL change, so a host can cache what it derives from the state. */\n public get StateVersion(): number {\n return this.stateVersion;\n }\n\n /** Whether the app-wide registry holds THIS controller's `browser_*` handlers. */\n public get OwnsTools(): boolean {\n const registered = this.agentClient?.GetRegisteredTools() ?? [];\n return this.handlers.size > 0 && Array.from(this.handlers).every(([name, handler]) => registered.find((t) => t.Name === name)?.Handler === handler);\n }\n\n /** Connects the controller to the agent client (tool dispatch) and the provider (server calls, pushed frames). */\n public Initialize(agentClient: AgentClientService, provider: GraphQLDataProvider | null): void {\n this.agentClient = agentClient;\n this.provider = provider;\n this.pushSub?.unsubscribe();\n this.pushSub = provider?.PushStatusUpdates().subscribe((raw: string) => this.HandlePushMessage(raw)) ?? null;\n }\n\n /**\n * Registers the `browser_*` tools for `conversationId` in standby mode when `AllowRemoteBrowser` is enabled,\n * so an agent turn can call `browser_OpenUrl` (auto-opening the browser drawer) before the user manually\n * opens the drawer. Does not start a server browser or light the header button until {@link Open} or\n * {@link ExecuteBrowserTool} runs.\n */\n public SetConversation(conversationId: string | null): void {\n const nextId = conversationId?.trim() || null;\n if (!nextId) {\n if (!this.standbyConversationId) {\n return;\n }\n this.standbyConversationId = null;\n if (!this.conversationId) {\n this.unregisterBrowserTools();\n }\n this.changed();\n return;\n }\n if (this.standbyConversationId && UUIDsEqual(this.standbyConversationId, nextId) && this.OwnsTools) {\n return;\n }\n this.standbyConversationId = nextId;\n this.registerBrowserTools();\n this.changed();\n }\n\n /**\n * Opens the browser for `conversationId` and claims the `browser_*` tools. A browser this controller\n * held for a different conversation is ended first.\n */\n public Open(conversationId: string): void {\n if (this.conversationId && UUIDsEqual(this.conversationId, conversationId)) {\n this.registerBrowserTools();\n return;\n }\n void this.Close();\n this.conversationId = conversationId;\n this.registerBrowserTools();\n this.changed();\n }\n\n /**\n * Ends the conversation's browser: stops its streams, gives up the tools this controller still owns,\n * and ends the server browser so no Chromium process (or billed hosted browser) is left running.\n */\n public async Close(): Promise<void> {\n const conversationId = this.conversationId;\n const hadStandby = this.standbyConversationId !== null;\n this.standbyConversationId = null;\n if (!conversationId) {\n if (hadStandby) {\n this.unregisterBrowserTools();\n this.changed();\n }\n return;\n }\n // Unbinding reads the session ID synchronously, so it must run before the ID is cleared.\n this.channel.UnbindSurface();\n this.unregisterBrowserTools();\n this.conversationId = null;\n this.currentUrl = null;\n this.changed();\n await this.executeServerAction(END_REMOTE_BROWSER_SESSION_MUTATION, { agentSessionID: conversationId });\n }\n\n /** Binds the drawer's live surface (starts the screencast, audio and human takeover). */\n public BindSurface(surface: RemoteBrowserSurfaceComponent): void {\n this.channel.BindSurface(surface);\n if (this.currentUrl) {\n surface.SetCurrentUrl(this.currentUrl);\n }\n }\n\n /** Unbinds the surface when the drawer is hidden; the browser itself stays open. */\n public UnbindSurface(): void {\n this.channel.UnbindSurface();\n }\n\n /** Navigates the browser, e.g. from the drawer's URL bar; a refusal or failure comes back in `ErrorMessage`. */\n public async Navigate(url: string): Promise<{ Success: boolean; ErrorMessage?: string }> {\n const result = await this.ExecuteBrowserTool(REMOTE_BROWSER_TOOL_NAMES.OpenUrl, { url });\n return { Success: result.Success, ErrorMessage: result.ErrorMessage };\n }\n\n /** Runs one `browser_*` tool against this conversation's browser. */\n public async ExecuteBrowserTool(toolName: string, params: Record<string, unknown>): Promise<{ Success: boolean; Data?: JSONValue; ErrorMessage?: string }> {\n if (!this.conversationId && this.standbyConversationId) {\n this.Open(this.standbyConversationId);\n }\n if (!this.conversationId) {\n return { Success: false, ErrorMessage: 'No browser is open for this conversation.' };\n }\n this.options.OnAutoOpenSurface?.();\n const raw = await this.channel.ApplyAgentTool(toolName, JSON.stringify(params ?? {}));\n let result: { success?: boolean; currentUrl?: string; detail?: string; error?: string };\n try {\n result = JSON.parse(raw);\n } catch {\n return { Success: true, Data: { raw } };\n }\n this.setUrl(result.currentUrl);\n return result.success === false\n ? { Success: false, Data: result as JSONObject, ErrorMessage: result.error ?? result.detail ?? 'Browser tool execution failed.' }\n : { Success: true, Data: result as JSONObject };\n }\n\n /** What the agent is told about the browser. */\n public GetAppContextSnapshot(): ConversationRemoteBrowserContextSnapshot {\n return { Open: this.conversationId !== null, CurrentUrl: this.currentUrl };\n }\n\n /**\n * Adds the browser to an app context while it is open or in standby for an allowed conversation: its state\n * under `AdditionalContext.RemoteBrowser`, and, while this controller owns them, the `browser_*` tools\n * under `Capabilities.Tools`, the tier an agent run reads a surface's tools from. Returns `base`\n * unchanged while no browser is open or in standby.\n */\n public WithBrowserContext(base: Record<string, unknown> | null): Record<string, unknown> | null {\n if (!this.conversationId && !this.standbyConversationId) {\n return base;\n }\n const context = base ?? {};\n const additional = asRecord(context['AdditionalContext']);\n const capabilities = asRecord(context['Capabilities']);\n const tools = Array.isArray(capabilities['Tools']) ? (capabilities['Tools'] as ClientToolMetadata[]) : [];\n return {\n ...context,\n AdditionalContext: { ...additional, RemoteBrowser: this.GetAppContextSnapshot() },\n ...(this.OwnsTools ? { Capabilities: { ...capabilities, Tools: [...tools, ...BROWSER_TOOL_METADATA] } } : {}),\n };\n }\n\n /** Ends the browser and releases the tools, push subscription and channel. */\n public Dispose(): void {\n this.disposed = true;\n void this.Close();\n this.pushSub?.unsubscribe();\n this.pushSub = null;\n this.channel.Dispose();\n }\n\n /**\n * Routes a pushed `RemoteBrowserScreencastFrame` or `RemoteBrowserAudioChunk` to the channel when it\n * belongs to this controller's browser.\n */\n public HandlePushMessage(rawMessage: string): void {\n if (!this.conversationId || !rawMessage) {\n return;\n }\n let message: {\n resolver?: string;\n type?: string;\n agentSessionID?: string;\n currentUrl?: string | null;\n dataBase64?: string;\n sampleRate?: number;\n channels?: number;\n seq?: number;\n };\n try {\n const outer = JSON.parse(rawMessage) as Record<string, unknown>;\n message = typeof outer['message'] === 'string' ? JSON.parse(outer['message']) : outer;\n } catch {\n return; // Not JSON: an unrelated status update.\n }\n if (message.resolver !== 'RemoteBrowserActionResolver' || !message.agentSessionID || !UUIDsEqual(message.agentSessionID, this.conversationId)) {\n return;\n }\n if (typeof message.dataBase64 !== 'string') {\n return;\n }\n if (message.type === 'RemoteBrowserScreencastFrame') {\n this.channel.OnScreencastFrame(message.dataBase64, message.currentUrl ?? null);\n this.setUrl(message.currentUrl);\n } else if (message.type === 'RemoteBrowserAudioChunk') {\n this.channel.OnAudioChunk({\n dataBase64: message.dataBase64,\n codec: 'webm-opus',\n sampleRate: message.sampleRate ?? 48000,\n channels: message.channels ?? 2,\n seq: message.seq ?? 0,\n });\n }\n }\n\n /** Records a new URL; frames repeat the same one, so only a real change notifies the host. */\n private setUrl(url: string | null | undefined): void {\n const next = url?.trim();\n if (next && next !== this.currentUrl) {\n this.currentUrl = next;\n this.changed();\n }\n }\n\n private changed(): void {\n this.stateVersion++;\n if (!this.disposed) {\n this.options.OnStateChange?.();\n }\n }\n\n private registerBrowserTools(): void {\n const agentClient = this.agentClient;\n if (!agentClient) {\n return;\n }\n for (const def of TEXT_BROWSER_TOOLS) {\n let handler = this.handlers.get(def.Name);\n if (!handler) {\n handler = (params: Record<string, unknown>) => this.ExecuteBrowserTool(def.Name, params);\n this.handlers.set(def.Name, handler);\n }\n agentClient.RegisterTool({ Name: def.Name, Description: def.Description, ParameterSchema: (def.ParametersSchema ?? {}) as JSONObject, Handler: handler });\n }\n const sessionId = this.provider?.sessionId;\n if (sessionId && (!agentClient.IsActive || agentClient.SessionId !== sessionId)) {\n agentClient.StartSession(sessionId);\n }\n }\n\n private unregisterBrowserTools(): void {\n const registered = this.agentClient?.GetRegisteredTools() ?? [];\n for (const [name, handler] of this.handlers) {\n if (registered.find((t) => t.Name === name)?.Handler === handler) {\n this.agentClient?.UnregisterTool(name);\n }\n }\n }\n\n private async executeServerAction<T>(query: string, variables: Record<string, JSONValue>): Promise<T | null> {\n try {\n if (this.options.ExecuteServerAction) {\n return await this.options.ExecuteServerAction<T>(query, variables);\n }\n return this.provider ? (((await this.provider.ExecuteGQL(query, variables)) as T) ?? null) : null;\n } catch (err) {\n if (err instanceof SafeGraphQLError && err.Code === REMOTE_BROWSER_REFUSED) {\n // Asking again gets the same answer: close, so the live view stops polling, and say why once. Only\n // for the browser still open: a refusal for one already left (its End, after a switch) changes nothing.\n if (UUIDsEqual(variables['agentSessionID'] as string | null, this.conversationId)) {\n void this.Close();\n this.options.OnSessionRefused?.(err.message);\n }\n } else {\n console.warn('[ConversationRemoteBrowserController] GraphQL execution failed:', err);\n }\n return null;\n }\n }\n\n private createChannelContext(): RealtimeChannelContext {\n const self = this;\n return {\n AgentName: 'ConversationAgent',\n get Provider(): GraphQLDataProvider | null {\n return self.provider;\n },\n get AgentSessionID(): string | null {\n return self.conversationId;\n },\n // The channel narrates page changes as notes; a text conversation only needs the URL out of them.\n SendContextNote: (text: string) => {\n const match = /^\\[browser\\] (?:current page|the page changed to): (\\S+)/.exec(text);\n self.setUrl(match?.[1]);\n },\n RequestSave: () => undefined,\n SetFocusMode: () => undefined,\n SaveAsArtifact: async () => null,\n ExecuteServerAction: <T>(query: string, variables: Record<string, JSONValue>) => self.executeServerAction<T>(query, variables),\n };\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n"]}
@@ -1,6 +1,10 @@
1
1
  import { RealtimeToolDefinition } from '@memberjunction/ai';
2
2
  import { type RealtimeChannelDescriptor } from '@memberjunction/ai-core-plus';
3
3
  import { BaseRealtimeChannelClient } from '@memberjunction/realtime-runtime';
4
+ /** Coalescing window (ms) that collapses synchronous/rapid navigation + dashboard hydration bursts into one wire note. */
5
+ export declare const CLIENT_CONTEXT_COALESCE_MS = 250;
6
+ /** Replaceable reconnect-memory state key for the active application screen context. */
7
+ export declare const APP_CONTEXT_MEMORY_STATE_KEY = "app-context";
4
8
  /** The stable name of the single proxy tool this channel registers with the realtime provider. */
5
9
  export declare const CONTEXT_TOOL_NAME = "ContextTool";
6
10
  /**
@@ -10,6 +14,12 @@ export declare const CONTEXT_TOOL_NAME = "ContextTool";
10
14
  export declare class ClientContextChannel extends BaseRealtimeChannelClient<object> {
11
15
  /** Subscription to the host app-context stream (perception); cleared on {@link Dispose}. */
12
16
  private appContextSub;
17
+ /** Last snapshot known by the live model (seeded from initial BehaviorSubject value or last flushed update). */
18
+ private baselineSnapshot;
19
+ /** Latest snapshot buffered inside the active coalescing window. */
20
+ private pendingSnapshot;
21
+ /** Active burst-coalescing timer; cleared on flush or {@link Dispose}. */
22
+ private coalesceTimer;
13
23
  /** Matches the seeded `MJ: AI Agent Channels` row's `Name`. */
14
24
  get ChannelName(): string;
15
25
  /** Routing prefix — the single `ContextTool` matches `ContextTool`.startsWith(prefix). */
@@ -42,16 +52,22 @@ export declare class ClientContextChannel extends BaseRealtimeChannelClient<obje
42
52
  /** Headless — no surface to bind. */
43
53
  BindSurface(): void;
44
54
  /**
45
- * Subscribes to the host's live app-context stream and streams each change to the model as a
46
- * compact context note (the perception half). Null-safe — hosts that supply no `AppContext$`
47
- * (custom apps) simply get no streaming, and the session-start prompt injection still applies.
55
+ * Subscribes to the host's live app-context stream and streams each coalesced delta to the model as a
56
+ * compact context note while keeping only the latest full snapshot in reconnect memory under
57
+ * `StateKey: 'app-context'`. Null-safe — hosts that supply no `AppContext$` (custom apps) simply get
58
+ * no streaming, and the session-start prompt injection still applies.
48
59
  */
49
60
  protected OnInitialize(): void;
61
+ /**
62
+ * Immediately flushes any buffered `AppContext$` update, emitting a compact delta on the live wire
63
+ * and recording the full latest snapshot under `StateKey: 'app-context'` for reconnect continuity.
64
+ */
65
+ FlushPending(): void;
50
66
  /** Tolerantly parses the `{ action, params, target? }` arguments. */
51
67
  private parseArgs;
52
68
  /** Reads a `target` — `{ channel, instance? }` — or `null` when absent or unusable (the call is then an app action). */
53
69
  private parseTarget;
54
- /** Unsubscribes the app-context stream and tears down. */
70
+ /** Unsubscribes the app-context stream, cancels any pending coalescer timer, and tears down. */
55
71
  Dispose(): void;
56
72
  }
57
73
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"client-context-channel.d.ts","sourceRoot":"","sources":["../../../../../src/lib/components/realtime/channels/client-context-channel.ts"],"names":[],"mappings":"AA8BA,OAAO,EAAc,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAA2D,KAAK,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAGvI,OAAO,EAAE,yBAAyB,EAAoC,MAAM,kCAAkC,CAAC;AAE/G,kGAAkG;AAClG,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAsC/C;;;GAGG;AACH,qBACa,oBAAqB,SAAQ,yBAAyB,CAAC,MAAM,CAAC;IACzE,4FAA4F;IAC5F,OAAO,CAAC,aAAa,CAA6B;IAElD,+DAA+D;IAC/D,IAAW,WAAW,IAAI,MAAM,CAE/B;IAED,0FAA0F;IAC1F,IAAW,cAAc,IAAI,MAAM,CAElC;IAED,kFAAkF;IAClF,IAAW,QAAQ,IAAI,MAAM,CAE5B;IACD,IAAW,OAAO,IAAI,MAAM,CAE3B;IAED,6CAA6C;IACtC,kBAAkB,IAAI,sBAAsB,EAAE;IAIrD;;;;OAIG;IACa,aAAa,IAAI,yBAAyB;IAgB1D;;;;;;;;OAQG;IACU,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAwBhF,+FAA+F;YACjF,kBAAkB;IAchC,+GAA+G;IAC/G,OAAO,CAAC,wBAAwB;IAahC,qCAAqC;IAC9B,WAAW,IAAI,IAAI;IAI1B;;;;OAIG;cACgB,YAAY,IAAI,IAAI;IAkBvC,qEAAqE;IACrE,OAAO,CAAC,SAAS;IAkBjB,wHAAwH;IACxH,OAAO,CAAC,WAAW;IAanB,0DAA0D;IAC1C,OAAO,IAAI,IAAI;CAKhC;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAE/C"}
1
+ {"version":3,"file":"client-context-channel.d.ts","sourceRoot":"","sources":["../../../../../src/lib/components/realtime/channels/client-context-channel.ts"],"names":[],"mappings":"AA8BA,OAAO,EAAc,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAKL,KAAK,yBAAyB,EAC/B,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,yBAAyB,EAAoC,MAAM,kCAAkC,CAAC;AAE/G,0HAA0H;AAC1H,eAAO,MAAM,0BAA0B,MAAM,CAAC;AAE9C,wFAAwF;AACxF,eAAO,MAAM,4BAA4B,gBAAgB,CAAC;AAE1D,kGAAkG;AAClG,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAsC/C;;;GAGG;AACH,qBACa,oBAAqB,SAAQ,yBAAyB,CAAC,MAAM,CAAC;IACzE,4FAA4F;IAC5F,OAAO,CAAC,aAAa,CAA6B;IAClD,gHAAgH;IAChH,OAAO,CAAC,gBAAgB,CAAmC;IAC3D,oEAAoE;IACpE,OAAO,CAAC,eAAe,CAAmC;IAC1D,0EAA0E;IAC1E,OAAO,CAAC,aAAa,CAA8C;IAEnE,+DAA+D;IAC/D,IAAW,WAAW,IAAI,MAAM,CAE/B;IAED,0FAA0F;IAC1F,IAAW,cAAc,IAAI,MAAM,CAElC;IAED,kFAAkF;IAClF,IAAW,QAAQ,IAAI,MAAM,CAE5B;IACD,IAAW,OAAO,IAAI,MAAM,CAE3B;IAED,6CAA6C;IACtC,kBAAkB,IAAI,sBAAsB,EAAE;IAIrD;;;;OAIG;IACa,aAAa,IAAI,yBAAyB;IAgB1D;;;;;;;;OAQG;IACU,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAwBhF,+FAA+F;YACjF,kBAAkB;IAchC,+GAA+G;IAC/G,OAAO,CAAC,wBAAwB;IAahC,qCAAqC;IAC9B,WAAW,IAAI,IAAI;IAI1B;;;;;OAKG;cACgB,YAAY,IAAI,IAAI;IA0BvC;;;OAGG;IACI,YAAY,IAAI,IAAI;IA0B3B,qEAAqE;IACrE,OAAO,CAAC,SAAS;IAkBjB,wHAAwH;IACxH,OAAO,CAAC,WAAW;IAanB,gGAAgG;IAChF,OAAO,IAAI,IAAI;CAWhC;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAE/C"}
@@ -34,9 +34,13 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
34
34
  * @module @memberjunction/ng-conversations
35
35
  */
36
36
  import { RegisterClass } from '@memberjunction/global';
37
- import { FormatAppContextNote, REALTIME_CHANNEL_CONTRACT_VERSION } from '@memberjunction/ai-core-plus';
37
+ import { DiffAppContextSnapshot, FormatAppContextNote, REALTIME_CHANNEL_CONTRACT_VERSION, } from '@memberjunction/ai-core-plus';
38
38
  import { distinctUntilChanged } from 'rxjs/operators';
39
39
  import { BaseRealtimeChannelClient } from '@memberjunction/realtime-runtime';
40
+ /** Coalescing window (ms) that collapses synchronous/rapid navigation + dashboard hydration bursts into one wire note. */
41
+ export const CLIENT_CONTEXT_COALESCE_MS = 250;
42
+ /** Replaceable reconnect-memory state key for the active application screen context. */
43
+ export const APP_CONTEXT_MEMORY_STATE_KEY = 'app-context';
40
44
  /** The stable name of the single proxy tool this channel registers with the realtime provider. */
41
45
  export const CONTEXT_TOOL_NAME = 'ContextTool';
42
46
  /** The single stable proxy tool — declared once; the live catalog of valid `action`s rides context. */
@@ -80,6 +84,12 @@ const CONTEXT_TOOL_DEFINITION = {
80
84
  let ClientContextChannel = class ClientContextChannel extends BaseRealtimeChannelClient {
81
85
  /** Subscription to the host app-context stream (perception); cleared on {@link Dispose}. */
82
86
  appContextSub = null;
87
+ /** Last snapshot known by the live model (seeded from initial BehaviorSubject value or last flushed update). */
88
+ baselineSnapshot = null;
89
+ /** Latest snapshot buffered inside the active coalescing window. */
90
+ pendingSnapshot = null;
91
+ /** Active burst-coalescing timer; cleared on flush or {@link Dispose}. */
92
+ coalesceTimer = null;
83
93
  /** Matches the seeded `MJ: AI Agent Channels` row's `Name`. */
84
94
  get ChannelName() {
85
95
  return 'ClientContextChannel';
@@ -178,26 +188,64 @@ let ClientContextChannel = class ClientContextChannel extends BaseRealtimeChanne
178
188
  /* no-op: this channel renders no surface */
179
189
  }
180
190
  /**
181
- * Subscribes to the host's live app-context stream and streams each change to the model as a
182
- * compact context note (the perception half). Null-safe — hosts that supply no `AppContext$`
183
- * (custom apps) simply get no streaming, and the session-start prompt injection still applies.
191
+ * Subscribes to the host's live app-context stream and streams each coalesced delta to the model as a
192
+ * compact context note while keeping only the latest full snapshot in reconnect memory under
193
+ * `StateKey: 'app-context'`. Null-safe — hosts that supply no `AppContext$` (custom apps) simply get
194
+ * no streaming, and the session-start prompt injection still applies.
184
195
  */
185
196
  OnInitialize() {
186
197
  const stream = this.Context?.AppContext$;
187
198
  if (!stream) {
188
199
  return;
189
200
  }
201
+ let subscribingSynchronously = true;
190
202
  this.appContextSub = stream
191
203
  .pipe(distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)))
192
204
  .subscribe((snapshot) => {
193
205
  if (!snapshot) {
194
206
  return;
195
207
  }
196
- const note = FormatAppContextNote(snapshot);
197
- if (note) {
198
- this.Context?.SendContextNote(note);
208
+ if (subscribingSynchronously) {
209
+ // BehaviorSubject's current value was already injected into SystemPrompt at session mint:
210
+ // record it as the diff baseline without sending a duplicate t=0 wire note.
211
+ this.baselineSnapshot = snapshot;
212
+ return;
213
+ }
214
+ this.pendingSnapshot = snapshot;
215
+ if (this.coalesceTimer === null) {
216
+ this.coalesceTimer = setTimeout(() => this.FlushPending(), CLIENT_CONTEXT_COALESCE_MS);
199
217
  }
200
218
  });
219
+ subscribingSynchronously = false;
220
+ }
221
+ /**
222
+ * Immediately flushes any buffered `AppContext$` update, emitting a compact delta on the live wire
223
+ * and recording the full latest snapshot under `StateKey: 'app-context'` for reconnect continuity.
224
+ */
225
+ FlushPending() {
226
+ if (this.coalesceTimer !== null) {
227
+ clearTimeout(this.coalesceTimer);
228
+ this.coalesceTimer = null;
229
+ }
230
+ const latest = this.pendingSnapshot;
231
+ this.pendingSnapshot = null;
232
+ if (!latest) {
233
+ return;
234
+ }
235
+ const delta = DiffAppContextSnapshot(this.baselineSnapshot, latest);
236
+ this.baselineSnapshot = latest;
237
+ if (!delta) {
238
+ return;
239
+ }
240
+ const wireNote = FormatAppContextNote(delta);
241
+ if (!wireNote) {
242
+ return;
243
+ }
244
+ const fullMemoryNote = FormatAppContextNote(latest);
245
+ this.Context?.SendContextNote(wireNote, {
246
+ StateKey: APP_CONTEXT_MEMORY_STATE_KEY,
247
+ ...(fullMemoryNote && fullMemoryNote !== wireNote ? { MemoryText: fullMemoryNote } : {}),
248
+ });
201
249
  }
202
250
  /** Tolerantly parses the `{ action, params, target? }` arguments. */
203
251
  parseArgs(argsJson) {
@@ -226,8 +274,14 @@ let ClientContextChannel = class ClientContextChannel extends BaseRealtimeChanne
226
274
  const instance = typeof target.instance === 'string' && target.instance.trim().length > 0 ? target.instance.trim() : undefined;
227
275
  return instance ? { channel, instance } : { channel };
228
276
  }
229
- /** Unsubscribes the app-context stream and tears down. */
277
+ /** Unsubscribes the app-context stream, cancels any pending coalescer timer, and tears down. */
230
278
  Dispose() {
279
+ if (this.coalesceTimer !== null) {
280
+ clearTimeout(this.coalesceTimer);
281
+ this.coalesceTimer = null;
282
+ }
283
+ this.pendingSnapshot = null;
284
+ this.baselineSnapshot = null;
231
285
  this.appContextSub?.unsubscribe();
232
286
  this.appContextSub = null;
233
287
  super.Dispose();
@@ -1 +1 @@
1
- {"version":3,"file":"client-context-channel.js","sourceRoot":"","sources":["../../../../../src/lib/components/realtime/channels/client-context-channel.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,OAAO,EAAE,oBAAoB,EAAE,iCAAiC,EAAkC,MAAM,8BAA8B,CAAC;AAEvI,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,yBAAyB,EAAoC,MAAM,kCAAkC,CAAC;AAE/G,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC;AAE/C,uGAAuG;AACvG,MAAM,uBAAuB,GAA2B;IACtD,IAAI,EAAE,iBAAiB;IACvB,WAAW,EACT,8FAA8F;QAC9F,mGAAmG;QACnG,oGAAoG;QACpG,mGAAmG;QACnG,iGAAiG;QACjG,oGAAoG;QACpG,mBAAmB;IACrB,gBAAgB,EAAE;QAChB,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE;YACV,MAAM,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AC,aAAa,GAAG,IAAI,CAAC;QAC1B,KAAK,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC;CACF,CAAA;AAjLY,oBAAoB;IADhC,aAAa,CAAC,yBAAyB,EAAE,sBAAsB,CAAC;GACpD,oBAAoB,CAiLhC;;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACtC,gFAAgF;AAClF,CAAC","sourcesContent":["/**\n * @fileoverview The headless **Client Context** channel — the browser half of the live wire that\n * keeps the realtime co-agent continuously aware of the user's app context and lets it act in the\n * app through a single stable proxy tool.\n *\n * Paired with `ClientContextChannelServer` (`@memberjunction/ai-agents`) via the seeded\n * `MJ: AI Agent Channels` row (`Name: 'ClientContextChannel'`, `IsHeadless: 1`,\n * `ClientPluginClass: 'ClientContextChannel'`).\n *\n * Two responsibilities, both client-side (no server round-trip in the client-direct topology):\n *\n * 1. **Perception (streaming).** It subscribes to the host's live app-context stream\n * ({@link RealtimeChannelContext.AppContext$}, fed by Explorer from `NavigationService`) and, on\n * every change, pushes a compact `SendContextNote` so the model always knows where the user is,\n * what they see, and which tools/agents are available — the *continuous* half of client-context\n * delivery (the session-start half is injected into the companion prompt server-side at mint).\n *\n * 2. **Action (the `ContextTool` proxy).** It declares ONE stable tool, `ContextTool`, so the\n * provider tool surface never changes mid-session (which connect-bound providers reject). The\n * model invokes any currently-available surface client tool via `ContextTool({ action, params })`;\n * the channel routes that to the host's {@link RealtimeChannelContext.ExecuteClientTool} (which runs\n * the surface handler the host registered from `SetAgentClientTools`) and returns a structured\n * result the model narrates.\n *\n * **Headless:** no surface component — it never mounts a tab (`GetSurfaceComponent` stays `null`;\n * `BindSurface` is a no-op). It is a wire, not a panel.\n *\n * @module @memberjunction/ng-conversations\n */\nimport { RegisterClass } from '@memberjunction/global';\nimport { JSONObject, RealtimeToolDefinition } from '@memberjunction/ai';\nimport { FormatAppContextNote, REALTIME_CHANNEL_CONTRACT_VERSION, type RealtimeChannelDescriptor } from '@memberjunction/ai-core-plus';\nimport { Subscription } from 'rxjs';\nimport { distinctUntilChanged } from 'rxjs/operators';\nimport { BaseRealtimeChannelClient, type RealtimeContextActionResult } from '@memberjunction/realtime-runtime';\n\n/** The stable name of the single proxy tool this channel registers with the realtime provider. */\nexport const CONTEXT_TOOL_NAME = 'ContextTool';\n\n/** The single stable proxy tool — declared once; the live catalog of valid `action`s rides context. */\nconst CONTEXT_TOOL_DEFINITION: RealtimeToolDefinition = {\n Name: CONTEXT_TOOL_NAME,\n Description:\n \"Perform an action in the application the user is currently in, or on one of the interactive \" +\n \"channels listed in your channel notes. The set of valid actions (the client tools and the things \" +\n \"you can do on the current surface) is provided to you continuously as context — only call actions \" +\n \"listed as currently available. Pass the action name and its parameters. To act on an interactive \" +\n \"channel instead of the app, also pass `target` naming the channel (and, for a channel that has \" +\n \"several, the instance); to open a channel that is available but not open yet, use action \\\"open\\\" \" +\n \"with that target.\",\n ParametersSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n description: 'The name of a currently-available action/tool to run (from the context you were given).'\n },\n params: {\n type: 'object',\n description: \"The action's parameters, matching its advertised input schema.\"\n },\n target: {\n type: 'object',\n description: 'Set this to act on an interactive channel rather than the app. Omit it for app actions.',\n properties: {\n channel: { type: 'string', description: 'The channel to address (from your channel notes).' },\n instance: { type: 'string', description: 'Which instance, for a channel that has several. Usually omitted.' }\n },\n required: ['channel']\n }\n },\n required: ['action']\n }\n};\n\n/**\n * The headless Client Context channel client. One instance per realtime session (created by the\n * session service from the `MJ: AI Agent Channels` registry — never construct directly).\n */\n@RegisterClass(BaseRealtimeChannelClient, 'ClientContextChannel')\nexport class ClientContextChannel extends BaseRealtimeChannelClient<object> {\n /** Subscription to the host app-context stream (perception); cleared on {@link Dispose}. */\n private appContextSub: Subscription | null = null;\n\n /** Matches the seeded `MJ: AI Agent Channels` row's `Name`. */\n public get ChannelName(): string {\n return 'ClientContextChannel';\n }\n\n /** Routing prefix — the single `ContextTool` matches `ContextTool`.startsWith(prefix). */\n public get ToolNamePrefix(): string {\n return CONTEXT_TOOL_NAME;\n }\n\n /** Headless — never rendered, but the abstract contract requires a label/icon. */\n public get TabTitle(): string {\n return 'App Context';\n }\n public get TabIcon(): string {\n return 'fa-solid fa-satellite-dish';\n }\n\n /** Declares the single stable proxy tool. */\n public GetToolDefinitions(): RealtimeToolDefinition[] {\n return [CONTEXT_TOOL_DEFINITION];\n }\n\n /**\n * The channel's self-description. It has NO verbs of its own: it is the door, not a room — `ContextTool`\n * runs app client tools, or addresses another channel through `target`. Declaring that explicitly keeps\n * it from being addressed as if it were a channel with things to do.\n */\n public override GetDescriptor(): RealtimeChannelDescriptor {\n return {\n Key: this.ChannelName,\n Version: REALTIME_CHANNEL_CONTRACT_VERSION,\n DisplayName: this.TabTitle,\n Instructions:\n 'Keeps you aware of where the user is in the app and lets you act there through ContextTool. ' +\n 'It is not itself something to operate.',\n Nouns: [],\n Verbs: [],\n DisplayPolicy: 'headless',\n DefaultAvailability: 'all-sessions',\n MaxExposure: 'state'\n };\n }\n\n /**\n * Routes a `ContextTool({ action, params, target? })` call. With a `target` the call is handed to the\n * runtime, which validates it against the addressed channel's verb schema (a malformed call comes back\n * as a structured, model-recoverable error) and opens an `on-demand` channel when asked; without one it\n * runs the host's registered surface client tool, exactly as before.\n *\n * Tolerant: malformed args, a missing host executor, or an unknown/throwing tool all serialize to\n * a structured `{ success: false, output }` the model narrates (never throws).\n */\n public async ApplyAgentTool(toolName: string, argsJson: string): Promise<string> {\n if (toolName !== CONTEXT_TOOL_NAME) {\n return JSON.stringify({ success: false, output: `Unknown context tool \"${toolName}\".` });\n }\n const parsed = this.parseArgs(argsJson);\n if (!parsed.action) {\n return JSON.stringify({ success: false, output: 'ContextTool requires an \"action\" naming the tool to run.' });\n }\n if (parsed.target) {\n return this.applyChannelAction(parsed.action, parsed.params, parsed.target);\n }\n const executor = this.Context?.ExecuteClientTool;\n if (!executor) {\n return JSON.stringify({\n success: false,\n output: 'No app surface is available to perform that action right now.'\n });\n }\n const result = await executor(parsed.action, parsed.params);\n return result.Success\n ? JSON.stringify({ success: true, output: result.Result ?? 'Done.' })\n : JSON.stringify({ success: false, output: result.ErrorMessage ?? 'The action could not be performed.' });\n }\n\n /** Runs a channel-addressed call through the runtime and serializes its structured outcome. */\n private async applyChannelAction(\n action: string,\n params: Record<string, unknown>,\n target: { channel: string; instance?: string }\n ): Promise<string> {\n const dispatch = this.Context?.DispatchContextAction;\n if (!dispatch) {\n return JSON.stringify({ success: false, output: 'Channel actions are not available in this session.' });\n }\n // The params came off the wire as JSON, so they are JSON by construction.\n const outcome = await dispatch({ Target: { Channel: target.channel, Instance: target.instance }, Action: action, Params: params as JSONObject });\n return JSON.stringify(this.serializeDispatchOutcome(outcome));\n }\n\n /** The model-facing shape of a dispatch outcome: success carries the result; a refusal carries what to fix. */\n private serializeDispatchOutcome(outcome: RealtimeContextActionResult): Record<string, unknown> {\n if (outcome.Success) {\n return { success: true, output: outcome.Result ?? 'Done.' };\n }\n return {\n success: false,\n output: outcome.ErrorMessage ?? 'The action could not be performed.',\n errorCode: outcome.ErrorCode,\n ...(outcome.Details ? { details: outcome.Details } : {}),\n ...(outcome.Available ? { available: outcome.Available } : {})\n };\n }\n\n /** Headless — no surface to bind. */\n public BindSurface(): void {\n /* no-op: this channel renders no surface */\n }\n\n /**\n * Subscribes to the host's live app-context stream and streams each change to the model as a\n * compact context note (the perception half). Null-safe — hosts that supply no `AppContext$`\n * (custom apps) simply get no streaming, and the session-start prompt injection still applies.\n */\n protected override OnInitialize(): void {\n const stream = this.Context?.AppContext$;\n if (!stream) {\n return;\n }\n this.appContextSub = stream\n .pipe(distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)))\n .subscribe((snapshot) => {\n if (!snapshot) {\n return;\n }\n const note = FormatAppContextNote(snapshot);\n if (note) {\n this.Context?.SendContextNote(note);\n }\n });\n }\n\n /** Tolerantly parses the `{ action, params, target? }` arguments. */\n private parseArgs(argsJson: string): {\n action: string | null;\n params: Record<string, unknown>;\n target: { channel: string; instance?: string } | null;\n } {\n try {\n const parsed = JSON.parse(argsJson) as { action?: unknown; params?: unknown; target?: unknown };\n const action = typeof parsed.action === 'string' && parsed.action.trim().length > 0 ? parsed.action.trim() : null;\n const params =\n parsed.params && typeof parsed.params === 'object' && !Array.isArray(parsed.params)\n ? (parsed.params as Record<string, unknown>)\n : {};\n return { action, params, target: this.parseTarget(parsed.target) };\n } catch {\n return { action: null, params: {}, target: null };\n }\n }\n\n /** Reads a `target` — `{ channel, instance? }` — or `null` when absent or unusable (the call is then an app action). */\n private parseTarget(raw: unknown): { channel: string; instance?: string } | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return null;\n }\n const target = raw as { channel?: unknown; instance?: unknown };\n const channel = typeof target.channel === 'string' ? target.channel.trim() : '';\n if (channel.length === 0) {\n return null;\n }\n const instance = typeof target.instance === 'string' && target.instance.trim().length > 0 ? target.instance.trim() : undefined;\n return instance ? { channel, instance } : { channel };\n }\n\n /** Unsubscribes the app-context stream and tears down. */\n public override Dispose(): void {\n this.appContextSub?.unsubscribe();\n this.appContextSub = null;\n super.Dispose();\n }\n}\n\n/**\n * Tree-shaking prevention for {@link ClientContextChannel}'s `@RegisterClass` registration. Called\n * from a static code path in `conversations.module.ts` so the registration always executes —\n * mirroring every other realtime channel client.\n */\nexport function LoadClientContextChannel(): void {\n // no-op — the import + call create a static reference bundlers cannot eliminate\n}\n"]}
1
+ {"version":3,"file":"client-context-channel.js","sourceRoot":"","sources":["../../../../../src/lib/components/realtime/channels/client-context-channel.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,iCAAiC,GAGlC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,yBA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C,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChF,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,QAAQ,GAAG,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/H,OAAO,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC;IACxD,CAAC;IAED,gGAAgG;IAChF,OAAO;QACrB,IAAI,IAAI,CAAC,aAAa,KAAK,IAAI,EAAE,CAAC;YAChC,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACjC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC5B,CAAC;QACD,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC5B,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAC7B,IAAI,CAAC,aAAa,EAAE,WAAW,EAAE,CAAC;QAClC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,KAAK,CAAC,OAAO,EAAE,CAAC;IAClB,CAAC;CACF,CAAA;AApOY,oBAAoB;IADhC,aAAa,CAAC,yBAAyB,EAAE,sBAAsB,CAAC;GACpD,oBAAoB,CAoOhC;;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACtC,gFAAgF;AAClF,CAAC","sourcesContent":["/**\n * @fileoverview The headless **Client Context** channel — the browser half of the live wire that\n * keeps the realtime co-agent continuously aware of the user's app context and lets it act in the\n * app through a single stable proxy tool.\n *\n * Paired with `ClientContextChannelServer` (`@memberjunction/ai-agents`) via the seeded\n * `MJ: AI Agent Channels` row (`Name: 'ClientContextChannel'`, `IsHeadless: 1`,\n * `ClientPluginClass: 'ClientContextChannel'`).\n *\n * Two responsibilities, both client-side (no server round-trip in the client-direct topology):\n *\n * 1. **Perception (streaming).** It subscribes to the host's live app-context stream\n * ({@link RealtimeChannelContext.AppContext$}, fed by Explorer from `NavigationService`) and, on\n * every change, pushes a compact `SendContextNote` so the model always knows where the user is,\n * what they see, and which tools/agents are available — the *continuous* half of client-context\n * delivery (the session-start half is injected into the companion prompt server-side at mint).\n *\n * 2. **Action (the `ContextTool` proxy).** It declares ONE stable tool, `ContextTool`, so the\n * provider tool surface never changes mid-session (which connect-bound providers reject). The\n * model invokes any currently-available surface client tool via `ContextTool({ action, params })`;\n * the channel routes that to the host's {@link RealtimeChannelContext.ExecuteClientTool} (which runs\n * the surface handler the host registered from `SetAgentClientTools`) and returns a structured\n * result the model narrates.\n *\n * **Headless:** no surface component — it never mounts a tab (`GetSurfaceComponent` stays `null`;\n * `BindSurface` is a no-op). It is a wire, not a panel.\n *\n * @module @memberjunction/ng-conversations\n */\nimport { RegisterClass } from '@memberjunction/global';\nimport { JSONObject, RealtimeToolDefinition } from '@memberjunction/ai';\nimport {\n DiffAppContextSnapshot,\n FormatAppContextNote,\n REALTIME_CHANNEL_CONTRACT_VERSION,\n type AppContextSnapshot,\n type RealtimeChannelDescriptor,\n} from '@memberjunction/ai-core-plus';\nimport { Subscription } from 'rxjs';\nimport { distinctUntilChanged } from 'rxjs/operators';\nimport { BaseRealtimeChannelClient, type RealtimeContextActionResult } from '@memberjunction/realtime-runtime';\n\n/** Coalescing window (ms) that collapses synchronous/rapid navigation + dashboard hydration bursts into one wire note. */\nexport const CLIENT_CONTEXT_COALESCE_MS = 250;\n\n/** Replaceable reconnect-memory state key for the active application screen context. */\nexport const APP_CONTEXT_MEMORY_STATE_KEY = 'app-context';\n\n/** The stable name of the single proxy tool this channel registers with the realtime provider. */\nexport const CONTEXT_TOOL_NAME = 'ContextTool';\n\n/** The single stable proxy tool — declared once; the live catalog of valid `action`s rides context. */\nconst CONTEXT_TOOL_DEFINITION: RealtimeToolDefinition = {\n Name: CONTEXT_TOOL_NAME,\n Description:\n \"Perform an action in the application the user is currently in, or on one of the interactive \" +\n \"channels listed in your channel notes. The set of valid actions (the client tools and the things \" +\n \"you can do on the current surface) is provided to you continuously as context — only call actions \" +\n \"listed as currently available. Pass the action name and its parameters. To act on an interactive \" +\n \"channel instead of the app, also pass `target` naming the channel (and, for a channel that has \" +\n \"several, the instance); to open a channel that is available but not open yet, use action \\\"open\\\" \" +\n \"with that target.\",\n ParametersSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n description: 'The name of a currently-available action/tool to run (from the context you were given).'\n },\n params: {\n type: 'object',\n description: \"The action's parameters, matching its advertised input schema.\"\n },\n target: {\n type: 'object',\n description: 'Set this to act on an interactive channel rather than the app. Omit it for app actions.',\n properties: {\n channel: { type: 'string', description: 'The channel to address (from your channel notes).' },\n instance: { type: 'string', description: 'Which instance, for a channel that has several. Usually omitted.' }\n },\n required: ['channel']\n }\n },\n required: ['action']\n }\n};\n\n/**\n * The headless Client Context channel client. One instance per realtime session (created by the\n * session service from the `MJ: AI Agent Channels` registry — never construct directly).\n */\n@RegisterClass(BaseRealtimeChannelClient, 'ClientContextChannel')\nexport class ClientContextChannel extends BaseRealtimeChannelClient<object> {\n /** Subscription to the host app-context stream (perception); cleared on {@link Dispose}. */\n private appContextSub: Subscription | null = null;\n /** Last snapshot known by the live model (seeded from initial BehaviorSubject value or last flushed update). */\n private baselineSnapshot: AppContextSnapshot | null = null;\n /** Latest snapshot buffered inside the active coalescing window. */\n private pendingSnapshot: AppContextSnapshot | null = null;\n /** Active burst-coalescing timer; cleared on flush or {@link Dispose}. */\n private coalesceTimer: ReturnType<typeof setTimeout> | null = null;\n\n /** Matches the seeded `MJ: AI Agent Channels` row's `Name`. */\n public get ChannelName(): string {\n return 'ClientContextChannel';\n }\n\n /** Routing prefix — the single `ContextTool` matches `ContextTool`.startsWith(prefix). */\n public get ToolNamePrefix(): string {\n return CONTEXT_TOOL_NAME;\n }\n\n /** Headless — never rendered, but the abstract contract requires a label/icon. */\n public get TabTitle(): string {\n return 'App Context';\n }\n public get TabIcon(): string {\n return 'fa-solid fa-satellite-dish';\n }\n\n /** Declares the single stable proxy tool. */\n public GetToolDefinitions(): RealtimeToolDefinition[] {\n return [CONTEXT_TOOL_DEFINITION];\n }\n\n /**\n * The channel's self-description. It has NO verbs of its own: it is the door, not a room — `ContextTool`\n * runs app client tools, or addresses another channel through `target`. Declaring that explicitly keeps\n * it from being addressed as if it were a channel with things to do.\n */\n public override GetDescriptor(): RealtimeChannelDescriptor {\n return {\n Key: this.ChannelName,\n Version: REALTIME_CHANNEL_CONTRACT_VERSION,\n DisplayName: this.TabTitle,\n Instructions:\n 'Keeps you aware of where the user is in the app and lets you act there through ContextTool. ' +\n 'It is not itself something to operate.',\n Nouns: [],\n Verbs: [],\n DisplayPolicy: 'headless',\n DefaultAvailability: 'all-sessions',\n MaxExposure: 'state'\n };\n }\n\n /**\n * Routes a `ContextTool({ action, params, target? })` call. With a `target` the call is handed to the\n * runtime, which validates it against the addressed channel's verb schema (a malformed call comes back\n * as a structured, model-recoverable error) and opens an `on-demand` channel when asked; without one it\n * runs the host's registered surface client tool, exactly as before.\n *\n * Tolerant: malformed args, a missing host executor, or an unknown/throwing tool all serialize to\n * a structured `{ success: false, output }` the model narrates (never throws).\n */\n public async ApplyAgentTool(toolName: string, argsJson: string): Promise<string> {\n if (toolName !== CONTEXT_TOOL_NAME) {\n return JSON.stringify({ success: false, output: `Unknown context tool \"${toolName}\".` });\n }\n const parsed = this.parseArgs(argsJson);\n if (!parsed.action) {\n return JSON.stringify({ success: false, output: 'ContextTool requires an \"action\" naming the tool to run.' });\n }\n if (parsed.target) {\n return this.applyChannelAction(parsed.action, parsed.params, parsed.target);\n }\n const executor = this.Context?.ExecuteClientTool;\n if (!executor) {\n return JSON.stringify({\n success: false,\n output: 'No app surface is available to perform that action right now.'\n });\n }\n const result = await executor(parsed.action, parsed.params);\n return result.Success\n ? JSON.stringify({ success: true, output: result.Result ?? 'Done.' })\n : JSON.stringify({ success: false, output: result.ErrorMessage ?? 'The action could not be performed.' });\n }\n\n /** Runs a channel-addressed call through the runtime and serializes its structured outcome. */\n private async applyChannelAction(\n action: string,\n params: Record<string, unknown>,\n target: { channel: string; instance?: string }\n ): Promise<string> {\n const dispatch = this.Context?.DispatchContextAction;\n if (!dispatch) {\n return JSON.stringify({ success: false, output: 'Channel actions are not available in this session.' });\n }\n // The params came off the wire as JSON, so they are JSON by construction.\n const outcome = await dispatch({ Target: { Channel: target.channel, Instance: target.instance }, Action: action, Params: params as JSONObject });\n return JSON.stringify(this.serializeDispatchOutcome(outcome));\n }\n\n /** The model-facing shape of a dispatch outcome: success carries the result; a refusal carries what to fix. */\n private serializeDispatchOutcome(outcome: RealtimeContextActionResult): Record<string, unknown> {\n if (outcome.Success) {\n return { success: true, output: outcome.Result ?? 'Done.' };\n }\n return {\n success: false,\n output: outcome.ErrorMessage ?? 'The action could not be performed.',\n errorCode: outcome.ErrorCode,\n ...(outcome.Details ? { details: outcome.Details } : {}),\n ...(outcome.Available ? { available: outcome.Available } : {})\n };\n }\n\n /** Headless — no surface to bind. */\n public BindSurface(): void {\n /* no-op: this channel renders no surface */\n }\n\n /**\n * Subscribes to the host's live app-context stream and streams each coalesced delta to the model as a\n * compact context note while keeping only the latest full snapshot in reconnect memory under\n * `StateKey: 'app-context'`. Null-safe — hosts that supply no `AppContext$` (custom apps) simply get\n * no streaming, and the session-start prompt injection still applies.\n */\n protected override OnInitialize(): void {\n const stream = this.Context?.AppContext$;\n if (!stream) {\n return;\n }\n let subscribingSynchronously = true;\n this.appContextSub = stream\n .pipe(distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)))\n .subscribe((snapshot) => {\n if (!snapshot) {\n return;\n }\n if (subscribingSynchronously) {\n // BehaviorSubject's current value was already injected into SystemPrompt at session mint:\n // record it as the diff baseline without sending a duplicate t=0 wire note.\n this.baselineSnapshot = snapshot;\n return;\n }\n this.pendingSnapshot = snapshot;\n if (this.coalesceTimer === null) {\n this.coalesceTimer = setTimeout(() => this.FlushPending(), CLIENT_CONTEXT_COALESCE_MS);\n }\n });\n subscribingSynchronously = false;\n }\n\n /**\n * Immediately flushes any buffered `AppContext$` update, emitting a compact delta on the live wire\n * and recording the full latest snapshot under `StateKey: 'app-context'` for reconnect continuity.\n */\n public FlushPending(): void {\n if (this.coalesceTimer !== null) {\n clearTimeout(this.coalesceTimer);\n this.coalesceTimer = null;\n }\n const latest = this.pendingSnapshot;\n this.pendingSnapshot = null;\n if (!latest) {\n return;\n }\n const delta = DiffAppContextSnapshot(this.baselineSnapshot, latest);\n this.baselineSnapshot = latest;\n if (!delta) {\n return;\n }\n const wireNote = FormatAppContextNote(delta);\n if (!wireNote) {\n return;\n }\n const fullMemoryNote = FormatAppContextNote(latest);\n this.Context?.SendContextNote(wireNote, {\n StateKey: APP_CONTEXT_MEMORY_STATE_KEY,\n ...(fullMemoryNote && fullMemoryNote !== wireNote ? { MemoryText: fullMemoryNote } : {}),\n });\n }\n\n /** Tolerantly parses the `{ action, params, target? }` arguments. */\n private parseArgs(argsJson: string): {\n action: string | null;\n params: Record<string, unknown>;\n target: { channel: string; instance?: string } | null;\n } {\n try {\n const parsed = JSON.parse(argsJson) as { action?: unknown; params?: unknown; target?: unknown };\n const action = typeof parsed.action === 'string' && parsed.action.trim().length > 0 ? parsed.action.trim() : null;\n const params =\n parsed.params && typeof parsed.params === 'object' && !Array.isArray(parsed.params)\n ? (parsed.params as Record<string, unknown>)\n : {};\n return { action, params, target: this.parseTarget(parsed.target) };\n } catch {\n return { action: null, params: {}, target: null };\n }\n }\n\n /** Reads a `target` — `{ channel, instance? }` — or `null` when absent or unusable (the call is then an app action). */\n private parseTarget(raw: unknown): { channel: string; instance?: string } | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return null;\n }\n const target = raw as { channel?: unknown; instance?: unknown };\n const channel = typeof target.channel === 'string' ? target.channel.trim() : '';\n if (channel.length === 0) {\n return null;\n }\n const instance = typeof target.instance === 'string' && target.instance.trim().length > 0 ? target.instance.trim() : undefined;\n return instance ? { channel, instance } : { channel };\n }\n\n /** Unsubscribes the app-context stream, cancels any pending coalescer timer, and tears down. */\n public override Dispose(): void {\n if (this.coalesceTimer !== null) {\n clearTimeout(this.coalesceTimer);\n this.coalesceTimer = null;\n }\n this.pendingSnapshot = null;\n this.baselineSnapshot = null;\n this.appContextSub?.unsubscribe();\n this.appContextSub = null;\n super.Dispose();\n }\n}\n\n/**\n * Tree-shaking prevention for {@link ClientContextChannel}'s `@RegisterClass` registration. Called\n * from a static code path in `conversations.module.ts` so the registration always executes —\n * mirroring every other realtime channel client.\n */\nexport function LoadClientContextChannel(): void {\n // no-op — the import + call create a static reference bundlers cannot eliminate\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"remote-browser-tools.d.ts","sourceRoot":"","sources":["../../../../../src/lib/components/realtime/remote-browser/remote-browser-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAE5D;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,aAAa,CAAC;AAErD,gFAAgF;AAChF,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;CAe5B,CAAC;AAEX;;;GAGG;AACH,MAAM,MAAM,uBAAuB,GAC/B,UAAU,GACV,SAAS,GACT,MAAM,GACN,OAAO,GACP,MAAM,GACN,KAAK,GACL,QAAQ,GACR,MAAM,GACN,SAAS,GACT,MAAM,GACN,aAAa,CAAC;AAElB;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IAClC,uDAAuD;IACvD,IAAI,EAAE,uBAAuB,CAAC;IAC9B,4BAA4B;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6CAA6C;IAC7C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,4DAA4D;IAC5D,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,4DAA4D;IAC5D,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,6DAA6D;IAC7D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,yDAAyD;IACzD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,kEAAkE;IAClE,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,mFAAmF;AACnF,KAAK,YAAY,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,YAAY,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,CAAA;CAAE,CAAC;AAYxG;;;;;GAKG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;CAAG;AAEvD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,GAAG,mBAAmB,CA0EzG;AAED;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,EAAE,sBAAsB,EA6InE,CAAC"}
1
+ {"version":3,"file":"remote-browser-tools.d.ts","sourceRoot":"","sources":["../../../../../src/lib/components/realtime/remote-browser/remote-browser-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAE5D;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,aAAa,CAAC;AAErD,gFAAgF;AAChF,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;CAe5B,CAAC;AAEX;;;GAGG;AACH,MAAM,MAAM,uBAAuB,GAC/B,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function MapToolToAction(toolName, args) {
129
129
  export const REMOTE_BROWSER_TOOL_DEFINITIONS = [
130
130
  {
131
131
  Name: REMOTE_BROWSER_TOOL_NAMES.OpenUrl,
132
- Description: 'Navigate the shared browser to a URL. The user watches the live page in the Browser tab.',
132
+ Description: 'Navigate the shared browser to a URL. The user watches the live page in the Browser tab. If the user names a form, application, or page without pasting a URL, check retrieved content for the URL before opening it.',
133
133
  ParametersSchema: {
134
134
  type: 'object',
135
135
  properties: {
@@ -151,7 +151,7 @@ export const REMOTE_BROWSER_TOOL_DEFINITIONS = [
151
151
  properties: {
152
152
  values: {
153
153
  type: 'object',
154
- description: 'Object mapping each field ref or label to its value, e.g. {"f1": "Ada Lovelace", "f2": "ada@example.com"}. Use true or false for a checkbox and the option text for a select.',
154
+ description: 'Object mapping each field ref or label to its value, e.g. {"f1": "Ada Lovelace", "f2": "ada@example.com"}. Use true or false for a checkbox, option text (or comma-separated options) for a checkbox or radio group, and the option text for a select.',
155
155
  },
156
156
  },
157
157
  required: ['values'],