@promptbook/components 0.114.0-3 → 0.114.0-4

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 (152) hide show
  1. package/README.md +2 -10
  2. package/esm/index.es.js +559 -4005
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/src/book-2.0/agent-source/AgentBasicInformation.d.ts +3 -3
  5. package/esm/src/cli/cli-commands/coder/boilerplateCount.d.ts +52 -0
  6. package/esm/src/cli/cli-commands/coder/generate-boilerplates.d.ts +3 -2
  7. package/esm/src/commitments/{COMPONENT/COMPONENT.d.ts → META_FULLNAME/META_FULLNAME.d.ts} +8 -5
  8. package/esm/src/commitments/META_ID/META_ID.d.ts +32 -0
  9. package/esm/src/commitments/index.d.ts +4 -12
  10. package/esm/src/llm-providers/agent/Agent.d.ts +1 -1
  11. package/esm/src/llm-providers/openai/OpenAiAgentKitExecutionToolsToolBuilder.d.ts +1 -1
  12. package/esm/src/{commitments/USE_BROWSER → scrapers/_common/utils}/fetchUrlContent.d.ts +2 -3
  13. package/esm/src/version.d.ts +1 -1
  14. package/package.json +1 -1
  15. package/umd/index.umd.js +563 -4009
  16. package/umd/index.umd.js.map +1 -1
  17. package/umd/src/book-2.0/agent-source/AgentBasicInformation.d.ts +3 -3
  18. package/umd/src/cli/cli-commands/coder/boilerplateCount.d.ts +52 -0
  19. package/umd/src/cli/cli-commands/coder/generate-boilerplates.d.ts +3 -2
  20. package/umd/src/commitments/{COMPONENT/COMPONENT.d.ts → META_FULLNAME/META_FULLNAME.d.ts} +8 -5
  21. package/umd/src/commitments/META_ID/META_ID.d.ts +32 -0
  22. package/umd/src/commitments/index.d.ts +4 -12
  23. package/umd/src/llm-providers/agent/Agent.d.ts +1 -1
  24. package/umd/src/llm-providers/openai/OpenAiAgentKitExecutionToolsToolBuilder.d.ts +1 -1
  25. package/umd/src/{commitments/USE_BROWSER → scrapers/_common/utils}/fetchUrlContent.d.ts +2 -3
  26. package/umd/src/version.d.ts +1 -1
  27. package/esm/src/commitments/MEMORY/MEMORY.d.ts +0 -48
  28. package/esm/src/commitments/MEMORY/MemoryToolNames.d.ts +0 -11
  29. package/esm/src/commitments/MEMORY/MemoryToolRuntimeAdapter.d.ts +0 -149
  30. package/esm/src/commitments/MEMORY/createMemorySystemMessage.d.ts +0 -6
  31. package/esm/src/commitments/MEMORY/createMemoryToolFunctions.d.ts +0 -8
  32. package/esm/src/commitments/MEMORY/createMemoryTools.d.ts +0 -14
  33. package/esm/src/commitments/MEMORY/getMemoryCommitmentDocumentation.d.ts +0 -6
  34. package/esm/src/commitments/MEMORY/getMemoryToolRuntimeAdapterOrDisabledResult.d.ts +0 -17
  35. package/esm/src/commitments/MEMORY/getMemoryToolTitles.d.ts +0 -7
  36. package/esm/src/commitments/MEMORY/parseMemoryToolArgs.d.ts +0 -61
  37. package/esm/src/commitments/MEMORY/resolveMemoryRuntimeContext.d.ts +0 -8
  38. package/esm/src/commitments/MEMORY/setMemoryToolRuntimeAdapter.d.ts +0 -13
  39. package/esm/src/commitments/META/META.d.ts +0 -65
  40. package/esm/src/commitments/USE/aggregateUseCommitmentSystemMessages.d.ts +0 -32
  41. package/esm/src/commitments/USE_BROWSER/USE_BROWSER.d.ts +0 -58
  42. package/esm/src/commitments/USE_BROWSER/fetchUrlContentViaBrowser.d.ts +0 -13
  43. package/esm/src/commitments/USE_BROWSER/resolveRunBrowserToolForNode.d.ts +0 -10
  44. package/esm/src/commitments/USE_DEEPSEARCH/USE_DEEPSEARCH.d.ts +0 -47
  45. package/esm/src/commitments/USE_EMAIL/USE_EMAIL.d.ts +0 -38
  46. package/esm/src/commitments/USE_EMAIL/parseUseEmailCommitmentContent.d.ts +0 -21
  47. package/esm/src/commitments/USE_EMAIL/parseUseEmailCommitmentContent.test.d.ts +0 -1
  48. package/esm/src/commitments/USE_EMAIL/resolveSendEmailToolForNode.d.ts +0 -11
  49. package/esm/src/commitments/USE_EMAIL/sendEmailViaBrowser.d.ts +0 -13
  50. package/esm/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.d.ts +0 -46
  51. package/esm/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.test.d.ts +0 -1
  52. package/esm/src/commitments/USE_SPAWN/USE_SPAWN.d.ts +0 -38
  53. package/esm/src/commitments/USE_SPAWN/USE_SPAWN.test.d.ts +0 -1
  54. package/esm/src/commitments/USE_SPAWN/resolveSpawnAgentToolForNode.d.ts +0 -9
  55. package/esm/src/commitments/USE_SPAWN/spawnAgentViaBrowser.d.ts +0 -12
  56. package/esm/src/commitments/USE_TIME/USE_TIME.d.ts +0 -43
  57. package/esm/src/commitments/USE_TIME/USE_TIME.test.d.ts +0 -1
  58. package/esm/src/commitments/USE_TIMEOUT/TimeoutToolNames.d.ts +0 -11
  59. package/esm/src/commitments/USE_TIMEOUT/TimeoutToolRuntimeAdapter.d.ts +0 -212
  60. package/esm/src/commitments/USE_TIMEOUT/USE_TIMEOUT.d.ts +0 -38
  61. package/esm/src/commitments/USE_TIMEOUT/USE_TIMEOUT.test.d.ts +0 -1
  62. package/esm/src/commitments/USE_TIMEOUT/createTimeoutSystemMessage.d.ts +0 -6
  63. package/esm/src/commitments/USE_TIMEOUT/createTimeoutToolFunctions.d.ts +0 -8
  64. package/esm/src/commitments/USE_TIMEOUT/createTimeoutTools.d.ts +0 -7
  65. package/esm/src/commitments/USE_TIMEOUT/getTimeoutToolRuntimeAdapterOrDisabledResult.d.ts +0 -17
  66. package/esm/src/commitments/USE_TIMEOUT/parseTimeoutToolArgs.d.ts +0 -78
  67. package/esm/src/commitments/USE_TIMEOUT/resolveTimeoutRuntimeContext.d.ts +0 -8
  68. package/esm/src/commitments/USE_TIMEOUT/setTimeoutToolRuntimeAdapter.d.ts +0 -13
  69. package/esm/src/commitments/WALLET/WALLET.d.ts +0 -21
  70. package/esm/src/commitments/WALLET/WALLET.test.d.ts +0 -1
  71. package/esm/src/commitments/WALLET/WalletToolNames.d.ts +0 -12
  72. package/esm/src/commitments/WALLET/WalletToolRuntimeAdapter.d.ts +0 -163
  73. package/esm/src/commitments/WALLET/createWalletSystemMessage.d.ts +0 -6
  74. package/esm/src/commitments/WALLET/createWalletToolFunctions.d.ts +0 -8
  75. package/esm/src/commitments/WALLET/createWalletTools.d.ts +0 -7
  76. package/esm/src/commitments/WALLET/getWalletCommitmentDocumentation.d.ts +0 -6
  77. package/esm/src/commitments/WALLET/getWalletToolRuntimeAdapterOrDisabledResult.d.ts +0 -16
  78. package/esm/src/commitments/WALLET/getWalletToolTitles.d.ts +0 -7
  79. package/esm/src/commitments/WALLET/parseWalletToolArgs.d.ts +0 -51
  80. package/esm/src/commitments/WALLET/resolveWalletRuntimeContext.d.ts +0 -8
  81. package/esm/src/commitments/WALLET/setWalletToolRuntimeAdapter.d.ts +0 -13
  82. package/esm/src/commitments/_common/createSerpSearchToolFunction.d.ts +0 -12
  83. package/umd/src/book-2.0/agent-source/createAgentModelRequirements.useCommitmentAggregation.test.d.ts +0 -1
  84. package/umd/src/commitments/MEMORY/MEMORY.d.ts +0 -48
  85. package/umd/src/commitments/MEMORY/MEMORY.test.d.ts +0 -1
  86. package/umd/src/commitments/MEMORY/MemoryToolNames.d.ts +0 -11
  87. package/umd/src/commitments/MEMORY/MemoryToolRuntimeAdapter.d.ts +0 -149
  88. package/umd/src/commitments/MEMORY/createMemorySystemMessage.d.ts +0 -6
  89. package/umd/src/commitments/MEMORY/createMemoryToolFunctions.d.ts +0 -8
  90. package/umd/src/commitments/MEMORY/createMemoryTools.d.ts +0 -14
  91. package/umd/src/commitments/MEMORY/getMemoryCommitmentDocumentation.d.ts +0 -6
  92. package/umd/src/commitments/MEMORY/getMemoryToolRuntimeAdapterOrDisabledResult.d.ts +0 -17
  93. package/umd/src/commitments/MEMORY/getMemoryToolTitles.d.ts +0 -7
  94. package/umd/src/commitments/MEMORY/parseMemoryToolArgs.d.ts +0 -61
  95. package/umd/src/commitments/MEMORY/resolveMemoryRuntimeContext.d.ts +0 -8
  96. package/umd/src/commitments/MEMORY/setMemoryToolRuntimeAdapter.d.ts +0 -13
  97. package/umd/src/commitments/META/META.d.ts +0 -65
  98. package/umd/src/commitments/USE/aggregateUseCommitmentSystemMessages.d.ts +0 -32
  99. package/umd/src/commitments/USE_BROWSER/USE_BROWSER.d.ts +0 -58
  100. package/umd/src/commitments/USE_BROWSER/USE_BROWSER.test.d.ts +0 -1
  101. package/umd/src/commitments/USE_BROWSER/fetchUrlContentViaBrowser.d.ts +0 -13
  102. package/umd/src/commitments/USE_BROWSER/resolveRunBrowserToolForNode.d.ts +0 -10
  103. package/umd/src/commitments/USE_BROWSER/resolveRunBrowserToolForNode.test.d.ts +0 -1
  104. package/umd/src/commitments/USE_DEEPSEARCH/USE_DEEPSEARCH.d.ts +0 -47
  105. package/umd/src/commitments/USE_DEEPSEARCH/USE_DEEPSEARCH.test.d.ts +0 -1
  106. package/umd/src/commitments/USE_EMAIL/USE_EMAIL.d.ts +0 -38
  107. package/umd/src/commitments/USE_EMAIL/USE_EMAIL.test.d.ts +0 -1
  108. package/umd/src/commitments/USE_EMAIL/parseUseEmailCommitmentContent.d.ts +0 -21
  109. package/umd/src/commitments/USE_EMAIL/parseUseEmailCommitmentContent.test.d.ts +0 -1
  110. package/umd/src/commitments/USE_EMAIL/resolveSendEmailToolForNode.d.ts +0 -11
  111. package/umd/src/commitments/USE_EMAIL/sendEmailViaBrowser.d.ts +0 -13
  112. package/umd/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.d.ts +0 -46
  113. package/umd/src/commitments/USE_SEARCH_ENGINE/USE_SEARCH_ENGINE.test.d.ts +0 -1
  114. package/umd/src/commitments/USE_SPAWN/USE_SPAWN.d.ts +0 -38
  115. package/umd/src/commitments/USE_SPAWN/USE_SPAWN.test.d.ts +0 -1
  116. package/umd/src/commitments/USE_SPAWN/resolveSpawnAgentToolForNode.d.ts +0 -9
  117. package/umd/src/commitments/USE_SPAWN/spawnAgentViaBrowser.d.ts +0 -12
  118. package/umd/src/commitments/USE_TIME/USE_TIME.d.ts +0 -43
  119. package/umd/src/commitments/USE_TIME/USE_TIME.test.d.ts +0 -1
  120. package/umd/src/commitments/USE_TIMEOUT/TimeoutToolNames.d.ts +0 -11
  121. package/umd/src/commitments/USE_TIMEOUT/TimeoutToolRuntimeAdapter.d.ts +0 -212
  122. package/umd/src/commitments/USE_TIMEOUT/USE_TIMEOUT.d.ts +0 -38
  123. package/umd/src/commitments/USE_TIMEOUT/USE_TIMEOUT.test.d.ts +0 -1
  124. package/umd/src/commitments/USE_TIMEOUT/createTimeoutSystemMessage.d.ts +0 -6
  125. package/umd/src/commitments/USE_TIMEOUT/createTimeoutToolFunctions.d.ts +0 -8
  126. package/umd/src/commitments/USE_TIMEOUT/createTimeoutTools.d.ts +0 -7
  127. package/umd/src/commitments/USE_TIMEOUT/getTimeoutToolRuntimeAdapterOrDisabledResult.d.ts +0 -17
  128. package/umd/src/commitments/USE_TIMEOUT/parseTimeoutToolArgs.d.ts +0 -78
  129. package/umd/src/commitments/USE_TIMEOUT/resolveTimeoutRuntimeContext.d.ts +0 -8
  130. package/umd/src/commitments/USE_TIMEOUT/setTimeoutToolRuntimeAdapter.d.ts +0 -13
  131. package/umd/src/commitments/WALLET/WALLET.d.ts +0 -21
  132. package/umd/src/commitments/WALLET/WALLET.test.d.ts +0 -1
  133. package/umd/src/commitments/WALLET/WalletToolNames.d.ts +0 -12
  134. package/umd/src/commitments/WALLET/WalletToolRuntimeAdapter.d.ts +0 -163
  135. package/umd/src/commitments/WALLET/createWalletSystemMessage.d.ts +0 -6
  136. package/umd/src/commitments/WALLET/createWalletToolFunctions.d.ts +0 -8
  137. package/umd/src/commitments/WALLET/createWalletTools.d.ts +0 -7
  138. package/umd/src/commitments/WALLET/getWalletCommitmentDocumentation.d.ts +0 -6
  139. package/umd/src/commitments/WALLET/getWalletToolRuntimeAdapterOrDisabledResult.d.ts +0 -16
  140. package/umd/src/commitments/WALLET/getWalletToolTitles.d.ts +0 -7
  141. package/umd/src/commitments/WALLET/parseWalletToolArgs.d.ts +0 -51
  142. package/umd/src/commitments/WALLET/resolveWalletRuntimeContext.d.ts +0 -8
  143. package/umd/src/commitments/WALLET/setWalletToolRuntimeAdapter.d.ts +0 -13
  144. package/umd/src/commitments/_common/createSerpSearchToolFunction.d.ts +0 -12
  145. /package/esm/src/book-2.0/agent-source/{createAgentModelRequirements.useCommitmentAggregation.test.d.ts → createAgentModelRequirements.commitmentAggregation.test.d.ts} +0 -0
  146. /package/esm/src/{commitments/MEMORY/MEMORY.test.d.ts → cli/cli-commands/coder/boilerplateCount.test.d.ts} +0 -0
  147. /package/esm/src/{commitments/USE_BROWSER/USE_BROWSER.test.d.ts → cli/cli-commands/coder/generate-boilerplates.test.d.ts} +0 -0
  148. /package/esm/src/commitments/{META → META_DESCRIPTION}/META_DESCRIPTION.d.ts +0 -0
  149. /package/{esm/src/commitments/USE_BROWSER/resolveRunBrowserToolForNode.test.d.ts → umd/src/book-2.0/agent-source/createAgentModelRequirements.commitmentAggregation.test.d.ts} +0 -0
  150. /package/{esm/src/commitments/USE_DEEPSEARCH/USE_DEEPSEARCH.test.d.ts → umd/src/cli/cli-commands/coder/boilerplateCount.test.d.ts} +0 -0
  151. /package/{esm/src/commitments/USE_EMAIL/USE_EMAIL.test.d.ts → umd/src/cli/cli-commands/coder/generate-boilerplates.test.d.ts} +0 -0
  152. /package/umd/src/commitments/{META → META_DESCRIPTION}/META_DESCRIPTION.d.ts +0 -0
package/esm/index.es.js CHANGED
@@ -5,7 +5,6 @@ import CryptoJS from 'crypto-js';
5
5
  import hexEncoder from 'crypto-js/enc-hex';
6
6
  import { basename, join, dirname, isAbsolute } from 'path';
7
7
  import 'crypto';
8
- import moment from 'moment';
9
8
  import { lookup, extension } from 'mime-types';
10
9
  import { createPortal } from 'react-dom';
11
10
  import MonacoEditor, { useMonaco } from '@monaco-editor/react';
@@ -17,6 +16,7 @@ import { toCanvas } from 'html-to-image';
17
16
  import { jsPDF } from 'jspdf';
18
17
  import { createRoot } from 'react-dom/client';
19
18
  import { Archive, Music, FileCode, FileText, File as File$1, ImageIcon, FileJson, Presentation, FileSpreadsheet, Table, Video, Globe2, Maximize2, X, Star, Reply, Pause, Play, Volume2Icon, VolumeXIcon, VibrateIcon, VibrateOffIcon } from 'lucide-react';
19
+ import moment from 'moment';
20
20
  import 'moment/locale/cs';
21
21
  import { forTime } from 'waitasecond';
22
22
  import sha256 from 'crypto-js/sha256';
@@ -39,7 +39,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
39
39
  * @generated
40
40
  * @see https://github.com/webgptorg/promptbook
41
41
  */
42
- const PROMPTBOOK_ENGINE_VERSION = '0.114.0-3';
42
+ const PROMPTBOOK_ENGINE_VERSION = '0.114.0-4';
43
43
  /**
44
44
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
45
45
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -9293,7 +9293,7 @@ class ActionCommitmentDefinition extends BaseCommitmentDefinition {
9293
9293
  Research Assistant
9294
9294
 
9295
9295
  PERSONA You are a helpful research assistant
9296
- USE SEARCH ENGINE
9296
+ USE MCP https://mcp.example.com/server
9297
9297
  RULE Always cite your sources when providing information from the web
9298
9298
  \`\`\`
9299
9299
 
@@ -9313,8 +9313,8 @@ class ActionCommitmentDefinition extends BaseCommitmentDefinition {
9313
9313
  Code Assistant
9314
9314
 
9315
9315
  PERSONA You are a programming assistant
9316
- USE BROWSER
9317
- USE SEARCH ENGINE
9316
+ USE PROJECT https://github.com/example/project
9317
+ USE MCP https://mcp.example.com/server
9318
9318
  RULE Prefer the narrowest useful capability for the task.
9319
9319
  \`\`\`
9320
9320
  `);
@@ -9415,65 +9415,6 @@ class ClosedCommitmentDefinition extends BaseCommitmentDefinition {
9415
9415
  }
9416
9416
  // Note: [💞] Ignore a discrepancy between file name and entity name
9417
9417
 
9418
- /**
9419
- * COMPONENT commitment definition
9420
- *
9421
- * The COMPONENT commitment defines a UI component that the agent can render in the chat.
9422
- *
9423
- * @private [🪔] Maybe export the commitments through some package
9424
- */
9425
- class ComponentCommitmentDefinition extends BaseCommitmentDefinition {
9426
- constructor() {
9427
- super('COMPONENT');
9428
- }
9429
- /**
9430
- * Short one-line description of COMPONENT.
9431
- */
9432
- get description() {
9433
- return 'Define a UI component that the agent can render in the chat.';
9434
- }
9435
- /**
9436
- * Icon for this commitment.
9437
- */
9438
- get icon() {
9439
- return '🧩';
9440
- }
9441
- /**
9442
- * Markdown documentation for COMPONENT commitment.
9443
- */
9444
- get documentation() {
9445
- return spaceTrim$1(`
9446
- # COMPONENT
9447
-
9448
- Defines a UI component that the agent can render in the chat.
9449
-
9450
- ## Key aspects
9451
-
9452
- - Tells the agent that a specific component is available.
9453
- - Provides syntax for using the component.
9454
-
9455
- ## Example
9456
-
9457
- \`\`\`book
9458
- COMPONENT Arrow
9459
- The agent should render an arrow component in the chat UI.
9460
- Syntax:
9461
- <Arrow direction="up" color="red" />
9462
- \`\`\`
9463
- `);
9464
- }
9465
- applyToAgentModelRequirements(requirements, content) {
9466
- const trimmedContent = content.trim();
9467
- if (!trimmedContent) {
9468
- return requirements;
9469
- }
9470
- // Add component capability to the system message
9471
- const componentSection = `Component: ${trimmedContent}`;
9472
- return this.appendToSystemMessage(requirements, componentSection, '\n\n');
9473
- }
9474
- }
9475
- // Note: [💞] Ignore a discrepancy between file name and entity name
9476
-
9477
9418
  /**
9478
9419
  * DELETE commitment definition
9479
9420
  *
@@ -10794,653 +10735,6 @@ class LanguageCommitmentDefinition extends BaseCommitmentDefinition {
10794
10735
  }
10795
10736
  // Note: [💞] Ignore a discrepancy between file name and entity name
10796
10737
 
10797
- /**
10798
- * @@@
10799
- *
10800
- * @private utility for commitments
10801
- */
10802
- function formatOptionalInstructionBlock(label, content) {
10803
- const trimmedContent = spaceTrim$1(content);
10804
- if (!trimmedContent) {
10805
- return '';
10806
- }
10807
- return spaceTrim$1((block) => `
10808
- - ${label}:
10809
- ${block(trimmedContent
10810
- .split(/\r?\n/)
10811
- .map((line) => `- ${line}`)
10812
- .join('\n'))}
10813
- `);
10814
- }
10815
-
10816
- /**
10817
- * Names of tools used by the MEMORY commitment.
10818
- *
10819
- * @private function of MemoryCommitmentDefinition
10820
- */
10821
- const MemoryToolNames = {
10822
- retrieve: 'retrieve_user_memory',
10823
- store: 'store_user_memory',
10824
- update: 'update_user_memory',
10825
- delete: 'delete_user_memory',
10826
- };
10827
-
10828
- /**
10829
- * Builds the MEMORY instruction block appended to the system message.
10830
- *
10831
- * @private function of MemoryCommitmentDefinition
10832
- */
10833
- function createMemorySystemMessage(extraInstructions) {
10834
- return spaceTrim$1((block) => `
10835
- ## Memory
10836
-
10837
- - Prefer storing agent-scoped memories; only make them global when the fact should apply across all your agents.
10838
- - You can use persistent user memory tools.
10839
- - Use \`${MemoryToolNames.retrieve}\` to load relevant memory before answering.
10840
- - Use \`${MemoryToolNames.store}\` to save stable user-specific facts that improve future help.
10841
- - Use \`${MemoryToolNames.update}\` to refresh an existing memory when the content changes.
10842
- - Use \`${MemoryToolNames.delete}\` to delete memories that are no longer accurate (deletions are soft and hidden from future queries).
10843
- - Store concise memory items and avoid duplicates.
10844
- - Never claim memory was saved or loaded unless the tool confirms it.
10845
- ${block(extraInstructions)}
10846
- `);
10847
- }
10848
-
10849
- /**
10850
- * Builds a disabled memory-tool response payload.
10851
- *
10852
- * @private function of MemoryCommitmentDefinition
10853
- */
10854
- function createDisabledMemoryResult(action, message) {
10855
- if (action === 'retrieve') {
10856
- return {
10857
- action,
10858
- status: 'disabled',
10859
- memories: [],
10860
- message,
10861
- };
10862
- }
10863
- if (action === 'store') {
10864
- return {
10865
- action,
10866
- status: 'disabled',
10867
- message,
10868
- };
10869
- }
10870
- if (action === 'update') {
10871
- return {
10872
- action,
10873
- status: 'disabled',
10874
- message,
10875
- };
10876
- }
10877
- if (action === 'delete') {
10878
- return {
10879
- action,
10880
- status: 'disabled',
10881
- message,
10882
- };
10883
- }
10884
- throw new Error(`Unsupported memory tool action: ${action}`);
10885
- }
10886
- /**
10887
- * Gets the runtime adapter and returns a disabled result when unavailable.
10888
- *
10889
- * @private function of MemoryCommitmentDefinition
10890
- */
10891
- function getMemoryToolRuntimeAdapterOrDisabledResult(action, runtimeContext) {
10892
- if (!runtimeContext.enabled || runtimeContext.isTeamConversation || runtimeContext.isPrivateMode) {
10893
- const message = runtimeContext.isPrivateMode
10894
- ? 'Memory is disabled because private mode is active.'
10895
- : runtimeContext.isTeamConversation
10896
- ? 'Memory is disabled for TEAM conversations.'
10897
- : 'Memory is disabled for unauthenticated users.';
10898
- return {
10899
- adapter: null,
10900
- disabledResult: createDisabledMemoryResult(action, message),
10901
- };
10902
- }
10903
- {
10904
- return {
10905
- adapter: null,
10906
- disabledResult: createDisabledMemoryResult(action, 'Memory runtime is not available in this environment.'),
10907
- };
10908
- }
10909
- }
10910
-
10911
- /**
10912
- * Parses a memory identifier argument shared across MEMORY tools.
10913
- *
10914
- * @private function of MemoryCommitmentDefinition
10915
- */
10916
- function parseMemoryIdArg(value) {
10917
- const memoryId = typeof value === 'string' ? value.trim() : '';
10918
- if (!memoryId) {
10919
- throw new Error('Memory id is required.');
10920
- }
10921
- return memoryId;
10922
- }
10923
- /**
10924
- * Collection of MEMORY tool argument parsers.
10925
- *
10926
- * @private function of MemoryCommitmentDefinition
10927
- */
10928
- const parseMemoryToolArgs = {
10929
- /**
10930
- * Parses retrieve memory arguments.
10931
- */
10932
- retrieve(args) {
10933
- const query = typeof args.query === 'string' ? args.query.trim() : undefined;
10934
- const limit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.floor(args.limit) : undefined;
10935
- return {
10936
- query: query && query.length > 0 ? query : undefined,
10937
- limit: limit && limit > 0 ? Math.min(limit, 20) : undefined,
10938
- };
10939
- },
10940
- /**
10941
- * Parses store memory arguments.
10942
- */
10943
- store(args) {
10944
- const content = typeof args.content === 'string' ? args.content.trim() : '';
10945
- if (!content) {
10946
- throw new Error('Memory content is required.');
10947
- }
10948
- return {
10949
- content,
10950
- isGlobal: args.isGlobal === true,
10951
- };
10952
- },
10953
- /**
10954
- * Parses update memory arguments.
10955
- */
10956
- update(args) {
10957
- const memoryId = parseMemoryIdArg(args.memoryId);
10958
- const content = typeof args.content === 'string' ? args.content.trim() : '';
10959
- if (!content) {
10960
- throw new Error('Memory content is required.');
10961
- }
10962
- const isGlobal = typeof args.isGlobal === 'boolean' ? args.isGlobal : undefined;
10963
- return {
10964
- memoryId,
10965
- content,
10966
- isGlobal,
10967
- };
10968
- },
10969
- /**
10970
- * Parses delete memory arguments.
10971
- */
10972
- delete(args) {
10973
- return {
10974
- memoryId: parseMemoryIdArg(args.memoryId),
10975
- };
10976
- },
10977
- };
10978
-
10979
- /**
10980
- * Prompt parameter key used to pass hidden runtime context to tool execution.
10981
- *
10982
- * @private internal runtime wiring for commitment tools
10983
- */
10984
- const TOOL_RUNTIME_CONTEXT_PARAMETER = 'promptbookToolRuntimeContext';
10985
- /**
10986
- * Hidden argument key used to pass runtime context into individual tool calls.
10987
- *
10988
- * @private internal runtime wiring for commitment tools
10989
- */
10990
- const TOOL_RUNTIME_CONTEXT_ARGUMENT = '__promptbookToolRuntimeContext';
10991
- /**
10992
- * Prompt parameter key used to pass a hidden tool-progress listener token into script execution.
10993
- *
10994
- * @private internal runtime wiring for commitment tools
10995
- */
10996
- const TOOL_PROGRESS_TOKEN_PARAMETER = 'promptbookToolProgressToken';
10997
- /**
10998
- * Hidden argument key used to pass a tool-progress listener token into individual tool calls.
10999
- *
11000
- * @private internal runtime wiring for commitment tools
11001
- */
11002
- const TOOL_PROGRESS_TOKEN_ARGUMENT = '__promptbookToolProgressToken';
11003
- /**
11004
- * Monotonic counter used for hidden progress-listener tokens.
11005
- *
11006
- * @private internal runtime wiring for commitment tools
11007
- */
11008
- let toolCallProgressListenerCounter = 0;
11009
- /**
11010
- * Active tool-progress listeners keyed by hidden execution token.
11011
- *
11012
- * @private internal runtime wiring for commitment tools
11013
- */
11014
- const toolCallProgressListeners = new Map();
11015
- /**
11016
- * Parses unknown runtime context payload into a normalized object.
11017
- *
11018
- * @private internal runtime wiring for commitment tools
11019
- */
11020
- function parseToolRuntimeContext(rawValue) {
11021
- if (!rawValue) {
11022
- return null;
11023
- }
11024
- let parsed = rawValue;
11025
- if (typeof rawValue === 'string') {
11026
- try {
11027
- parsed = JSON.parse(rawValue);
11028
- }
11029
- catch (_a) {
11030
- return null;
11031
- }
11032
- }
11033
- if (!parsed || typeof parsed !== 'object') {
11034
- return null;
11035
- }
11036
- return parsed;
11037
- }
11038
- /**
11039
- * Reads runtime context attached to tool call arguments.
11040
- *
11041
- * @private internal runtime wiring for commitment tools
11042
- */
11043
- function readToolRuntimeContextFromToolArgs(args) {
11044
- return parseToolRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]);
11045
- }
11046
- /**
11047
- * Serializes runtime context for prompt parameters.
11048
- *
11049
- * @private internal runtime wiring for commitment tools
11050
- */
11051
- function serializeToolRuntimeContext(context) {
11052
- return JSON.stringify(context);
11053
- }
11054
- /**
11055
- * Registers one in-memory listener that receives progress updates emitted by a running tool.
11056
- *
11057
- * The returned token is passed into script execution as a hidden argument so tool implementations
11058
- * can stream progress without exposing extra parameters to the model.
11059
- *
11060
- * @param listener - Listener notified about tool progress.
11061
- * @returns Hidden token used to route progress updates.
11062
- *
11063
- * @private internal runtime wiring for commitment tools
11064
- */
11065
- function registerToolCallProgressListener(listener) {
11066
- toolCallProgressListenerCounter += 1;
11067
- const token = `tool-progress:${Date.now()}:${toolCallProgressListenerCounter}`;
11068
- toolCallProgressListeners.set(token, listener);
11069
- return token;
11070
- }
11071
- /**
11072
- * Unregisters one in-memory progress listener.
11073
- *
11074
- * @param token - Token previously created by `registerToolCallProgressListener`.
11075
- *
11076
- * @private internal runtime wiring for commitment tools
11077
- */
11078
- function unregisterToolCallProgressListener(token) {
11079
- toolCallProgressListeners.delete(token);
11080
- }
11081
- // Note: [💞] Ignore a discrepancy between file name and entity name
11082
-
11083
- /**
11084
- * Resolves runtime context from hidden tool arguments.
11085
- *
11086
- * @private function of MemoryCommitmentDefinition
11087
- */
11088
- function resolveMemoryRuntimeContext(args) {
11089
- const runtimeContext = readToolRuntimeContextFromToolArgs(args);
11090
- const memoryContext = runtimeContext === null || runtimeContext === void 0 ? void 0 : runtimeContext.memory;
11091
- return {
11092
- enabled: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.enabled) === true,
11093
- userId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.userId,
11094
- username: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.username,
11095
- agentId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentId,
11096
- agentName: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentName,
11097
- isTeamConversation: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.isTeamConversation) === true,
11098
- isPrivateMode: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.isPrivateMode) === true,
11099
- };
11100
- }
11101
-
11102
- /**
11103
- * Gets MEMORY tool function implementations.
11104
- *
11105
- * @private function of MemoryCommitmentDefinition
11106
- */
11107
- function createMemoryToolFunctions() {
11108
- return {
11109
- async [MemoryToolNames.retrieve](args) {
11110
- const runtimeContext = resolveMemoryRuntimeContext(args);
11111
- const { adapter, disabledResult } = getMemoryToolRuntimeAdapterOrDisabledResult('retrieve', runtimeContext);
11112
- if (!adapter || disabledResult) {
11113
- return JSON.stringify(disabledResult);
11114
- }
11115
- const parsedArgs = parseMemoryToolArgs.retrieve(args);
11116
- try {
11117
- const memories = await adapter.retrieveMemories(parsedArgs, runtimeContext);
11118
- const result = {
11119
- action: 'retrieve',
11120
- status: 'ok',
11121
- query: parsedArgs.query,
11122
- memories,
11123
- };
11124
- return JSON.stringify(result);
11125
- }
11126
- catch (error) {
11127
- const result = {
11128
- action: 'retrieve',
11129
- status: 'error',
11130
- query: parsedArgs.query,
11131
- memories: [],
11132
- message: error instanceof Error ? error.message : String(error),
11133
- };
11134
- return JSON.stringify(result);
11135
- }
11136
- },
11137
- async [MemoryToolNames.store](args) {
11138
- const runtimeContext = resolveMemoryRuntimeContext(args);
11139
- const { adapter, disabledResult } = getMemoryToolRuntimeAdapterOrDisabledResult('store', runtimeContext);
11140
- if (!adapter || disabledResult) {
11141
- return JSON.stringify(disabledResult);
11142
- }
11143
- try {
11144
- const parsedArgs = parseMemoryToolArgs.store(args);
11145
- const memory = await adapter.storeMemory(parsedArgs, runtimeContext);
11146
- const result = {
11147
- action: 'store',
11148
- status: 'stored',
11149
- memory,
11150
- };
11151
- return JSON.stringify(result);
11152
- }
11153
- catch (error) {
11154
- const result = {
11155
- action: 'store',
11156
- status: 'error',
11157
- message: error instanceof Error ? error.message : String(error),
11158
- };
11159
- return JSON.stringify(result);
11160
- }
11161
- },
11162
- async [MemoryToolNames.update](args) {
11163
- const runtimeContext = resolveMemoryRuntimeContext(args);
11164
- const { adapter, disabledResult } = getMemoryToolRuntimeAdapterOrDisabledResult('update', runtimeContext);
11165
- if (!adapter || disabledResult) {
11166
- return JSON.stringify(disabledResult);
11167
- }
11168
- try {
11169
- const parsedArgs = parseMemoryToolArgs.update(args);
11170
- const memory = await adapter.updateMemory(parsedArgs, runtimeContext);
11171
- const result = {
11172
- action: 'update',
11173
- status: 'updated',
11174
- memory,
11175
- };
11176
- return JSON.stringify(result);
11177
- }
11178
- catch (error) {
11179
- const result = {
11180
- action: 'update',
11181
- status: 'error',
11182
- message: error instanceof Error ? error.message : String(error),
11183
- };
11184
- return JSON.stringify(result);
11185
- }
11186
- },
11187
- async [MemoryToolNames.delete](args) {
11188
- const runtimeContext = resolveMemoryRuntimeContext(args);
11189
- const { adapter, disabledResult } = getMemoryToolRuntimeAdapterOrDisabledResult('delete', runtimeContext);
11190
- if (!adapter || disabledResult) {
11191
- return JSON.stringify(disabledResult);
11192
- }
11193
- try {
11194
- const parsedArgs = parseMemoryToolArgs.delete(args);
11195
- const deleted = await adapter.deleteMemory(parsedArgs, runtimeContext);
11196
- const result = {
11197
- action: 'delete',
11198
- status: 'deleted',
11199
- memoryId: deleted.id,
11200
- };
11201
- return JSON.stringify(result);
11202
- }
11203
- catch (error) {
11204
- const result = {
11205
- action: 'delete',
11206
- status: 'error',
11207
- message: error instanceof Error ? error.message : String(error),
11208
- };
11209
- return JSON.stringify(result);
11210
- }
11211
- },
11212
- };
11213
- }
11214
-
11215
- /**
11216
- * Creates MEMORY tool definitions while preserving already-registered tools.
11217
- *
11218
- * @private function of MemoryCommitmentDefinition
11219
- */
11220
- function createMemoryTools(existingTools) {
11221
- const tools = [...(existingTools || [])];
11222
- if (!tools.some((tool) => tool.name === MemoryToolNames.retrieve)) {
11223
- tools.push({
11224
- name: MemoryToolNames.retrieve,
11225
- description: spaceTrim$1(`
11226
- Retrieve previously stored user memories relevant to the current conversation.
11227
- Use this before responding when user context can improve the answer.
11228
- `),
11229
- parameters: {
11230
- type: 'object',
11231
- properties: {
11232
- query: {
11233
- type: 'string',
11234
- description: 'Optional query used to filter relevant memories.',
11235
- },
11236
- limit: {
11237
- type: 'integer',
11238
- description: 'Optional maximum number of memories to return (default 5, max 20).',
11239
- },
11240
- },
11241
- },
11242
- });
11243
- }
11244
- if (!tools.some((tool) => tool.name === MemoryToolNames.store)) {
11245
- tools.push({
11246
- name: MemoryToolNames.store,
11247
- description: spaceTrim$1(`
11248
- Store a durable user memory that should be remembered in future conversations.
11249
- Store only stable and useful user-specific facts or preferences.
11250
- `),
11251
- parameters: {
11252
- type: 'object',
11253
- properties: {
11254
- content: {
11255
- type: 'string',
11256
- description: 'Memory text to store.',
11257
- },
11258
- isGlobal: {
11259
- type: 'boolean',
11260
- description: 'Set true to make this memory global across all user agents.',
11261
- },
11262
- },
11263
- required: ['content'],
11264
- },
11265
- });
11266
- }
11267
- if (!tools.some((tool) => tool.name === MemoryToolNames.update)) {
11268
- tools.push({
11269
- name: MemoryToolNames.update,
11270
- description: spaceTrim$1(`
11271
- Update an existing user memory after retrieving it, so the stored fact stays accurate.
11272
- Always pass the memory id you retrieved along with the new content.
11273
- `),
11274
- parameters: {
11275
- type: 'object',
11276
- properties: {
11277
- memoryId: {
11278
- type: 'string',
11279
- description: 'Unique identifier of the memory entry to update.',
11280
- },
11281
- content: {
11282
- type: 'string',
11283
- description: 'Updated memory text.',
11284
- },
11285
- isGlobal: {
11286
- type: 'boolean',
11287
- description: 'Set true to keep the fact global; omit or false to keep it agent-scoped.',
11288
- },
11289
- },
11290
- required: ['memoryId', 'content'],
11291
- },
11292
- });
11293
- }
11294
- if (!tools.some((tool) => tool.name === MemoryToolNames.delete)) {
11295
- tools.push({
11296
- name: MemoryToolNames.delete,
11297
- description: spaceTrim$1(`
11298
- Delete a user memory that is no longer relevant. Deletions are soft so the record is hidden from future queries.
11299
- `),
11300
- parameters: {
11301
- type: 'object',
11302
- properties: {
11303
- memoryId: {
11304
- type: 'string',
11305
- description: 'Unique identifier of the memory entry to delete.',
11306
- },
11307
- },
11308
- required: ['memoryId'],
11309
- },
11310
- });
11311
- }
11312
- return tools;
11313
- }
11314
-
11315
- /**
11316
- * Markdown documentation for MEMORY commitment.
11317
- *
11318
- * @private function of MemoryCommitmentDefinition
11319
- */
11320
- function getMemoryCommitmentDocumentation(type) {
11321
- return spaceTrim$1(`
11322
- # ${type}
11323
-
11324
- Enables persistent user memory for the current agent. The memory is stored by the runtime and can be retrieved in future conversations.
11325
-
11326
- ## Key aspects
11327
-
11328
- - Both \`MEMORY\` and \`MEMORIES\` work identically.
11329
- - Stores user-specific details through runtime tools.
11330
- - Retrieves relevant memories for personalized responses.
11331
- - Supports optional extra instructions in the commitment content.
11332
-
11333
- ## Examples
11334
-
11335
- \`\`\`book
11336
- Personal Assistant
11337
-
11338
- PERSONA You are a personal productivity assistant
11339
- MEMORY Remember user projects and long-term preferences.
11340
- GOAL Help optimize daily productivity and workflow
11341
- \`\`\`
11342
-
11343
- \`\`\`book
11344
- Learning Companion
11345
-
11346
- PERSONA You are an educational companion for programming students
11347
- MEMORY Remember only the student's learning progress and preferred study style.
11348
- GOAL Provide progressive learning experiences tailored to student's pace
11349
- \`\`\`
11350
-
11351
- \`\`\`book
11352
- Customer Support Agent
11353
-
11354
- PERSONA You are a customer support representative
11355
- MEMORY Remember only important support history and communication preferences.
11356
- GOAL Provide personalized support based on customer history
11357
- \`\`\`
11358
- `);
11359
- }
11360
-
11361
- /**
11362
- * Gets human-readable titles for MEMORY tool functions.
11363
- *
11364
- * @private function of MemoryCommitmentDefinition
11365
- */
11366
- function getMemoryToolTitles() {
11367
- return {
11368
- [MemoryToolNames.retrieve]: 'User memory',
11369
- [MemoryToolNames.store]: 'Store user memory',
11370
- [MemoryToolNames.update]: 'Update user memory',
11371
- [MemoryToolNames.delete]: 'Delete user memory',
11372
- };
11373
- }
11374
-
11375
- /**
11376
- * MEMORY commitment definition
11377
- *
11378
- * The MEMORY commitment is similar to KNOWLEDGE but has a focus on remembering past
11379
- * interactions and user preferences. It helps the agent maintain context about the
11380
- * user's history, preferences, and previous conversations.
11381
- *
11382
- * Example usage in agent source:
11383
- *
11384
- * ```book
11385
- * MEMORY User prefers detailed technical explanations
11386
- * MEMORY Previously worked on React projects
11387
- * MEMORY Timezone: UTC-5 (Eastern Time)
11388
- * ```
11389
- *
11390
- * @private [🪔] Maybe export the commitments through some package
11391
- */
11392
- class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
11393
- constructor(type = 'MEMORY') {
11394
- super(type);
11395
- }
11396
- get requiresContent() {
11397
- return false;
11398
- }
11399
- /**
11400
- * Short one-line description of MEMORY.
11401
- */
11402
- get description() {
11403
- return 'Remember past interactions and user **preferences** for personalized responses.';
11404
- }
11405
- /**
11406
- * Icon for this commitment.
11407
- */
11408
- get icon() {
11409
- return '🧠';
11410
- }
11411
- /**
11412
- * Markdown documentation for MEMORY commitment.
11413
- */
11414
- get documentation() {
11415
- return getMemoryCommitmentDocumentation(this.type);
11416
- }
11417
- applyToAgentModelRequirements(requirements, content) {
11418
- const extraInstructions = formatOptionalInstructionBlock('Memory instructions', content);
11419
- const tools = createMemoryTools(requirements.tools);
11420
- return this.appendToSystemMessage({
11421
- ...requirements,
11422
- tools,
11423
- _metadata: {
11424
- ...requirements._metadata,
11425
- useMemory: content || true,
11426
- },
11427
- }, createMemorySystemMessage(extraInstructions));
11428
- }
11429
- /**
11430
- * Gets human-readable titles for MEMORY tool functions.
11431
- */
11432
- getToolTitles() {
11433
- return getMemoryToolTitles();
11434
- }
11435
- /**
11436
- * Gets MEMORY tool function implementations.
11437
- */
11438
- getToolFunctions() {
11439
- return createMemoryToolFunctions();
11440
- }
11441
- }
11442
- // Note: [💞] Ignore a discrepancy between file name and entity name
11443
-
11444
10738
  /**
11445
10739
  * AGENT MESSAGE commitment definition
11446
10740
  *
@@ -11900,161 +11194,6 @@ class MessageSuffixCommitmentDefinition extends BaseCommitmentDefinition {
11900
11194
  }
11901
11195
  // Note: [💞] Ignore a discrepancy between file name and entity name
11902
11196
 
11903
- /**
11904
- * META commitment definition
11905
- *
11906
- * The META commitment handles all meta-information about the agent such as:
11907
- * - META AVATAR / META VISUAL: Sets the agent's built-in default avatar visual
11908
- * - META IMAGE: Sets the agent's avatar/profile image URL
11909
- * - META LINK: Provides profile/source links for the person the agent models
11910
- * - META DOMAIN: Sets the canonical custom domain/host of the agent
11911
- * - META TITLE: Sets the agent's display title
11912
- * - META DESCRIPTION: Sets the agent's description
11913
- * - META INPUT PLACEHOLDER: Sets chat input placeholder text
11914
- * - META THINKING MESSAGE: Adds custom thinking placeholder variants
11915
- * - META [ANYTHING]: Any other meta information in uppercase format
11916
- *
11917
- * These commitments are special because they don't affect the system message,
11918
- * but are handled separately in the parsing logic for profile display.
11919
- *
11920
- * Example usage in agent source:
11921
- *
11922
- * ```book
11923
- * META VISUAL pixel-art
11924
- * META IMAGE https://example.com/avatar.jpg
11925
- * META LINK https://twitter.com/username
11926
- * META DOMAIN my-agent.com
11927
- * META TITLE Professional Assistant
11928
- * META DESCRIPTION An AI assistant specialized in business tasks
11929
- * META INPUT PLACEHOLDER Write a message...
11930
- * META THINKING MESSAGE Thinking...
11931
- * META AUTHOR John Doe
11932
- * META VERSION 1.0
11933
- * ```
11934
- *
11935
- * @private [🪔] Maybe export the commitments through some package
11936
- */
11937
- class MetaCommitmentDefinition extends BaseCommitmentDefinition {
11938
- constructor() {
11939
- super('META');
11940
- }
11941
- /**
11942
- * Short one-line description of META commitments.
11943
- */
11944
- get description() {
11945
- return 'Set meta-information about the agent (IMAGE, LINK, TITLE, DESCRIPTION, etc.).';
11946
- }
11947
- /**
11948
- * Icon for this commitment.
11949
- */
11950
- get icon() {
11951
- return 'ℹ️';
11952
- }
11953
- /**
11954
- * Markdown documentation for META commitment.
11955
- */
11956
- get documentation() {
11957
- return spaceTrim$1(`
11958
- # META
11959
-
11960
- Sets meta-information about the agent that is used for display and attribution purposes.
11961
-
11962
- ## Supported META types
11963
-
11964
- - **META AVATAR** / **META VISUAL** - Sets the agent's built-in default avatar visual
11965
- - **META IMAGE** - Sets the agent's avatar/profile image URL
11966
- - **META LINK** - Provides profile/source links for the person the agent models
11967
- - **META DOMAIN** - Sets the canonical custom domain/host of the agent
11968
- - **META TITLE** - Sets the agent's display title
11969
- - **META DESCRIPTION** - Sets the agent's description
11970
- - **META INPUT PLACEHOLDER** - Sets chat input placeholder text
11971
- - **META THINKING MESSAGE** - Adds custom thinking placeholder variants
11972
- - **META [ANYTHING]** - Any other meta information in uppercase format
11973
-
11974
- ## Key aspects
11975
-
11976
- - Does not modify the agent's behavior or responses
11977
- - Used for visual representation and attribution in user interfaces
11978
- - Multiple META commitments of different types can be used
11979
- - Multiple META LINK commitments can be used for different social profiles
11980
- - Multiple META THINKING MESSAGE commitments can be used for different thinking placeholder variants
11981
- - If multiple META commitments of the same type are specified, the last one takes precedence (except for LINK)
11982
-
11983
- ## Examples
11984
-
11985
- ### Basic meta information
11986
-
11987
- \`\`\`book
11988
- Professional Assistant
11989
-
11990
- META VISUAL octopus3
11991
- META IMAGE https://example.com/professional-avatar.jpg
11992
- META TITLE Senior Business Consultant
11993
- META DESCRIPTION Specialized in strategic planning and project management
11994
- META LINK https://linkedin.com/in/professional
11995
- \`\`\`
11996
-
11997
- ### Multiple links and custom meta
11998
-
11999
- \`\`\`book
12000
- Open Source Developer
12001
-
12002
- META IMAGE /assets/dev-avatar.png
12003
- META LINK https://github.com/developer
12004
- META LINK https://twitter.com/devhandle
12005
- META AUTHOR Jane Smith
12006
- META VERSION 2.1
12007
- META LICENSE MIT
12008
- \`\`\`
12009
-
12010
- ### Creative assistant
12011
-
12012
- \`\`\`book
12013
- Creative Helper
12014
-
12015
- META IMAGE https://example.com/creative-bot.jpg
12016
- META TITLE Creative Writing Assistant
12017
- META DESCRIPTION Helps with brainstorming, storytelling, and creative projects
12018
- META INSPIRATION Books, movies, and real-world experiences
12019
- \`\`\`
12020
- `);
12021
- }
12022
- applyToAgentModelRequirements(requirements, content) {
12023
- // META commitments don't modify the system message or model requirements
12024
- // They are handled separately in the parsing logic for meta information extraction
12025
- // This method exists for consistency with the CommitmentDefinition interface
12026
- return requirements;
12027
- }
12028
- /**
12029
- * Extracts meta information from the content based on the meta type
12030
- * This is used by the parsing logic
12031
- */
12032
- extractMetaValue(metaType, content) {
12033
- const trimmedContent = content.trim();
12034
- return trimmedContent || null;
12035
- }
12036
- /**
12037
- * Validates if the provided content is a valid URL (for IMAGE and LINK types)
12038
- */
12039
- isValidUrl(content) {
12040
- try {
12041
- new URL(content.trim());
12042
- return true;
12043
- }
12044
- catch (_a) {
12045
- return false;
12046
- }
12047
- }
12048
- /**
12049
- * Checks if this is a known meta type
12050
- */
12051
- isKnownMetaType(metaType) {
12052
- const knownTypes = ['AVATAR', 'IMAGE', 'LINK', 'TITLE', 'DESCRIPTION', 'AUTHOR', 'VERSION', 'LICENSE'];
12053
- return knownTypes.includes(metaType.toUpperCase());
12054
- }
12055
- }
12056
- // Note: [💞] Ignore a discrepancy between file name and entity name
12057
-
12058
11197
  /**
12059
11198
  * META AVATAR commitment definition
12060
11199
  *
@@ -12219,6 +11358,81 @@ class MetaColorCommitmentDefinition extends BaseCommitmentDefinition {
12219
11358
  }
12220
11359
  // Note: [💞] Ignore a discrepancy between file name and entity name
12221
11360
 
11361
+ /**
11362
+ * META DESCRIPTION commitment definition
11363
+ *
11364
+ * The META DESCRIPTION commitment sets the agent's meta description for the profile page.
11365
+ * This commitment is special because it doesn't affect the system message,
11366
+ * but is handled separately in the parsing logic.
11367
+ *
11368
+ * Example usage in agent source:
11369
+ *
11370
+ * ```book
11371
+ * META DESCRIPTION An AI assistant specialized in business tasks
11372
+ * ```
11373
+ *
11374
+ * @private [🪔] Maybe export the commitments through some package
11375
+ */
11376
+ class MetaDescriptionCommitmentDefinition extends BaseCommitmentDefinition {
11377
+ constructor() {
11378
+ super('META DESCRIPTION');
11379
+ }
11380
+ /**
11381
+ * Short one-line description of META DESCRIPTION.
11382
+ */
11383
+ get description() {
11384
+ return "Set the agent's meta description.";
11385
+ }
11386
+ /**
11387
+ * Icon for this commitment.
11388
+ */
11389
+ get icon() {
11390
+ return '📝';
11391
+ }
11392
+ /**
11393
+ * Markdown documentation for META DESCRIPTION commitment.
11394
+ */
11395
+ get documentation() {
11396
+ return spaceTrim$1(`
11397
+ # META DESCRIPTION
11398
+
11399
+ Sets the agent's meta description for the profile page.
11400
+
11401
+ ## Key aspects
11402
+
11403
+ - Does not modify the agent's behavior or responses.
11404
+ - Only one \`META DESCRIPTION\` should be used per agent.
11405
+ - If multiple are specified, the last one takes precedence.
11406
+ - Used for SEO and display in user interfaces.
11407
+ - If not present, the agent description falls back to \`PERSONA\` or the first few lines of the agent source.
11408
+
11409
+ ## Examples
11410
+
11411
+ \`\`\`book
11412
+ Professional Assistant
11413
+
11414
+ META DESCRIPTION Specialized in strategic planning and project management
11415
+ PERSONA You are a professional business assistant
11416
+ WRITING RULES Maintain a formal and courteous tone
11417
+ \`\`\`
11418
+ `);
11419
+ }
11420
+ applyToAgentModelRequirements(requirements, content) {
11421
+ // META DESCRIPTION doesn't modify the system message or model requirements
11422
+ // It's handled separately in the parsing logic
11423
+ return requirements;
11424
+ }
11425
+ /**
11426
+ * Extracts the meta description from the content
11427
+ * This is used by the parsing logic
11428
+ */
11429
+ extractMetaDescription(content) {
11430
+ const trimmedContent = content.trim();
11431
+ return trimmedContent || null;
11432
+ }
11433
+ }
11434
+ // Note: [💞] Ignore a discrepancy between file name and entity name
11435
+
12222
11436
  /**
12223
11437
  * META DOMAIN commitment definition
12224
11438
  *
@@ -12435,6 +11649,131 @@ class MetaFontCommitmentDefinition extends BaseCommitmentDefinition {
12435
11649
  }
12436
11650
  // Note: [💞] Ignore a discrepancy between file name and entity name
12437
11651
 
11652
+ /**
11653
+ * META FULLNAME commitment definition
11654
+ *
11655
+ * The `META FULLNAME` commitment sets the full display name of the agent, which can differ
11656
+ * from the agent name on the first line of the agent source, for example when the agent
11657
+ * should be presented with academic titles.
11658
+ * This commitment is metadata-only and does not modify model requirements.
11659
+ *
11660
+ * @private [🪔] Maybe export the commitments through some package
11661
+ */
11662
+ class MetaFullnameCommitmentDefinition extends BaseCommitmentDefinition {
11663
+ constructor() {
11664
+ super('META FULLNAME');
11665
+ }
11666
+ /**
11667
+ * Short one-line description of META FULLNAME.
11668
+ */
11669
+ get description() {
11670
+ return "Set the agent's full display name.";
11671
+ }
11672
+ /**
11673
+ * Icon for this commitment.
11674
+ */
11675
+ get icon() {
11676
+ return '🪪';
11677
+ }
11678
+ /**
11679
+ * Markdown documentation for META FULLNAME commitment.
11680
+ */
11681
+ get documentation() {
11682
+ return spaceTrim$1(`
11683
+ # META FULLNAME
11684
+
11685
+ Sets the full display name of the agent shown in profiles, chats, and exports.
11686
+
11687
+ ## Key aspects
11688
+
11689
+ - Does not modify the agent's behavior or responses.
11690
+ - If not present, the agent name from the first line of the agent source is used.
11691
+ - If multiple \`META FULLNAME\` commitments are specified, the last one takes precedence.
11692
+
11693
+ ## Examples
11694
+
11695
+ \`\`\`book
11696
+ Pavol Hejný
11697
+
11698
+ META FULLNAME Dr. Ing. Pavol Hejný, PhD.
11699
+ PERSONA Developer with 10 years of experience in building AI applications.
11700
+ \`\`\`
11701
+ `);
11702
+ }
11703
+ applyToAgentModelRequirements(requirements, content) {
11704
+ // META FULLNAME does not modify the model requirements.
11705
+ // It is consumed by profile parsing.
11706
+ return requirements;
11707
+ }
11708
+ }
11709
+ // Note: [💞] Ignore a discrepancy between file name and entity name
11710
+
11711
+ /**
11712
+ * META ID commitment definition
11713
+ *
11714
+ * The `META ID` commitment carries the permanent id of the agent when an agent source is moved
11715
+ * between systems. It is a low-level commitment which is normally written and stripped by the
11716
+ * persistence layer instead of being written by hand.
11717
+ * This commitment is metadata-only and does not modify model requirements.
11718
+ *
11719
+ * @private [🪔] Maybe export the commitments through some package
11720
+ */
11721
+ class MetaIdCommitmentDefinition extends BaseCommitmentDefinition {
11722
+ constructor() {
11723
+ super('META ID');
11724
+ }
11725
+ /**
11726
+ * Short one-line description of META ID.
11727
+ */
11728
+ get description() {
11729
+ return "Set the agent's permanent id.";
11730
+ }
11731
+ /**
11732
+ * Icon for this commitment.
11733
+ */
11734
+ get icon() {
11735
+ return '🔖';
11736
+ }
11737
+ /**
11738
+ * `META ID` is written by the persistence layer, not by agent authors.
11739
+ */
11740
+ get isLowLevel() {
11741
+ return true;
11742
+ }
11743
+ /**
11744
+ * Markdown documentation for META ID commitment.
11745
+ */
11746
+ get documentation() {
11747
+ return spaceTrim$1(`
11748
+ # META ID
11749
+
11750
+ Carries the permanent id of the agent inside the agent source.
11751
+
11752
+ ## Key aspects
11753
+
11754
+ - Does not modify the agent's behavior or responses.
11755
+ - Written and stripped by the persistence layer, it should not be written by hand.
11756
+ - When an agent source without \`META ID\` is stored, a fresh permanent id is assigned.
11757
+ - If multiple \`META ID\` commitments are specified, the last one takes precedence.
11758
+
11759
+ ## Examples
11760
+
11761
+ \`\`\`book
11762
+ My agent
11763
+
11764
+ META ID doQMRg82izNfJa
11765
+ PERSONA My agent is an expert in something.
11766
+ \`\`\`
11767
+ `);
11768
+ }
11769
+ applyToAgentModelRequirements(requirements, content) {
11770
+ // META ID does not modify the model requirements.
11771
+ // It is consumed by profile parsing and agent persistence.
11772
+ return requirements;
11773
+ }
11774
+ }
11775
+ // Note: [💞] Ignore a discrepancy between file name and entity name
11776
+
12438
11777
  /**
12439
11778
  * META IMAGE commitment definition
12440
11779
  *
@@ -14218,6 +13557,110 @@ function isSameOriginAgentUrl(agentUrl, localServerUrl) {
14218
13557
  }
14219
13558
  // Note: [💞] Ignore a discrepancy between file name and entity name
14220
13559
 
13560
+ /**
13561
+ * Prompt parameter key used to pass hidden runtime context to tool execution.
13562
+ *
13563
+ * @private internal runtime wiring for commitment tools
13564
+ */
13565
+ const TOOL_RUNTIME_CONTEXT_PARAMETER = 'promptbookToolRuntimeContext';
13566
+ /**
13567
+ * Hidden argument key used to pass runtime context into individual tool calls.
13568
+ *
13569
+ * @private internal runtime wiring for commitment tools
13570
+ */
13571
+ const TOOL_RUNTIME_CONTEXT_ARGUMENT = '__promptbookToolRuntimeContext';
13572
+ /**
13573
+ * Prompt parameter key used to pass a hidden tool-progress listener token into script execution.
13574
+ *
13575
+ * @private internal runtime wiring for commitment tools
13576
+ */
13577
+ const TOOL_PROGRESS_TOKEN_PARAMETER = 'promptbookToolProgressToken';
13578
+ /**
13579
+ * Hidden argument key used to pass a tool-progress listener token into individual tool calls.
13580
+ *
13581
+ * @private internal runtime wiring for commitment tools
13582
+ */
13583
+ const TOOL_PROGRESS_TOKEN_ARGUMENT = '__promptbookToolProgressToken';
13584
+ /**
13585
+ * Monotonic counter used for hidden progress-listener tokens.
13586
+ *
13587
+ * @private internal runtime wiring for commitment tools
13588
+ */
13589
+ let toolCallProgressListenerCounter = 0;
13590
+ /**
13591
+ * Active tool-progress listeners keyed by hidden execution token.
13592
+ *
13593
+ * @private internal runtime wiring for commitment tools
13594
+ */
13595
+ const toolCallProgressListeners = new Map();
13596
+ /**
13597
+ * Parses unknown runtime context payload into a normalized object.
13598
+ *
13599
+ * @private internal runtime wiring for commitment tools
13600
+ */
13601
+ function parseToolRuntimeContext(rawValue) {
13602
+ if (!rawValue) {
13603
+ return null;
13604
+ }
13605
+ let parsed = rawValue;
13606
+ if (typeof rawValue === 'string') {
13607
+ try {
13608
+ parsed = JSON.parse(rawValue);
13609
+ }
13610
+ catch (_a) {
13611
+ return null;
13612
+ }
13613
+ }
13614
+ if (!parsed || typeof parsed !== 'object') {
13615
+ return null;
13616
+ }
13617
+ return parsed;
13618
+ }
13619
+ /**
13620
+ * Reads runtime context attached to tool call arguments.
13621
+ *
13622
+ * @private internal runtime wiring for commitment tools
13623
+ */
13624
+ function readToolRuntimeContextFromToolArgs(args) {
13625
+ return parseToolRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]);
13626
+ }
13627
+ /**
13628
+ * Serializes runtime context for prompt parameters.
13629
+ *
13630
+ * @private internal runtime wiring for commitment tools
13631
+ */
13632
+ function serializeToolRuntimeContext(context) {
13633
+ return JSON.stringify(context);
13634
+ }
13635
+ /**
13636
+ * Registers one in-memory listener that receives progress updates emitted by a running tool.
13637
+ *
13638
+ * The returned token is passed into script execution as a hidden argument so tool implementations
13639
+ * can stream progress without exposing extra parameters to the model.
13640
+ *
13641
+ * @param listener - Listener notified about tool progress.
13642
+ * @returns Hidden token used to route progress updates.
13643
+ *
13644
+ * @private internal runtime wiring for commitment tools
13645
+ */
13646
+ function registerToolCallProgressListener(listener) {
13647
+ toolCallProgressListenerCounter += 1;
13648
+ const token = `tool-progress:${Date.now()}:${toolCallProgressListenerCounter}`;
13649
+ toolCallProgressListeners.set(token, listener);
13650
+ return token;
13651
+ }
13652
+ /**
13653
+ * Unregisters one in-memory progress listener.
13654
+ *
13655
+ * @param token - Token previously created by `registerToolCallProgressListener`.
13656
+ *
13657
+ * @private internal runtime wiring for commitment tools
13658
+ */
13659
+ function unregisterToolCallProgressListener(token) {
13660
+ toolCallProgressListeners.delete(token);
13661
+ }
13662
+ // Note: [💞] Ignore a discrepancy between file name and entity name
13663
+
14221
13664
  /**
14222
13665
  * Map of team tool functions.
14223
13666
  */
@@ -14805,430 +14248,23 @@ class TemplateCommitmentDefinition extends BaseCommitmentDefinition {
14805
14248
  // Note: [💞] Ignore a discrepancy between file name and entity name
14806
14249
 
14807
14250
  /**
14808
- * All `USE` commitment types currently participating in final system-message aggregation.
14809
- *
14810
- * @private internal constant for `aggregateUseCommitmentSystemMessages`
14811
- */
14812
- const AGGREGATED_USE_COMMITMENT_TYPES = [
14813
- 'USE BROWSER',
14814
- 'USE DEEPSEARCH',
14815
- 'USE SEARCH ENGINE',
14816
- 'USE TIME',
14817
- ];
14818
- /**
14819
- * Prefix used for temporary in-system-message placeholders that preserve the first-occurrence position of aggregated `USE` sections.
14820
- *
14821
- * @private internal constant for `appendAggregatedUseCommitmentPlaceholder`
14822
- */
14823
- const AGGREGATED_USE_COMMITMENT_PLACEHOLDER_PREFIX = '# AGGREGATED USE COMMITMENT: ';
14824
- /**
14825
- * Type guard for `USE` commitment types that are aggregated in the final system message.
14826
- *
14827
- * @param type - Commitment type to check.
14828
- * @returns `true` when the commitment participates in `USE` system-message aggregation.
14829
- *
14830
- * @private internal utility of `aggregateUseCommitmentSystemMessages`
14831
- */
14832
- function isAggregatedUseCommitmentType(type) {
14833
- return AGGREGATED_USE_COMMITMENT_TYPES.includes(type);
14834
- }
14835
- /**
14836
- * Creates the placeholder token used to reserve the first-occurrence position of an aggregated `USE` system-message section.
14837
- *
14838
- * @param type - Aggregated `USE` commitment type.
14839
- * @returns Single-line placeholder comment stored in the interim system message.
14840
- *
14841
- * @private internal utility of `appendAggregatedUseCommitmentPlaceholder`
14842
- */
14843
- function getAggregatedUseCommitmentPlaceholder(type) {
14844
- return `${AGGREGATED_USE_COMMITMENT_PLACEHOLDER_PREFIX}${type}`;
14845
- }
14846
- /**
14847
- * Combines distinct additional instruction blocks in source order.
14848
- *
14849
- * @param additionalInstructions - Deduplicated instruction blocks collected from the agent source.
14850
- * @returns Combined instruction text ready for `formatOptionalInstructionBlock`.
14851
- *
14852
- * @private internal utility of `createAggregatedUseCommitmentSystemMessage`
14853
- */
14854
- function combineAdditionalInstructions(additionalInstructions) {
14855
- return additionalInstructions.join('\n');
14856
- }
14857
- /**
14858
- * Creates the final aggregated system-message section for a supported `USE` commitment type.
14859
- *
14860
- * @param type - Aggregated `USE` commitment type.
14861
- * @param additionalInstructions - Distinct additional instructions in source order.
14862
- * @returns Final system-message block for the commitment type.
14863
- *
14864
- * @private internal utility of `aggregateUseCommitmentSystemMessages`
14865
- */
14866
- function createAggregatedUseCommitmentSystemMessage(type, additionalInstructions) {
14867
- const combinedAdditionalInstructions = combineAdditionalInstructions(additionalInstructions);
14868
- switch (type) {
14869
- case 'USE TIME':
14870
- return spaceTrim$1((block) => `
14871
- ## Time and date context
14872
-
14873
- - It is ${moment().format('MMMM YYYY')} now.
14874
- - If you need more precise current time information, use the tool \`get_current_time\`.
14875
- ${block(formatOptionalInstructionBlock('Time instructions', combinedAdditionalInstructions))}
14876
- `);
14877
- case 'USE BROWSER':
14878
- return spaceTrim$1((block) => `
14879
- ## Browser
14880
-
14881
- - Use \`fetch_url_content\` to retrieve content from specific URLs (webpages or documents) using scrapers.
14882
- - Use \`run_browser\` for real interactive browser automation (navigation, clicks, typing, waiting, scrolling).
14883
- - When you need to know information from a specific website or document, use the tools provided.
14884
- ${block(formatOptionalInstructionBlock('Browser instructions', combinedAdditionalInstructions))}
14885
- `);
14886
- case 'USE SEARCH ENGINE':
14887
- return spaceTrim$1((block) => `
14888
- ## Web Search
14889
-
14890
- - Use \`web_search\` to find up-to-date information or facts.
14891
- - When you need to know some information from the internet, use the search tool provided.
14892
- - Do not make up information when you can search for it.
14893
- - Do not tell the user you cannot search for information, YOU CAN.
14894
- ${block(formatOptionalInstructionBlock('Search instructions', combinedAdditionalInstructions))}
14895
- `);
14896
- case 'USE DEEPSEARCH':
14897
- return spaceTrim$1((block) => `
14898
- ## Deep Research
14899
-
14900
- - Use \`deep_search\` for broader research tasks that need multi-step investigation, comparison, or synthesis across multiple sources.
14901
- - Prefer it over quick search when the user asks for a well-grounded brief, report, or deeper investigation.
14902
- - Do not pretend you cannot research current information when this tool is available.
14903
- ${block(formatOptionalInstructionBlock('DeepSearch instructions', combinedAdditionalInstructions))}
14904
- `);
14905
- }
14906
- }
14907
- /**
14908
- * Adds the placeholder for an aggregated `USE` system-message section only once, preserving the section position from the first occurrence.
14909
- *
14910
- * @param requirements - Current model requirements.
14911
- * @param type - Aggregated `USE` commitment type being applied.
14912
- * @returns Requirements with the placeholder inserted when it was not already present.
14913
- *
14914
- * @private internal utility of `USE` commitments
14915
- */
14916
- function appendAggregatedUseCommitmentPlaceholder(requirements, type) {
14917
- const placeholder = getAggregatedUseCommitmentPlaceholder(type);
14918
- if (requirements.systemMessage.includes(placeholder)) {
14919
- return requirements;
14920
- }
14921
- const systemMessage = requirements.systemMessage.trim()
14922
- ? `${requirements.systemMessage}\n\n${placeholder}`
14923
- : placeholder;
14924
- return {
14925
- ...requirements,
14926
- systemMessage,
14927
- };
14928
- }
14929
- /**
14930
- * Replaces temporary `USE` placeholders with one aggregated system-message block per commitment type.
14931
- *
14932
- * Distinct additional-instruction blocks are merged in stable source order while the hard-coded section is emitted only once.
14933
- *
14934
- * @param requirements - Model requirements produced by commitment-by-commitment application.
14935
- * @param commitments - Filtered commitments in their original source order.
14936
- * @returns Requirements with aggregated `USE` system-message sections.
14937
- *
14938
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
14939
- */
14940
- function aggregateUseCommitmentSystemMessages(requirements, commitments) {
14941
- const additionalInstructionsByType = new Map();
14942
- for (const commitment of commitments) {
14943
- if (!isAggregatedUseCommitmentType(commitment.type)) {
14944
- continue;
14945
- }
14946
- let additionalInstructions = additionalInstructionsByType.get(commitment.type);
14947
- if (!additionalInstructions) {
14948
- additionalInstructions = [];
14949
- additionalInstructionsByType.set(commitment.type, additionalInstructions);
14950
- }
14951
- const normalizedContent = spaceTrim$1(commitment.content);
14952
- if (normalizedContent && !additionalInstructions.includes(normalizedContent)) {
14953
- additionalInstructions.push(normalizedContent);
14954
- }
14955
- }
14956
- let systemMessage = requirements.systemMessage;
14957
- for (const [type, additionalInstructions] of additionalInstructionsByType) {
14958
- const placeholder = getAggregatedUseCommitmentPlaceholder(type);
14959
- if (!systemMessage.includes(placeholder)) {
14960
- continue;
14961
- }
14962
- systemMessage = systemMessage.replace(placeholder, createAggregatedUseCommitmentSystemMessage(type, additionalInstructions));
14963
- }
14964
- return {
14965
- ...requirements,
14966
- systemMessage,
14967
- };
14968
- }
14969
-
14970
- /**
14971
- * Client-side safe wrapper for fetching URL content
14972
- *
14973
- * This function proxies requests to the Agents Server API endpoint for scraping,
14974
- * making it safe to use in browser environments.
14975
- *
14976
- * @param url The URL to fetch and scrape
14977
- * @param agentsServerUrl The base URL of the agents server (defaults to current origin)
14978
- * @returns Markdown content from the URL
14979
- *
14980
- * @private internal utility for USE BROWSER commitment
14981
- */
14982
- async function fetchUrlContentViaBrowser(url, agentsServerUrl) {
14983
- try {
14984
- // Determine the agents server URL
14985
- const baseUrl = agentsServerUrl || (typeof window !== 'undefined' ? window.location.origin : '');
14986
- if (!baseUrl) {
14987
- throw new Error('Agents server URL is required in non-browser environments');
14988
- }
14989
- // Build the API endpoint URL
14990
- const apiUrl = new URL('/api/scrape', baseUrl);
14991
- apiUrl.searchParams.set('url', url);
14992
- // Fetch from the API endpoint
14993
- const response = await fetch(apiUrl.toString());
14994
- if (!response.ok) {
14995
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
14996
- throw new Error(`Failed to scrape URL: ${errorData.error || response.statusText}`);
14997
- }
14998
- const data = await response.json();
14999
- if (!data.success || !data.content) {
15000
- throw new Error(`Scraping failed: ${data.error || 'No content returned'}`);
15001
- }
15002
- return data.content;
15003
- }
15004
- catch (error) {
15005
- const errorMessage = error instanceof Error ? error.message : String(error);
15006
- throw new Error(`Error fetching URL content via browser: ${errorMessage}`);
15007
- }
15008
- }
15009
-
15010
- /**
15011
- * USE BROWSER commitment definition
15012
- *
15013
- * The `USE BROWSER` commitment indicates that the agent should utilize browser tools
15014
- * to access and retrieve up-to-date information from the internet when necessary.
15015
- *
15016
- * This commitment provides two levels of browser access:
15017
- * 1. One-shot URL fetching: Simple function to fetch and scrape URL content
15018
- * 2. Running browser: For complex tasks like scrolling, clicking, form filling, etc.
15019
- *
15020
- * The content following `USE BROWSER` is an arbitrary text that the agent should know
15021
- * (e.g. browsing scope or preferred sources).
15022
- *
15023
- * Example usage in agent source:
15024
- *
15025
- * ```book
15026
- * USE BROWSER
15027
- * USE BROWSER Prefer official documentation and source websites.
15028
- * ```
14251
+ * @@@
15029
14252
  *
15030
- * @private [🪔] Maybe export the commitments through some package
14253
+ * @private utility for commitments
15031
14254
  */
15032
- class UseBrowserCommitmentDefinition extends BaseCommitmentDefinition {
15033
- constructor() {
15034
- super('USE BROWSER', ['BROWSER']);
15035
- }
15036
- /**
15037
- * The `USE BROWSER` commitment is standalone.
15038
- */
15039
- get requiresContent() {
15040
- return false;
15041
- }
15042
- /**
15043
- * Short one-line description of USE BROWSER.
15044
- */
15045
- get description() {
15046
- return 'Enable the agent to use browser tools for accessing internet information.';
15047
- }
15048
- /**
15049
- * Icon for this commitment.
15050
- */
15051
- get icon() {
15052
- return '🌐';
15053
- }
15054
- /**
15055
- * Markdown documentation for USE BROWSER commitment.
15056
- */
15057
- get documentation() {
15058
- return spaceTrim$1(`
15059
- # USE BROWSER
15060
-
15061
- Enables the agent to use browser tools to access and retrieve up-to-date information from the internet.
15062
-
15063
- ## Key aspects
15064
-
15065
- - The content following \`USE BROWSER\` is an arbitrary text that the agent should know (e.g. browsing scope or preferred sources).
15066
- - Provides two levels of browser access:
15067
- 1. **One-shot URL fetching**: Simple function to fetch and scrape URL content (active)
15068
- 2. **Running browser**: For complex tasks like scrolling, clicking, form filling, etc. (runtime-dependent)
15069
- - The actual browser tool usage is handled by the agent runtime
15070
- - On the Agents Server, every agent browses in its own persistent isolated browser profile, so cookies and logged-in sessions survive across chats (the profile is linked from the agent wallet)
15071
- - Allows the agent to fetch current information from websites and documents
15072
- - Useful for research tasks, fact-checking, and accessing dynamic content
15073
- - Supports various content types including HTML pages and PDF documents
15074
-
15075
- ## Examples
15076
-
15077
- \`\`\`book
15078
- Research Assistant
15079
-
15080
- PERSONA You are a helpful research assistant specialized in finding current information
15081
- USE BROWSER
15082
- RULE Always cite your sources when providing information from the web
15083
- \`\`\`
15084
-
15085
- \`\`\`book
15086
- News Analyst
15087
-
15088
- PERSONA You are a news analyst who stays up-to-date with current events
15089
- USE BROWSER
15090
- WRITING RULES Present news in a balanced and objective manner
15091
- ACTION Can search for and summarize news articles
15092
- \`\`\`
15093
-
15094
- \`\`\`book
15095
- Company Lawyer
15096
-
15097
- PERSONA You are a company lawyer providing legal advice
15098
- USE BROWSER
15099
- KNOWLEDGE Corporate law and legal procedures
15100
- RULE Always recommend consulting with a licensed attorney for specific legal matters
15101
- \`\`\`
15102
- `);
15103
- }
15104
- /**
15105
- * Gets human-readable titles for tool functions provided by this commitment.
15106
- */
15107
- getToolTitles() {
15108
- return {
15109
- fetch_url_content: 'Fetch URL content',
15110
- run_browser: 'Run browser',
15111
- };
15112
- }
15113
- applyToAgentModelRequirements(requirements, content) {
15114
- // Get existing tools array or create new one
15115
- const existingTools = requirements.tools || [];
15116
- // Add browser tools if not already present
15117
- const toolsToAdd = [];
15118
- // Tool 1: One-shot URL content fetching
15119
- if (!existingTools.some((tool) => tool.name === 'fetch_url_content')) {
15120
- toolsToAdd.push({
15121
- name: 'fetch_url_content',
15122
- description: spaceTrim$1(`
15123
- Fetches and scrapes the content from a URL (webpage or document).
15124
- This tool retrieves the content of the specified URL and converts it to markdown format.
15125
- Use this when you need to access information from a specific website or document.
15126
- Supports various content types including HTML pages and PDF documents.
15127
- `),
15128
- parameters: {
15129
- type: 'object',
15130
- properties: {
15131
- url: {
15132
- type: 'string',
15133
- description: 'The URL to fetch and scrape (e.g., "https://example.com" or "https://example.com/document.pdf")',
15134
- },
15135
- },
15136
- required: ['url'],
15137
- },
15138
- });
15139
- }
15140
- // Tool 2: Running browser for complex page interactions
15141
- if (!existingTools.some((tool) => tool.name === 'run_browser')) {
15142
- toolsToAdd.push({
15143
- name: 'run_browser',
15144
- description: spaceTrim$1(`
15145
- Launches a browser session for complex interactions.
15146
- This tool is for advanced browser automation tasks like scrolling, clicking, form filling, etc.
15147
- Use this when simple one-shot URL fetching is not enough.
15148
- `),
15149
- parameters: {
15150
- type: 'object',
15151
- properties: {
15152
- url: {
15153
- type: 'string',
15154
- description: 'The initial URL to navigate to',
15155
- },
15156
- actions: {
15157
- type: 'array',
15158
- description: 'Array of actions to perform in the browser',
15159
- items: {
15160
- type: 'object',
15161
- properties: {
15162
- type: {
15163
- type: 'string',
15164
- enum: ['navigate', 'click', 'scroll', 'type', 'wait'],
15165
- },
15166
- selector: {
15167
- type: 'string',
15168
- description: 'CSS selector for the element (for click, type actions)',
15169
- },
15170
- value: {
15171
- type: 'string',
15172
- description: 'Value to type or navigate to',
15173
- },
15174
- },
15175
- },
15176
- },
15177
- },
15178
- required: ['url'],
15179
- },
15180
- });
15181
- }
15182
- const updatedTools = [...existingTools, ...toolsToAdd];
15183
- return appendAggregatedUseCommitmentPlaceholder({
15184
- ...requirements,
15185
- tools: updatedTools,
15186
- _metadata: {
15187
- ...requirements._metadata,
15188
- useBrowser: true,
15189
- },
15190
- }, this.type);
15191
- }
15192
- /**
15193
- * Gets the browser tool function implementations.
15194
- *
15195
- * This method automatically detects the environment and uses:
15196
- * - Server-side: Direct scraping via fetchUrlContent (Node.js)
15197
- * - Browser: Proxy through Agents Server API via fetchUrlContentViaBrowser
15198
- */
15199
- getToolFunctions() {
15200
- return {
15201
- /**
15202
- * @@@
15203
- *
15204
- * Note: [🛺] This function has implementation both for browser and node, this is the proxied one for browser
15205
- */
15206
- async fetch_url_content(args) {
15207
- console.log('!!!! [Tool] fetch_url_content called', { args });
15208
- const { url } = args;
15209
- return await fetchUrlContentViaBrowser(url);
15210
- },
15211
- /**
15212
- * @@@
15213
- */
15214
- async run_browser(args) {
15215
- console.log('!!!! [Tool] run_browser called', { args });
15216
- const { url } = args;
15217
- return spaceTrim$1(`
15218
- # Running browser
15219
-
15220
- The running browser tool is not available in this runtime.
15221
-
15222
- This environment does not provide the server-side browser automation backend.
15223
- In Agents Server Node runtime, this tool is resolved to a Playwright CLI implementation.
15224
-
15225
- Requested URL: ${url}
15226
- `);
15227
- },
15228
- };
14255
+ function formatOptionalInstructionBlock(label, content) {
14256
+ const trimmedContent = spaceTrim$1(content);
14257
+ if (!trimmedContent) {
14258
+ return '';
15229
14259
  }
14260
+ return spaceTrim$1((block) => `
14261
+ - ${label}:
14262
+ ${block(trimmedContent
14263
+ .split(/\r?\n/)
14264
+ .map((line) => `- ${line}`)
14265
+ .join('\n'))}
14266
+ `);
15230
14267
  }
15231
- // Note: [💞] Ignore a discrepancy between file name and entity name
15232
14268
 
15233
14269
  /**
15234
14270
  * Hostnames accepted for Google Calendar references.
@@ -15553,7 +14589,7 @@ function resolveUseCalendarToolRuntime(args) {
15553
14589
  const runtimeContext = (readToolRuntimeContextFromToolArgs(args) ||
15554
14590
  {});
15555
14591
  const configuredCalendars = normalizeConfiguredCalendars$1((_a = runtimeContext.calendars) === null || _a === void 0 ? void 0 : _a.connections);
15556
- const calendarArgument = normalizeOptionalText$2(args.calendarUrl);
14592
+ const calendarArgument = normalizeOptionalText$1(args.calendarUrl);
15557
14593
  let calendarReference = null;
15558
14594
  if (calendarArgument) {
15559
14595
  calendarReference = parseGoogleCalendarReference(calendarArgument);
@@ -15573,7 +14609,7 @@ function resolveUseCalendarToolRuntime(args) {
15573
14609
  if (!calendarReference) {
15574
14610
  throw new Error('Calendar is required but was not resolved.');
15575
14611
  }
15576
- const accessToken = normalizeOptionalText$2((_b = runtimeContext.calendars) === null || _b === void 0 ? void 0 : _b.googleAccessToken) || '';
14612
+ const accessToken = normalizeOptionalText$1((_b = runtimeContext.calendars) === null || _b === void 0 ? void 0 : _b.googleAccessToken) || '';
15577
14613
  if (!accessToken) {
15578
14614
  throw new CalendarWalletCredentialRequiredError({
15579
14615
  calendarReference,
@@ -15606,7 +14642,7 @@ function normalizeConfiguredCalendars$1(rawCalendars) {
15606
14642
  continue;
15607
14643
  }
15608
14644
  const calendar = rawCalendar;
15609
- const rawUrl = normalizeOptionalText$2(calendar.url);
14645
+ const rawUrl = normalizeOptionalText$1(calendar.url);
15610
14646
  if (!rawUrl) {
15611
14647
  continue;
15612
14648
  }
@@ -15657,7 +14693,7 @@ function createCalendarWalletCredentialRequiredResult(error) {
15657
14693
  *
15658
14694
  * @private function of resolveUseCalendarToolRuntimeOrWalletCredentialResult
15659
14695
  */
15660
- function normalizeOptionalText$2(value) {
14696
+ function normalizeOptionalText$1(value) {
15661
14697
  if (typeof value !== 'string') {
15662
14698
  return undefined;
15663
14699
  }
@@ -15689,13 +14725,13 @@ function createUseCalendarToolFunctions() {
15689
14725
  async [UseCalendarToolNames.listEvents](args) {
15690
14726
  return withUseCalendarRuntime(args, async ({ calendarReference, accessToken }) => {
15691
14727
  const query = {};
15692
- if (normalizeOptionalText$1(args.timeMin)) {
14728
+ if (normalizeOptionalText(args.timeMin)) {
15693
14729
  query.timeMin = args.timeMin.trim();
15694
14730
  }
15695
- if (normalizeOptionalText$1(args.timeMax)) {
14731
+ if (normalizeOptionalText(args.timeMax)) {
15696
14732
  query.timeMax = args.timeMax.trim();
15697
14733
  }
15698
- if (normalizeOptionalText$1(args.query)) {
14734
+ if (normalizeOptionalText(args.query)) {
15699
14735
  query.q = args.query.trim();
15700
14736
  }
15701
14737
  if (typeof args.maxResults === 'number' && Number.isFinite(args.maxResults) && args.maxResults > 0) {
@@ -15707,7 +14743,7 @@ function createUseCalendarToolFunctions() {
15707
14743
  if (args.orderBy === 'startTime' || args.orderBy === 'updated') {
15708
14744
  query.orderBy = args.orderBy;
15709
14745
  }
15710
- if (normalizeOptionalText$1(args.timeZone)) {
14746
+ if (normalizeOptionalText(args.timeZone)) {
15711
14747
  query.timeZone = args.timeZone.trim();
15712
14748
  }
15713
14749
  const payload = await callGoogleCalendarApi(accessToken, {
@@ -15745,11 +14781,11 @@ function createUseCalendarToolFunctions() {
15745
14781
  return withUseCalendarRuntime(args, async ({ calendarReference, accessToken }) => {
15746
14782
  const requestBody = createGoogleCalendarEventPayload({
15747
14783
  summary: normalizeRequiredText(args.summary, 'summary'),
15748
- description: normalizeOptionalText$1(args.description),
15749
- location: normalizeOptionalText$1(args.location),
14784
+ description: normalizeOptionalText(args.description),
14785
+ location: normalizeOptionalText(args.location),
15750
14786
  start: normalizeRequiredText(args.start, 'start'),
15751
14787
  end: normalizeRequiredText(args.end, 'end'),
15752
- timeZone: normalizeOptionalText$1(args.timeZone),
14788
+ timeZone: normalizeOptionalText(args.timeZone),
15753
14789
  attendees: normalizeAttendees(args.attendees),
15754
14790
  reminderMinutes: normalizeReminderMinutes(args.reminderMinutes),
15755
14791
  });
@@ -15771,12 +14807,12 @@ function createUseCalendarToolFunctions() {
15771
14807
  return withUseCalendarRuntime(args, async ({ calendarReference, accessToken }) => {
15772
14808
  const eventId = normalizeRequiredText(args.eventId, 'eventId');
15773
14809
  const requestBody = createGoogleCalendarEventPayload({
15774
- summary: normalizeOptionalText$1(args.summary),
15775
- description: normalizeOptionalText$1(args.description),
15776
- location: normalizeOptionalText$1(args.location),
15777
- start: normalizeOptionalText$1(args.start),
15778
- end: normalizeOptionalText$1(args.end),
15779
- timeZone: normalizeOptionalText$1(args.timeZone),
14810
+ summary: normalizeOptionalText(args.summary),
14811
+ description: normalizeOptionalText(args.description),
14812
+ location: normalizeOptionalText(args.location),
14813
+ start: normalizeOptionalText(args.start),
14814
+ end: normalizeOptionalText(args.end),
14815
+ timeZone: normalizeOptionalText(args.timeZone),
15780
14816
  attendees: normalizeAttendees(args.attendees),
15781
14817
  reminderMinutes: normalizeReminderMinutes(args.reminderMinutes),
15782
14818
  });
@@ -15823,7 +14859,7 @@ function createUseCalendarToolFunctions() {
15823
14859
  path: `/calendars/${encodeGoogleCalendarId(calendarReference.calendarId)}/events/${encodeURIComponent(eventId)}`,
15824
14860
  });
15825
14861
  const existingAttendees = ((existingEvent === null || existingEvent === void 0 ? void 0 : existingEvent.attendees) || [])
15826
- .map((attendee) => normalizeOptionalText$1(attendee.email))
14862
+ .map((attendee) => normalizeOptionalText(attendee.email))
15827
14863
  .filter((email) => Boolean(email));
15828
14864
  const mergedAttendees = [...new Set([...existingAttendees, ...guests])];
15829
14865
  const payload = await callGoogleCalendarApi(accessToken, {
@@ -15871,7 +14907,7 @@ function encodeGoogleCalendarId(calendarId) {
15871
14907
  * @private function of createUseCalendarToolFunctions
15872
14908
  */
15873
14909
  function normalizeRequiredText(value, fieldName) {
15874
- const normalizedValue = normalizeOptionalText$1(value);
14910
+ const normalizedValue = normalizeOptionalText(value);
15875
14911
  if (!normalizedValue) {
15876
14912
  throw new Error(`Tool "${fieldName}" requires non-empty value.`);
15877
14913
  }
@@ -15882,7 +14918,7 @@ function normalizeRequiredText(value, fieldName) {
15882
14918
  *
15883
14919
  * @private function of createUseCalendarToolFunctions
15884
14920
  */
15885
- function normalizeOptionalText$1(value) {
14921
+ function normalizeOptionalText(value) {
15886
14922
  if (typeof value !== 'string') {
15887
14923
  return undefined;
15888
14924
  }
@@ -16456,484 +15492,6 @@ function addConfiguredCalendarIfMissing(configuredCalendars, calendarReference)
16456
15492
  }
16457
15493
  // Note: [💞] Ignore a discrepancy between file name and entity name
16458
15494
 
16459
- /**
16460
- * A search engine implementation that uses the SerpApi to fetch Google search results.
16461
- *
16462
- * @private <- TODO: !!!! Export via some package
16463
- */
16464
- class SerpSearchEngine {
16465
- get title() {
16466
- return 'SerpApi Search Engine';
16467
- }
16468
- get description() {
16469
- return 'Search engine that uses SerpApi to fetch Google search results';
16470
- }
16471
- checkConfiguration() {
16472
- if (!process.env.SERP_API_KEY) {
16473
- throw new Error('SERP_API_KEY is not configured');
16474
- }
16475
- }
16476
- async search(query, options = {}) {
16477
- const apiKey = process.env.SERP_API_KEY;
16478
- if (!apiKey) {
16479
- throw new Error('SERP_API_KEY is not configured');
16480
- }
16481
- const url = new URL('https://serpapi.com/search');
16482
- url.searchParams.set('api_key', apiKey);
16483
- url.searchParams.set('engine', 'google');
16484
- url.searchParams.set('q', query);
16485
- for (const [key, value] of Object.entries(options)) {
16486
- url.searchParams.set(key, String(value));
16487
- }
16488
- const response = await fetch(url.toString());
16489
- if (!response.ok) {
16490
- const body = await response.text();
16491
- throw new Error(`SerpApi failed with status ${response.status}: ${response.statusText}\n${body}`);
16492
- }
16493
- const data = (await response.json());
16494
- return (data.organic_results || []).map((item) => ({
16495
- title: item.title,
16496
- url: item.link,
16497
- snippet: item.snippet || '',
16498
- }));
16499
- }
16500
- }
16501
-
16502
- /**
16503
- * Creates one SERP-backed tool function used as a local fallback for search-like commitments.
16504
- *
16505
- * @param toolName - Technical tool name used for validation messages.
16506
- * @param resultLabel - Human-readable label used in formatted results.
16507
- * @returns Async tool function compatible with commitment tool registration.
16508
- *
16509
- * @private internal helper for search-like commitments
16510
- */
16511
- function createSerpSearchToolFunction(toolName, resultLabel) {
16512
- return async (rawArgs) => {
16513
- const { query, ...searchOptions } = rawArgs;
16514
- if (typeof query !== 'string' || !query.trim()) {
16515
- throw new Error(`${toolName} query is required`);
16516
- }
16517
- const searchEngine = new SerpSearchEngine();
16518
- const results = await searchEngine.search(query, searchOptions);
16519
- return spaceTrim$1((block) => `
16520
- ${resultLabel} results for "${query}"${Object.keys(searchOptions).length === 0 ? '' : ` with options ${JSON.stringify(searchOptions)}`}:
16521
-
16522
- ${block(results
16523
- .map((result) => spaceTrim$1(`
16524
- - **${result.title}**
16525
- ${result.url}
16526
- ${result.snippet}
16527
- `))
16528
- .join('\n\n'))}
16529
- `);
16530
- };
16531
- }
16532
-
16533
- /**
16534
- * USE DEEPSEARCH commitment definition
16535
- *
16536
- * The `USE DEEPSEARCH` commitment indicates that the agent should use a deeper research-oriented
16537
- * search workflow instead of lightweight web search when it needs fresh information from the internet.
16538
- *
16539
- * The content following `USE DEEPSEARCH` is an arbitrary text that the agent should know
16540
- * (e.g. search scope or research instructions).
16541
- *
16542
- * Example usage in agent source:
16543
- *
16544
- * ```book
16545
- * USE DEEPSEARCH
16546
- * USE DEEPSEARCH Compare official vendor documentation with independent benchmarks.
16547
- * ```
16548
- *
16549
- * @private [🪔] Maybe export the commitments through some package
16550
- */
16551
- class UseDeepSearchCommitmentDefinition extends BaseCommitmentDefinition {
16552
- constructor() {
16553
- super('USE DEEPSEARCH');
16554
- }
16555
- get requiresContent() {
16556
- return false;
16557
- }
16558
- /**
16559
- * Short one-line description of USE DEEPSEARCH.
16560
- */
16561
- get description() {
16562
- return 'Enable the agent to use DeepSearch for more thorough internet research.';
16563
- }
16564
- /**
16565
- * Icon for this commitment.
16566
- */
16567
- get icon() {
16568
- return '🔬';
16569
- }
16570
- /**
16571
- * Markdown documentation for USE DEEPSEARCH commitment.
16572
- */
16573
- get documentation() {
16574
- return spaceTrim$1(`
16575
- # USE DEEPSEARCH
16576
-
16577
- Enables the agent to use DeepSearch for broader, more thorough internet research than lightweight web search.
16578
-
16579
- ## Key aspects
16580
-
16581
- - The content following \`USE DEEPSEARCH\` is arbitrary guidance for the research workflow.
16582
- - In Agents Server, the OpenAI Agents SDK runtime uses a nested deep-research agent for this tool.
16583
- - Use this for investigations, comparisons, market scans, or other tasks that benefit from deeper synthesis.
16584
- - Prefer regular \`USE SEARCH ENGINE\` when a quick factual lookup is enough.
16585
-
16586
- ## Examples
16587
-
16588
- \`\`\`book
16589
- Due Diligence Researcher
16590
-
16591
- GOAL Investigate vendors thoroughly before making recommendations.
16592
- USE DEEPSEARCH Compare official sources with credible third-party analysis.
16593
- RULE Cite the strongest supporting sources in the final answer.
16594
- \`\`\`
16595
-
16596
- \`\`\`book
16597
- Market Analyst
16598
-
16599
- GOAL Build concise but well-grounded research briefs.
16600
- USE DEEPSEARCH Focus on recent public information and competing viewpoints.
16601
- CLOSED
16602
- \`\`\`
16603
- `);
16604
- }
16605
- applyToAgentModelRequirements(requirements, content) {
16606
- const existingTools = requirements.tools || [];
16607
- const updatedTools = existingTools.some((tool) => tool.name === 'deep_search')
16608
- ? existingTools
16609
- : [
16610
- ...existingTools,
16611
- {
16612
- name: 'deep_search',
16613
- description: spaceTrim$1(`
16614
- Research the internet deeply and synthesize a grounded answer.
16615
- Use this tool for broader investigations, comparisons, and requests that need more than a quick search.
16616
- `),
16617
- parameters: {
16618
- type: 'object',
16619
- properties: {
16620
- query: {
16621
- type: 'string',
16622
- description: 'The research question or investigation request.',
16623
- },
16624
- },
16625
- required: ['query'],
16626
- additionalProperties: false,
16627
- },
16628
- },
16629
- ];
16630
- return appendAggregatedUseCommitmentPlaceholder({
16631
- ...requirements,
16632
- tools: updatedTools,
16633
- _metadata: {
16634
- ...requirements._metadata,
16635
- useDeepSearch: content || true,
16636
- },
16637
- }, this.type);
16638
- }
16639
- /**
16640
- * Gets human-readable titles for tool functions provided by this commitment.
16641
- */
16642
- getToolTitles() {
16643
- return {
16644
- deep_search: 'DeepSearch',
16645
- };
16646
- }
16647
- /**
16648
- * Gets the local fallback implementation for the `deep_search` tool.
16649
- */
16650
- getToolFunctions() {
16651
- return {
16652
- deep_search: createSerpSearchToolFunction('deep_search', 'DeepSearch'),
16653
- };
16654
- }
16655
- }
16656
- // Note: [💞] Ignore a discrepancy between file name and entity name
16657
-
16658
- /**
16659
- * Checks if value is valid email
16660
- *
16661
- * @public exported from `@promptbook/utils`
16662
- */
16663
- function isValidEmail(email) {
16664
- if (typeof email !== 'string') {
16665
- return false;
16666
- }
16667
- if (email.split(/\r?\n/).length > 1) {
16668
- return false;
16669
- }
16670
- return /^.+@.+\..+$/.test(email);
16671
- }
16672
-
16673
- /**
16674
- * Lightweight email token matcher used for `USE EMAIL` first-line parsing.
16675
- *
16676
- * @private internal USE EMAIL constant
16677
- */
16678
- const EMAIL_TOKEN_PATTERN = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
16679
- /**
16680
- * Parses `USE EMAIL` commitment content into optional sender email + additional instructions.
16681
- *
16682
- * Examples:
16683
- * - `agent@example.com`
16684
- * - `agent@example.com Keep emails concise`
16685
- * - `Keep emails concise`
16686
- *
16687
- * @private internal utility of USE EMAIL commitment
16688
- */
16689
- function parseUseEmailCommitmentContent(content) {
16690
- const trimmedContent = spaceTrim$1(content);
16691
- if (!trimmedContent) {
16692
- return {
16693
- senderEmail: null,
16694
- senderEmailRaw: null,
16695
- instructions: '',
16696
- };
16697
- }
16698
- const lines = trimmedContent
16699
- .split(/\r?\n/)
16700
- .map((line) => line.trim())
16701
- .filter(Boolean);
16702
- if (lines.length === 0) {
16703
- return {
16704
- senderEmail: null,
16705
- senderEmailRaw: null,
16706
- instructions: '',
16707
- };
16708
- }
16709
- const firstLine = lines[0] || '';
16710
- const senderMatch = firstLine.match(EMAIL_TOKEN_PATTERN);
16711
- const senderEmailRaw = (senderMatch === null || senderMatch === void 0 ? void 0 : senderMatch[0]) || null;
16712
- const senderEmail = senderEmailRaw && isValidEmail(senderEmailRaw) ? senderEmailRaw : null;
16713
- let firstLineWithoutSender = firstLine;
16714
- if (senderEmailRaw) {
16715
- const matchIndex = firstLine.indexOf(senderEmailRaw);
16716
- const prefix = firstLine.slice(0, matchIndex).trim();
16717
- const suffix = firstLine.slice(matchIndex + senderEmailRaw.length).trim();
16718
- firstLineWithoutSender = [prefix, suffix].filter(Boolean).join(' ').trim();
16719
- }
16720
- const instructionLines = [firstLineWithoutSender, ...lines.slice(1)].filter(Boolean);
16721
- const instructions = instructionLines.join('\n').trim();
16722
- return {
16723
- senderEmail,
16724
- senderEmailRaw,
16725
- instructions,
16726
- };
16727
- }
16728
-
16729
- /**
16730
- * Client-side safe wrapper for sending emails.
16731
- *
16732
- * This function proxies requests to the Agents Server API endpoint for email queuing,
16733
- * making it safe to use in browser environments.
16734
- *
16735
- * @param args Email payload forwarded to the server-side `send_email` tool
16736
- * @param agentsServerUrl The base URL of the agents server (defaults to current origin)
16737
- * @returns Result string from the server-side send_email tool
16738
- *
16739
- * @private internal utility for USE EMAIL commitment
16740
- */
16741
- async function sendEmailViaBrowser(args, agentsServerUrl) {
16742
- try {
16743
- const baseUrl = agentsServerUrl || (typeof window !== 'undefined' ? window.location.origin : '');
16744
- if (!baseUrl) {
16745
- throw new Error('Agents server URL is required in non-browser environments');
16746
- }
16747
- const apiUrl = new URL('/api/send-email', baseUrl);
16748
- const response = await fetch(apiUrl.toString(), {
16749
- method: 'POST',
16750
- headers: {
16751
- 'Content-Type': 'application/json',
16752
- },
16753
- body: JSON.stringify(args),
16754
- });
16755
- if (!response.ok) {
16756
- const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
16757
- throw new Error(`Failed to send email: ${errorData.error || response.statusText}`);
16758
- }
16759
- const data = await response.json();
16760
- if (!data.success) {
16761
- throw new Error(`Email sending failed: ${data.error || 'Unknown error'}`);
16762
- }
16763
- return typeof data.result === 'string' ? data.result : JSON.stringify(data.result);
16764
- }
16765
- catch (error) {
16766
- const errorMessage = error instanceof Error ? error.message : String(error);
16767
- throw new Error(`Error sending email via browser: ${errorMessage}`);
16768
- }
16769
- }
16770
-
16771
- /**
16772
- * Tool name used by USE EMAIL.
16773
- *
16774
- * @private internal USE EMAIL constant
16775
- */
16776
- const SEND_EMAIL_TOOL_NAME = 'send_email';
16777
- /**
16778
- * USE EMAIL commitment definition.
16779
- *
16780
- * The `USE EMAIL` commitment enables outbound email sending through the `send_email` tool.
16781
- *
16782
- * @private [🪔] Maybe export the commitments through some package
16783
- */
16784
- class UseEmailCommitmentDefinition extends BaseCommitmentDefinition {
16785
- constructor() {
16786
- super('USE EMAIL', ['EMAIL', 'MAIL']);
16787
- }
16788
- get requiresContent() {
16789
- return false;
16790
- }
16791
- /**
16792
- * Short one-line description of USE EMAIL.
16793
- */
16794
- get description() {
16795
- return 'Enable outbound email sending through a wallet-backed SMTP configuration.';
16796
- }
16797
- /**
16798
- * Icon for this commitment.
16799
- */
16800
- get icon() {
16801
- return '📧';
16802
- }
16803
- /**
16804
- * Markdown documentation for USE EMAIL commitment.
16805
- */
16806
- get documentation() {
16807
- return spaceTrim$1(`
16808
- # USE EMAIL
16809
-
16810
- Enables the agent to send outbound emails through SMTP.
16811
-
16812
- ## Key aspects
16813
-
16814
- - The agent sends email via the \`send_email\` tool.
16815
- - SMTP credentials are expected from wallet records (\`ACCESS_TOKEN\`, service \`smtp\`, key \`use-email-smtp-credentials\`).
16816
- - Commitment content can optionally begin with a default sender email address:
16817
- - \`USE EMAIL agent@example.com\`
16818
- - Remaining commitment content is treated as optional email-writing instructions.
16819
-
16820
- ## Examples
16821
-
16822
- \`\`\`book
16823
- Writing Agent
16824
- USE EMAIL agent@example.com
16825
- RULE Write emails to customers according to the instructions from user.
16826
- \`\`\`
16827
-
16828
- \`\`\`book
16829
- Formal Email Assistant
16830
- USE EMAIL agent@example.com Keep emails concise and formal.
16831
- \`\`\`
16832
- `);
16833
- }
16834
- applyToAgentModelRequirements(requirements, content) {
16835
- var _a;
16836
- const parsedCommitment = parseUseEmailCommitmentContent(content);
16837
- const updatedTools = addUseEmailTools(requirements.tools || []);
16838
- // Collect all configured sender emails across multiple USE EMAIL commitments
16839
- const existingSenders = Array.isArray((_a = requirements._metadata) === null || _a === void 0 ? void 0 : _a.useEmailSenders)
16840
- ? [...requirements._metadata.useEmailSenders]
16841
- : [];
16842
- if (parsedCommitment.senderEmail && !existingSenders.includes(parsedCommitment.senderEmail)) {
16843
- existingSenders.push(parsedCommitment.senderEmail);
16844
- }
16845
- const senderBullets = existingSenders.length > 0
16846
- ? existingSenders
16847
- .map((email, index) => index === 0
16848
- ? `- Default sender address: "${email}".`
16849
- : `- Additional sender address: "${email}".`)
16850
- .join('\n')
16851
- : '';
16852
- const extraInstructions = formatOptionalInstructionBlock('Email instructions', parsedCommitment.instructions);
16853
- const emailSectionContent = spaceTrim$1((block) => `
16854
- ## Emails
16855
-
16856
- - Use \`${SEND_EMAIL_TOOL_NAME}\` to send outbound emails.
16857
- ${block(senderBullets)}
16858
- ${block(extraInstructions)}
16859
- `);
16860
- return this.replaceOrCreateSection({
16861
- ...requirements,
16862
- tools: updatedTools,
16863
- _metadata: {
16864
- ...requirements._metadata,
16865
- useEmail: true,
16866
- ...(parsedCommitment.senderEmail ? { useEmailSender: parsedCommitment.senderEmail } : {}),
16867
- useEmailSenders: existingSenders,
16868
- },
16869
- }, 'Emails', emailSectionContent);
16870
- }
16871
- /**
16872
- * Gets human-readable titles for tool functions provided by this commitment.
16873
- */
16874
- getToolTitles() {
16875
- return {
16876
- [SEND_EMAIL_TOOL_NAME]: 'Send email',
16877
- };
16878
- }
16879
- /**
16880
- * Gets the browser-safe `send_email` implementation.
16881
- *
16882
- * Node.js runtime overrides this via `getAllCommitmentsToolFunctionsForNode`.
16883
- */
16884
- getToolFunctions() {
16885
- return {
16886
- async [SEND_EMAIL_TOOL_NAME](args) {
16887
- return sendEmailViaBrowser(args);
16888
- },
16889
- };
16890
- }
16891
- }
16892
- /**
16893
- * Adds USE EMAIL tool definition while keeping already registered tools untouched.
16894
- *
16895
- * @private utility of USE EMAIL commitment
16896
- */
16897
- function addUseEmailTools(existingTools) {
16898
- if (existingTools.some((tool) => tool.name === SEND_EMAIL_TOOL_NAME)) {
16899
- return [...existingTools];
16900
- }
16901
- return [
16902
- ...existingTools,
16903
- {
16904
- name: SEND_EMAIL_TOOL_NAME,
16905
- description: 'Send an outbound email.',
16906
- parameters: {
16907
- type: 'object',
16908
- properties: {
16909
- message: {
16910
- type: 'object',
16911
- description: 'Email payload. Use metadata.subject for the subject line.',
16912
- },
16913
- to: {
16914
- type: 'string',
16915
- description: 'Legacy alias for recipients (use comma-separated emails or JSON array encoded as string).',
16916
- },
16917
- cc: {
16918
- type: 'string',
16919
- description: 'Optional CC recipients (use comma-separated emails or JSON array encoded as string).',
16920
- },
16921
- subject: {
16922
- type: 'string',
16923
- description: 'Legacy alias for subject.',
16924
- },
16925
- body: {
16926
- type: 'string',
16927
- description: 'Legacy alias for markdown body content.',
16928
- },
16929
- },
16930
- required: [],
16931
- },
16932
- },
16933
- ];
16934
- }
16935
- // Note: [💞] Ignore a discrepancy between file name and entity name
16936
-
16937
15495
  /**
16938
15496
  * USE IMAGE GENERATOR commitment definition
16939
15497
  *
@@ -19162,1503 +17720,6 @@ function addConfiguredProjectIfMissing(configuredProjects, repositoryReference)
19162
17720
  }
19163
17721
  // Note: [💞] Ignore a discrepancy between file name and entity name
19164
17722
 
19165
- /**
19166
- * USE SEARCH ENGINE commitment definition
19167
- *
19168
- * The `USE SEARCH ENGINE` commitment indicates that the agent should utilize a search engine tool
19169
- * to access and retrieve up-to-date information from the internet when necessary.
19170
- *
19171
- * The content following `USE SEARCH ENGINE` is an arbitrary text that the agent should know (e.g. search scope or instructions).
19172
- *
19173
- * Example usage in agent source:
19174
- *
19175
- * ```book
19176
- * USE SEARCH ENGINE
19177
- * USE SEARCH ENGINE Hledej informace o Přemyslovcích
19178
- * ```
19179
- *
19180
- * @private [🪔] Maybe export the commitments through some package
19181
- */
19182
- class UseSearchEngineCommitmentDefinition extends BaseCommitmentDefinition {
19183
- constructor() {
19184
- super('USE SEARCH ENGINE', ['USE SEARCH']);
19185
- }
19186
- get requiresContent() {
19187
- return false;
19188
- }
19189
- /**
19190
- * Short one-line description of USE SEARCH ENGINE.
19191
- */
19192
- get description() {
19193
- return 'Enable the agent to use a search engine tool for accessing internet information.';
19194
- }
19195
- /**
19196
- * Icon for this commitment.
19197
- */
19198
- get icon() {
19199
- return '🔍';
19200
- }
19201
- /**
19202
- * Markdown documentation for USE SEARCH ENGINE commitment.
19203
- */
19204
- get documentation() {
19205
- return spaceTrim$1(`
19206
- # USE SEARCH ENGINE
19207
-
19208
- Enables the agent to use a search engine tool to access and retrieve up-to-date information from the internet.
19209
-
19210
- ## Key aspects
19211
-
19212
- - The content following \`USE SEARCH ENGINE\` is an arbitrary text that the agent should know (e.g. search scope or instructions).
19213
- - The actual search engine tool usage is handled by the agent runtime
19214
- - Allows the agent to search for current information from the web
19215
- - Useful for research tasks, finding facts, and accessing dynamic content
19216
-
19217
- ## Examples
19218
-
19219
- \`\`\`book
19220
- Research Assistant
19221
-
19222
- PERSONA You are a helpful research assistant specialized in finding current information
19223
- USE SEARCH ENGINE
19224
- RULE Always cite your sources when providing information from the web
19225
- \`\`\`
19226
-
19227
- \`\`\`book
19228
- Fact Checker
19229
-
19230
- PERSONA You are a fact checker
19231
- USE SEARCH ENGINE
19232
- ACTION Search for claims and verify them against reliable sources
19233
- \`\`\`
19234
- `);
19235
- }
19236
- applyToAgentModelRequirements(requirements, content) {
19237
- // Get existing tools array or create new one
19238
- const existingTools = requirements.tools || [];
19239
- // Add 'web_search' to tools if not already present
19240
- const updatedTools = existingTools.some((tool) => tool.name === 'web_search')
19241
- ? existingTools
19242
- : [
19243
- ...existingTools,
19244
- {
19245
- name: 'web_search',
19246
- description: spaceTrim$1(`
19247
- Search the internet for information.
19248
- Use this tool when you need to find up-to-date information or facts that you don't know.
19249
- `),
19250
- parameters: {
19251
- type: 'object',
19252
- properties: {
19253
- query: {
19254
- type: 'string',
19255
- description: 'The search query',
19256
- },
19257
- location: {
19258
- type: 'string',
19259
- description: 'The location for the search (e.g., "Austin, Texas, United States" or "Prague, Czechia")',
19260
- },
19261
- gl: {
19262
- type: 'string',
19263
- description: 'The country code (e.g., "us" for United States, "cz" for Czechia)',
19264
- },
19265
- hl: {
19266
- type: 'string',
19267
- description: 'The language code (e.g., "en" for English, "cs" for Czech)',
19268
- },
19269
- num: {
19270
- type: 'integer',
19271
- description: 'Number of results to return',
19272
- },
19273
- engine: {
19274
- type: 'string',
19275
- description: 'The search engine to use (e.g., "google", "bing", "yahoo", "baidu")',
19276
- },
19277
- google_domain: {
19278
- type: 'string',
19279
- description: 'The Google domain to use (e.g., "google.com", "google.cz")',
19280
- },
19281
- },
19282
- required: ['query'],
19283
- },
19284
- },
19285
- ];
19286
- return appendAggregatedUseCommitmentPlaceholder({
19287
- ...requirements,
19288
- tools: updatedTools,
19289
- _metadata: {
19290
- ...requirements._metadata,
19291
- useSearchEngine: content || true,
19292
- },
19293
- }, this.type);
19294
- }
19295
- /**
19296
- * Gets human-readable titles for tool functions provided by this commitment.
19297
- */
19298
- getToolTitles() {
19299
- return {
19300
- web_search: 'Web search',
19301
- };
19302
- }
19303
- /**
19304
- * Gets the `web_search` tool function implementation.
19305
- */
19306
- getToolFunctions() {
19307
- return {
19308
- web_search: createSerpSearchToolFunction('web_search', 'Search'),
19309
- };
19310
- }
19311
- }
19312
- // Note: [💞] Ignore a discrepancy between file name and entity name
19313
-
19314
- /**
19315
- * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
19316
- *
19317
- * @public exported from `@promptbook/core`
19318
- */
19319
- class ParseError extends Error {
19320
- constructor(message) {
19321
- super(message);
19322
- this.name = 'ParseError';
19323
- Object.setPrototypeOf(this, ParseError.prototype);
19324
- }
19325
- }
19326
- // TODO: Maybe split `ParseError` and `ApplyError`
19327
-
19328
- /**
19329
- * Supported visibility states for persisted agents.
19330
- *
19331
- * @public exported from `@promptbook/core`
19332
- */
19333
- const AGENT_VISIBILITY_VALUES = ['PRIVATE', 'UNLISTED', 'PUBLIC'];
19334
- /**
19335
- * Returns `true` when the value is one of supported visibility states.
19336
- *
19337
- * @param value - Raw value to validate.
19338
- * @returns Whether the value is a valid `AgentVisibility`.
19339
- *
19340
- * @public exported from `@promptbook/core`
19341
- */
19342
- function isAgentVisibility(value) {
19343
- return typeof value === 'string' && AGENT_VISIBILITY_VALUES.includes(value);
19344
- }
19345
- /**
19346
- * Normalizes raw visibility text into a supported value.
19347
- *
19348
- * @param value - Raw visibility value.
19349
- * @returns Normalized visibility, or `null` when invalid.
19350
- *
19351
- * @public exported from `@promptbook/core`
19352
- */
19353
- function normalizeAgentVisibility(value) {
19354
- if (typeof value !== 'string') {
19355
- return null;
19356
- }
19357
- const normalized = value.trim().toUpperCase();
19358
- return isAgentVisibility(normalized) ? normalized : null;
19359
- }
19360
- // Note: [💞] Ignore a discrepancy between file name and entity name
19361
-
19362
- /**
19363
- * This error type indicates that some limit was reached
19364
- *
19365
- * @public exported from `@promptbook/core`
19366
- */
19367
- class LimitReachedError extends Error {
19368
- constructor(message) {
19369
- super(message);
19370
- this.name = 'LimitReachedError';
19371
- Object.setPrototypeOf(this, LimitReachedError.prototype);
19372
- }
19373
- }
19374
-
19375
- /**
19376
- * Maximum allowed source length for create-agent payloads.
19377
- *
19378
- * @private shared create-agent contract
19379
- */
19380
- const CREATE_AGENT_INPUT_SOURCE_MAX_LENGTH = 120000;
19381
- /**
19382
- * Builds strict JSON schema for create-agent tool parameters.
19383
- *
19384
- * @private shared create-agent contract
19385
- */
19386
- function createCreateAgentInputToolParametersSchema() {
19387
- return {
19388
- type: 'object',
19389
- additionalProperties: false,
19390
- properties: {
19391
- source: {
19392
- type: 'string',
19393
- description: 'Full source of the new persisted agent (Promptbook/book markdown).',
19394
- },
19395
- folderId: {
19396
- type: 'number',
19397
- description: 'Optional folder identifier where the new agent should be placed.',
19398
- },
19399
- sortOrder: {
19400
- type: 'number',
19401
- description: 'Optional sort order inside the selected folder.',
19402
- },
19403
- visibility: {
19404
- type: 'string',
19405
- description: 'Optional visibility: PRIVATE, UNLISTED, or PUBLIC.',
19406
- },
19407
- },
19408
- required: ['source'],
19409
- };
19410
- }
19411
-
19412
- /**
19413
- * Browser-safe wrapper for spawning one persisted Agents Server agent.
19414
- *
19415
- * This function proxies requests to the Agents Server `/api/spawn-agent` endpoint.
19416
- *
19417
- * @param args Tool payload forwarded to server-side `spawn_agent` tool.
19418
- * @param agentsServerUrl Optional explicit agents server base URL.
19419
- * @returns JSON string with structured spawn result.
19420
- *
19421
- * @private internal utility for USE SPAWN commitment
19422
- */
19423
- async function spawnAgentViaBrowser(args, agentsServerUrl) {
19424
- try {
19425
- const baseUrl = agentsServerUrl || (typeof window !== 'undefined' ? window.location.origin : '');
19426
- if (!baseUrl) {
19427
- throw new Error('Agents server URL is required in non-browser environments');
19428
- }
19429
- const apiUrl = new URL('/api/spawn-agent', baseUrl);
19430
- const response = await fetch(apiUrl.toString(), {
19431
- method: 'POST',
19432
- headers: {
19433
- 'Content-Type': 'application/json',
19434
- },
19435
- body: JSON.stringify(args),
19436
- });
19437
- const payload = (await response.json().catch(() => ({})));
19438
- if (payload.result !== undefined) {
19439
- return typeof payload.result === 'string' ? payload.result : JSON.stringify(payload.result);
19440
- }
19441
- if (!response.ok || payload.success === false) {
19442
- throw new Error(`Failed to spawn agent: ${typeof payload.error === 'string' ? payload.error : response.statusText}`);
19443
- }
19444
- return JSON.stringify(payload);
19445
- }
19446
- catch (error) {
19447
- const errorMessage = error instanceof Error ? error.message : String(error);
19448
- throw new Error(`Error spawning agent via browser: ${errorMessage}`);
19449
- }
19450
- }
19451
-
19452
- /**
19453
- * Tool name used by USE SPAWN.
19454
- *
19455
- * @private internal USE SPAWN constant
19456
- */
19457
- const SPAWN_AGENT_TOOL_NAME = 'spawn_agent';
19458
- /**
19459
- * USE SPAWN commitment definition.
19460
- *
19461
- * The `USE SPAWN` commitment enables creating new persistent child agents through one tool call.
19462
- *
19463
- * @private [🪔] Maybe export the commitments through some package
19464
- */
19465
- class UseSpawnCommitmentDefinition extends BaseCommitmentDefinition {
19466
- constructor() {
19467
- super('USE SPAWN', ['SPAWN']);
19468
- }
19469
- get requiresContent() {
19470
- return false;
19471
- }
19472
- /**
19473
- * Short one-line description of USE SPAWN.
19474
- */
19475
- get description() {
19476
- return 'Enable the agent to create persistent child agents via Agents Server create-agent flow.';
19477
- }
19478
- /**
19479
- * Icon for this commitment.
19480
- */
19481
- get icon() {
19482
- return '🧬';
19483
- }
19484
- /**
19485
- * Markdown documentation for USE SPAWN commitment.
19486
- */
19487
- get documentation() {
19488
- return spaceTrim$1(`
19489
- # USE SPAWN
19490
-
19491
- Enables the agent to create a new persistent child agent using the \`spawn_agent\` tool.
19492
-
19493
- ## Key aspects
19494
-
19495
- - The spawned agent is persisted exactly like manually created agents.
19496
- - Tool input mirrors create-agent fields currently supported by Agents Server:
19497
- - \`source\` (required)
19498
- - \`folderId\` (optional)
19499
- - \`sortOrder\` (optional)
19500
- - \`visibility\` (optional)
19501
- - Unknown fields are rejected to avoid silent misconfiguration.
19502
- - \`source\` payload is size-limited.
19503
- - Agents Server applies permission and abuse protections (auth checks, limits).
19504
- - Optional text after \`USE SPAWN\` is treated as spawn-policy instructions.
19505
-
19506
- ## Examples
19507
-
19508
- \`\`\`book
19509
- Team Builder
19510
-
19511
- PERSONA You can create specialized assistants for the user.
19512
- USE SPAWN Spawn only when the user explicitly asks for a new persistent agent.
19513
- \`\`\`
19514
- `);
19515
- }
19516
- applyToAgentModelRequirements(requirements, content) {
19517
- const extraInstructions = formatOptionalInstructionBlock('Spawn instructions', content);
19518
- const existingTools = requirements.tools || [];
19519
- const tools = existingTools.some((tool) => tool.name === SPAWN_AGENT_TOOL_NAME)
19520
- ? existingTools
19521
- : [
19522
- ...existingTools,
19523
- {
19524
- name: SPAWN_AGENT_TOOL_NAME,
19525
- description: spaceTrim$1(`
19526
- Creates one new persistent child agent in Agents Server.
19527
- Use this when the user asks to create a new dedicated agent profile.
19528
- The tool returns JSON with \`status\`, \`agentId\`, and created \`agent\` or \`error\`.
19529
- `),
19530
- parameters: createCreateAgentInputToolParametersSchema(),
19531
- },
19532
- ];
19533
- return this.appendToSystemMessage({
19534
- ...requirements,
19535
- tools,
19536
- _metadata: {
19537
- ...requirements._metadata,
19538
- useSpawn: content || true,
19539
- },
19540
- }, spaceTrim$1((block) => `
19541
- ## Spawning agents
19542
-
19543
- - Use \`${SPAWN_AGENT_TOOL_NAME}\` only when user asks to create a persistent new agent.
19544
- - Pass full agent source in \`source\`.
19545
- - Keep \`source\` concise; the maximum accepted length is ${CREATE_AGENT_INPUT_SOURCE_MAX_LENGTH} characters.
19546
- - Do not add unknown fields in tool arguments.
19547
- ${block(extraInstructions)}
19548
- `));
19549
- }
19550
- /**
19551
- * Gets human-readable titles for tool functions provided by this commitment.
19552
- */
19553
- getToolTitles() {
19554
- return {
19555
- [SPAWN_AGENT_TOOL_NAME]: 'Spawn agent',
19556
- };
19557
- }
19558
- /**
19559
- * Gets browser-safe `spawn_agent` implementation.
19560
- *
19561
- * Node.js runtime overrides this through `getAllCommitmentsToolFunctionsForNode`.
19562
- */
19563
- getToolFunctions() {
19564
- return {
19565
- async [SPAWN_AGENT_TOOL_NAME](args) {
19566
- return spawnAgentViaBrowser(args);
19567
- },
19568
- };
19569
- }
19570
- }
19571
- // Note: [💞] Ignore a discrepancy between file name and entity name
19572
-
19573
- /**
19574
- * Creates system-message instructions for `USE TIMEOUT`.
19575
- *
19576
- * @private internal utility of USE TIMEOUT
19577
- */
19578
- function createTimeoutSystemMessage(extraInstructions) {
19579
- return spaceTrim$1((block) => `
19580
- ## Timeout scheduling
19581
-
19582
- - Use \`set_timeout\` to wake this same chat thread in the future.
19583
- - Use \`list_timeouts\` to review timeout ids/details across all chats for the same user+agent scope.
19584
- - \`cancel_timeout\` accepts either one timeout id or \`allActive: true\` to cancel all active timeouts in this same user+agent scope.
19585
- - Use \`update_timeout\` to pause/resume, edit next run, edit recurrence, or update timeout payload details.
19586
- - When one timeout elapses, you will receive a new user-like message that explicitly says it is a timeout wake-up and includes the \`timeoutId\`.
19587
- - Do not claim a timer was set or cancelled unless the tool confirms it.
19588
- ${block(extraInstructions)}
19589
- `);
19590
- }
19591
-
19592
- /**
19593
- * Marker property stored inside serialized tool-execution envelopes.
19594
- *
19595
- * @private internal tool-execution transport
19596
- */
19597
- const TOOL_EXECUTION_ENVELOPE_MARKER = '__promptbookToolExecutionEnvelope';
19598
- /**
19599
- * Creates one serialized tool-execution envelope.
19600
- *
19601
- * @private internal tool-execution transport
19602
- */
19603
- function createToolExecutionEnvelope(options) {
19604
- const envelope = {
19605
- [TOOL_EXECUTION_ENVELOPE_MARKER]: true,
19606
- assistantMessage: options.assistantMessage,
19607
- toolResult: options.toolResult,
19608
- };
19609
- return JSON.stringify(envelope);
19610
- }
19611
- /**
19612
- * Parses one serialized tool-execution envelope when present.
19613
- *
19614
- * @private internal tool-execution transport
19615
- */
19616
- function parseToolExecutionEnvelope(rawValue) {
19617
- if (typeof rawValue !== 'string') {
19618
- return null;
19619
- }
19620
- try {
19621
- const parsedValue = JSON.parse(rawValue);
19622
- if (!parsedValue ||
19623
- typeof parsedValue !== 'object' ||
19624
- parsedValue[TOOL_EXECUTION_ENVELOPE_MARKER] !== true ||
19625
- typeof parsedValue.assistantMessage !== 'string') {
19626
- return null;
19627
- }
19628
- return {
19629
- assistantMessage: parsedValue.assistantMessage,
19630
- toolResult: parsedValue.toolResult,
19631
- };
19632
- }
19633
- catch (_a) {
19634
- return null;
19635
- }
19636
- }
19637
- // Note: [💞] Ignore a discrepancy between file name and entity name
19638
-
19639
- /**
19640
- * Builds a disabled timeout-tool payload.
19641
- *
19642
- * @private internal utility of USE TIMEOUT
19643
- */
19644
- function createDisabledTimeoutResult(action, message) {
19645
- return {
19646
- action,
19647
- status: 'disabled',
19648
- message,
19649
- };
19650
- }
19651
- /**
19652
- * Resolves the runtime adapter for timeout tools or returns disabled payload when unavailable.
19653
- *
19654
- * @private internal utility of USE TIMEOUT
19655
- */
19656
- function getTimeoutToolRuntimeAdapterOrDisabledResult(action, runtimeContext) {
19657
- if (!runtimeContext.enabled || !runtimeContext.chatId) {
19658
- return {
19659
- adapter: null,
19660
- disabledResult: createDisabledTimeoutResult(action, 'Timeouts are unavailable because this conversation is not running inside a chat thread.'),
19661
- };
19662
- }
19663
- {
19664
- return {
19665
- adapter: null,
19666
- disabledResult: createDisabledTimeoutResult(action, 'Timeout runtime is not available in this environment.'),
19667
- };
19668
- }
19669
- }
19670
-
19671
- /**
19672
- * Generates random token
19673
- *
19674
- * Note: `$` is used to indicate that this function is not a pure function - it is not deterministic
19675
- * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
19676
- *
19677
- * @returns secure random token
19678
- *
19679
- * @private internal helper function
19680
- */
19681
- function $randomToken(randomness) {
19682
- return CryptoJS.lib.WordArray.random(randomness).toString(CryptoJS.enc.Hex);
19683
- }
19684
- // TODO: [🤶] Maybe export through `@promptbook/utils` or `@promptbook/random` package
19685
- // TODO: Maybe use nanoid instead https://github.com/ai/nanoid
19686
-
19687
- /**
19688
- * This error indicates errors during the execution of the pipeline
19689
- *
19690
- * @public exported from `@promptbook/core`
19691
- */
19692
- class PipelineExecutionError extends Error {
19693
- constructor(message) {
19694
- // Added id parameter
19695
- super(message);
19696
- this.name = 'PipelineExecutionError';
19697
- // TODO: [🐙] DRY - Maybe $randomId
19698
- this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
19699
- Object.setPrototypeOf(this, PipelineExecutionError.prototype);
19700
- }
19701
- }
19702
- // TODO: [🧠][🌂] Add id to all errors
19703
-
19704
- /**
19705
- * Default number of rows returned by `list_timeouts`.
19706
- *
19707
- * @private internal USE TIMEOUT constant
19708
- */
19709
- const DEFAULT_LIST_TIMEOUTS_LIMIT = 20;
19710
- /**
19711
- * Hard cap for `list_timeouts` page size.
19712
- *
19713
- * @private internal USE TIMEOUT constant
19714
- */
19715
- const MAX_LIST_TIMEOUTS_LIMIT = 100;
19716
- /**
19717
- * Creates one formatted timeout-argument validation error.
19718
- *
19719
- * @private internal utility of USE TIMEOUT
19720
- */
19721
- function createTimeoutToolArgsError(message) {
19722
- return new PipelineExecutionError(spaceTrim$1(`
19723
- ${message}
19724
- `));
19725
- }
19726
- /**
19727
- * Normalizes one optional timeout id string.
19728
- *
19729
- * @private internal utility of USE TIMEOUT
19730
- */
19731
- function normalizeOptionalTimeoutId(value) {
19732
- return typeof value === 'string' ? value.trim() : '';
19733
- }
19734
- /**
19735
- * Parses timeout target selection for tools that accept either `timeoutId` or `allActive: true`.
19736
- *
19737
- * @private internal utility of USE TIMEOUT
19738
- */
19739
- function parseTimeoutTargetSelection(args, options) {
19740
- const timeoutId = normalizeOptionalTimeoutId(args.timeoutId);
19741
- const allActive = args.allActive === true;
19742
- if (timeoutId && allActive) {
19743
- throw createTimeoutToolArgsError(options.bothMessage);
19744
- }
19745
- if (allActive) {
19746
- return { allActive: true };
19747
- }
19748
- if (!timeoutId) {
19749
- throw createTimeoutToolArgsError(options.missingMessage);
19750
- }
19751
- return {
19752
- timeoutId,
19753
- allActive: false,
19754
- };
19755
- }
19756
- /**
19757
- * Parses one explicit `dueAt` update value.
19758
- *
19759
- * @private internal utility of USE TIMEOUT
19760
- */
19761
- function parseOptionalTimeoutDueAt(value) {
19762
- if (typeof value !== 'string' || value.trim().length === 0) {
19763
- return undefined;
19764
- }
19765
- const normalizedDueAt = value.trim();
19766
- const dueAtTimestamp = Date.parse(normalizedDueAt);
19767
- if (!Number.isFinite(dueAtTimestamp)) {
19768
- throw createTimeoutToolArgsError('Timeout `dueAt` must be one valid ISO timestamp.');
19769
- }
19770
- return new Date(dueAtTimestamp).toISOString();
19771
- }
19772
- /**
19773
- * Parses one explicit `extendByMs` update value.
19774
- *
19775
- * @private internal utility of USE TIMEOUT
19776
- */
19777
- function parseOptionalTimeoutExtendByMs(value) {
19778
- if (typeof value !== 'number') {
19779
- return undefined;
19780
- }
19781
- if (!Number.isFinite(value) || value <= 0) {
19782
- throw createTimeoutToolArgsError('Timeout `extendByMs` must be a positive number of milliseconds.');
19783
- }
19784
- return Math.floor(value);
19785
- }
19786
- /**
19787
- * Parses one explicit `recurrenceIntervalMs` update value.
19788
- *
19789
- * @private internal utility of USE TIMEOUT
19790
- */
19791
- function parseOptionalTimeoutRecurrenceInterval(value) {
19792
- if (value === null) {
19793
- return null;
19794
- }
19795
- if (typeof value !== 'number') {
19796
- return undefined;
19797
- }
19798
- if (!Number.isFinite(value) || value <= 0) {
19799
- throw createTimeoutToolArgsError('Timeout `recurrenceIntervalMs` must be a positive number of milliseconds or `null`.');
19800
- }
19801
- return Math.floor(value);
19802
- }
19803
- /**
19804
- * Parses one explicit `message` update value.
19805
- *
19806
- * @private internal utility of USE TIMEOUT
19807
- */
19808
- function parseOptionalTimeoutMessage(value) {
19809
- if (value === null) {
19810
- return null;
19811
- }
19812
- if (typeof value !== 'string') {
19813
- return undefined;
19814
- }
19815
- const normalizedMessage = value.trim();
19816
- return normalizedMessage.length > 0 ? normalizedMessage : null;
19817
- }
19818
- /**
19819
- * Parses one explicit `parameters` update value.
19820
- *
19821
- * @private internal utility of USE TIMEOUT
19822
- */
19823
- function parseOptionalTimeoutParameters(value) {
19824
- if (value === undefined) {
19825
- return undefined;
19826
- }
19827
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
19828
- throw createTimeoutToolArgsError('Timeout `parameters` must be one JSON object.');
19829
- }
19830
- return value;
19831
- }
19832
- /**
19833
- * Parses one explicit `paused` update value.
19834
- *
19835
- * @private internal utility of USE TIMEOUT
19836
- */
19837
- function parseOptionalTimeoutPaused(value) {
19838
- return typeof value === 'boolean' ? value : undefined;
19839
- }
19840
- /**
19841
- * Parses patch fields for `update_timeout`.
19842
- *
19843
- * @private internal utility of USE TIMEOUT
19844
- */
19845
- function parseTimeoutUpdatePatch(args) {
19846
- const patch = {};
19847
- const dueAt = parseOptionalTimeoutDueAt(args.dueAt);
19848
- const extendByMs = parseOptionalTimeoutExtendByMs(args.extendByMs);
19849
- const recurrenceIntervalMs = parseOptionalTimeoutRecurrenceInterval(args.recurrenceIntervalMs);
19850
- const message = parseOptionalTimeoutMessage(args.message);
19851
- const parameters = parseOptionalTimeoutParameters(args.parameters);
19852
- const paused = parseOptionalTimeoutPaused(args.paused);
19853
- if (dueAt !== undefined) {
19854
- patch.dueAt = dueAt;
19855
- }
19856
- if (extendByMs !== undefined) {
19857
- patch.extendByMs = extendByMs;
19858
- }
19859
- if (patch.dueAt !== undefined && patch.extendByMs !== undefined) {
19860
- throw createTimeoutToolArgsError('Timeout update cannot include both `dueAt` and `extendByMs`.');
19861
- }
19862
- if (recurrenceIntervalMs !== undefined) {
19863
- patch.recurrenceIntervalMs = recurrenceIntervalMs;
19864
- }
19865
- if (message !== undefined) {
19866
- patch.message = message;
19867
- }
19868
- if (parameters !== undefined) {
19869
- patch.parameters = parameters;
19870
- }
19871
- if (paused !== undefined) {
19872
- patch.paused = paused;
19873
- }
19874
- return patch;
19875
- }
19876
- /**
19877
- * Determines whether the patch contains fields that are only supported for single-timeout updates.
19878
- *
19879
- * @private internal utility of USE TIMEOUT
19880
- */
19881
- function hasSingleTimeoutOnlyPatchFields(patch) {
19882
- return (patch.dueAt !== undefined ||
19883
- patch.extendByMs !== undefined ||
19884
- patch.recurrenceIntervalMs !== undefined ||
19885
- patch.message !== undefined ||
19886
- patch.parameters !== undefined);
19887
- }
19888
- /**
19889
- * Parses bulk timeout update arguments.
19890
- *
19891
- * @private internal utility of USE TIMEOUT
19892
- */
19893
- function parseBulkTimeoutUpdateArgs(patch) {
19894
- if (patch.paused === undefined) {
19895
- throw createTimeoutToolArgsError('Bulk timeout update with `allActive: true` requires `paused` to be explicitly set.');
19896
- }
19897
- if (hasSingleTimeoutOnlyPatchFields(patch)) {
19898
- throw createTimeoutToolArgsError('Bulk timeout update only supports the `paused` field.');
19899
- }
19900
- return {
19901
- allActive: true,
19902
- paused: patch.paused,
19903
- };
19904
- }
19905
- /**
19906
- * Parses single-timeout update arguments.
19907
- *
19908
- * @private internal utility of USE TIMEOUT
19909
- */
19910
- function parseSingleTimeoutUpdateArgs(timeoutId, patch) {
19911
- if (!timeoutId) {
19912
- throw createTimeoutToolArgsError('Timeout `timeoutId` is required for single-timeout updates.');
19913
- }
19914
- if (Object.keys(patch).length === 0) {
19915
- throw createTimeoutToolArgsError('Timeout update must include at least one editable field.');
19916
- }
19917
- return {
19918
- timeoutId,
19919
- patch,
19920
- };
19921
- }
19922
- /**
19923
- * Parses and validates `USE TIMEOUT` tool arguments.
19924
- *
19925
- * @private internal utility of USE TIMEOUT
19926
- */
19927
- const parseTimeoutToolArgs = {
19928
- /**
19929
- * Parses `set_timeout` input.
19930
- */
19931
- set(args) {
19932
- const parsedMilliseconds = Number(args.milliseconds);
19933
- if (!Number.isFinite(parsedMilliseconds) || parsedMilliseconds <= 0) {
19934
- throw new PipelineExecutionError(spaceTrim$1(`
19935
- Timeout \`milliseconds\` must be a positive number.
19936
- `));
19937
- }
19938
- const message = typeof args.message === 'string' ? args.message.trim() : '';
19939
- return {
19940
- milliseconds: Math.floor(parsedMilliseconds),
19941
- ...(message ? { message } : {}),
19942
- };
19943
- },
19944
- /**
19945
- * Parses `cancel_timeout` input.
19946
- */
19947
- cancel(args) {
19948
- const target = parseTimeoutTargetSelection(args, {
19949
- bothMessage: 'Timeout cancellation must target either one `timeoutId` or `allActive: true`, not both.',
19950
- missingMessage: 'Timeout `timeoutId` is required unless you pass `allActive: true`.',
19951
- });
19952
- if (target.allActive) {
19953
- return { allActive: true };
19954
- }
19955
- return { timeoutId: target.timeoutId };
19956
- },
19957
- /**
19958
- * Parses `list_timeouts` input.
19959
- */
19960
- list(args) {
19961
- if (args.includeFinished !== undefined && typeof args.includeFinished !== 'boolean') {
19962
- throw new PipelineExecutionError(spaceTrim$1(`
19963
- Timeout \`includeFinished\` must be a boolean when provided.
19964
- `));
19965
- }
19966
- const parsedLimit = args.limit === undefined ? DEFAULT_LIST_TIMEOUTS_LIMIT : Math.floor(Number(args.limit));
19967
- if (!Number.isFinite(parsedLimit) || parsedLimit <= 0) {
19968
- throw new PipelineExecutionError(spaceTrim$1(`
19969
- Timeout \`limit\` must be a positive number.
19970
- `));
19971
- }
19972
- if (parsedLimit > MAX_LIST_TIMEOUTS_LIMIT) {
19973
- throw new PipelineExecutionError(spaceTrim$1(`
19974
- Timeout \`limit\` must be at most \`${MAX_LIST_TIMEOUTS_LIMIT}\`.
19975
- `));
19976
- }
19977
- return {
19978
- includeFinished: args.includeFinished === true,
19979
- limit: parsedLimit,
19980
- };
19981
- },
19982
- /**
19983
- * Parses `update_timeout` input.
19984
- */
19985
- update(args) {
19986
- const target = parseTimeoutTargetSelection(args, {
19987
- bothMessage: 'Timeout update must target either one `timeoutId` or `allActive: true`, not both.',
19988
- missingMessage: 'Timeout update requires one `timeoutId` or `allActive: true`.',
19989
- });
19990
- const patch = parseTimeoutUpdatePatch(args);
19991
- return target.allActive
19992
- ? parseBulkTimeoutUpdateArgs(patch)
19993
- : parseSingleTimeoutUpdateArgs(target.timeoutId, patch);
19994
- },
19995
- };
19996
-
19997
- /**
19998
- * Resolves timeout runtime context from hidden tool arguments.
19999
- *
20000
- * @private internal utility of USE TIMEOUT
20001
- */
20002
- function resolveTimeoutRuntimeContext(args) {
20003
- const runtimeContext = readToolRuntimeContextFromToolArgs(args);
20004
- const chatContext = runtimeContext === null || runtimeContext === void 0 ? void 0 : runtimeContext.chat;
20005
- return {
20006
- enabled: Boolean(chatContext === null || chatContext === void 0 ? void 0 : chatContext.chatId),
20007
- chatId: chatContext === null || chatContext === void 0 ? void 0 : chatContext.chatId,
20008
- userId: chatContext === null || chatContext === void 0 ? void 0 : chatContext.userId,
20009
- agentId: chatContext === null || chatContext === void 0 ? void 0 : chatContext.agentId,
20010
- agentName: chatContext === null || chatContext === void 0 ? void 0 : chatContext.agentName,
20011
- promptParameters: normalizePromptParameters$1(chatContext === null || chatContext === void 0 ? void 0 : chatContext.parameters),
20012
- };
20013
- }
20014
- /**
20015
- * Normalizes stored prompt parameters carried by timeout runtime context.
20016
- *
20017
- * @private internal utility of USE TIMEOUT
20018
- */
20019
- function normalizePromptParameters$1(rawParameters) {
20020
- if (!rawParameters || typeof rawParameters !== 'object' || Array.isArray(rawParameters)) {
20021
- return {};
20022
- }
20023
- const normalizedEntries = Object.entries(rawParameters).filter(([, value]) => typeof value === 'string');
20024
- return Object.fromEntries(normalizedEntries);
20025
- }
20026
-
20027
- /**
20028
- * Tool names provided by the `USE TIMEOUT` commitment.
20029
- *
20030
- * @private internal USE TIMEOUT constant
20031
- */
20032
- const TimeoutToolNames = {
20033
- set: 'set_timeout',
20034
- cancel: 'cancel_timeout',
20035
- list: 'list_timeouts',
20036
- update: 'update_timeout',
20037
- };
20038
-
20039
- /**
20040
- * Maximum number of timeout rows rendered into the assistant-visible `list_timeouts` message.
20041
- *
20042
- * @private internal USE TIMEOUT constant
20043
- */
20044
- const MAX_ASSISTANT_VISIBLE_TIMEOUT_ROWS = 20;
20045
- /**
20046
- * Maximum number of timeout ids rendered in bulk-action summaries.
20047
- *
20048
- * @private internal USE TIMEOUT constant
20049
- */
20050
- const MAX_ASSISTANT_VISIBLE_BULK_TIMEOUT_IDS = 10;
20051
- /**
20052
- * Gets `USE TIMEOUT` tool function implementations.
20053
- *
20054
- * @private internal utility of USE TIMEOUT
20055
- */
20056
- function createTimeoutToolFunctions() {
20057
- return {
20058
- async [TimeoutToolNames.set](args) {
20059
- const runtimeContext = resolveTimeoutRuntimeContext(args);
20060
- const { adapter, disabledResult } = getTimeoutToolRuntimeAdapterOrDisabledResult('set', runtimeContext);
20061
- if (!adapter || disabledResult) {
20062
- return JSON.stringify(disabledResult);
20063
- }
20064
- try {
20065
- const parsedArgs = parseTimeoutToolArgs.set(args);
20066
- const scheduledTimeout = await adapter.scheduleTimeout(parsedArgs, runtimeContext);
20067
- const result = {
20068
- action: 'set',
20069
- status: 'set',
20070
- timeoutId: scheduledTimeout.timeoutId,
20071
- dueAt: scheduledTimeout.dueAt,
20072
- };
20073
- return createToolExecutionEnvelope({
20074
- assistantMessage: 'The timer was set.',
20075
- toolResult: result,
20076
- });
20077
- }
20078
- catch (error) {
20079
- const result = {
20080
- action: 'set',
20081
- status: 'error',
20082
- message: error instanceof Error ? error.message : String(error),
20083
- };
20084
- return JSON.stringify(result);
20085
- }
20086
- },
20087
- async [TimeoutToolNames.cancel](args) {
20088
- const runtimeContext = resolveTimeoutRuntimeContext(args);
20089
- const { adapter, disabledResult } = getTimeoutToolRuntimeAdapterOrDisabledResult('cancel', runtimeContext);
20090
- if (!adapter || disabledResult) {
20091
- return JSON.stringify(disabledResult);
20092
- }
20093
- try {
20094
- const parsedArgs = parseTimeoutToolArgs.cancel(args);
20095
- const cancelledTimeout = await adapter.cancelTimeout(parsedArgs, runtimeContext);
20096
- if (cancelledTimeout.status === 'cancelled_all') {
20097
- const result = {
20098
- action: 'cancel',
20099
- status: 'cancelled_all',
20100
- cancelledCount: cancelledTimeout.cancelledCount || 0,
20101
- cancelledTimeoutIds: cancelledTimeout.cancelledTimeoutIds || [],
20102
- hasMore: cancelledTimeout.hasMore,
20103
- };
20104
- return createToolExecutionEnvelope({
20105
- assistantMessage: createBulkCancelAssistantMessage({
20106
- cancelledCount: result.cancelledCount || 0,
20107
- cancelledTimeoutIds: result.cancelledTimeoutIds || [],
20108
- hasMore: result.hasMore,
20109
- }),
20110
- toolResult: result,
20111
- });
20112
- }
20113
- const result = {
20114
- action: 'cancel',
20115
- status: cancelledTimeout.status,
20116
- timeoutId: cancelledTimeout.timeoutId,
20117
- dueAt: cancelledTimeout.dueAt,
20118
- };
20119
- return createToolExecutionEnvelope({
20120
- assistantMessage: cancelledTimeout.status === 'cancelled'
20121
- ? 'The timer was cancelled.'
20122
- : 'The timer was already inactive.',
20123
- toolResult: result,
20124
- });
20125
- }
20126
- catch (error) {
20127
- const result = {
20128
- action: 'cancel',
20129
- status: 'error',
20130
- message: error instanceof Error ? error.message : String(error),
20131
- };
20132
- return JSON.stringify(result);
20133
- }
20134
- },
20135
- async [TimeoutToolNames.list](args) {
20136
- const runtimeContext = resolveTimeoutRuntimeContext(args);
20137
- const { adapter, disabledResult } = getTimeoutToolRuntimeAdapterOrDisabledResult('list', runtimeContext);
20138
- if (!adapter || disabledResult) {
20139
- return JSON.stringify(disabledResult);
20140
- }
20141
- try {
20142
- const parsedArgs = parseTimeoutToolArgs.list(args);
20143
- const listedTimeouts = await adapter.listTimeouts(parsedArgs, runtimeContext);
20144
- const result = {
20145
- action: 'list',
20146
- status: 'listed',
20147
- items: listedTimeouts.items,
20148
- total: listedTimeouts.total,
20149
- };
20150
- return createToolExecutionEnvelope({
20151
- assistantMessage: createListedTimeoutsAssistantMessage({
20152
- total: listedTimeouts.total,
20153
- items: listedTimeouts.items,
20154
- }),
20155
- toolResult: result,
20156
- });
20157
- }
20158
- catch (error) {
20159
- const result = {
20160
- action: 'list',
20161
- status: 'error',
20162
- message: error instanceof Error ? error.message : String(error),
20163
- };
20164
- return JSON.stringify(result);
20165
- }
20166
- },
20167
- async [TimeoutToolNames.update](args) {
20168
- const runtimeContext = resolveTimeoutRuntimeContext(args);
20169
- const { adapter, disabledResult } = getTimeoutToolRuntimeAdapterOrDisabledResult('update', runtimeContext);
20170
- if (!adapter || disabledResult) {
20171
- return JSON.stringify(disabledResult);
20172
- }
20173
- try {
20174
- const parsedArgs = parseTimeoutToolArgs.update(args);
20175
- const updatedTimeout = await adapter.updateTimeout(parsedArgs, runtimeContext);
20176
- if (updatedTimeout.status === 'updated_all') {
20177
- const result = {
20178
- action: 'update',
20179
- status: 'updated_all',
20180
- updatedCount: updatedTimeout.updatedCount,
20181
- matchedCount: updatedTimeout.matchedCount,
20182
- updatedTimeoutIds: updatedTimeout.updatedTimeoutIds,
20183
- hasMore: updatedTimeout.hasMore,
20184
- };
20185
- return createToolExecutionEnvelope({
20186
- assistantMessage: createBulkUpdateAssistantMessage({
20187
- paused: 'allActive' in parsedArgs && parsedArgs.allActive ? parsedArgs.paused : false,
20188
- updatedCount: updatedTimeout.updatedCount,
20189
- matchedCount: updatedTimeout.matchedCount,
20190
- updatedTimeoutIds: updatedTimeout.updatedTimeoutIds,
20191
- hasMore: updatedTimeout.hasMore,
20192
- }),
20193
- toolResult: result,
20194
- });
20195
- }
20196
- if (updatedTimeout.status === 'not_found') {
20197
- const result = {
20198
- action: 'update',
20199
- status: 'not_found',
20200
- timeoutId: updatedTimeout.timeoutId,
20201
- };
20202
- return createToolExecutionEnvelope({
20203
- assistantMessage: 'The timeout was not found.',
20204
- toolResult: result,
20205
- });
20206
- }
20207
- if (updatedTimeout.status === 'conflict') {
20208
- const conflictMessage = updatedTimeout.reason === 'running'
20209
- ? 'Running timeout cannot be edited.'
20210
- : 'Finished timeout cannot be edited.';
20211
- const result = {
20212
- action: 'update',
20213
- status: 'conflict',
20214
- timeoutId: updatedTimeout.timeoutId,
20215
- message: conflictMessage,
20216
- };
20217
- return createToolExecutionEnvelope({
20218
- assistantMessage: conflictMessage,
20219
- toolResult: result,
20220
- });
20221
- }
20222
- const result = {
20223
- action: 'update',
20224
- status: 'updated',
20225
- timeoutId: updatedTimeout.timeout.timeoutId,
20226
- dueAt: updatedTimeout.timeout.dueAt,
20227
- paused: updatedTimeout.timeout.paused,
20228
- recurrenceIntervalMs: updatedTimeout.timeout.recurrenceIntervalMs,
20229
- };
20230
- return createToolExecutionEnvelope({
20231
- assistantMessage: `Updated timeout ${JSON.stringify(updatedTimeout.timeout.timeoutId)}.`,
20232
- toolResult: result,
20233
- });
20234
- }
20235
- catch (error) {
20236
- const result = {
20237
- action: 'update',
20238
- status: 'error',
20239
- message: error instanceof Error ? error.message : String(error),
20240
- };
20241
- return JSON.stringify(result);
20242
- }
20243
- },
20244
- };
20245
- }
20246
- /**
20247
- * Creates assistant-visible summary for one `list_timeouts` response.
20248
- *
20249
- * @private internal utility of USE TIMEOUT
20250
- */
20251
- function createListedTimeoutsAssistantMessage(options) {
20252
- if (options.total <= 0 || options.items.length === 0) {
20253
- return 'Found 0 timeouts.';
20254
- }
20255
- const visibleItems = options.items.slice(0, MAX_ASSISTANT_VISIBLE_TIMEOUT_ROWS);
20256
- const summaryRows = visibleItems.map((item, index) => `${index + 1}. ${formatTimeoutListRow(item)}`);
20257
- const hiddenCount = Math.max(0, options.total - visibleItems.length);
20258
- if (hiddenCount > 0) {
20259
- summaryRows.push(`...and ${hiddenCount} more.`);
20260
- }
20261
- return spaceTrim$1((block) => `
20262
- Found ${options.total} ${options.total === 1 ? 'timeout' : 'timeouts'}:
20263
- ${block(summaryRows.join('\n'))}
20264
- `);
20265
- }
20266
- /**
20267
- * Formats one timeout row for assistant-visible timeout listings.
20268
- *
20269
- * @private internal utility of USE TIMEOUT
20270
- */
20271
- function formatTimeoutListRow(item) {
20272
- const normalizedMessage = typeof item.message === 'string' ? item.message.trim() : '';
20273
- const messageSuffix = normalizedMessage ? ` | message ${JSON.stringify(normalizedMessage)}` : '';
20274
- const recurrenceSuffix = typeof item.recurrenceIntervalMs === 'number' && item.recurrenceIntervalMs > 0
20275
- ? ` | recurrence ${item.recurrenceIntervalMs}ms`
20276
- : '';
20277
- const pausedSuffix = item.paused ? ' (paused)' : '';
20278
- return `${item.timeoutId} | ${item.status}${pausedSuffix} | chat ${item.chatId} | due ${item.dueAt}${recurrenceSuffix}${messageSuffix}`;
20279
- }
20280
- /**
20281
- * Creates assistant-visible summary for bulk timeout cancellation.
20282
- *
20283
- * @private internal utility of USE TIMEOUT
20284
- */
20285
- function createBulkCancelAssistantMessage(options) {
20286
- if (options.cancelledCount <= 0) {
20287
- return 'No active timeouts were found to cancel.';
20288
- }
20289
- const visibleTimeoutIds = options.cancelledTimeoutIds.slice(0, MAX_ASSISTANT_VISIBLE_BULK_TIMEOUT_IDS);
20290
- const hiddenIdsCount = Math.max(0, options.cancelledTimeoutIds.length - visibleTimeoutIds.length);
20291
- const hasMoreSuffix = options.hasMore ? ' Additional active timeouts may still exist.' : '';
20292
- const idsSuffix = visibleTimeoutIds.length > 0
20293
- ? ` Cancelled ids: ${visibleTimeoutIds.join(', ')}${hiddenIdsCount > 0 ? `, and ${hiddenIdsCount} more.` : '.'}`
20294
- : '';
20295
- return `Cancelled ${options.cancelledCount} active ${options.cancelledCount === 1 ? 'timeout' : 'timeouts'}.${idsSuffix}${hasMoreSuffix}`;
20296
- }
20297
- /**
20298
- * Creates assistant-visible summary for bulk timeout pause/resume updates.
20299
- *
20300
- * @private internal utility of USE TIMEOUT
20301
- */
20302
- function createBulkUpdateAssistantMessage(options) {
20303
- if (options.matchedCount <= 0) {
20304
- return options.paused
20305
- ? 'No active queued timeouts were found to pause.'
20306
- : 'No paused queued timeouts were found to resume.';
20307
- }
20308
- const verb = options.paused ? 'Paused' : 'Resumed';
20309
- const visibleTimeoutIds = options.updatedTimeoutIds.slice(0, MAX_ASSISTANT_VISIBLE_BULK_TIMEOUT_IDS);
20310
- const hiddenIdsCount = Math.max(0, options.updatedTimeoutIds.length - visibleTimeoutIds.length);
20311
- const skippedCount = Math.max(0, options.matchedCount - options.updatedCount);
20312
- const idsSuffix = visibleTimeoutIds.length > 0
20313
- ? ` Updated ids: ${visibleTimeoutIds.join(', ')}${hiddenIdsCount > 0 ? `, and ${hiddenIdsCount} more.` : '.'}`
20314
- : '';
20315
- const skippedSuffix = skippedCount > 0 ? ` Skipped ${skippedCount} due to concurrent changes.` : '';
20316
- const hasMoreSuffix = options.hasMore ? ' Additional matching timeouts may still exist.' : '';
20317
- return `${verb} ${options.updatedCount} ${options.updatedCount === 1 ? 'timeout' : 'timeouts'}.${idsSuffix}${skippedSuffix}${hasMoreSuffix}`;
20318
- }
20319
-
20320
- /**
20321
- * Adds `USE TIMEOUT` tool definitions while preserving already registered tools.
20322
- *
20323
- * @private internal utility of USE TIMEOUT
20324
- */
20325
- function createTimeoutTools(existingTools = []) {
20326
- const tools = [...existingTools];
20327
- if (!tools.some((tool) => tool.name === TimeoutToolNames.set)) {
20328
- tools.push({
20329
- name: TimeoutToolNames.set,
20330
- description: 'Schedule one thread-scoped wake-up in the current chat. The timer returns immediately and wakes this same conversation later.',
20331
- parameters: {
20332
- type: 'object',
20333
- properties: {
20334
- milliseconds: {
20335
- type: 'number',
20336
- description: 'Delay in milliseconds before the timeout wakes the same chat thread.',
20337
- },
20338
- message: {
20339
- type: 'string',
20340
- description: 'Optional note appended to the future timeout wake-up message.',
20341
- },
20342
- },
20343
- required: ['milliseconds'],
20344
- },
20345
- });
20346
- }
20347
- if (!tools.some((tool) => tool.name === TimeoutToolNames.cancel)) {
20348
- tools.push({
20349
- name: TimeoutToolNames.cancel,
20350
- description: 'Cancel one timeout by id or cancel all active timeouts across chats for the same user+agent scope.',
20351
- parameters: {
20352
- type: 'object',
20353
- properties: {
20354
- timeoutId: {
20355
- type: 'string',
20356
- description: 'Identifier returned earlier by `set_timeout` or `list_timeouts`.',
20357
- },
20358
- allActive: {
20359
- type: 'boolean',
20360
- description: 'When true, cancel all currently active timeouts across chats in this user+agent scope.',
20361
- },
20362
- },
20363
- },
20364
- });
20365
- }
20366
- if (!tools.some((tool) => tool.name === TimeoutToolNames.list)) {
20367
- tools.push({
20368
- name: TimeoutToolNames.list,
20369
- description: 'List timeout details across all chats for this same user+agent scope so they can be reviewed and managed.',
20370
- parameters: {
20371
- type: 'object',
20372
- properties: {
20373
- includeFinished: {
20374
- type: 'boolean',
20375
- description: 'When true, include completed, failed, and cancelled rows in addition to active timeouts.',
20376
- },
20377
- limit: {
20378
- type: 'number',
20379
- description: 'Maximum number of rows to return (default 20, max 100).',
20380
- },
20381
- },
20382
- },
20383
- });
20384
- }
20385
- if (!tools.some((tool) => tool.name === TimeoutToolNames.update)) {
20386
- tools.push({
20387
- name: TimeoutToolNames.update,
20388
- description: 'Update one timeout (pause/resume, next run, recurrence, payload) or pause/resume all active queued timeouts across chats.',
20389
- parameters: {
20390
- type: 'object',
20391
- properties: {
20392
- timeoutId: {
20393
- type: 'string',
20394
- description: 'Identifier returned earlier by `set_timeout` or `list_timeouts` for one timeout update.',
20395
- },
20396
- allActive: {
20397
- type: 'boolean',
20398
- description: 'When true, run one bulk pause/resume across all active queued timeouts in this same user+agent scope.',
20399
- },
20400
- paused: {
20401
- type: 'boolean',
20402
- description: 'Pause (`true`) or resume (`false`) one timeout; with `allActive: true` this pauses/resumes all active queued timeouts.',
20403
- },
20404
- dueAt: {
20405
- type: 'string',
20406
- description: 'Set the next run timestamp (ISO string). Cannot be used with `extendByMs`.',
20407
- },
20408
- extendByMs: {
20409
- type: 'number',
20410
- description: 'Move next run by this many milliseconds. Cannot be used with `dueAt`.',
20411
- },
20412
- recurrenceIntervalMs: {
20413
- type: 'number',
20414
- description: 'Set recurrence interval in milliseconds; pass `null` to disable recurrence.',
20415
- },
20416
- message: {
20417
- type: 'string',
20418
- description: 'Set wake-up message text for this timeout; pass empty string to clear.',
20419
- },
20420
- parameters: {
20421
- type: 'object',
20422
- description: 'Replace stored JSON parameters passed back when timeout fires.',
20423
- },
20424
- },
20425
- },
20426
- });
20427
- }
20428
- return tools;
20429
- }
20430
-
20431
- /**
20432
- * `USE TIMEOUT` commitment definition.
20433
- *
20434
- * The `USE TIMEOUT` commitment enables timeout wake-ups and scoped timeout management.
20435
- *
20436
- * @private [🪔] Maybe export the commitments through some package
20437
- */
20438
- class UseTimeoutCommitmentDefinition extends BaseCommitmentDefinition {
20439
- constructor() {
20440
- super('USE TIMEOUT');
20441
- }
20442
- get requiresContent() {
20443
- return false;
20444
- }
20445
- /**
20446
- * Short one-line description of `USE TIMEOUT`.
20447
- */
20448
- get description() {
20449
- return 'Enable timeout wake-ups plus scoped timeout listing, updates, and cancellation across chats.';
20450
- }
20451
- /**
20452
- * Icon for this commitment.
20453
- */
20454
- get icon() {
20455
- return '⏱️';
20456
- }
20457
- /**
20458
- * Markdown documentation for `USE TIMEOUT`.
20459
- */
20460
- get documentation() {
20461
- return spaceTrim$1(`
20462
- # USE TIMEOUT
20463
-
20464
- Enables timeout wake-ups and timeout management for the same user+agent scope.
20465
-
20466
- ## Key aspects
20467
-
20468
- - The agent uses \`set_timeout\` to schedule a future wake-up in the same chat thread.
20469
- - The tool returns immediately while the timeout is stored and executed by the runtime later.
20470
- - The wake-up arrives as a new user-like timeout message in the same conversation.
20471
- - The agent can inspect known timeout details via \`list_timeouts\`.
20472
- - The agent can cancel one timeout by \`timeoutId\` or cancel all active timeouts via \`cancel_timeout\`.
20473
- - The agent can pause/resume and edit timeout details via \`update_timeout\`.
20474
- - Commitment content is treated as optional timeout policy instructions.
20475
-
20476
- ## Examples
20477
-
20478
- \`\`\`book
20479
- Follow-up Agent
20480
- USE TIMEOUT Remind yourself only when follow-up work is explicitly requested.
20481
- \`\`\`
20482
- `);
20483
- }
20484
- applyToAgentModelRequirements(requirements, content) {
20485
- const extraInstructions = formatOptionalInstructionBlock('Timeout instructions', content);
20486
- return this.appendToSystemMessage({
20487
- ...requirements,
20488
- tools: createTimeoutTools(requirements.tools || []),
20489
- _metadata: {
20490
- ...requirements._metadata,
20491
- useTimeout: content || true,
20492
- },
20493
- }, createTimeoutSystemMessage(extraInstructions));
20494
- }
20495
- /**
20496
- * Gets human-readable titles for tool functions provided by this commitment.
20497
- */
20498
- getToolTitles() {
20499
- return {
20500
- [TimeoutToolNames.set]: 'Set timer',
20501
- [TimeoutToolNames.cancel]: 'Cancel timer',
20502
- [TimeoutToolNames.list]: 'List timers',
20503
- [TimeoutToolNames.update]: 'Update timer',
20504
- };
20505
- }
20506
- /**
20507
- * Gets `USE TIMEOUT` tool function implementations.
20508
- */
20509
- getToolFunctions() {
20510
- return createTimeoutToolFunctions();
20511
- }
20512
- }
20513
- // Note: [💞] Ignore a discrepancy between file name and entity name
20514
-
20515
- /**
20516
- * USE TIME commitment definition
20517
- *
20518
- * The `USE TIME` commitment indicates that the agent should be able to determine the current date and time.
20519
- *
20520
- * Example usage in agent source:
20521
- *
20522
- * ```book
20523
- * USE TIME
20524
- * USE TIME Prefer the user's local timezone.
20525
- * ```
20526
- *
20527
- * @private [🪔] Maybe export the commitments through some package
20528
- */
20529
- class UseTimeCommitmentDefinition extends BaseCommitmentDefinition {
20530
- constructor() {
20531
- super('USE TIME', ['CURRENT TIME', 'TIME', 'DATE']);
20532
- }
20533
- get requiresContent() {
20534
- return false;
20535
- }
20536
- /**
20537
- * Short one-line description of USE TIME.
20538
- */
20539
- get description() {
20540
- return 'Enable the agent to determine the current date and time.';
20541
- }
20542
- /**
20543
- * Icon for this commitment.
20544
- */
20545
- get icon() {
20546
- return '🕒';
20547
- }
20548
- /**
20549
- * Markdown documentation for USE TIME commitment.
20550
- */
20551
- get documentation() {
20552
- return spaceTrim$1(`
20553
- # USE TIME
20554
-
20555
- Enables the agent to determine the current date and time.
20556
-
20557
- ## Key aspects
20558
-
20559
- - This tool won't receive any input.
20560
- - It outputs the current date and time as an ISO 8601 string.
20561
- - Allows the agent to answer questions about the current time or date.
20562
- - The content following \`USE TIME\` is an arbitrary text that the agent should know (e.g. timezone preference).
20563
-
20564
- ## Examples
20565
-
20566
- \`\`\`book
20567
- Time-aware Assistant
20568
-
20569
- PERSONA You are a helpful assistant who knows the current time.
20570
- USE TIME
20571
- \`\`\`
20572
-
20573
- \`\`\`book
20574
- Travel Assistant
20575
-
20576
- PERSONA You help travelers with planning.
20577
- USE TIME Prefer the user's local timezone.
20578
- \`\`\`
20579
- `);
20580
- }
20581
- applyToAgentModelRequirements(requirements, content) {
20582
- // Get existing tools array or create new one
20583
- const existingTools = requirements.tools || [];
20584
- // Add 'get_current_time' to tools if not already present
20585
- const updatedTools = existingTools.some((tool) => tool.name === 'get_current_time')
20586
- ? existingTools
20587
- : [
20588
- ...existingTools,
20589
- {
20590
- name: 'get_current_time',
20591
- description: 'Get the current date and time in ISO 8601 format.',
20592
- parameters: {
20593
- type: 'object',
20594
- properties: {
20595
- timezone: {
20596
- type: 'string',
20597
- description: 'Optional timezone name (e.g. "Europe/Prague", "UTC", "America/New_York").',
20598
- },
20599
- },
20600
- required: [],
20601
- },
20602
- },
20603
- // <- TODO: !!!! define the function in LLM tools
20604
- ];
20605
- return appendAggregatedUseCommitmentPlaceholder({
20606
- ...requirements,
20607
- tools: updatedTools,
20608
- _metadata: {
20609
- ...requirements._metadata,
20610
- },
20611
- }, this.type);
20612
- }
20613
- /**
20614
- * Gets human-readable titles for tool functions provided by this commitment.
20615
- */
20616
- getToolTitles() {
20617
- return {
20618
- get_current_time: 'Get current time',
20619
- };
20620
- }
20621
- /**
20622
- * Gets the `get_current_time` tool function implementation.
20623
- */
20624
- getToolFunctions() {
20625
- return {
20626
- async get_current_time(args) {
20627
- var _a;
20628
- console.log('!!!! [Tool] get_current_time called', { args });
20629
- const { timezone } = args;
20630
- if (!timezone) {
20631
- return new Date().toISOString();
20632
- }
20633
- try {
20634
- // Note: Returning ISO 8601 string but in the requested timezone
20635
- const formatter = new Intl.DateTimeFormat('en-CA', {
20636
- timeZone: timezone,
20637
- year: 'numeric',
20638
- month: '2-digit',
20639
- day: '2-digit',
20640
- hour: '2-digit',
20641
- minute: '2-digit',
20642
- second: '2-digit',
20643
- hour12: false,
20644
- timeZoneName: 'shortOffset',
20645
- });
20646
- const parts = formatter.formatToParts(new Date());
20647
- const part = (type) => { var _a; return (_a = parts.find((p) => p.type === type)) === null || _a === void 0 ? void 0 : _a.value; };
20648
- // en-CA format is YYYY-MM-DD
20649
- const isoString = `${part('year')}-${part('month')}-${part('day')}T${part('hour')}:${part('minute')}:${part('second')}${(_a = part('timeZoneName')) === null || _a === void 0 ? void 0 : _a.replace('GMT', '')}`;
20650
- return isoString;
20651
- }
20652
- catch (error) {
20653
- // Fallback to UTC if timezone is invalid
20654
- return new Date().toISOString();
20655
- }
20656
- },
20657
- };
20658
- }
20659
- }
20660
- // Note: [💞] Ignore a discrepancy between file name and entity name
20661
-
20662
17723
  /**
20663
17724
  * Tool name used by the USE USER LOCATION commitment.
20664
17725
  *
@@ -20873,580 +17934,6 @@ class UseUserLocationCommitmentDefinition extends BaseCommitmentDefinition {
20873
17934
  }
20874
17935
  // Note: [💞] Ignore a discrepancy between file name and entity name
20875
17936
 
20876
- /**
20877
- * Names of tools used by the WALLET commitment.
20878
- *
20879
- * @private constant of WalletCommitmentDefinition
20880
- */
20881
- const WalletToolNames = {
20882
- retrieve: 'retrieve_wallet_records',
20883
- store: 'store_wallet_record',
20884
- update: 'update_wallet_record',
20885
- delete: 'delete_wallet_record',
20886
- request: 'request_wallet_record',
20887
- };
20888
-
20889
- /**
20890
- * Creates WALLET system-message instructions.
20891
- *
20892
- * @private function of WalletCommitmentDefinition
20893
- */
20894
- function createWalletSystemMessage(extraInstructions) {
20895
- return spaceTrim$1((block) => `
20896
- Wallet:
20897
- - Use "${WalletToolNames.retrieve}" before authenticated operations.
20898
- - Use "${WalletToolNames.store}" and "${WalletToolNames.update}" to maintain credentials.
20899
- - Use "${WalletToolNames.delete}" to remove invalid credentials.
20900
- - Use "${WalletToolNames.request}" to request missing credentials via UI popup.
20901
- - Scope records by user (\`isUserScoped\`) and/or by agent (\`isGlobal=false\`) as needed.
20902
- - Never expose raw credentials in chat responses.
20903
- ${block(extraInstructions)}
20904
- `);
20905
- }
20906
-
20907
- /**
20908
- * Resolves disabled message for wallet runtime context.
20909
- *
20910
- * @private function of WalletCommitmentDefinition
20911
- */
20912
- function resolveWalletDisabledMessage(runtimeContext) {
20913
- if (runtimeContext.isPrivateMode) {
20914
- return 'Wallet is disabled because private mode is active.';
20915
- }
20916
- if (runtimeContext.isTeamConversation) {
20917
- return 'Wallet is disabled for TEAM conversations.';
20918
- }
20919
- if (!runtimeContext.enabled) {
20920
- return 'Wallet is disabled for unauthenticated users.';
20921
- }
20922
- return null;
20923
- }
20924
- /**
20925
- * Resolves runtime adapter for wallet tools or returns disabled payload when unavailable.
20926
- *
20927
- * @private function of WalletCommitmentDefinition
20928
- */
20929
- function getWalletToolRuntimeAdapterOrDisabledResult(action, runtimeContext) {
20930
- const disabledMessage = resolveWalletDisabledMessage(runtimeContext);
20931
- if (disabledMessage) {
20932
- return {
20933
- adapter: null,
20934
- disabledResult: {
20935
- action,
20936
- status: 'disabled',
20937
- records: action === 'retrieve' ? [] : undefined,
20938
- message: disabledMessage,
20939
- },
20940
- };
20941
- }
20942
- {
20943
- return {
20944
- adapter: null,
20945
- disabledResult: {
20946
- action,
20947
- status: 'disabled',
20948
- records: action === 'retrieve' ? [] : undefined,
20949
- message: 'Wallet runtime is not available in this environment.',
20950
- },
20951
- };
20952
- }
20953
- }
20954
-
20955
- /**
20956
- * Parses store/update wallet payload.
20957
- *
20958
- * @private function of WalletCommitmentDefinition
20959
- */
20960
- function parseWalletPayload(args) {
20961
- const recordType = parseWalletRecordType(args.recordType);
20962
- return {
20963
- recordType,
20964
- service: parseWalletService(args.service),
20965
- key: parseWalletKey(args.key),
20966
- isUserScoped: args.isUserScoped === true,
20967
- isGlobal: args.isGlobal === true,
20968
- ...parseWalletSecrets({
20969
- recordType,
20970
- username: args.username,
20971
- password: args.password,
20972
- secret: args.secret,
20973
- cookies: args.cookies,
20974
- }),
20975
- };
20976
- }
20977
- /**
20978
- * Parses text argument and returns trimmed text when available.
20979
- *
20980
- * @private function of WalletCommitmentDefinition
20981
- */
20982
- function normalizeOptionalText(value) {
20983
- if (typeof value !== 'string') {
20984
- return undefined;
20985
- }
20986
- const trimmed = value.trim();
20987
- return trimmed || undefined;
20988
- }
20989
- /**
20990
- * Parses wallet service argument.
20991
- *
20992
- * @private function of WalletCommitmentDefinition
20993
- */
20994
- function parseWalletService(value) {
20995
- return (normalizeOptionalText(value) || 'generic').toLowerCase();
20996
- }
20997
- /**
20998
- * Parses wallet key argument.
20999
- *
21000
- * @private function of WalletCommitmentDefinition
21001
- */
21002
- function parseWalletKey(value) {
21003
- return normalizeOptionalText(value) || 'default';
21004
- }
21005
- /**
21006
- * Parses one wallet record id argument.
21007
- *
21008
- * @private function of WalletCommitmentDefinition
21009
- */
21010
- function parseWalletId(value) {
21011
- const walletId = normalizeOptionalText(value);
21012
- if (!walletId) {
21013
- throw new Error('Wallet id is required.');
21014
- }
21015
- return walletId;
21016
- }
21017
- /**
21018
- * Parses wallet record type.
21019
- *
21020
- * @private function of WalletCommitmentDefinition
21021
- */
21022
- function parseWalletRecordType(value, fallback) {
21023
- var _a;
21024
- const normalizedType = (_a = normalizeOptionalText(value)) === null || _a === void 0 ? void 0 : _a.toUpperCase();
21025
- if (normalizedType === 'USERNAME_PASSWORD') {
21026
- return 'USERNAME_PASSWORD';
21027
- }
21028
- if (normalizedType === 'SESSION_COOKIE') {
21029
- return 'SESSION_COOKIE';
21030
- }
21031
- if (normalizedType === 'ACCESS_TOKEN') {
21032
- return 'ACCESS_TOKEN';
21033
- }
21034
- if (fallback) {
21035
- return fallback;
21036
- }
21037
- throw new Error('Unsupported wallet recordType. Expected one of: USERNAME_PASSWORD, SESSION_COOKIE, ACCESS_TOKEN.');
21038
- }
21039
- /**
21040
- * Parses wallet secret fields according to record type.
21041
- *
21042
- * @private function of WalletCommitmentDefinition
21043
- */
21044
- function parseWalletSecrets(args) {
21045
- const username = normalizeOptionalText(args.username);
21046
- const password = normalizeOptionalText(args.password);
21047
- const secret = normalizeOptionalText(args.secret);
21048
- const cookies = normalizeOptionalText(args.cookies);
21049
- if (args.recordType === 'USERNAME_PASSWORD') {
21050
- if (!username || !password) {
21051
- throw new Error('Both username and password are required for USERNAME_PASSWORD.');
21052
- }
21053
- return { username, password };
21054
- }
21055
- if (args.recordType === 'SESSION_COOKIE') {
21056
- if (!cookies) {
21057
- throw new Error('Cookies are required for SESSION_COOKIE.');
21058
- }
21059
- return { cookies };
21060
- }
21061
- if (!secret) {
21062
- throw new Error('Secret is required for ACCESS_TOKEN.');
21063
- }
21064
- return { secret };
21065
- }
21066
- /**
21067
- * Collection of WALLET tool argument parsers.
21068
- *
21069
- * @private function of WalletCommitmentDefinition
21070
- */
21071
- const parseWalletToolArgs = {
21072
- /**
21073
- * Parses retrieve arguments.
21074
- */
21075
- retrieve(args) {
21076
- const limit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.floor(args.limit) : undefined;
21077
- return {
21078
- query: normalizeOptionalText(args.query),
21079
- recordType: normalizeOptionalText(args.recordType) ? parseWalletRecordType(args.recordType) : undefined,
21080
- service: normalizeOptionalText(args.service) ? parseWalletService(args.service) : undefined,
21081
- key: normalizeOptionalText(args.key) ? parseWalletKey(args.key) : undefined,
21082
- limit: limit && limit > 0 ? Math.min(limit, 20) : undefined,
21083
- };
21084
- },
21085
- /**
21086
- * Parses store payload.
21087
- */
21088
- store(args) {
21089
- return parseWalletPayload(args);
21090
- },
21091
- /**
21092
- * Parses update payload.
21093
- */
21094
- update(args) {
21095
- const walletId = parseWalletId(args.walletId);
21096
- const record = parseWalletPayload(args);
21097
- return {
21098
- ...record,
21099
- walletId,
21100
- };
21101
- },
21102
- /**
21103
- * Parses delete payload.
21104
- */
21105
- delete(args) {
21106
- return { walletId: parseWalletId(args.walletId) };
21107
- },
21108
- /**
21109
- * Parses request payload for user wallet input prompt.
21110
- */
21111
- request(args) {
21112
- return {
21113
- recordType: parseWalletRecordType(args.recordType, 'ACCESS_TOKEN'),
21114
- service: parseWalletService(args.service),
21115
- key: parseWalletKey(args.key),
21116
- message: normalizeOptionalText(args.message),
21117
- isUserScoped: args.isUserScoped === true,
21118
- isGlobal: args.isGlobal === true,
21119
- };
21120
- },
21121
- };
21122
-
21123
- /**
21124
- * Resolves runtime context from hidden tool arguments.
21125
- *
21126
- * @private function of WalletCommitmentDefinition
21127
- */
21128
- function resolveWalletRuntimeContext(args) {
21129
- const runtimeContext = readToolRuntimeContextFromToolArgs(args);
21130
- const memoryContext = runtimeContext === null || runtimeContext === void 0 ? void 0 : runtimeContext.memory;
21131
- return {
21132
- enabled: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.enabled) === true,
21133
- userId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.userId,
21134
- username: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.username,
21135
- agentId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentId,
21136
- agentName: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentName,
21137
- isTeamConversation: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.isTeamConversation) === true,
21138
- isPrivateMode: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.isPrivateMode) === true,
21139
- };
21140
- }
21141
-
21142
- /**
21143
- * Creates runtime wallet tool function implementations.
21144
- *
21145
- * @private function of WalletCommitmentDefinition
21146
- */
21147
- function createWalletToolFunctions() {
21148
- return {
21149
- async [WalletToolNames.retrieve](args) {
21150
- const runtimeContext = resolveWalletRuntimeContext(args);
21151
- const { adapter, disabledResult } = getWalletToolRuntimeAdapterOrDisabledResult('retrieve', runtimeContext);
21152
- if (!adapter || disabledResult) {
21153
- return JSON.stringify(disabledResult);
21154
- }
21155
- try {
21156
- const parsedArgs = parseWalletToolArgs.retrieve(args);
21157
- const records = await adapter.retrieveWalletRecords(parsedArgs, runtimeContext);
21158
- return JSON.stringify({
21159
- action: 'retrieve',
21160
- status: 'ok',
21161
- query: parsedArgs.query,
21162
- records,
21163
- });
21164
- }
21165
- catch (error) {
21166
- return JSON.stringify({
21167
- action: 'retrieve',
21168
- status: 'error',
21169
- records: [],
21170
- message: error instanceof Error ? error.message : String(error),
21171
- });
21172
- }
21173
- },
21174
- async [WalletToolNames.store](args) {
21175
- const runtimeContext = resolveWalletRuntimeContext(args);
21176
- const { adapter, disabledResult } = getWalletToolRuntimeAdapterOrDisabledResult('store', runtimeContext);
21177
- if (!adapter || disabledResult) {
21178
- return JSON.stringify(disabledResult);
21179
- }
21180
- try {
21181
- const parsedArgs = parseWalletToolArgs.store(args);
21182
- const record = await adapter.storeWalletRecord(parsedArgs, runtimeContext);
21183
- return JSON.stringify({
21184
- action: 'store',
21185
- status: 'stored',
21186
- record,
21187
- });
21188
- }
21189
- catch (error) {
21190
- return JSON.stringify({
21191
- action: 'store',
21192
- status: 'error',
21193
- message: error instanceof Error ? error.message : String(error),
21194
- });
21195
- }
21196
- },
21197
- async [WalletToolNames.update](args) {
21198
- const runtimeContext = resolveWalletRuntimeContext(args);
21199
- const { adapter, disabledResult } = getWalletToolRuntimeAdapterOrDisabledResult('update', runtimeContext);
21200
- if (!adapter || disabledResult) {
21201
- return JSON.stringify(disabledResult);
21202
- }
21203
- try {
21204
- const parsedArgs = parseWalletToolArgs.update(args);
21205
- const record = await adapter.updateWalletRecord(parsedArgs, runtimeContext);
21206
- return JSON.stringify({
21207
- action: 'update',
21208
- status: 'updated',
21209
- record,
21210
- });
21211
- }
21212
- catch (error) {
21213
- return JSON.stringify({
21214
- action: 'update',
21215
- status: 'error',
21216
- message: error instanceof Error ? error.message : String(error),
21217
- });
21218
- }
21219
- },
21220
- async [WalletToolNames.delete](args) {
21221
- const runtimeContext = resolveWalletRuntimeContext(args);
21222
- const { adapter, disabledResult } = getWalletToolRuntimeAdapterOrDisabledResult('delete', runtimeContext);
21223
- if (!adapter || disabledResult) {
21224
- return JSON.stringify(disabledResult);
21225
- }
21226
- try {
21227
- const parsedArgs = parseWalletToolArgs.delete(args);
21228
- const deleted = await adapter.deleteWalletRecord(parsedArgs, runtimeContext);
21229
- return JSON.stringify({
21230
- action: 'delete',
21231
- status: 'deleted',
21232
- walletId: deleted.id,
21233
- });
21234
- }
21235
- catch (error) {
21236
- return JSON.stringify({
21237
- action: 'delete',
21238
- status: 'error',
21239
- message: error instanceof Error ? error.message : String(error),
21240
- });
21241
- }
21242
- },
21243
- async [WalletToolNames.request](args) {
21244
- const runtimeContext = resolveWalletRuntimeContext(args);
21245
- const disabledMessage = resolveWalletDisabledMessage(runtimeContext);
21246
- if (disabledMessage) {
21247
- return JSON.stringify({
21248
- action: 'request',
21249
- status: 'disabled',
21250
- message: disabledMessage,
21251
- });
21252
- }
21253
- const request = parseWalletToolArgs.request(args);
21254
- return JSON.stringify({
21255
- action: 'request',
21256
- status: 'requested',
21257
- request,
21258
- message: request.message ||
21259
- `Request user to provide ${request.recordType} credentials for service "${request.service}".`,
21260
- });
21261
- },
21262
- };
21263
- }
21264
-
21265
- /**
21266
- * Creates tool definitions required by WALLET commitment.
21267
- *
21268
- * @private function of WalletCommitmentDefinition
21269
- */
21270
- function createWalletTools(existingTools) {
21271
- const tools = [...(existingTools || [])];
21272
- addWalletToolIfMissing(tools, {
21273
- name: WalletToolNames.retrieve,
21274
- description: 'Retrieve wallet records relevant to the current task.',
21275
- parameters: {
21276
- type: 'object',
21277
- properties: {
21278
- query: { type: 'string', description: 'Optional text query used to filter wallet records.' },
21279
- recordType: {
21280
- type: 'string',
21281
- description: 'Optional record type filter (USERNAME_PASSWORD, SESSION_COOKIE, ACCESS_TOKEN).',
21282
- },
21283
- service: { type: 'string', description: 'Optional service filter, for example github.' },
21284
- key: { type: 'string', description: 'Optional wallet key filter.' },
21285
- limit: { type: 'integer', description: 'Optional maximum number of records (default 5, max 20).' },
21286
- },
21287
- required: [],
21288
- },
21289
- });
21290
- addWalletToolIfMissing(tools, {
21291
- name: WalletToolNames.store,
21292
- description: 'Store one wallet record.',
21293
- parameters: {
21294
- type: 'object',
21295
- properties: {
21296
- recordType: {
21297
- type: 'string',
21298
- description: 'Record type: USERNAME_PASSWORD, SESSION_COOKIE, ACCESS_TOKEN.',
21299
- },
21300
- service: { type: 'string', description: 'Service identifier, for example github.' },
21301
- key: { type: 'string', description: 'Logical credential key.' },
21302
- username: { type: 'string', description: 'Username for USERNAME_PASSWORD.' },
21303
- password: { type: 'string', description: 'Password for USERNAME_PASSWORD.' },
21304
- secret: { type: 'string', description: 'Token/API key for ACCESS_TOKEN.' },
21305
- cookies: { type: 'string', description: 'Cookie header/json for SESSION_COOKIE.' },
21306
- isUserScoped: { type: 'boolean', description: 'Set true to scope this record to current user.' },
21307
- isGlobal: { type: 'boolean', description: 'Set true to make this record global.' },
21308
- },
21309
- required: ['recordType', 'service'],
21310
- },
21311
- });
21312
- addWalletToolIfMissing(tools, {
21313
- name: WalletToolNames.update,
21314
- description: 'Update one existing wallet record.',
21315
- parameters: {
21316
- type: 'object',
21317
- properties: {
21318
- walletId: { type: 'string', description: 'Wallet record id to update.' },
21319
- recordType: {
21320
- type: 'string',
21321
- description: 'Record type: USERNAME_PASSWORD, SESSION_COOKIE, ACCESS_TOKEN.',
21322
- },
21323
- service: { type: 'string', description: 'Service identifier, for example github.' },
21324
- key: { type: 'string', description: 'Logical credential key.' },
21325
- username: { type: 'string', description: 'Username for USERNAME_PASSWORD.' },
21326
- password: { type: 'string', description: 'Password for USERNAME_PASSWORD.' },
21327
- secret: { type: 'string', description: 'Token/API key for ACCESS_TOKEN.' },
21328
- cookies: { type: 'string', description: 'Cookie header/json for SESSION_COOKIE.' },
21329
- isUserScoped: { type: 'boolean', description: 'Set true to scope this record to current user.' },
21330
- isGlobal: { type: 'boolean', description: 'Set true to make this record global.' },
21331
- },
21332
- required: ['walletId', 'recordType', 'service'],
21333
- },
21334
- });
21335
- addWalletToolIfMissing(tools, {
21336
- name: WalletToolNames.delete,
21337
- description: 'Delete one wallet record.',
21338
- parameters: {
21339
- type: 'object',
21340
- properties: {
21341
- walletId: { type: 'string', description: 'Wallet record id to delete.' },
21342
- },
21343
- required: ['walletId'],
21344
- },
21345
- });
21346
- addWalletToolIfMissing(tools, {
21347
- name: WalletToolNames.request,
21348
- description: 'Request missing credential from user via popup.',
21349
- parameters: {
21350
- type: 'object',
21351
- properties: {
21352
- recordType: {
21353
- type: 'string',
21354
- description: 'Requested record type: USERNAME_PASSWORD, SESSION_COOKIE, ACCESS_TOKEN.',
21355
- },
21356
- service: { type: 'string', description: 'Service identifier.' },
21357
- key: { type: 'string', description: 'Logical credential key.' },
21358
- message: { type: 'string', description: 'Optional UI message for user.' },
21359
- isUserScoped: {
21360
- type: 'boolean',
21361
- description: 'Set true when record should be scoped to current user.',
21362
- },
21363
- isGlobal: { type: 'boolean', description: 'Set true when record should be global.' },
21364
- },
21365
- required: [],
21366
- },
21367
- });
21368
- return tools;
21369
- }
21370
- /**
21371
- * Registers one wallet tool when missing in current tool list.
21372
- *
21373
- * @private function of WalletCommitmentDefinition
21374
- */
21375
- function addWalletToolIfMissing(tools, tool) {
21376
- if (!tools.some((existingTool) => existingTool.name === tool.name)) {
21377
- tools.push(tool);
21378
- }
21379
- }
21380
-
21381
- /**
21382
- * Gets markdown documentation for WALLET commitment.
21383
- *
21384
- * @private function of WalletCommitmentDefinition
21385
- */
21386
- function getWalletCommitmentDocumentation(type) {
21387
- return spaceTrim$1(`
21388
- # ${type}
21389
-
21390
- Enables private credential storage for tokens, usernames/passwords, and session cookies.
21391
- `);
21392
- }
21393
-
21394
- /**
21395
- * Gets human-readable titles for WALLET tool functions.
21396
- *
21397
- * @private function of WalletCommitmentDefinition
21398
- */
21399
- function getWalletToolTitles() {
21400
- return {
21401
- [WalletToolNames.retrieve]: 'Wallet',
21402
- [WalletToolNames.store]: 'Store wallet record',
21403
- [WalletToolNames.update]: 'Update wallet record',
21404
- [WalletToolNames.delete]: 'Delete wallet record',
21405
- [WalletToolNames.request]: 'Request wallet record',
21406
- };
21407
- }
21408
-
21409
- /**
21410
- * WALLET commitment definition.
21411
- *
21412
- * @private [🪔] Maybe export the commitments through some package
21413
- */
21414
- class WalletCommitmentDefinition extends BaseCommitmentDefinition {
21415
- constructor(type = 'WALLET') {
21416
- super(type);
21417
- }
21418
- get requiresContent() {
21419
- return false;
21420
- }
21421
- get description() {
21422
- return 'Enable persistent private credential storage (tokens, logins, cookies) scoped per agent or globally.';
21423
- }
21424
- get icon() {
21425
- return '👛';
21426
- }
21427
- get documentation() {
21428
- return getWalletCommitmentDocumentation(this.type);
21429
- }
21430
- applyToAgentModelRequirements(requirements, content) {
21431
- const extraInstructions = formatOptionalInstructionBlock('Wallet instructions', content);
21432
- return this.appendToSystemMessage({
21433
- ...requirements,
21434
- tools: createWalletTools(requirements.tools),
21435
- _metadata: {
21436
- ...requirements._metadata,
21437
- useWallet: content || true,
21438
- },
21439
- }, createWalletSystemMessage(extraInstructions));
21440
- }
21441
- getToolTitles() {
21442
- return getWalletToolTitles();
21443
- }
21444
- getToolFunctions() {
21445
- return createWalletToolFunctions();
21446
- }
21447
- }
21448
- // Note: [💞] Ignore a discrepancy between file name and entity name
21449
-
21450
17937
  /**
21451
17938
  * `WRITING RULES` commitment definition.
21452
17939
  *
@@ -21673,8 +18160,6 @@ const COMMITMENT_REGISTRY = [
21673
18160
  new PersonaCommitmentDefinition('PERSONA'),
21674
18161
  new PersonaCommitmentDefinition('PERSONAE'),
21675
18162
  new KnowledgeCommitmentDefinition(),
21676
- new MemoryCommitmentDefinition('MEMORY'),
21677
- new MemoryCommitmentDefinition('MEMORIES'),
21678
18163
  new StyleCommitmentDefinition('STYLE'),
21679
18164
  new StyleCommitmentDefinition('STYLES'),
21680
18165
  new RuleCommitmentDefinition('RULE'),
@@ -21696,7 +18181,6 @@ const COMMITMENT_REGISTRY = [
21696
18181
  new ModelCommitmentDefinition('MODELS'),
21697
18182
  new ActionCommitmentDefinition('ACTION'),
21698
18183
  new ActionCommitmentDefinition('ACTIONS'),
21699
- new ComponentCommitmentDefinition(),
21700
18184
  new MetaAvatarCommitmentDefinition(),
21701
18185
  new MetaAvatarCommitmentDefinition('META VISUAL'),
21702
18186
  new MetaImageCommitmentDefinition(),
@@ -21704,11 +18188,13 @@ const COMMITMENT_REGISTRY = [
21704
18188
  new MetaFontCommitmentDefinition(),
21705
18189
  new MetaLinkCommitmentDefinition(),
21706
18190
  new MetaDomainCommitmentDefinition(),
18191
+ new MetaDescriptionCommitmentDefinition(),
21707
18192
  new MetaDisclaimerCommitmentDefinition(),
18193
+ new MetaFullnameCommitmentDefinition(),
18194
+ new MetaIdCommitmentDefinition(),
21708
18195
  new MetaInputPlaceholderCommitmentDefinition(),
21709
18196
  new MetaThinkingMessageCommitmentDefinition(),
21710
18197
  new MetaVisibilityCommitmentDefinition(),
21711
- new MetaCommitmentDefinition(),
21712
18198
  new MetaVoiceCommitmentDefinition(),
21713
18199
  new NoteCommitmentDefinition('NOTE'),
21714
18200
  new NoteCommitmentDefinition('NOTES'),
@@ -21724,8 +18210,6 @@ const COMMITMENT_REGISTRY = [
21724
18210
  new MessageSuffixCommitmentDefinition(),
21725
18211
  new MessageCommitmentDefinition('MESSAGE'),
21726
18212
  new MessageCommitmentDefinition('MESSAGES'),
21727
- new WalletCommitmentDefinition('WALLET'),
21728
- new WalletCommitmentDefinition('WALLETS'),
21729
18213
  new ScenarioCommitmentDefinition('SCENARIO'),
21730
18214
  new ScenarioCommitmentDefinition('SCENARIOS'),
21731
18215
  new DeleteCommitmentDefinition('DELETE'),
@@ -21736,15 +18220,8 @@ const COMMITMENT_REGISTRY = [
21736
18220
  new OpenCommitmentDefinition(),
21737
18221
  new ClosedCommitmentDefinition(),
21738
18222
  new TeamCommitmentDefinition(),
21739
- new UseBrowserCommitmentDefinition(),
21740
- new UseDeepSearchCommitmentDefinition(),
21741
- new UseSearchEngineCommitmentDefinition(),
21742
- new UseSpawnCommitmentDefinition(),
21743
- new UseTimeoutCommitmentDefinition(),
21744
- new UseTimeCommitmentDefinition(),
21745
18223
  new UseUserLocationCommitmentDefinition(),
21746
18224
  new UseCalendarCommitmentDefinition(),
21747
- new UseEmailCommitmentDefinition(),
21748
18225
  new UsePopupCommitmentDefinition(),
21749
18226
  new UseImageGeneratorCommitmentDefinition('USE IMAGE GENERATOR'),
21750
18227
  new UseMcpCommitmentDefinition(),
@@ -22053,59 +18530,6 @@ function extractInitialMessage(commitments) {
22053
18530
  return initialMessage;
22054
18531
  }
22055
18532
 
22056
- /**
22057
- * Normalizes a given text to camelCase format.
22058
- *
22059
- * Note: [🔂] This function is idempotent.
22060
- *
22061
- * @param text The text to be normalized.
22062
- * @param _isFirstLetterCapital Whether the first letter should be capitalized.
22063
- * @returns The camelCase formatted string.
22064
- * @example 'helloWorld'
22065
- * @example 'iLovePromptbook'
22066
- *
22067
- * @public exported from `@promptbook/utils`
22068
- */
22069
- function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
22070
- let charType;
22071
- let lastCharType = null;
22072
- let normalizedName = '';
22073
- for (const char of text) {
22074
- let normalizedChar;
22075
- if (/^[a-z]$/.test(char)) {
22076
- charType = 'LOWERCASE';
22077
- normalizedChar = char;
22078
- }
22079
- else if (/^[A-Z]$/.test(char)) {
22080
- charType = 'UPPERCASE';
22081
- normalizedChar = char.toLowerCase();
22082
- }
22083
- else if (/^[0-9]$/.test(char)) {
22084
- charType = 'NUMBER';
22085
- normalizedChar = char;
22086
- }
22087
- else {
22088
- charType = 'OTHER';
22089
- normalizedChar = '';
22090
- }
22091
- if (!lastCharType) {
22092
- if (_isFirstLetterCapital) {
22093
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
22094
- }
22095
- }
22096
- else if (charType !== lastCharType &&
22097
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
22098
- !(lastCharType === 'NUMBER') &&
22099
- !(charType === 'NUMBER')) {
22100
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
22101
- }
22102
- normalizedName += normalizedChar;
22103
- lastCharType = charType;
22104
- }
22105
- return normalizedName;
22106
- }
22107
- // TODO: [🌺] Use some intermediate util splitWords
22108
-
22109
18533
  /**
22110
18534
  * Normalizes a domain-like string into a comparable hostname form.
22111
18535
  *
@@ -22144,6 +18568,54 @@ function hasHttpProtocol(value) {
22144
18568
  return value.startsWith('http://') || value.startsWith('https://');
22145
18569
  }
22146
18570
 
18571
+ /**
18572
+ * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
18573
+ *
18574
+ * @public exported from `@promptbook/core`
18575
+ */
18576
+ class ParseError extends Error {
18577
+ constructor(message) {
18578
+ super(message);
18579
+ this.name = 'ParseError';
18580
+ Object.setPrototypeOf(this, ParseError.prototype);
18581
+ }
18582
+ }
18583
+ // TODO: Maybe split `ParseError` and `ApplyError`
18584
+
18585
+ /**
18586
+ * Supported visibility states for persisted agents.
18587
+ *
18588
+ * @public exported from `@promptbook/core`
18589
+ */
18590
+ const AGENT_VISIBILITY_VALUES = ['PRIVATE', 'UNLISTED', 'PUBLIC'];
18591
+ /**
18592
+ * Returns `true` when the value is one of supported visibility states.
18593
+ *
18594
+ * @param value - Raw value to validate.
18595
+ * @returns Whether the value is a valid `AgentVisibility`.
18596
+ *
18597
+ * @public exported from `@promptbook/core`
18598
+ */
18599
+ function isAgentVisibility(value) {
18600
+ return typeof value === 'string' && AGENT_VISIBILITY_VALUES.includes(value);
18601
+ }
18602
+ /**
18603
+ * Normalizes raw visibility text into a supported value.
18604
+ *
18605
+ * @param value - Raw visibility value.
18606
+ * @returns Normalized visibility, or `null` when invalid.
18607
+ *
18608
+ * @public exported from `@promptbook/core`
18609
+ */
18610
+ function normalizeAgentVisibility(value) {
18611
+ if (typeof value !== 'string') {
18612
+ return null;
18613
+ }
18614
+ const normalized = value.trim().toUpperCase();
18615
+ return isAgentVisibility(normalized) ? normalized : null;
18616
+ }
18617
+ // Note: [💞] Ignore a discrepancy between file name and entity name
18618
+
22147
18619
  /**
22148
18620
  * Dedicated handlers for META-style commitments that directly map onto parsed meta fields.
22149
18621
  */
@@ -22155,6 +18627,8 @@ const META_COMMITMENT_APPLIERS = {
22155
18627
  'META IMAGE': applyMetaImageContent,
22156
18628
  'META DESCRIPTION': applyMetaDescriptionContent,
22157
18629
  'META DISCLAIMER': applyMetaDisclaimerContent,
18630
+ 'META FULLNAME': applyMetaFullnameContent,
18631
+ 'META ID': applyMetaIdContent,
22158
18632
  'META INPUT PLACEHOLDER': applyMetaInputPlaceholderContent,
22159
18633
  'META THINKING MESSAGE': applyMetaThinkingMessageContent,
22160
18634
  'MESSAGE SUFFIX': applyMessageSuffixContent,
@@ -22172,32 +18646,8 @@ function applyMetaCommitment(state, commitment) {
22172
18646
  const applyMetaContent = META_COMMITMENT_APPLIERS[commitment.type];
22173
18647
  if (applyMetaContent) {
22174
18648
  applyMetaContent(state, commitment.content);
22175
- return;
22176
- }
22177
- if (commitment.type === 'META') {
22178
- applyGenericMetaCommitment(state, commitment.content);
22179
18649
  }
22180
18650
  }
22181
- /**
22182
- * Applies the generic META commitment form (`META TYPE value`).
22183
- */
22184
- function applyGenericMetaCommitment(state, content) {
22185
- const metaTypeRaw = content.split(' ')[0] || 'NONE';
22186
- const metaValue = spaceTrim$1(content.substring(metaTypeRaw.length));
22187
- if (metaTypeRaw === 'LINK') {
22188
- state.links.push(metaValue);
22189
- }
22190
- if (metaTypeRaw.toUpperCase() === 'AVATAR') {
22191
- applyMetaAvatarContent(state, metaValue);
22192
- return;
22193
- }
22194
- if (metaTypeRaw.toUpperCase() === 'VISIBILITY') {
22195
- applyMetaVisibilityContent(state, metaValue);
22196
- return;
22197
- }
22198
- const metaType = normalizeTo_camelCase(metaTypeRaw);
22199
- state.meta[metaType] = metaValue;
22200
- }
22201
18651
  /**
22202
18652
  * Applies META AVATAR / META VISUAL content into the canonical `meta.avatar` field.
22203
18653
  */
@@ -22241,6 +18691,18 @@ function applyMetaDescriptionContent(state, content) {
22241
18691
  function applyMetaDisclaimerContent(state, content) {
22242
18692
  state.meta.disclaimer = content;
22243
18693
  }
18694
+ /**
18695
+ * Applies META FULLNAME content into the canonical `meta.fullname` field.
18696
+ */
18697
+ function applyMetaFullnameContent(state, content) {
18698
+ state.meta.fullname = spaceTrim$1(content);
18699
+ }
18700
+ /**
18701
+ * Applies META ID content into the canonical `meta.id` field.
18702
+ */
18703
+ function applyMetaIdContent(state, content) {
18704
+ state.meta.id = spaceTrim$1(content);
18705
+ }
22244
18706
  /**
22245
18707
  * Applies META INPUT PLACEHOLDER content into the canonical `meta.inputPlaceholder` field.
22246
18708
  */
@@ -22345,46 +18807,11 @@ function consumeConversationSampleCommitment(state, commitment) {
22345
18807
  * Static capability descriptors for commitments that map one-to-one to a visible capability.
22346
18808
  */
22347
18809
  const SIMPLE_CAPABILITY_BY_COMMITMENT_TYPE = {
22348
- 'USE BROWSER': {
22349
- type: 'browser',
22350
- label: 'Browser',
22351
- iconName: 'Globe',
22352
- },
22353
- 'USE SEARCH ENGINE': {
22354
- type: 'search-engine',
22355
- label: 'Internet',
22356
- iconName: 'Search',
22357
- },
22358
- 'USE SEARCH': {
22359
- type: 'search-engine',
22360
- label: 'Internet',
22361
- iconName: 'Search',
22362
- },
22363
- 'USE DEEPSEARCH': {
22364
- type: 'search-engine',
22365
- label: 'DeepSearch',
22366
- iconName: 'Search',
22367
- },
22368
- 'USE TIME': {
22369
- type: 'time',
22370
- label: 'Time',
22371
- iconName: 'Clock',
22372
- },
22373
- 'USE TIMEOUT': {
22374
- type: 'timeout',
22375
- label: 'Timers',
22376
- iconName: 'Clock',
22377
- },
22378
18810
  'USE USER LOCATION': {
22379
18811
  type: 'user-location',
22380
18812
  label: 'User location',
22381
18813
  iconName: 'MapPin',
22382
18814
  },
22383
- 'USE EMAIL': {
22384
- type: 'email',
22385
- label: 'Email',
22386
- iconName: 'Mail',
22387
- },
22388
18815
  'USE POPUP': {
22389
18816
  type: 'popup',
22390
18817
  label: 'Popup',
@@ -24264,7 +20691,7 @@ function createCommitmentRegex(commitmentTypes) {
24264
20691
  }
24265
20692
  const commitmentPatterns = [...commitmentTypes]
24266
20693
  .sort((a, b) => b.length - a.length)
24267
- .map((type) => (type === 'META' ? 'META\\s+\\w+' : type.replace(/\s+/, '\\s+')))
20694
+ .map((type) => type.replace(/\s+/, '\\s+'))
24268
20695
  .join('|');
24269
20696
  return new RegExp(`^\\s*(${commitmentPatterns})(?=\\s|$)`);
24270
20697
  }
@@ -30454,6 +26881,59 @@ const pdfSaveFormatDefinition = {
30454
26881
  // TODO: !!! Add QR code with branding to the footer
30455
26882
  // TODO: !!! Add print option
30456
26883
 
26884
+ /**
26885
+ * Normalizes a given text to camelCase format.
26886
+ *
26887
+ * Note: [🔂] This function is idempotent.
26888
+ *
26889
+ * @param text The text to be normalized.
26890
+ * @param _isFirstLetterCapital Whether the first letter should be capitalized.
26891
+ * @returns The camelCase formatted string.
26892
+ * @example 'helloWorld'
26893
+ * @example 'iLovePromptbook'
26894
+ *
26895
+ * @public exported from `@promptbook/utils`
26896
+ */
26897
+ function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
26898
+ let charType;
26899
+ let lastCharType = null;
26900
+ let normalizedName = '';
26901
+ for (const char of text) {
26902
+ let normalizedChar;
26903
+ if (/^[a-z]$/.test(char)) {
26904
+ charType = 'LOWERCASE';
26905
+ normalizedChar = char;
26906
+ }
26907
+ else if (/^[A-Z]$/.test(char)) {
26908
+ charType = 'UPPERCASE';
26909
+ normalizedChar = char.toLowerCase();
26910
+ }
26911
+ else if (/^[0-9]$/.test(char)) {
26912
+ charType = 'NUMBER';
26913
+ normalizedChar = char;
26914
+ }
26915
+ else {
26916
+ charType = 'OTHER';
26917
+ normalizedChar = '';
26918
+ }
26919
+ if (!lastCharType) {
26920
+ if (_isFirstLetterCapital) {
26921
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
26922
+ }
26923
+ }
26924
+ else if (charType !== lastCharType &&
26925
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
26926
+ !(lastCharType === 'NUMBER') &&
26927
+ !(charType === 'NUMBER')) {
26928
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
26929
+ }
26930
+ normalizedName += normalizedChar;
26931
+ lastCharType = charType;
26932
+ }
26933
+ return normalizedName;
26934
+ }
26935
+ // TODO: [🌺] Use some intermediate util splitWords
26936
+
30457
26937
  /**
30458
26938
  * Normalizes a given text to PascalCase format.
30459
26939
  *
@@ -45330,6 +41810,21 @@ function useSendMessageToLlmChat() {
45330
41810
  const CHAT_STREAM_KEEP_ALIVE_TOKEN = 'STREAM_KEEP_ALIVE';
45331
41811
  // Note: [💞] Ignore a discrepancy between file name and entity name
45332
41812
 
41813
+ /**
41814
+ * Checks if value is valid email
41815
+ *
41816
+ * @public exported from `@promptbook/utils`
41817
+ */
41818
+ function isValidEmail(email) {
41819
+ if (typeof email !== 'string') {
41820
+ return false;
41821
+ }
41822
+ if (email.split(/\r?\n/).length > 1) {
41823
+ return false;
41824
+ }
41825
+ return /^.+@.+\..+$/.test(email);
41826
+ }
41827
+
45333
41828
  /**
45334
41829
  * Function isValidJsonString will tell you if the string is valid JSON or not
45335
41830
  *
@@ -45403,6 +41898,52 @@ function isValidPipelineString(pipelineString) {
45403
41898
  }
45404
41899
  // TODO: [🧠][🈴] Where is the best location for this file
45405
41900
 
41901
+ /**
41902
+ * Generates random token
41903
+ *
41904
+ * Note: `$` is used to indicate that this function is not a pure function - it is not deterministic
41905
+ * Note: This function is cryptographically secure (it uses crypto.randomBytes internally)
41906
+ *
41907
+ * @returns secure random token
41908
+ *
41909
+ * @private internal helper function
41910
+ */
41911
+ function $randomToken(randomness) {
41912
+ return CryptoJS.lib.WordArray.random(randomness).toString(CryptoJS.enc.Hex);
41913
+ }
41914
+ // TODO: [🤶] Maybe export through `@promptbook/utils` or `@promptbook/random` package
41915
+ // TODO: Maybe use nanoid instead https://github.com/ai/nanoid
41916
+
41917
+ /**
41918
+ * This error indicates errors during the execution of the pipeline
41919
+ *
41920
+ * @public exported from `@promptbook/core`
41921
+ */
41922
+ class PipelineExecutionError extends Error {
41923
+ constructor(message) {
41924
+ // Added id parameter
41925
+ super(message);
41926
+ this.name = 'PipelineExecutionError';
41927
+ // TODO: [🐙] DRY - Maybe $randomId
41928
+ this.id = `error-${$randomToken(8 /* <- TODO: To global config + Use Base58 to avoid similar char conflicts */)}`;
41929
+ Object.setPrototypeOf(this, PipelineExecutionError.prototype);
41930
+ }
41931
+ }
41932
+ // TODO: [🧠][🌂] Add id to all errors
41933
+
41934
+ /**
41935
+ * This error type indicates that some limit was reached
41936
+ *
41937
+ * @public exported from `@promptbook/core`
41938
+ */
41939
+ class LimitReachedError extends Error {
41940
+ constructor(message) {
41941
+ super(message);
41942
+ this.name = 'LimitReachedError';
41943
+ Object.setPrototypeOf(this, LimitReachedError.prototype);
41944
+ }
41945
+ }
41946
+
45406
41947
  /**
45407
41948
  * Replaces parameters in template with values from parameters object
45408
41949
  *
@@ -52511,12 +49052,6 @@ const OVERWRITTEN_COMMITMENT_GROUP_BY_TYPE = new Map([
52511
49052
  ['GOAL', 'GOAL'],
52512
49053
  ['GOALS', 'GOAL'],
52513
49054
  ]);
52514
- /**
52515
- * Legacy commitments that should be parsed for compatibility but ignored by the model-requirements pipeline.
52516
- *
52517
- * @private internal constant of `filterCommitmentsForAgentModelRequirements`
52518
- */
52519
- const IGNORED_COMMITMENT_TYPES = new Set(['WALLET', 'WALLETS']);
52520
49055
  /**
52521
49056
  * Applies the commitment filtering rules used before commitment definitions are executed.
52522
49057
  *
@@ -52565,9 +49100,6 @@ function filterOverwrittenCommitments(commitments) {
52565
49100
  function filterDeletedCommitments(commitments) {
52566
49101
  const filteredCommitments = [];
52567
49102
  for (const commitment of commitments) {
52568
- if (isIgnoredCommitmentType(commitment.type)) {
52569
- continue;
52570
- }
52571
49103
  if (!isDeleteCommitmentType(commitment.type)) {
52572
49104
  filteredCommitments.push(commitment);
52573
49105
  continue;
@@ -52598,17 +49130,6 @@ function filterDeletedCommitments(commitments) {
52598
49130
  function isDeleteCommitmentType(commitmentType) {
52599
49131
  return DELETE_COMMITMENT_TYPES.has(commitmentType);
52600
49132
  }
52601
- /**
52602
- * Checks whether a parsed commitment is intentionally ignored by the current model compiler.
52603
- *
52604
- * @param commitmentType - Commitment type to check.
52605
- * @returns `true` when the commitment should not affect model requirements.
52606
- *
52607
- * @private internal utility of `filterDeletedCommitments`
52608
- */
52609
- function isIgnoredCommitmentType(commitmentType) {
52610
- return IGNORED_COMMITMENT_TYPES.has(commitmentType);
52611
- }
52612
49133
  /**
52613
49134
  * Extracts normalized parameter names used for DELETE-like invalidation matching.
52614
49135
  *
@@ -52742,7 +49263,6 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
52742
49263
  const filteredCommitments = filterCommitmentsForAgentModelRequirements(parseResult.commitments);
52743
49264
  let requirements = createInitialAgentModelRequirements(parseResult.agentName, modelName);
52744
49265
  requirements = await applyCommitmentsToAgentModelRequirements(requirements, filteredCommitments, options);
52745
- requirements = aggregateUseCommitmentSystemMessages(requirements, filteredCommitments);
52746
49266
  requirements = await augmentAgentModelRequirementsFromSource(requirements, parseResult, agentSource);
52747
49267
  requirements = await materializeInlineKnowledgeSources(requirements, options === null || options === void 0 ? void 0 : options.inlineKnowledgeSourceUploader);
52748
49268
  return finalizeRequirements(requirements);
@@ -53270,6 +49790,40 @@ class OpenAiAgentKitExecutionToolsOutputTypeMapper {
53270
49790
  }
53271
49791
  }
53272
49792
 
49793
+ /**
49794
+ * Marker property stored inside serialized tool-execution envelopes.
49795
+ *
49796
+ * @private internal tool-execution transport
49797
+ */
49798
+ const TOOL_EXECUTION_ENVELOPE_MARKER = '__promptbookToolExecutionEnvelope';
49799
+ /**
49800
+ * Parses one serialized tool-execution envelope when present.
49801
+ *
49802
+ * @private internal tool-execution transport
49803
+ */
49804
+ function parseToolExecutionEnvelope(rawValue) {
49805
+ if (typeof rawValue !== 'string') {
49806
+ return null;
49807
+ }
49808
+ try {
49809
+ const parsedValue = JSON.parse(rawValue);
49810
+ if (!parsedValue ||
49811
+ typeof parsedValue !== 'object' ||
49812
+ parsedValue[TOOL_EXECUTION_ENVELOPE_MARKER] !== true ||
49813
+ typeof parsedValue.assistantMessage !== 'string') {
49814
+ return null;
49815
+ }
49816
+ return {
49817
+ assistantMessage: parsedValue.assistantMessage,
49818
+ toolResult: parsedValue.toolResult,
49819
+ };
49820
+ }
49821
+ catch (_a) {
49822
+ return null;
49823
+ }
49824
+ }
49825
+ // Note: [💞] Ignore a discrepancy between file name and entity name
49826
+
53273
49827
  /**
53274
49828
  * Builds a tool invocation script that injects hidden runtime context into tool args.
53275
49829
  *
@@ -53341,7 +49895,7 @@ const loadOpenAiAgentsModule = createLazyModuleLoader(() => import('@openai/agen
53341
49895
  */
53342
49896
  const DEFAULT_DEEP_SEARCH_MODEL_NAME = 'o4-mini-deep-research';
53343
49897
  /**
53344
- * Tool name used by the Book commitment-backed DeepSearch capability.
49898
+ * Tool name used by the DeepSearch capability.
53345
49899
  */
53346
49900
  const DEEP_SEARCH_TOOL_NAME = 'deep_search';
53347
49901
  /**
@@ -53611,7 +50165,7 @@ class OpenAiAgentKitExecutionToolsToolBuilder {
53611
50165
  };
53612
50166
  }
53613
50167
  /**
53614
- * Creates the native Agent SDK tool used for `USE DEEPSEARCH`.
50168
+ * Creates the native Agent SDK tool used for the DeepSearch capability.
53615
50169
  */
53616
50170
  async createDeepSearchAgentKitTool(toolDefinition) {
53617
50171
  const { Agent: AgentFromKit, webSearchTool } = await loadOpenAiAgentsModule();
@@ -61708,7 +58262,7 @@ class Agent extends AgentLlmExecutionTools {
61708
58262
  this.links = [];
61709
58263
  /**
61710
58264
  * Capabilities of the agent
61711
- * This is parsed from commitments like USE BROWSER, USE SEARCH ENGINE, KNOWLEDGE, etc.
58265
+ * This is parsed from commitments like USE CALENDAR, USE PROJECT, KNOWLEDGE, etc.
61712
58266
  */
61713
58267
  this.capabilities = [];
61714
58268
  /**