@promptbook/remote-server 0.112.0-56 → 0.112.0-57

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 (37) hide show
  1. package/esm/index.es.js +826 -841
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/ParsedAgentSourceWithCommitments.d.ts +7 -0
  4. package/esm/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/applyCommitmentsToAgentModelRequirements.d.ts +14 -0
  5. package/esm/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/augmentAgentModelRequirementsFromSource.d.ts +14 -0
  6. package/esm/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/filterCommitmentsForAgentModelRequirements.d.ts +10 -0
  7. package/esm/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/materializeInlineKnowledgeSources.d.ts +12 -0
  8. package/esm/src/book-2.0/agent-source/parseAgentSource/ParseAgentSourceState.d.ts +10 -0
  9. package/esm/src/book-2.0/agent-source/parseAgentSource/ParsedAgentProfile.d.ts +7 -0
  10. package/esm/src/book-2.0/agent-source/parseAgentSource/applyMetaCommitment.d.ts +8 -0
  11. package/esm/src/book-2.0/agent-source/parseAgentSource/consumeConversationSampleCommitment.d.ts +8 -0
  12. package/esm/src/book-2.0/agent-source/parseAgentSource/createCapabilitiesFromCommitment.d.ts +9 -0
  13. package/esm/src/book-2.0/agent-source/parseAgentSource/ensureMetaFullname.d.ts +7 -0
  14. package/esm/src/book-2.0/agent-source/parseAgentSource/extractAgentProfileText.d.ts +8 -0
  15. package/esm/src/book-2.0/agent-source/parseAgentSource/extractInitialMessage.d.ts +7 -0
  16. package/esm/src/book-2.0/agent-source/parseAgentSource/extractParsedAgentProfile.d.ts +8 -0
  17. package/esm/src/types/LlmToolDefinition.d.ts +17 -7
  18. package/esm/src/version.d.ts +1 -1
  19. package/package.json +2 -2
  20. package/umd/index.umd.js +826 -841
  21. package/umd/index.umd.js.map +1 -1
  22. package/umd/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/ParsedAgentSourceWithCommitments.d.ts +7 -0
  23. package/umd/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/applyCommitmentsToAgentModelRequirements.d.ts +14 -0
  24. package/umd/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/augmentAgentModelRequirementsFromSource.d.ts +14 -0
  25. package/umd/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/filterCommitmentsForAgentModelRequirements.d.ts +10 -0
  26. package/umd/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments/materializeInlineKnowledgeSources.d.ts +12 -0
  27. package/umd/src/book-2.0/agent-source/parseAgentSource/ParseAgentSourceState.d.ts +10 -0
  28. package/umd/src/book-2.0/agent-source/parseAgentSource/ParsedAgentProfile.d.ts +7 -0
  29. package/umd/src/book-2.0/agent-source/parseAgentSource/applyMetaCommitment.d.ts +8 -0
  30. package/umd/src/book-2.0/agent-source/parseAgentSource/consumeConversationSampleCommitment.d.ts +8 -0
  31. package/umd/src/book-2.0/agent-source/parseAgentSource/createCapabilitiesFromCommitment.d.ts +9 -0
  32. package/umd/src/book-2.0/agent-source/parseAgentSource/ensureMetaFullname.d.ts +7 -0
  33. package/umd/src/book-2.0/agent-source/parseAgentSource/extractAgentProfileText.d.ts +8 -0
  34. package/umd/src/book-2.0/agent-source/parseAgentSource/extractInitialMessage.d.ts +7 -0
  35. package/umd/src/book-2.0/agent-source/parseAgentSource/extractParsedAgentProfile.d.ts +8 -0
  36. package/umd/src/types/LlmToolDefinition.d.ts +17 -7
  37. package/umd/src/version.d.ts +1 -1
package/umd/index.umd.js CHANGED
@@ -50,7 +50,7 @@
50
50
  * @generated
51
51
  * @see https://github.com/webgptorg/promptbook
52
52
  */
53
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-56';
53
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-57';
54
54
  /**
55
55
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
56
56
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -21009,6 +21009,44 @@
21009
21009
  * @private constant of createUseCalendarTools
21010
21010
  */
21011
21011
  const CALENDAR_URL_PARAMETER_DESCRIPTION = 'Google Calendar URL configured by USE CALENDAR (for example "https://calendar.google.com/...").';
21012
+ /**
21013
+ * Shared schema for string arrays used by USE CALENDAR tools.
21014
+ *
21015
+ * @private constant of createUseCalendarTools
21016
+ */
21017
+ const STRING_ARRAY_ITEMS_SCHEMA = {
21018
+ type: 'string',
21019
+ };
21020
+ /**
21021
+ * Shared schema for integer arrays used by USE CALENDAR tools.
21022
+ *
21023
+ * @private constant of createUseCalendarTools
21024
+ */
21025
+ const INTEGER_ARRAY_ITEMS_SCHEMA = {
21026
+ type: 'integer',
21027
+ };
21028
+ /**
21029
+ * Shared `sendUpdates` schema used by USE CALENDAR tools.
21030
+ *
21031
+ * @private constant of createUseCalendarTools
21032
+ */
21033
+ const SEND_UPDATES_PARAMETER_SCHEMA = {
21034
+ type: 'string',
21035
+ description: 'Guest update policy ("all", "externalOnly", "none").',
21036
+ enum: ['all', 'externalOnly', 'none'],
21037
+ };
21038
+ /**
21039
+ * Creates an array parameter schema with explicit item definition so OpenAI accepts it.
21040
+ *
21041
+ * @private function of createUseCalendarTools
21042
+ */
21043
+ function createArrayParameterSchema(description, items) {
21044
+ return {
21045
+ type: 'array',
21046
+ description,
21047
+ items,
21048
+ };
21049
+ }
21012
21050
  /**
21013
21051
  * Adds USE CALENDAR tool definitions while keeping already registered tools untouched.
21014
21052
  *
@@ -21115,18 +21153,9 @@
21115
21153
  type: 'string',
21116
21154
  description: 'Optional timezone for datetime values.',
21117
21155
  },
21118
- attendees: {
21119
- type: 'array',
21120
- description: 'Optional guest email list.',
21121
- },
21122
- reminderMinutes: {
21123
- type: 'array',
21124
- description: 'Optional popup reminder minute offsets.',
21125
- },
21126
- sendUpdates: {
21127
- type: 'string',
21128
- description: 'Guest update policy ("all", "externalOnly", "none").',
21129
- },
21156
+ attendees: createArrayParameterSchema('Optional guest email list.', STRING_ARRAY_ITEMS_SCHEMA),
21157
+ reminderMinutes: createArrayParameterSchema('Optional popup reminder minute offsets.', INTEGER_ARRAY_ITEMS_SCHEMA),
21158
+ sendUpdates: SEND_UPDATES_PARAMETER_SCHEMA,
21130
21159
  },
21131
21160
  required: ['summary', 'start', 'end'],
21132
21161
  },
@@ -21169,18 +21198,9 @@
21169
21198
  type: 'string',
21170
21199
  description: 'Optional timezone for datetime values.',
21171
21200
  },
21172
- attendees: {
21173
- type: 'array',
21174
- description: 'Optional replacement guest email list.',
21175
- },
21176
- reminderMinutes: {
21177
- type: 'array',
21178
- description: 'Optional replacement popup reminder minute offsets.',
21179
- },
21180
- sendUpdates: {
21181
- type: 'string',
21182
- description: 'Guest update policy ("all", "externalOnly", "none").',
21183
- },
21201
+ attendees: createArrayParameterSchema('Optional replacement guest email list.', STRING_ARRAY_ITEMS_SCHEMA),
21202
+ reminderMinutes: createArrayParameterSchema('Optional replacement popup reminder minute offsets.', INTEGER_ARRAY_ITEMS_SCHEMA),
21203
+ sendUpdates: SEND_UPDATES_PARAMETER_SCHEMA,
21184
21204
  },
21185
21205
  required: ['eventId'],
21186
21206
  },
@@ -21199,10 +21219,7 @@
21199
21219
  type: 'string',
21200
21220
  description: 'Google Calendar event id.',
21201
21221
  },
21202
- sendUpdates: {
21203
- type: 'string',
21204
- description: 'Guest update policy ("all", "externalOnly", "none").',
21205
- },
21222
+ sendUpdates: SEND_UPDATES_PARAMETER_SCHEMA,
21206
21223
  },
21207
21224
  required: ['eventId'],
21208
21225
  },
@@ -21221,14 +21238,8 @@
21221
21238
  type: 'string',
21222
21239
  description: 'Google Calendar event id.',
21223
21240
  },
21224
- guests: {
21225
- type: 'array',
21226
- description: 'Guest email list to add to the event.',
21227
- },
21228
- sendUpdates: {
21229
- type: 'string',
21230
- description: 'Guest update policy ("all", "externalOnly", "none").',
21231
- },
21241
+ guests: createArrayParameterSchema('Guest email list to add to the event.', STRING_ARRAY_ITEMS_SCHEMA),
21242
+ sendUpdates: SEND_UPDATES_PARAMETER_SCHEMA,
21232
21243
  },
21233
21244
  required: ['eventId', 'guests'],
21234
21245
  },
@@ -28322,44 +28333,6 @@
28322
28333
  return normalizeAgentName(`Agent ${agentHash.substring(0, LIMITS.SHORT_NAME_LENGTH)}`);
28323
28334
  }
28324
28335
 
28325
- /**
28326
- * Normalizes a domain-like string into a comparable hostname form.
28327
- *
28328
- * The returned value is lowercased and stripped to hostname only
28329
- * (protocol, path, query, hash, and port are removed).
28330
- *
28331
- * @param rawDomain - Raw domain value (for example `my-agent.com` or `https://my-agent.com/path`).
28332
- * @returns Normalized hostname or `null` when the value cannot be normalized.
28333
- *
28334
- * @private utility for host/domain matching
28335
- */
28336
- function normalizeDomainForMatching(rawDomain) {
28337
- const trimmedDomain = rawDomain.trim();
28338
- if (!trimmedDomain) {
28339
- return null;
28340
- }
28341
- const candidateUrl = hasHttpProtocol(trimmedDomain) ? trimmedDomain : `https://${trimmedDomain}`;
28342
- try {
28343
- const parsedUrl = new URL(candidateUrl);
28344
- const normalizedHostname = parsedUrl.hostname.trim().toLowerCase();
28345
- return normalizedHostname || null;
28346
- }
28347
- catch (_a) {
28348
- return null;
28349
- }
28350
- }
28351
- /**
28352
- * Checks whether the value already includes an HTTP(S) protocol prefix.
28353
- *
28354
- * @param value - Raw value to inspect.
28355
- * @returns True when the value starts with `http://` or `https://`.
28356
- *
28357
- * @private utility for host/domain matching
28358
- */
28359
- function hasHttpProtocol(value) {
28360
- return value.startsWith('http://') || value.startsWith('https://');
28361
- }
28362
-
28363
28336
  /**
28364
28337
  * Consumes the agent-name prelude from raw source.
28365
28338
  *
@@ -28596,126 +28569,16 @@
28596
28569
  }
28597
28570
 
28598
28571
  /**
28599
- * Parses basic information from agent source
28600
- *
28601
- * There are 2 similar functions:
28602
- * - `parseAgentSource` which is a lightweight parser for agent source, it parses basic information and its purpose is to be quick and synchronous. The commitments there are hardcoded.
28603
- * - `createAgentModelRequirements` which is an asynchronous function that creates model requirements it applies each commitment one by one and works asynchronously.
28604
- *
28605
- * @public exported from `@promptbook/core`
28606
- */
28607
- function parseAgentSource(agentSource) {
28608
- const parseResult = parseAgentSourceWithCommitments(agentSource);
28609
- const resolvedAgentName = parseResult.agentName || createDefaultAgentName(agentSource);
28610
- const personaDescription = extractAgentProfileText(parseResult.commitments);
28611
- const initialMessage = extractInitialMessage(parseResult.commitments);
28612
- const parsedProfile = extractParsedAgentProfile(parseResult.commitments);
28613
- ensureMetaFullname(parsedProfile.meta, resolvedAgentName);
28614
- return {
28615
- agentName: normalizeAgentName(resolvedAgentName),
28616
- agentHash: computeAgentHash(agentSource),
28617
- permanentId: parsedProfile.meta.id,
28618
- personaDescription,
28619
- initialMessage,
28620
- meta: parsedProfile.meta,
28621
- links: parsedProfile.links,
28622
- parameters: parseParameters(agentSource),
28623
- capabilities: parsedProfile.capabilities,
28624
- samples: parsedProfile.samples,
28625
- knowledgeSources: parsedProfile.knowledgeSources,
28626
- };
28627
- }
28628
- /**
28629
- * Static capability descriptors for commitments that map one-to-one to a visible capability.
28630
- *
28631
- * @private internal utility of `parseAgentSource`
28632
- */
28633
- const SIMPLE_CAPABILITY_BY_COMMITMENT_TYPE = {
28634
- 'USE BROWSER': {
28635
- type: 'browser',
28636
- label: 'Browser',
28637
- iconName: 'Globe',
28638
- },
28639
- 'USE SEARCH ENGINE': {
28640
- type: 'search-engine',
28641
- label: 'Internet',
28642
- iconName: 'Search',
28643
- },
28644
- 'USE SEARCH': {
28645
- type: 'search-engine',
28646
- label: 'Internet',
28647
- iconName: 'Search',
28648
- },
28649
- 'USE DEEPSEARCH': {
28650
- type: 'search-engine',
28651
- label: 'DeepSearch',
28652
- iconName: 'Search',
28653
- },
28654
- 'USE TIME': {
28655
- type: 'time',
28656
- label: 'Time',
28657
- iconName: 'Clock',
28658
- },
28659
- 'USE TIMEOUT': {
28660
- type: 'timeout',
28661
- label: 'Timers',
28662
- iconName: 'Clock',
28663
- },
28664
- 'USE USER LOCATION': {
28665
- type: 'user-location',
28666
- label: 'User location',
28667
- iconName: 'MapPin',
28668
- },
28669
- 'USE EMAIL': {
28670
- type: 'email',
28671
- label: 'Email',
28672
- iconName: 'Mail',
28673
- },
28674
- 'USE POPUP': {
28675
- type: 'popup',
28676
- label: 'Popup',
28677
- iconName: 'SquareArrowOutUpRight',
28678
- },
28679
- 'USE IMAGE GENERATOR': {
28680
- type: 'image-generator',
28681
- label: 'Image Generator',
28682
- iconName: 'Image',
28683
- },
28684
- 'USE PRIVACY': {
28685
- type: 'privacy',
28686
- label: 'Privacy',
28687
- iconName: 'Shield',
28688
- },
28689
- 'USE CALENDAR': {
28690
- type: 'calendar',
28691
- label: 'Calendar',
28692
- iconName: 'Calendar',
28693
- },
28694
- };
28695
- /**
28696
- * Dedicated handlers for META-style commitments that directly map onto parsed meta fields.
28697
- *
28698
- * @private internal utility of `parseAgentSource`
28699
- */
28700
- const META_COMMITMENT_APPLIERS = {
28701
- 'META AVATAR': applyMetaAvatarContent,
28702
- 'META LINK': applyMetaLinkContent,
28703
- 'META DOMAIN': applyMetaDomainContent,
28704
- 'META IMAGE': applyMetaImageContent,
28705
- 'META DESCRIPTION': applyMetaDescriptionContent,
28706
- 'META DISCLAIMER': applyMetaDisclaimerContent,
28707
- 'META INPUT PLACEHOLDER': applyMetaInputPlaceholderContent,
28708
- 'MESSAGE SUFFIX': applyMessageSuffixContent,
28709
- 'META COLOR': applyMetaColorContent,
28710
- 'META FONT': applyMetaFontContent,
28711
- 'META VOICE': applyMetaVoiceContent,
28712
- };
28713
- /**
28714
- * Detects local slash-based references used by FROM and IMPORT commitments.
28572
+ * Ensures the parsed profile always exposes a fullname value.
28715
28573
  *
28716
28574
  * @private internal utility of `parseAgentSource`
28717
28575
  */
28718
- const LOCAL_AGENT_REFERENCE_PREFIXES = ['./', '../', '/'];
28576
+ function ensureMetaFullname(meta, fallbackFullname) {
28577
+ if (!meta.fullname) {
28578
+ meta.fullname = fallbackFullname;
28579
+ }
28580
+ }
28581
+
28719
28582
  /**
28720
28583
  * Resolves the public agent profile text from the last GOAL/GOALS commitment,
28721
28584
  * falling back to the deprecated PERSONA/PERSONAE commitments when no goal exists.
@@ -28745,6 +28608,7 @@
28745
28608
  }
28746
28609
  return null;
28747
28610
  }
28611
+
28748
28612
  /**
28749
28613
  * Resolves the last INITIAL MESSAGE commitment, which is the public initial-message value.
28750
28614
  *
@@ -28759,53 +28623,194 @@
28759
28623
  }
28760
28624
  return initialMessage;
28761
28625
  }
28626
+
28762
28627
  /**
28763
- * Collects capability, sample, meta, link, and knowledge-source data from commitments.
28628
+ * Normalizes a domain-like string into a comparable hostname form.
28764
28629
  *
28765
- * @private internal utility of `parseAgentSource`
28766
- */
28767
- function extractParsedAgentProfile(commitments) {
28768
- const state = {
28769
- meta: {},
28770
- links: [],
28771
- capabilities: [],
28772
- samples: [],
28773
- knowledgeSources: [],
28774
- pendingUserMessage: null,
28775
- knownKnowledgeSourceUrls: new Set(),
28776
- };
28777
- for (const commitment of commitments) {
28778
- processParsedCommitment(state, commitment);
28779
- }
28780
- return {
28781
- meta: state.meta,
28782
- links: state.links,
28783
- capabilities: state.capabilities,
28784
- samples: state.samples,
28785
- knowledgeSources: state.knowledgeSources,
28786
- };
28787
- }
28788
- /**
28789
- * Processes one parsed commitment through the sample, capability, and meta stages.
28630
+ * The returned value is lowercased and stripped to hostname only
28631
+ * (protocol, path, query, hash, and port are removed).
28790
28632
  *
28791
- * @private internal utility of `parseAgentSource`
28633
+ * @param rawDomain - Raw domain value (for example `my-agent.com` or `https://my-agent.com/path`).
28634
+ * @returns Normalized hostname or `null` when the value cannot be normalized.
28635
+ *
28636
+ * @private utility for host/domain matching
28792
28637
  */
28793
- function processParsedCommitment(state, commitment) {
28794
- if (consumeConversationSampleCommitment(state, commitment)) {
28795
- return;
28638
+ function normalizeDomainForMatching(rawDomain) {
28639
+ const trimmedDomain = rawDomain.trim();
28640
+ if (!trimmedDomain) {
28641
+ return null;
28796
28642
  }
28797
- const capabilities = createCapabilitiesFromCommitment(state, commitment);
28798
- if (capabilities.length > 0) {
28799
- state.capabilities.push(...capabilities);
28800
- return;
28643
+ const candidateUrl = hasHttpProtocol(trimmedDomain) ? trimmedDomain : `https://${trimmedDomain}`;
28644
+ try {
28645
+ const parsedUrl = new URL(candidateUrl);
28646
+ const normalizedHostname = parsedUrl.hostname.trim().toLowerCase();
28647
+ return normalizedHostname || null;
28648
+ }
28649
+ catch (_a) {
28650
+ return null;
28801
28651
  }
28802
- applyMetaCommitment(state, commitment);
28803
28652
  }
28804
28653
  /**
28805
- * Updates sample-conversation state for communication commitments.
28654
+ * Checks whether the value already includes an HTTP(S) protocol prefix.
28806
28655
  *
28807
- * @private internal utility of `parseAgentSource`
28808
- */
28656
+ * @param value - Raw value to inspect.
28657
+ * @returns True when the value starts with `http://` or `https://`.
28658
+ *
28659
+ * @private utility for host/domain matching
28660
+ */
28661
+ function hasHttpProtocol(value) {
28662
+ return value.startsWith('http://') || value.startsWith('https://');
28663
+ }
28664
+
28665
+ /**
28666
+ * Dedicated handlers for META-style commitments that directly map onto parsed meta fields.
28667
+ */
28668
+ const META_COMMITMENT_APPLIERS = {
28669
+ 'META AVATAR': applyMetaAvatarContent,
28670
+ 'META LINK': applyMetaLinkContent,
28671
+ 'META DOMAIN': applyMetaDomainContent,
28672
+ 'META IMAGE': applyMetaImageContent,
28673
+ 'META DESCRIPTION': applyMetaDescriptionContent,
28674
+ 'META DISCLAIMER': applyMetaDisclaimerContent,
28675
+ 'META INPUT PLACEHOLDER': applyMetaInputPlaceholderContent,
28676
+ 'MESSAGE SUFFIX': applyMessageSuffixContent,
28677
+ 'META COLOR': applyMetaColorContent,
28678
+ 'META FONT': applyMetaFontContent,
28679
+ 'META VOICE': applyMetaVoiceContent,
28680
+ };
28681
+ /**
28682
+ * Applies META-style commitments that mutate parsed profile metadata.
28683
+ *
28684
+ * @private internal utility of `parseAgentSource`
28685
+ */
28686
+ function applyMetaCommitment(state, commitment) {
28687
+ const applyMetaContent = META_COMMITMENT_APPLIERS[commitment.type];
28688
+ if (applyMetaContent) {
28689
+ applyMetaContent(state, commitment.content);
28690
+ return;
28691
+ }
28692
+ if (commitment.type === 'META') {
28693
+ applyGenericMetaCommitment(state, commitment.content);
28694
+ }
28695
+ }
28696
+ /**
28697
+ * Applies the generic META commitment form (`META TYPE value`).
28698
+ */
28699
+ function applyGenericMetaCommitment(state, content) {
28700
+ const metaTypeRaw = content.split(' ')[0] || 'NONE';
28701
+ const metaValue = _spaceTrim.spaceTrim(content.substring(metaTypeRaw.length));
28702
+ if (metaTypeRaw === 'LINK') {
28703
+ state.links.push(metaValue);
28704
+ }
28705
+ if (metaTypeRaw.toUpperCase() === 'AVATAR') {
28706
+ applyMetaAvatarContent(state, metaValue);
28707
+ return;
28708
+ }
28709
+ const metaType = normalizeTo_camelCase(metaTypeRaw);
28710
+ state.meta[metaType] = metaValue;
28711
+ }
28712
+ /**
28713
+ * Applies META AVATAR content into the canonical `meta.avatar` field.
28714
+ */
28715
+ function applyMetaAvatarContent(state, content) {
28716
+ const avatarVisualId = resolveAvatarVisualId(content);
28717
+ if (avatarVisualId) {
28718
+ state.meta.avatar = avatarVisualId;
28719
+ return;
28720
+ }
28721
+ delete state.meta.avatar;
28722
+ }
28723
+ /**
28724
+ * Applies META LINK content into links and the canonical `meta.link` field.
28725
+ */
28726
+ function applyMetaLinkContent(state, content) {
28727
+ const linkValue = _spaceTrim.spaceTrim(content);
28728
+ state.links.push(linkValue);
28729
+ state.meta.link = linkValue;
28730
+ }
28731
+ /**
28732
+ * Applies META DOMAIN content into the normalized `meta.domain` field.
28733
+ */
28734
+ function applyMetaDomainContent(state, content) {
28735
+ state.meta.domain = normalizeMetaDomain(content);
28736
+ }
28737
+ /**
28738
+ * Applies META IMAGE content into the canonical `meta.image` field.
28739
+ */
28740
+ function applyMetaImageContent(state, content) {
28741
+ state.meta.image = _spaceTrim.spaceTrim(content);
28742
+ }
28743
+ /**
28744
+ * Applies META DESCRIPTION content into the canonical `meta.description` field.
28745
+ */
28746
+ function applyMetaDescriptionContent(state, content) {
28747
+ state.meta.description = _spaceTrim.spaceTrim(content);
28748
+ }
28749
+ /**
28750
+ * Applies META DISCLAIMER content into the canonical `meta.disclaimer` field.
28751
+ */
28752
+ function applyMetaDisclaimerContent(state, content) {
28753
+ state.meta.disclaimer = content;
28754
+ }
28755
+ /**
28756
+ * Applies META INPUT PLACEHOLDER content into the canonical `meta.inputPlaceholder` field.
28757
+ */
28758
+ function applyMetaInputPlaceholderContent(state, content) {
28759
+ state.meta.inputPlaceholder = _spaceTrim.spaceTrim(content);
28760
+ }
28761
+ /**
28762
+ * Applies MESSAGE SUFFIX content into the canonical `meta.messageSuffix` field.
28763
+ */
28764
+ function applyMessageSuffixContent(state, content) {
28765
+ state.meta.messageSuffix = content;
28766
+ }
28767
+ /**
28768
+ * Applies META COLOR content into the canonical `meta.color` field.
28769
+ */
28770
+ function applyMetaColorContent(state, content) {
28771
+ state.meta.color = normalizeSeparator(content);
28772
+ }
28773
+ /**
28774
+ * Applies META FONT content into the canonical `meta.font` field.
28775
+ */
28776
+ function applyMetaFontContent(state, content) {
28777
+ state.meta.font = normalizeSeparator(content);
28778
+ }
28779
+ /**
28780
+ * Applies META VOICE content into the canonical `meta.voice` field.
28781
+ */
28782
+ function applyMetaVoiceContent(state, content) {
28783
+ state.meta.voice = _spaceTrim.spaceTrim(content);
28784
+ }
28785
+ /**
28786
+ * Normalizes the separator in the content
28787
+ *
28788
+ * @param content - The content to normalize
28789
+ * @returns The content with normalized separators
28790
+ */
28791
+ function normalizeSeparator(content) {
28792
+ const trimmed = _spaceTrim.spaceTrim(content);
28793
+ if (trimmed.includes(',')) {
28794
+ return trimmed;
28795
+ }
28796
+ return trimmed.split(/\s+/).join(', ');
28797
+ }
28798
+ /**
28799
+ * Normalizes META DOMAIN content to a hostname-like value when possible.
28800
+ *
28801
+ * @param content - Raw META DOMAIN content.
28802
+ * @returns Normalized domain or a trimmed fallback.
28803
+ */
28804
+ function normalizeMetaDomain(content) {
28805
+ const trimmed = _spaceTrim.spaceTrim(content);
28806
+ return normalizeDomainForMatching(trimmed) || trimmed.toLowerCase();
28807
+ }
28808
+
28809
+ /**
28810
+ * Updates sample-conversation state for communication commitments.
28811
+ *
28812
+ * @private internal utility of `parseAgentSource`
28813
+ */
28809
28814
  function consumeConversationSampleCommitment(state, commitment) {
28810
28815
  switch (commitment.type) {
28811
28816
  case 'INITIAL MESSAGE':
@@ -28827,6 +28832,76 @@
28827
28832
  return false;
28828
28833
  }
28829
28834
  }
28835
+
28836
+ /**
28837
+ * Static capability descriptors for commitments that map one-to-one to a visible capability.
28838
+ */
28839
+ const SIMPLE_CAPABILITY_BY_COMMITMENT_TYPE = {
28840
+ 'USE BROWSER': {
28841
+ type: 'browser',
28842
+ label: 'Browser',
28843
+ iconName: 'Globe',
28844
+ },
28845
+ 'USE SEARCH ENGINE': {
28846
+ type: 'search-engine',
28847
+ label: 'Internet',
28848
+ iconName: 'Search',
28849
+ },
28850
+ 'USE SEARCH': {
28851
+ type: 'search-engine',
28852
+ label: 'Internet',
28853
+ iconName: 'Search',
28854
+ },
28855
+ 'USE DEEPSEARCH': {
28856
+ type: 'search-engine',
28857
+ label: 'DeepSearch',
28858
+ iconName: 'Search',
28859
+ },
28860
+ 'USE TIME': {
28861
+ type: 'time',
28862
+ label: 'Time',
28863
+ iconName: 'Clock',
28864
+ },
28865
+ 'USE TIMEOUT': {
28866
+ type: 'timeout',
28867
+ label: 'Timers',
28868
+ iconName: 'Clock',
28869
+ },
28870
+ 'USE USER LOCATION': {
28871
+ type: 'user-location',
28872
+ label: 'User location',
28873
+ iconName: 'MapPin',
28874
+ },
28875
+ 'USE EMAIL': {
28876
+ type: 'email',
28877
+ label: 'Email',
28878
+ iconName: 'Mail',
28879
+ },
28880
+ 'USE POPUP': {
28881
+ type: 'popup',
28882
+ label: 'Popup',
28883
+ iconName: 'SquareArrowOutUpRight',
28884
+ },
28885
+ 'USE IMAGE GENERATOR': {
28886
+ type: 'image-generator',
28887
+ label: 'Image Generator',
28888
+ iconName: 'Image',
28889
+ },
28890
+ 'USE PRIVACY': {
28891
+ type: 'privacy',
28892
+ label: 'Privacy',
28893
+ iconName: 'Shield',
28894
+ },
28895
+ 'USE CALENDAR': {
28896
+ type: 'calendar',
28897
+ label: 'Calendar',
28898
+ iconName: 'Calendar',
28899
+ },
28900
+ };
28901
+ /**
28902
+ * Detects local slash-based references used by FROM and IMPORT commitments.
28903
+ */
28904
+ const LOCAL_AGENT_REFERENCE_PREFIXES = ['./', '../', '/'];
28830
28905
  /**
28831
28906
  * Creates the visible capabilities produced by one parsed commitment.
28832
28907
  *
@@ -28856,8 +28931,6 @@
28856
28931
  }
28857
28932
  /**
28858
28933
  * Clones one static capability descriptor for a simple capability commitment.
28859
- *
28860
- * @private internal utility of `parseAgentSource`
28861
28934
  */
28862
28935
  function createSimpleCapability(commitmentType) {
28863
28936
  const capability = SIMPLE_CAPABILITY_BY_COMMITMENT_TYPE[commitmentType];
@@ -28865,8 +28938,6 @@
28865
28938
  }
28866
28939
  /**
28867
28940
  * Creates the USE PROJECT capability badge.
28868
- *
28869
- * @private internal utility of `parseAgentSource`
28870
28941
  */
28871
28942
  function createProjectCapability(content) {
28872
28943
  var _a;
@@ -28880,8 +28951,6 @@
28880
28951
  }
28881
28952
  /**
28882
28953
  * Creates the FROM inheritance capability when the reference should stay visible in the profile.
28883
- *
28884
- * @private internal utility of `parseAgentSource`
28885
28954
  */
28886
28955
  function createInheritanceCapability(content) {
28887
28956
  const reference = extractFirstCommitmentLine(content);
@@ -28908,8 +28977,6 @@
28908
28977
  }
28909
28978
  /**
28910
28979
  * Creates the IMPORT capability badge.
28911
- *
28912
- * @private internal utility of `parseAgentSource`
28913
28980
  */
28914
28981
  function createImportCapability(content) {
28915
28982
  const reference = extractFirstCommitmentLine(content);
@@ -28937,8 +29004,6 @@
28937
29004
  }
28938
29005
  /**
28939
29006
  * Creates TEAM capability badges for all parsed teammates.
28940
- *
28941
- * @private internal utility of `parseAgentSource`
28942
29007
  */
28943
29008
  function createTeamCapabilities(content) {
28944
29009
  const teammates = parseTeamCommitmentContent(content);
@@ -28951,8 +29016,6 @@
28951
29016
  }
28952
29017
  /**
28953
29018
  * Creates the KNOWLEDGE capability badge and records URL-based knowledge sources.
28954
- *
28955
- * @private internal utility of `parseAgentSource`
28956
29019
  */
28957
29020
  function createKnowledgeCapability(state, content) {
28958
29021
  const trimmedContent = _spaceTrim.spaceTrim(content);
@@ -28967,8 +29030,6 @@
28967
29030
  }
28968
29031
  /**
28969
29032
  * Stores unique URL-based knowledge sources for later citation resolution.
28970
- *
28971
- * @private internal utility of `parseAgentSource`
28972
29033
  */
28973
29034
  function rememberKnowledgeSources(state, extractedUrls) {
28974
29035
  for (const extractedUrl of extractedUrls) {
@@ -28992,8 +29053,6 @@
28992
29053
  }
28993
29054
  /**
28994
29055
  * Derives the visible KNOWLEDGE badge label and icon from commitment content.
28995
- *
28996
- * @private internal utility of `parseAgentSource`
28997
29056
  */
28998
29057
  function createKnowledgeCapabilityPresentation(content, extractedUrls) {
28999
29058
  let label = content;
@@ -29026,8 +29085,6 @@
29026
29085
  }
29027
29086
  /**
29028
29087
  * Shortens text-only KNOWLEDGE commitments into the same preview label as before.
29029
- *
29030
- * @private internal utility of `parseAgentSource`
29031
29088
  */
29032
29089
  function createKnowledgeTextLabel(content) {
29033
29090
  const words = content.split(/\s+/);
@@ -29037,185 +29094,88 @@
29037
29094
  return content;
29038
29095
  }
29039
29096
  /**
29040
- * Applies META-style commitments that mutate parsed profile metadata.
29041
- *
29042
- * @private internal utility of `parseAgentSource`
29043
- */
29044
- function applyMetaCommitment(state, commitment) {
29045
- const applyMetaContent = META_COMMITMENT_APPLIERS[commitment.type];
29046
- if (applyMetaContent) {
29047
- applyMetaContent(state, commitment.content);
29048
- return;
29049
- }
29050
- if (commitment.type === 'META') {
29051
- applyGenericMetaCommitment(state, commitment.content);
29052
- }
29053
- }
29054
- /**
29055
- * Applies the generic META commitment form (`META TYPE value`).
29056
- *
29057
- * @private internal utility of `parseAgentSource`
29058
- */
29059
- function applyGenericMetaCommitment(state, content) {
29060
- const metaTypeRaw = content.split(' ')[0] || 'NONE';
29061
- const metaValue = _spaceTrim.spaceTrim(content.substring(metaTypeRaw.length));
29062
- if (metaTypeRaw === 'LINK') {
29063
- state.links.push(metaValue);
29064
- }
29065
- if (metaTypeRaw.toUpperCase() === 'AVATAR') {
29066
- applyMetaAvatarContent(state, metaValue);
29067
- return;
29068
- }
29069
- const metaType = normalizeTo_camelCase(metaTypeRaw);
29070
- state.meta[metaType] = metaValue;
29071
- }
29072
- /**
29073
- * Applies META AVATAR content into the canonical `meta.avatar` field.
29074
- *
29075
- * @private internal utility of `parseAgentSource`
29076
- */
29077
- function applyMetaAvatarContent(state, content) {
29078
- const avatarVisualId = resolveAvatarVisualId(content);
29079
- if (avatarVisualId) {
29080
- state.meta.avatar = avatarVisualId;
29081
- return;
29082
- }
29083
- delete state.meta.avatar;
29084
- }
29085
- /**
29086
- * Applies META LINK content into links and the canonical `meta.link` field.
29087
- *
29088
- * @private internal utility of `parseAgentSource`
29089
- */
29090
- function applyMetaLinkContent(state, content) {
29091
- const linkValue = _spaceTrim.spaceTrim(content);
29092
- state.links.push(linkValue);
29093
- state.meta.link = linkValue;
29094
- }
29095
- /**
29096
- * Applies META DOMAIN content into the normalized `meta.domain` field.
29097
- *
29098
- * @private internal utility of `parseAgentSource`
29099
- */
29100
- function applyMetaDomainContent(state, content) {
29101
- state.meta.domain = normalizeMetaDomain(content);
29102
- }
29103
- /**
29104
- * Applies META IMAGE content into the canonical `meta.image` field.
29105
- *
29106
- * @private internal utility of `parseAgentSource`
29107
- */
29108
- function applyMetaImageContent(state, content) {
29109
- state.meta.image = _spaceTrim.spaceTrim(content);
29110
- }
29111
- /**
29112
- * Applies META DESCRIPTION content into the canonical `meta.description` field.
29113
- *
29114
- * @private internal utility of `parseAgentSource`
29115
- */
29116
- function applyMetaDescriptionContent(state, content) {
29117
- state.meta.description = _spaceTrim.spaceTrim(content);
29118
- }
29119
- /**
29120
- * Applies META DISCLAIMER content into the canonical `meta.disclaimer` field.
29121
- *
29122
- * @private internal utility of `parseAgentSource`
29123
- */
29124
- function applyMetaDisclaimerContent(state, content) {
29125
- state.meta.disclaimer = content;
29126
- }
29127
- /**
29128
- * Applies META INPUT PLACEHOLDER content into the canonical `meta.inputPlaceholder` field.
29129
- *
29130
- * @private internal utility of `parseAgentSource`
29131
- */
29132
- function applyMetaInputPlaceholderContent(state, content) {
29133
- state.meta.inputPlaceholder = _spaceTrim.spaceTrim(content);
29134
- }
29135
- /**
29136
- * Applies MESSAGE SUFFIX content into the canonical `meta.messageSuffix` field.
29137
- *
29138
- * @private internal utility of `parseAgentSource`
29139
- */
29140
- function applyMessageSuffixContent(state, content) {
29141
- state.meta.messageSuffix = content;
29142
- }
29143
- /**
29144
- * Applies META COLOR content into the canonical `meta.color` field.
29145
- *
29146
- * @private internal utility of `parseAgentSource`
29147
- */
29148
- function applyMetaColorContent(state, content) {
29149
- state.meta.color = normalizeSeparator(content);
29150
- }
29151
- /**
29152
- * Applies META FONT content into the canonical `meta.font` field.
29153
- *
29154
- * @private internal utility of `parseAgentSource`
29155
- */
29156
- function applyMetaFontContent(state, content) {
29157
- state.meta.font = normalizeSeparator(content);
29158
- }
29159
- /**
29160
- * Applies META VOICE content into the canonical `meta.voice` field.
29161
- *
29162
- * @private internal utility of `parseAgentSource`
29163
- */
29164
- function applyMetaVoiceContent(state, content) {
29165
- state.meta.voice = _spaceTrim.spaceTrim(content);
29166
- }
29167
- /**
29168
- * Ensures the parsed profile always exposes a fullname value.
29169
- *
29170
- * @private internal utility of `parseAgentSource`
29171
- */
29172
- function ensureMetaFullname(meta, fallbackFullname) {
29173
- if (!meta.fullname) {
29174
- meta.fullname = fallbackFullname;
29175
- }
29176
- }
29177
- /**
29178
- * Extracts the first logical line from multiline commitment content.
29179
- *
29180
- * @private internal utility of `parseAgentSource`
29097
+ * Extracts the first logical line from multiline commitment content.
29181
29098
  */
29182
29099
  function extractFirstCommitmentLine(content) {
29183
29100
  return _spaceTrim.spaceTrim(content).split(/\r?\n/)[0] || '';
29184
29101
  }
29185
29102
  /**
29186
29103
  * Detects local FROM/IMPORT references that should use local-link labels and icons.
29187
- *
29188
- * @private internal utility of `parseAgentSource`
29189
29104
  */
29190
29105
  function isLocalAgentReference(reference) {
29191
29106
  return LOCAL_AGENT_REFERENCE_PREFIXES.some((prefix) => reference.startsWith(prefix));
29192
29107
  }
29108
+
29193
29109
  /**
29194
- * Normalizes the separator in the content
29195
- *
29196
- * @param content - The content to normalize
29197
- * @returns The content with normalized separators
29110
+ * Collects capability, sample, meta, link, and knowledge-source data from commitments.
29198
29111
  *
29199
29112
  * @private internal utility of `parseAgentSource`
29200
29113
  */
29201
- function normalizeSeparator(content) {
29202
- const trimmed = _spaceTrim.spaceTrim(content);
29203
- if (trimmed.includes(',')) {
29204
- return trimmed;
29114
+ function extractParsedAgentProfile(commitments) {
29115
+ const state = {
29116
+ meta: {},
29117
+ links: [],
29118
+ capabilities: [],
29119
+ samples: [],
29120
+ knowledgeSources: [],
29121
+ pendingUserMessage: null,
29122
+ knownKnowledgeSourceUrls: new Set(),
29123
+ };
29124
+ for (const commitment of commitments) {
29125
+ processParsedCommitment(state, commitment);
29205
29126
  }
29206
- return trimmed.split(/\s+/).join(', ');
29127
+ return {
29128
+ meta: state.meta,
29129
+ links: state.links,
29130
+ capabilities: state.capabilities,
29131
+ samples: state.samples,
29132
+ knowledgeSources: state.knowledgeSources,
29133
+ };
29207
29134
  }
29208
29135
  /**
29209
- * Normalizes META DOMAIN content to a hostname-like value when possible.
29136
+ * Processes one parsed commitment through the sample, capability, and meta stages.
29137
+ */
29138
+ function processParsedCommitment(state, commitment) {
29139
+ if (consumeConversationSampleCommitment(state, commitment)) {
29140
+ return;
29141
+ }
29142
+ const capabilities = createCapabilitiesFromCommitment(state, commitment);
29143
+ if (capabilities.length > 0) {
29144
+ state.capabilities.push(...capabilities);
29145
+ return;
29146
+ }
29147
+ applyMetaCommitment(state, commitment);
29148
+ }
29149
+
29150
+ /**
29151
+ * Parses basic information from agent source
29210
29152
  *
29211
- * @param content - Raw META DOMAIN content.
29212
- * @returns Normalized domain or a trimmed fallback.
29153
+ * There are 2 similar functions:
29154
+ * - `parseAgentSource` which is a lightweight parser for agent source, it parses basic information and its purpose is to be quick and synchronous. The commitments there are hardcoded.
29155
+ * - `createAgentModelRequirements` which is an asynchronous function that creates model requirements it applies each commitment one by one and works asynchronously.
29213
29156
  *
29214
- * @private internal utility of `parseAgentSource`
29157
+ * @public exported from `@promptbook/core`
29215
29158
  */
29216
- function normalizeMetaDomain(content) {
29217
- const trimmed = _spaceTrim.spaceTrim(content);
29218
- return normalizeDomainForMatching(trimmed) || trimmed.toLowerCase();
29159
+ function parseAgentSource(agentSource) {
29160
+ const parseResult = parseAgentSourceWithCommitments(agentSource);
29161
+ const resolvedAgentName = parseResult.agentName || createDefaultAgentName(agentSource);
29162
+ const personaDescription = extractAgentProfileText(parseResult.commitments);
29163
+ const initialMessage = extractInitialMessage(parseResult.commitments);
29164
+ const parsedProfile = extractParsedAgentProfile(parseResult.commitments);
29165
+ ensureMetaFullname(parsedProfile.meta, resolvedAgentName);
29166
+ return {
29167
+ agentName: normalizeAgentName(resolvedAgentName),
29168
+ agentHash: computeAgentHash(agentSource),
29169
+ permanentId: parsedProfile.meta.id,
29170
+ personaDescription,
29171
+ initialMessage,
29172
+ meta: parsedProfile.meta,
29173
+ links: parsedProfile.links,
29174
+ parameters: parseParameters(agentSource),
29175
+ capabilities: parsedProfile.capabilities,
29176
+ samples: parsedProfile.samples,
29177
+ knowledgeSources: parsedProfile.knowledgeSources,
29178
+ };
29219
29179
  }
29220
29180
  // TODO: [🕛] Unite `AgentBasicInformation`, `ChatParticipant`, `LlmExecutionTools` + `LlmToolsMetadata`
29221
29181
 
@@ -29233,395 +29193,96 @@
29233
29193
  just(false) /* <- Note: [⛹️] How to deal with commitment aliases */) {
29234
29194
  throw new UnexpectedError(`Duplicate tool function name detected: \`${funcName}\` provided by commitment \`${commitmentDefinition.type}\``);
29235
29195
  }
29236
- allToolTitles[funcName] = title;
29237
- }
29238
- }
29239
- return allToolTitles;
29240
- }
29241
-
29242
- /**
29243
- * Restricts an Updatable to a (2) BehaviorSubject variant
29244
- *
29245
- * @see Updatable
29246
- *
29247
- * @private internal utility <- TODO: [🧠] Maybe export from `@promptbook/types`
29248
- */
29249
- function asUpdatableSubject(value) {
29250
- if (value instanceof rxjs.BehaviorSubject) {
29251
- return value;
29252
- }
29253
- else if (Array.isArray(value)) {
29254
- if (value.length !== 2) {
29255
- throw new TypeError('`asUpdatableSubject`: Invalid tuple length, expected 2 elements');
29256
- }
29257
- if (typeof value[1] !== 'function') {
29258
- throw new TypeError('`asUpdatableSubject`: Invalid tuple, expected second element to be a function');
29259
- }
29260
- const [theValue, setValue] = value;
29261
- const subject = new rxjs.BehaviorSubject(theValue);
29262
- subject.subscribe((newValue) => {
29263
- setValue(newValue);
29264
- });
29265
- return subject;
29266
- }
29267
- else {
29268
- return new rxjs.BehaviorSubject(value);
29269
- }
29270
- }
29271
- // TODO: [🧠] Maybe `BehaviorSubject` is too heavy for this use case, maybe just tuple `[value,setValue]` is enough
29272
-
29273
- /**
29274
- * Creates an empty/basic agent model requirements object
29275
- * This serves as the starting point for the reduce-like pattern
29276
- * where each commitment applies its changes to build the final requirements
29277
- *
29278
- * @public exported from `@promptbook/core`
29279
- */
29280
- function createEmptyAgentModelRequirements() {
29281
- return {
29282
- systemMessage: '',
29283
- promptSuffix: '',
29284
- // modelName: 'gpt-5',
29285
- modelName: 'gpt-5.4-mini',
29286
- temperature: 0.7,
29287
- topP: 0.9,
29288
- topK: 50,
29289
- parentAgentUrl: null,
29290
- isClosed: false,
29291
- };
29292
- }
29293
- /**
29294
- * Creates a basic agent model requirements with just the agent name
29295
- * This is used when we have an agent name but no commitments
29296
- *
29297
- * @public exported from `@promptbook/core`
29298
- */
29299
- function createBasicAgentModelRequirements(agentName) {
29300
- const empty = createEmptyAgentModelRequirements();
29301
- return {
29302
- ...empty,
29303
- systemMessage: `You are ${agentName || 'AI Agent'}`,
29304
- };
29305
- }
29306
- // TODO: [🐤] Deduplicate `AgentModelRequirements` and `ModelRequirements` model requirements
29307
-
29308
- /**
29309
- * Gets a commitment definition by its type
29310
- *
29311
- * @param type The commitment type to look up
29312
- * @returns The commitment definition or null if not found
29313
- *
29314
- * @public exported from `@promptbook/core`
29315
- */
29316
- function getCommitmentDefinition(type) {
29317
- return COMMITMENT_REGISTRY.find((commitmentDefinition) => commitmentDefinition.type === type) || null;
29318
- }
29319
-
29320
- /**
29321
- * Plugin for importing agent books *(`.book` files)*
29322
- *
29323
- * @private [🥝] Maybe export the import plugins through some package
29324
- */
29325
- const AgentFileImportPlugin = {
29326
- name: 'agent-file-import-plugin',
29327
- canImport(mimeType) {
29328
- // [🧠] Should we have a specific MIME type for agent books?
29329
- // For now, let's assume it's identified by .book extension or certain MIME types if provided
29330
- return mimeType === 'text/x-promptbook' || mimeType === 'application/x-promptbook';
29331
- },
29332
- import(content) {
29333
- const parseResult = parseAgentSourceWithCommitments(content);
29334
- // Bring only the agent corpus (non-commitment lines and relevant commitments)
29335
- // Stripping the agent name (which is usually the first line)
29336
- const corpus = parseResult.nonCommitmentLines
29337
- .filter((line, index) => index > 0 || !parseResult.agentName)
29338
- .join('\n')
29339
- .trim();
29340
- // Also include relevant commitments that make up the "corpus" of the agent
29341
- // For example PERSONA, RULE, KNOWLEDGE
29342
- const relevantCommitments = parseResult.commitments
29343
- .filter((c) => ['PERSONA', 'RULE', 'KNOWLEDGE'].includes(c.type))
29344
- .map((c) => `${c.type} ${c.content}`)
29345
- .join('\n\n');
29346
- return _spaceTrim.spaceTrim((block) => `
29347
- ${block(relevantCommitments)}
29348
-
29349
- ${block(corpus)}
29350
- `).trim();
29351
- },
29352
- };
29353
-
29354
- /**
29355
- * Plugin for importing JSON files
29356
- *
29357
- * @private [🥝] Maybe export the import plugins through some package
29358
- */
29359
- const JsonFileImportPlugin = {
29360
- name: 'json-file-import-plugin',
29361
- canImport(mimeType) {
29362
- return mimeType === 'application/json' || mimeType.endsWith('+json');
29363
- },
29364
- import(content) {
29365
- try {
29366
- const json = JSON.parse(content);
29367
- const formattedJson = JSON.stringify(json, null, 4);
29368
- return `\`\`\`json\n${formattedJson}\n\`\`\``;
29369
- }
29370
- catch (error) {
29371
- // If JSON is invalid, still import it but maybe not as pretty JSON
29372
- return `\`\`\`json\n${content}\n\`\`\``;
29373
- }
29374
- },
29375
- };
29376
-
29377
- /**
29378
- * Plugin for importing generic text files
29379
- *
29380
- * @private [🥝] Maybe export the import plugins through some package
29381
- */
29382
- const TextFileImportPlugin = {
29383
- name: 'text-file-import-plugin',
29384
- canImport(mimeType) {
29385
- return (mimeType === 'text/plain' ||
29386
- mimeType === 'text/markdown' ||
29387
- mimeType === 'text/x-typescript' ||
29388
- mimeType === 'text/javascript' ||
29389
- mimeType === 'text/css' ||
29390
- mimeType === 'text/html' ||
29391
- mimeType.startsWith('text/'));
29392
- },
29393
- import(content, mimeType) {
29394
- const extension = mimeTypeToExtension(mimeType);
29395
- const codeBlockType = extension || 'txt';
29396
- return `\`\`\`${codeBlockType}\n${content}\n\`\`\``;
29397
- },
29398
- };
29399
-
29400
- /**
29401
- * All available file import plugins
29402
- *
29403
- * @private [🥝] Maybe export the import plugins through some package
29404
- */
29405
- const $fileImportPlugins = [
29406
- AgentFileImportPlugin,
29407
- JsonFileImportPlugin,
29408
- TextFileImportPlugin,
29409
- ];
29410
-
29411
- /**
29412
- * Removes single-hash comment lines (`# Comment`) from a system message
29413
- * This is used to clean up the final system message before sending it to the AI model
29414
- * while preserving the original content with comments in metadata
29415
- *
29416
- * @param systemMessage The system message that may contain comment lines
29417
- * @returns The system message with single-hash comment lines removed
29418
- *
29419
- * @private - TODO: [🧠] Maybe should be public?
29420
- */
29421
- function removeCommentsFromSystemMessage(systemMessage) {
29422
- if (!systemMessage) {
29423
- return systemMessage;
29424
- }
29425
- const lines = systemMessage.split(/\r?\n/);
29426
- const filteredLines = lines.filter((line) => {
29427
- const trimmedLine = line.trim();
29428
- // Remove only single-hash comment markers (`# Comment`) and keep markdown headings (`## Heading`).
29429
- return !/^#(?!#)\s/.test(trimmedLine);
29430
- });
29431
- return filteredLines.join('\n').trim();
29432
- }
29433
-
29434
- /**
29435
- * Commitment types whose content may contain compact agent references that must be resolved before applying the commitment.
29436
- *
29437
- * @private internal constant of `createAgentModelRequirementsWithCommitments`
29438
- */
29439
- const COMMITMENTS_WITH_AGENT_REFERENCES = new Set(['FROM', 'IMPORT', 'IMPORTS', 'TEAM']);
29440
- /**
29441
- * DELETE-like commitment types that invalidate earlier tagged commitments.
29442
- *
29443
- * @private internal constant of `createAgentModelRequirementsWithCommitments`
29444
- */
29445
- const DELETE_COMMITMENT_TYPES = new Set(['DELETE', 'CANCEL', 'DISCARD', 'REMOVE']);
29446
- /**
29447
- * Commitments whose earlier occurrences are overwritten by the last occurrence in source order.
29448
- *
29449
- * @private internal constant of `createAgentModelRequirementsWithCommitments`
29450
- */
29451
- const OVERWRITTEN_COMMITMENT_GROUP_BY_TYPE = new Map([
29452
- ['GOAL', 'GOAL'],
29453
- ['GOALS', 'GOAL'],
29454
- ]);
29455
- /**
29456
- * Regex pattern matching markdown horizontal lines that should not be copied into the final system message.
29457
- *
29458
- * @private internal constant of `createAgentModelRequirementsWithCommitments`
29459
- */
29460
- const HORIZONTAL_LINE_PATTERN = /^[\s]*[-_*][\s]*[-_*][\s]*[-_*][\s]*[-_*]*[\s]*$/;
29461
- /**
29462
- * MIME type prefixes treated as binary and therefore not eligible for text import plugins.
29463
- *
29464
- * @private internal constant of `createAgentModelRequirementsWithCommitments`
29465
- */
29466
- const BINARY_MIME_TYPE_PREFIXES = [
29467
- 'image/',
29468
- 'video/',
29469
- 'audio/',
29470
- 'application/octet-stream',
29471
- 'application/pdf',
29472
- 'application/zip',
29473
- ];
29474
- /**
29475
- * Returns a safe fallback content when a resolver fails to transform a reference commitment.
29476
- *
29477
- * @param commitmentType - Commitment being resolved.
29478
- * @param originalContent - Original unresolved commitment content.
29479
- * @returns Fallback content that keeps requirement creation resilient.
29480
- *
29481
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29482
- */
29483
- function getSafeReferenceCommitmentFallback(commitmentType, originalContent) {
29484
- if (commitmentType === 'FROM') {
29485
- return 'VOID';
29486
- }
29487
- if (commitmentType === 'IMPORT' || commitmentType === 'IMPORTS' || commitmentType === 'TEAM') {
29488
- return '';
29489
- }
29490
- return originalContent;
29491
- }
29492
- /**
29493
- * Creates agent model requirements by parsing commitments, applying them in source order,
29494
- * and finalizing derived sections such as imports, example interactions, and inline knowledge uploads.
29495
- *
29496
- * @param agentSource - Agent source book to parse.
29497
- * @param modelName - Optional override for the agent model name.
29498
- * @param options - Additional options such as reference and teammate resolvers.
29499
- * @returns Fully prepared model requirements for the parsed agent source.
29500
- *
29501
- * @private internal utility of `createAgentModelRequirements`
29502
- */
29503
- async function createAgentModelRequirementsWithCommitments(agentSource, modelName, options) {
29504
- const parseResult = parseAgentSourceWithCommitments(agentSource);
29505
- const filteredCommitments = filterOverwrittenCommitments(filterDeletedCommitments(parseResult.commitments));
29506
- let requirements = createInitialAgentModelRequirements(parseResult.agentName, modelName);
29507
- requirements = await applyCommitmentsToRequirements(requirements, filteredCommitments, options);
29508
- requirements = aggregateUseCommitmentSystemMessages(requirements, filteredCommitments);
29509
- requirements = await importReferencedFiles(requirements);
29510
- requirements = appendMcpServers(requirements, agentSource);
29511
- requirements = appendNonCommitmentContent(requirements, parseResult);
29512
- requirements = appendExampleInteractions(requirements, parseResult);
29513
- requirements = await applyPendingInlineKnowledgeSources(requirements, options === null || options === void 0 ? void 0 : options.inlineKnowledgeSourceUploader);
29514
- return finalizeRequirements(requirements);
29515
- }
29516
- /**
29517
- * Removes earlier commitments that are overwritten by later commitments of the same semantic group.
29518
- *
29519
- * This currently keeps only the last `GOAL` / `GOALS` commitment so inheritance rewrites
29520
- * and multi-goal sources expose one effective goal to the runtime.
29521
- *
29522
- * @param commitments - Parsed commitments after DELETE-like filtering.
29523
- * @returns Commitments with overwritten entries removed while preserving source order.
29524
- *
29525
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29526
- */
29527
- function filterOverwrittenCommitments(commitments) {
29528
- const seenOverwriteGroups = new Set();
29529
- const keptCommitments = [];
29530
- for (let index = commitments.length - 1; index >= 0; index--) {
29531
- const commitment = commitments[index];
29532
- const overwriteGroup = OVERWRITTEN_COMMITMENT_GROUP_BY_TYPE.get(commitment.type);
29533
- if (!overwriteGroup) {
29534
- keptCommitments.push(commitment);
29535
- continue;
29536
- }
29537
- if (seenOverwriteGroups.has(overwriteGroup)) {
29538
- continue;
29539
- }
29540
- seenOverwriteGroups.add(overwriteGroup);
29541
- keptCommitments.push(commitment);
29542
- }
29543
- return keptCommitments.reverse();
29544
- }
29545
- /**
29546
- * Creates the initial requirements object with the parsed agent name stored in metadata and an optional model override.
29547
- *
29548
- * @param agentName - Parsed agent name from the source prelude.
29549
- * @param modelName - Optional explicit model name override.
29550
- * @returns Initial requirements before any commitment is applied.
29551
- *
29552
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29553
- */
29554
- function createInitialAgentModelRequirements(agentName, modelName) {
29555
- const initialRequirements = createBasicAgentModelRequirements(agentName);
29556
- const requirementsWithMetadata = {
29557
- ...initialRequirements,
29558
- _metadata: {
29559
- ...initialRequirements._metadata,
29560
- agentName,
29561
- },
29562
- };
29563
- if (!modelName) {
29564
- return requirementsWithMetadata;
29196
+ allToolTitles[funcName] = title;
29197
+ }
29565
29198
  }
29566
- return {
29567
- ...requirementsWithMetadata,
29568
- modelName,
29569
- };
29199
+ return allToolTitles;
29570
29200
  }
29201
+
29571
29202
  /**
29572
- * Applies DELETE-like invalidation commitments and returns only commitments that should continue through the pipeline.
29203
+ * Restricts an Updatable to a (2) BehaviorSubject variant
29573
29204
  *
29574
- * @param commitments - Parsed commitments in original source order.
29575
- * @returns Filtered commitments with earlier deleted items removed.
29205
+ * @see Updatable
29576
29206
  *
29577
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29207
+ * @private internal utility <- TODO: [🧠] Maybe export from `@promptbook/types`
29578
29208
  */
29579
- function filterDeletedCommitments(commitments) {
29580
- const filteredCommitments = [];
29581
- for (const commitment of commitments) {
29582
- if (!isDeleteCommitmentType(commitment.type)) {
29583
- filteredCommitments.push(commitment);
29584
- continue;
29585
- }
29586
- const targetParameterNames = getCommitmentParameterNames(commitment.content);
29587
- if (targetParameterNames.length === 0) {
29588
- continue;
29209
+ function asUpdatableSubject(value) {
29210
+ if (value instanceof rxjs.BehaviorSubject) {
29211
+ return value;
29212
+ }
29213
+ else if (Array.isArray(value)) {
29214
+ if (value.length !== 2) {
29215
+ throw new TypeError('`asUpdatableSubject`: Invalid tuple length, expected 2 elements');
29589
29216
  }
29590
- for (let index = filteredCommitments.length - 1; index >= 0; index--) {
29591
- const previousCommitment = filteredCommitments[index];
29592
- const previousParameterNames = getCommitmentParameterNames(previousCommitment.content);
29593
- const isTargeted = previousParameterNames.some((parameterName) => targetParameterNames.includes(parameterName));
29594
- if (isTargeted) {
29595
- filteredCommitments.splice(index, 1);
29596
- }
29217
+ if (typeof value[1] !== 'function') {
29218
+ throw new TypeError('`asUpdatableSubject`: Invalid tuple, expected second element to be a function');
29597
29219
  }
29220
+ const [theValue, setValue] = value;
29221
+ const subject = new rxjs.BehaviorSubject(theValue);
29222
+ subject.subscribe((newValue) => {
29223
+ setValue(newValue);
29224
+ });
29225
+ return subject;
29226
+ }
29227
+ else {
29228
+ return new rxjs.BehaviorSubject(value);
29598
29229
  }
29599
- return filteredCommitments;
29600
29230
  }
29231
+ // TODO: [🧠] Maybe `BehaviorSubject` is too heavy for this use case, maybe just tuple `[value,setValue]` is enough
29232
+
29601
29233
  /**
29602
- * Checks whether a commitment type behaves like DELETE and therefore invalidates earlier tagged commitments.
29234
+ * Creates an empty/basic agent model requirements object
29235
+ * This serves as the starting point for the reduce-like pattern
29236
+ * where each commitment applies its changes to build the final requirements
29603
29237
  *
29604
- * @param commitmentType - Commitment type to check.
29605
- * @returns `true` when the commitment removes prior tagged commitments.
29238
+ * @public exported from `@promptbook/core`
29239
+ */
29240
+ function createEmptyAgentModelRequirements() {
29241
+ return {
29242
+ systemMessage: '',
29243
+ promptSuffix: '',
29244
+ // modelName: 'gpt-5',
29245
+ modelName: 'gpt-5.4-mini',
29246
+ temperature: 0.7,
29247
+ topP: 0.9,
29248
+ topK: 50,
29249
+ parentAgentUrl: null,
29250
+ isClosed: false,
29251
+ };
29252
+ }
29253
+ /**
29254
+ * Creates a basic agent model requirements with just the agent name
29255
+ * This is used when we have an agent name but no commitments
29606
29256
  *
29607
- * @private internal utility of `filterDeletedCommitments`
29257
+ * @public exported from `@promptbook/core`
29608
29258
  */
29609
- function isDeleteCommitmentType(commitmentType) {
29610
- return DELETE_COMMITMENT_TYPES.has(commitmentType);
29259
+ function createBasicAgentModelRequirements(agentName) {
29260
+ const empty = createEmptyAgentModelRequirements();
29261
+ return {
29262
+ ...empty,
29263
+ systemMessage: `You are ${agentName || 'AI Agent'}`,
29264
+ };
29611
29265
  }
29266
+ // TODO: [🐤] Deduplicate `AgentModelRequirements` and `ModelRequirements` model requirements
29267
+
29612
29268
  /**
29613
- * Extracts normalized parameter names used for DELETE-like invalidation matching.
29269
+ * Gets a commitment definition by its type
29614
29270
  *
29615
- * @param content - Commitment content to parse.
29616
- * @returns Lower-cased non-empty parameter names.
29271
+ * @param type The commitment type to look up
29272
+ * @returns The commitment definition or null if not found
29617
29273
  *
29618
- * @private internal utility of `filterDeletedCommitments`
29274
+ * @public exported from `@promptbook/core`
29619
29275
  */
29620
- function getCommitmentParameterNames(content) {
29621
- return parseParameters(content)
29622
- .map((parameter) => parameter.name.trim().toLowerCase())
29623
- .filter(Boolean);
29276
+ function getCommitmentDefinition(type) {
29277
+ return COMMITMENT_REGISTRY.find((commitmentDefinition) => commitmentDefinition.type === type) || null;
29624
29278
  }
29279
+
29280
+ /**
29281
+ * Commitment types whose content may contain compact agent references that must be resolved before applying the commitment.
29282
+ *
29283
+ * @private internal constant of `applyCommitmentsToAgentModelRequirements`
29284
+ */
29285
+ const COMMITMENTS_WITH_AGENT_REFERENCES = new Set(['FROM', 'IMPORT', 'IMPORTS', 'TEAM']);
29625
29286
  /**
29626
29287
  * Applies parsed commitments one by one while keeping the per-commitment steps focused and easy to follow.
29627
29288
  *
@@ -29630,9 +29291,9 @@
29630
29291
  * @param options - Optional reference and teammate resolvers.
29631
29292
  * @returns Requirements after all applicable commitments are processed.
29632
29293
  *
29633
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29294
+ * @private function of `createAgentModelRequirementsWithCommitments`
29634
29295
  */
29635
- async function applyCommitmentsToRequirements(requirements, commitments, options) {
29296
+ async function applyCommitmentsToAgentModelRequirements(requirements, commitments, options) {
29636
29297
  for (const [index, commitment] of commitments.entries()) {
29637
29298
  if (shouldSkipCommitmentApplication(commitment, index, commitments.length)) {
29638
29299
  continue;
@@ -29650,7 +29311,7 @@
29650
29311
  * @param agentReferenceResolver - Optional resolver for compact agent references.
29651
29312
  * @returns Original or resolved commitment content.
29652
29313
  *
29653
- * @private internal utility of `applyCommitmentsToRequirements`
29314
+ * @private internal utility of `applyCommitmentsToAgentModelRequirements`
29654
29315
  */
29655
29316
  async function resolveCommitmentContent(commitment, agentReferenceResolver) {
29656
29317
  if (!agentReferenceResolver || !isAgentReferenceCommitment(commitment.type)) {
@@ -29664,6 +29325,24 @@
29664
29325
  return getSafeReferenceCommitmentFallback(commitment.type, commitment.content);
29665
29326
  }
29666
29327
  }
29328
+ /**
29329
+ * Returns a safe fallback content when a resolver fails to transform a reference commitment.
29330
+ *
29331
+ * @param commitmentType - Commitment being resolved.
29332
+ * @param originalContent - Original unresolved commitment content.
29333
+ * @returns Fallback content that keeps requirement creation resilient.
29334
+ *
29335
+ * @private internal utility of `applyCommitmentsToAgentModelRequirements`
29336
+ */
29337
+ function getSafeReferenceCommitmentFallback(commitmentType, originalContent) {
29338
+ if (commitmentType === 'FROM') {
29339
+ return 'VOID';
29340
+ }
29341
+ if (commitmentType === 'IMPORT' || commitmentType === 'IMPORTS' || commitmentType === 'TEAM') {
29342
+ return '';
29343
+ }
29344
+ return originalContent;
29345
+ }
29667
29346
  /**
29668
29347
  * Checks whether the commitment content may need agent-reference resolution before application.
29669
29348
  *
@@ -29683,7 +29362,7 @@
29683
29362
  * @param commitmentCount - Total number of filtered commitments.
29684
29363
  * @returns `true` when the commitment should not be applied.
29685
29364
  *
29686
- * @private internal utility of `applyCommitmentsToRequirements`
29365
+ * @private internal utility of `applyCommitmentsToAgentModelRequirements`
29687
29366
  */
29688
29367
  function shouldSkipCommitmentApplication(commitment, commitmentIndex, commitmentCount) {
29689
29368
  return commitment.type === 'CLOSED' && commitmentIndex !== commitmentCount - 1;
@@ -29697,7 +29376,7 @@
29697
29376
  * @param options - Optional teammate profile resolvers.
29698
29377
  * @returns Requirements with pre-resolved teammate profiles stored in metadata when possible.
29699
29378
  *
29700
- * @private internal utility of `applyCommitmentsToRequirements`
29379
+ * @private internal utility of `applyCommitmentsToAgentModelRequirements`
29701
29380
  */
29702
29381
  async function preResolveTeammateProfilesForTeamCommitment(requirements, commitment, commitmentContent, options) {
29703
29382
  var _a;
@@ -29736,36 +29415,163 @@
29736
29415
  * @param metadata - Current requirements metadata.
29737
29416
  * @returns Mutable copy of the cached teammate profile map.
29738
29417
  *
29739
- * @private internal utility of `preResolveTeammateProfilesForTeamCommitment`
29418
+ * @private internal utility of `preResolveTeammateProfilesForTeamCommitment`
29419
+ */
29420
+ function clonePreResolvedTeammateProfiles(metadata) {
29421
+ var _a;
29422
+ return {
29423
+ ...((_a = metadata === null || metadata === void 0 ? void 0 : metadata.preResolvedTeammateProfiles) !== null && _a !== void 0 ? _a : {}),
29424
+ };
29425
+ }
29426
+ /**
29427
+ * Applies the registered commitment definition while isolating the failure handling from the main loop.
29428
+ *
29429
+ * @param requirements - Current requirements snapshot.
29430
+ * @param commitment - Commitment whose definition should be applied.
29431
+ * @param commitmentContent - Final content passed into the definition.
29432
+ * @returns Updated requirements, or the original requirements when the commitment fails.
29433
+ *
29434
+ * @private internal utility of `applyCommitmentsToAgentModelRequirements`
29435
+ */
29436
+ function applyCommitmentDefinitionSafely(requirements, commitment, commitmentContent) {
29437
+ const definition = getCommitmentDefinition(commitment.type);
29438
+ if (!definition) {
29439
+ return requirements;
29440
+ }
29441
+ try {
29442
+ return definition.applyToAgentModelRequirements(requirements, commitmentContent);
29443
+ }
29444
+ catch (error) {
29445
+ console.warn(`Failed to apply commitment ${commitment.type}:`, error);
29446
+ return requirements;
29447
+ }
29448
+ }
29449
+
29450
+ /**
29451
+ * Plugin for importing agent books *(`.book` files)*
29452
+ *
29453
+ * @private [🥝] Maybe export the import plugins through some package
29454
+ */
29455
+ const AgentFileImportPlugin = {
29456
+ name: 'agent-file-import-plugin',
29457
+ canImport(mimeType) {
29458
+ // [🧠] Should we have a specific MIME type for agent books?
29459
+ // For now, let's assume it's identified by .book extension or certain MIME types if provided
29460
+ return mimeType === 'text/x-promptbook' || mimeType === 'application/x-promptbook';
29461
+ },
29462
+ import(content) {
29463
+ const parseResult = parseAgentSourceWithCommitments(content);
29464
+ // Bring only the agent corpus (non-commitment lines and relevant commitments)
29465
+ // Stripping the agent name (which is usually the first line)
29466
+ const corpus = parseResult.nonCommitmentLines
29467
+ .filter((line, index) => index > 0 || !parseResult.agentName)
29468
+ .join('\n')
29469
+ .trim();
29470
+ // Also include relevant commitments that make up the "corpus" of the agent
29471
+ // For example PERSONA, RULE, KNOWLEDGE
29472
+ const relevantCommitments = parseResult.commitments
29473
+ .filter((c) => ['PERSONA', 'RULE', 'KNOWLEDGE'].includes(c.type))
29474
+ .map((c) => `${c.type} ${c.content}`)
29475
+ .join('\n\n');
29476
+ return _spaceTrim.spaceTrim((block) => `
29477
+ ${block(relevantCommitments)}
29478
+
29479
+ ${block(corpus)}
29480
+ `).trim();
29481
+ },
29482
+ };
29483
+
29484
+ /**
29485
+ * Plugin for importing JSON files
29486
+ *
29487
+ * @private [🥝] Maybe export the import plugins through some package
29488
+ */
29489
+ const JsonFileImportPlugin = {
29490
+ name: 'json-file-import-plugin',
29491
+ canImport(mimeType) {
29492
+ return mimeType === 'application/json' || mimeType.endsWith('+json');
29493
+ },
29494
+ import(content) {
29495
+ try {
29496
+ const json = JSON.parse(content);
29497
+ const formattedJson = JSON.stringify(json, null, 4);
29498
+ return `\`\`\`json\n${formattedJson}\n\`\`\``;
29499
+ }
29500
+ catch (error) {
29501
+ // If JSON is invalid, still import it but maybe not as pretty JSON
29502
+ return `\`\`\`json\n${content}\n\`\`\``;
29503
+ }
29504
+ },
29505
+ };
29506
+
29507
+ /**
29508
+ * Plugin for importing generic text files
29509
+ *
29510
+ * @private [🥝] Maybe export the import plugins through some package
29511
+ */
29512
+ const TextFileImportPlugin = {
29513
+ name: 'text-file-import-plugin',
29514
+ canImport(mimeType) {
29515
+ return (mimeType === 'text/plain' ||
29516
+ mimeType === 'text/markdown' ||
29517
+ mimeType === 'text/x-typescript' ||
29518
+ mimeType === 'text/javascript' ||
29519
+ mimeType === 'text/css' ||
29520
+ mimeType === 'text/html' ||
29521
+ mimeType.startsWith('text/'));
29522
+ },
29523
+ import(content, mimeType) {
29524
+ const extension = mimeTypeToExtension(mimeType);
29525
+ const codeBlockType = extension || 'txt';
29526
+ return `\`\`\`${codeBlockType}\n${content}\n\`\`\``;
29527
+ },
29528
+ };
29529
+
29530
+ /**
29531
+ * All available file import plugins
29532
+ *
29533
+ * @private [🥝] Maybe export the import plugins through some package
29534
+ */
29535
+ const $fileImportPlugins = [
29536
+ AgentFileImportPlugin,
29537
+ JsonFileImportPlugin,
29538
+ TextFileImportPlugin,
29539
+ ];
29540
+
29541
+ /**
29542
+ * Regex pattern matching markdown horizontal lines that should not be copied into the final system message.
29543
+ *
29544
+ * @private internal constant of `augmentAgentModelRequirementsFromSource`
29545
+ */
29546
+ const HORIZONTAL_LINE_PATTERN = /^[\s]*[-_*][\s]*[-_*][\s]*[-_*][\s]*[-_*]*[\s]*$/;
29547
+ /**
29548
+ * MIME type prefixes treated as binary and therefore not eligible for text import plugins.
29549
+ *
29550
+ * @private internal constant of `augmentAgentModelRequirementsFromSource`
29740
29551
  */
29741
- function clonePreResolvedTeammateProfiles(metadata) {
29742
- var _a;
29743
- return {
29744
- ...((_a = metadata === null || metadata === void 0 ? void 0 : metadata.preResolvedTeammateProfiles) !== null && _a !== void 0 ? _a : {}),
29745
- };
29746
- }
29552
+ const BINARY_MIME_TYPE_PREFIXES = [
29553
+ 'image/',
29554
+ 'video/',
29555
+ 'audio/',
29556
+ 'application/octet-stream',
29557
+ 'application/pdf',
29558
+ 'application/zip',
29559
+ ];
29747
29560
  /**
29748
- * Applies the registered commitment definition while isolating the failure handling from the main loop.
29561
+ * Adds source-derived sections after commitments have been applied.
29749
29562
  *
29750
- * @param requirements - Current requirements snapshot.
29751
- * @param commitment - Commitment whose definition should be applied.
29752
- * @param commitmentContent - Final content passed into the definition.
29753
- * @returns Updated requirements, or the original requirements when the commitment fails.
29563
+ * @param requirements - Requirements after commitment application and USE aggregation.
29564
+ * @param parseResult - Parsed source used to recover non-commitment prose and examples.
29565
+ * @param agentSource - Original source used to recover MCP server declarations.
29566
+ * @returns Requirements with source-derived sections appended.
29754
29567
  *
29755
- * @private internal utility of `applyCommitmentsToRequirements`
29568
+ * @private function of `createAgentModelRequirementsWithCommitments`
29756
29569
  */
29757
- function applyCommitmentDefinitionSafely(requirements, commitment, commitmentContent) {
29758
- const definition = getCommitmentDefinition(commitment.type);
29759
- if (!definition) {
29760
- return requirements;
29761
- }
29762
- try {
29763
- return definition.applyToAgentModelRequirements(requirements, commitmentContent);
29764
- }
29765
- catch (error) {
29766
- console.warn(`Failed to apply commitment ${commitment.type}:`, error);
29767
- return requirements;
29768
- }
29570
+ async function augmentAgentModelRequirementsFromSource(requirements, parseResult, agentSource) {
29571
+ requirements = await importReferencedFiles(requirements);
29572
+ requirements = appendMcpServers(requirements, agentSource);
29573
+ requirements = appendNonCommitmentContent(requirements, parseResult);
29574
+ return appendExampleInteractions(requirements, parseResult);
29769
29575
  }
29770
29576
  /**
29771
29577
  * Imports text files referenced by IMPORT commitments and appends their transformed content to the system message.
@@ -29773,7 +29579,7 @@
29773
29579
  * @param requirements - Requirements possibly containing `importedFileUrls`.
29774
29580
  * @returns Requirements with imported file content appended to the system message.
29775
29581
  *
29776
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29582
+ * @private internal utility of `augmentAgentModelRequirementsFromSource`
29777
29583
  */
29778
29584
  async function importReferencedFiles(requirements) {
29779
29585
  const importedFileUrls = requirements.importedFileUrls;
@@ -29859,7 +29665,7 @@
29859
29665
  * @param agentSource - Original agent source used for MCP extraction.
29860
29666
  * @returns Requirements with `mcpServers` set when MCP commitments are present.
29861
29667
  *
29862
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29668
+ * @private internal utility of `augmentAgentModelRequirementsFromSource`
29863
29669
  */
29864
29670
  function appendMcpServers(requirements, agentSource) {
29865
29671
  const mcpServers = extractMcpServers(agentSource);
@@ -29878,7 +29684,7 @@
29878
29684
  * @param parseResult - Parsed source including non-commitment lines.
29879
29685
  * @returns Requirements with the remaining prose appended to the system message.
29880
29686
  *
29881
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29687
+ * @private internal utility of `augmentAgentModelRequirementsFromSource`
29882
29688
  */
29883
29689
  function appendNonCommitmentContent(requirements, parseResult) {
29884
29690
  const nonCommitmentContent = getNonCommitmentContent(parseResult);
@@ -29921,7 +29727,7 @@
29921
29727
  * @param parseResult - Parsed source used to recover initial message content.
29922
29728
  * @returns Requirements with the example interaction block appended when examples exist.
29923
29729
  *
29924
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29730
+ * @private internal utility of `augmentAgentModelRequirementsFromSource`
29925
29731
  */
29926
29732
  function appendExampleInteractions(requirements, parseResult) {
29927
29733
  const exampleInteractionsContent = createExampleInteractionsContent(parseResult, requirements.samples);
@@ -29976,7 +29782,7 @@
29976
29782
  * @param section - Section content to append.
29977
29783
  * @returns Requirements with the additional system-message block appended.
29978
29784
  *
29979
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29785
+ * @private internal utility of `augmentAgentModelRequirementsFromSource`
29980
29786
  */
29981
29787
  function appendSystemMessageSection(requirements, section) {
29982
29788
  return {
@@ -29985,29 +29791,149 @@
29985
29791
  };
29986
29792
  }
29987
29793
  /**
29988
- * Performs the final system-message cleanup pass after all other augmentation steps are complete.
29794
+ * Mocked security check for imported files.
29989
29795
  *
29990
- * @param requirements - Fully built requirements before final cleanup.
29991
- * @returns Requirements with comment lines removed from the final system message.
29796
+ * @param urlOrPath - The URL or local path of the file to check.
29797
+ * @returns A promise that resolves if the file is considered safe.
29992
29798
  *
29993
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29799
+ * @private internal utility of `createImportedFileSystemMessage`
29994
29800
  */
29995
- function finalizeRequirements(requirements) {
29996
- return {
29997
- ...requirements,
29998
- systemMessage: removeCommentsFromSystemMessage(requirements.systemMessage),
29999
- };
29801
+ async function mockedSecurityCheck(urlOrPath) {
29802
+ // TODO: Implement proper security checks
29803
+ await new Promise((resolve) => setTimeout(resolve, 10));
29804
+ if (urlOrPath.includes('malicious')) {
29805
+ throw new Error(`Security check failed for: ${urlOrPath}`);
29806
+ }
29807
+ }
29808
+ /**
29809
+ * Checks whether the given MIME type belongs to a binary file.
29810
+ *
29811
+ * @param mimeType - The MIME type to check.
29812
+ * @returns `true` when the MIME type is treated as binary.
29813
+ *
29814
+ * @private internal utility of `createImportedFileSystemMessage`
29815
+ */
29816
+ function isBinaryMimeType(mimeType) {
29817
+ return BINARY_MIME_TYPE_PREFIXES.some((prefix) => mimeType.startsWith(prefix));
29818
+ }
29819
+
29820
+ /**
29821
+ * DELETE-like commitment types that invalidate earlier tagged commitments.
29822
+ *
29823
+ * @private internal constant of `filterCommitmentsForAgentModelRequirements`
29824
+ */
29825
+ const DELETE_COMMITMENT_TYPES = new Set(['DELETE', 'CANCEL', 'DISCARD', 'REMOVE']);
29826
+ /**
29827
+ * Commitments whose earlier occurrences are overwritten by the last occurrence in source order.
29828
+ *
29829
+ * @private internal constant of `filterCommitmentsForAgentModelRequirements`
29830
+ */
29831
+ const OVERWRITTEN_COMMITMENT_GROUP_BY_TYPE = new Map([
29832
+ ['GOAL', 'GOAL'],
29833
+ ['GOALS', 'GOAL'],
29834
+ ]);
29835
+ /**
29836
+ * Applies the commitment filtering rules used before commitment definitions are executed.
29837
+ *
29838
+ * @param commitments - Parsed commitments in original source order.
29839
+ * @returns Commitments after DELETE-like invalidation and overwritten-goal filtering.
29840
+ *
29841
+ * @private function of `createAgentModelRequirementsWithCommitments`
29842
+ */
29843
+ function filterCommitmentsForAgentModelRequirements(commitments) {
29844
+ return filterOverwrittenCommitments(filterDeletedCommitments(commitments));
29845
+ }
29846
+ /**
29847
+ * Removes earlier commitments that are overwritten by later commitments of the same semantic group.
29848
+ *
29849
+ * @param commitments - Parsed commitments after DELETE-like filtering.
29850
+ * @returns Commitments with overwritten entries removed while preserving source order.
29851
+ *
29852
+ * @private internal utility of `filterCommitmentsForAgentModelRequirements`
29853
+ */
29854
+ function filterOverwrittenCommitments(commitments) {
29855
+ const seenOverwriteGroups = new Set();
29856
+ const keptCommitments = [];
29857
+ for (let index = commitments.length - 1; index >= 0; index--) {
29858
+ const commitment = commitments[index];
29859
+ const overwriteGroup = OVERWRITTEN_COMMITMENT_GROUP_BY_TYPE.get(commitment.type);
29860
+ if (!overwriteGroup) {
29861
+ keptCommitments.push(commitment);
29862
+ continue;
29863
+ }
29864
+ if (seenOverwriteGroups.has(overwriteGroup)) {
29865
+ continue;
29866
+ }
29867
+ seenOverwriteGroups.add(overwriteGroup);
29868
+ keptCommitments.push(commitment);
29869
+ }
29870
+ return keptCommitments.reverse();
29871
+ }
29872
+ /**
29873
+ * Applies DELETE-like invalidation commitments and returns only commitments that should continue through the pipeline.
29874
+ *
29875
+ * @param commitments - Parsed commitments in original source order.
29876
+ * @returns Filtered commitments with earlier deleted items removed.
29877
+ *
29878
+ * @private internal utility of `filterCommitmentsForAgentModelRequirements`
29879
+ */
29880
+ function filterDeletedCommitments(commitments) {
29881
+ const filteredCommitments = [];
29882
+ for (const commitment of commitments) {
29883
+ if (!isDeleteCommitmentType(commitment.type)) {
29884
+ filteredCommitments.push(commitment);
29885
+ continue;
29886
+ }
29887
+ const targetParameterNames = getCommitmentParameterNames(commitment.content);
29888
+ if (targetParameterNames.length === 0) {
29889
+ continue;
29890
+ }
29891
+ for (let index = filteredCommitments.length - 1; index >= 0; index--) {
29892
+ const previousCommitment = filteredCommitments[index];
29893
+ const previousParameterNames = getCommitmentParameterNames(previousCommitment.content);
29894
+ const isTargeted = previousParameterNames.some((parameterName) => targetParameterNames.includes(parameterName));
29895
+ if (isTargeted) {
29896
+ filteredCommitments.splice(index, 1);
29897
+ }
29898
+ }
29899
+ }
29900
+ return filteredCommitments;
29901
+ }
29902
+ /**
29903
+ * Checks whether a commitment type behaves like DELETE and therefore invalidates earlier tagged commitments.
29904
+ *
29905
+ * @param commitmentType - Commitment type to check.
29906
+ * @returns `true` when the commitment removes prior tagged commitments.
29907
+ *
29908
+ * @private internal utility of `filterDeletedCommitments`
29909
+ */
29910
+ function isDeleteCommitmentType(commitmentType) {
29911
+ return DELETE_COMMITMENT_TYPES.has(commitmentType);
29912
+ }
29913
+ /**
29914
+ * Extracts normalized parameter names used for DELETE-like invalidation matching.
29915
+ *
29916
+ * @param content - Commitment content to parse.
29917
+ * @returns Lower-cased non-empty parameter names.
29918
+ *
29919
+ * @private internal utility of `filterDeletedCommitments`
29920
+ */
29921
+ function getCommitmentParameterNames(content) {
29922
+ return parseParameters(content)
29923
+ .map((parameter) => parameter.name.trim().toLowerCase())
29924
+ .filter(Boolean);
30000
29925
  }
29926
+
30001
29927
  /**
30002
- * Attempts to upload inline knowledge entries, falling back to legacy data URLs when the upload fails or is not configured.
29928
+ * Converts staged inline knowledge files into the final knowledge source URLs stored on requirements.
30003
29929
  *
30004
29930
  * @param requirements - Current requirements snapshot.
30005
29931
  * @param uploader - Optional uploader for inline knowledge files.
30006
29932
  * @returns Requirements with inline knowledge converted into upload URLs or data URLs.
30007
29933
  *
30008
- * @private internal utility of `createAgentModelRequirementsWithCommitments`
29934
+ * @private function of `createAgentModelRequirementsWithCommitments`
30009
29935
  */
30010
- async function applyPendingInlineKnowledgeSources(requirements, uploader) {
29936
+ async function materializeInlineKnowledgeSources(requirements, uploader) {
30011
29937
  var _a;
30012
29938
  const inlineSources = extractInlineKnowledgeSources(requirements._metadata);
30013
29939
  if (inlineSources.length === 0) {
@@ -30033,7 +29959,7 @@
30033
29959
  * @param uploader - Upload implementation provided by the caller.
30034
29960
  * @returns Uploaded knowledge URL or a legacy data URL fallback.
30035
29961
  *
30036
- * @private internal utility of `applyPendingInlineKnowledgeSources`
29962
+ * @private internal utility of `materializeInlineKnowledgeSources`
30037
29963
  */
30038
29964
  async function uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader) {
30039
29965
  try {
@@ -30053,7 +29979,7 @@
30053
29979
  * @param metadata - Current requirements metadata.
30054
29980
  * @returns Inline knowledge files collected during commitment application.
30055
29981
  *
30056
- * @private internal utility of `applyPendingInlineKnowledgeSources`
29982
+ * @private internal utility of `materializeInlineKnowledgeSources`
30057
29983
  */
30058
29984
  function extractInlineKnowledgeSources(metadata) {
30059
29985
  if (!metadata) {
@@ -30068,7 +29994,7 @@
30068
29994
  * @param metadata - Current requirements metadata.
30069
29995
  * @returns Metadata without the temporary inline knowledge staging field.
30070
29996
  *
30071
- * @private internal utility of `applyPendingInlineKnowledgeSources`
29997
+ * @private internal utility of `materializeInlineKnowledgeSources`
30072
29998
  */
30073
29999
  function stripInlineKnowledgeMetadata(metadata) {
30074
30000
  if (!metadata || !Object.prototype.hasOwnProperty.call(metadata, 'inlineKnowledgeSources')) {
@@ -30077,31 +30003,90 @@
30077
30003
  const { inlineKnowledgeSources: _unusedInlineKnowledgeSources, ...rest } = metadata;
30078
30004
  return Object.keys(rest).length > 0 ? rest : undefined;
30079
30005
  }
30006
+
30080
30007
  /**
30081
- * Mocked security check for imported files.
30008
+ * Removes single-hash comment lines (`# Comment`) from a system message
30009
+ * This is used to clean up the final system message before sending it to the AI model
30010
+ * while preserving the original content with comments in metadata
30082
30011
  *
30083
- * @param urlOrPath - The URL or local path of the file to check.
30084
- * @returns A promise that resolves if the file is considered safe.
30012
+ * @param systemMessage The system message that may contain comment lines
30013
+ * @returns The system message with single-hash comment lines removed
30085
30014
  *
30086
- * @private internal utility of `createImportedFileSystemMessage`
30015
+ * @private - TODO: [🧠] Maybe should be public?
30087
30016
  */
30088
- async function mockedSecurityCheck(urlOrPath) {
30089
- // TODO: Implement proper security checks
30090
- await new Promise((resolve) => setTimeout(resolve, 10));
30091
- if (urlOrPath.includes('malicious')) {
30092
- throw new Error(`Security check failed for: ${urlOrPath}`);
30017
+ function removeCommentsFromSystemMessage(systemMessage) {
30018
+ if (!systemMessage) {
30019
+ return systemMessage;
30020
+ }
30021
+ const lines = systemMessage.split(/\r?\n/);
30022
+ const filteredLines = lines.filter((line) => {
30023
+ const trimmedLine = line.trim();
30024
+ // Remove only single-hash comment markers (`# Comment`) and keep markdown headings (`## Heading`).
30025
+ return !/^#(?!#)\s/.test(trimmedLine);
30026
+ });
30027
+ return filteredLines.join('\n').trim();
30028
+ }
30029
+
30030
+ /**
30031
+ * Creates agent model requirements by parsing commitments, applying them in source order,
30032
+ * and finalizing derived sections such as imports, example interactions, and inline knowledge uploads.
30033
+ *
30034
+ * @param agentSource - Agent source book to parse.
30035
+ * @param modelName - Optional override for the agent model name.
30036
+ * @param options - Additional options such as reference and teammate resolvers.
30037
+ * @returns Fully prepared model requirements for the parsed agent source.
30038
+ *
30039
+ * @private internal utility of `createAgentModelRequirements`
30040
+ */
30041
+ async function createAgentModelRequirementsWithCommitments(agentSource, modelName, options) {
30042
+ const parseResult = parseAgentSourceWithCommitments(agentSource);
30043
+ const filteredCommitments = filterCommitmentsForAgentModelRequirements(parseResult.commitments);
30044
+ let requirements = createInitialAgentModelRequirements(parseResult.agentName, modelName);
30045
+ requirements = await applyCommitmentsToAgentModelRequirements(requirements, filteredCommitments, options);
30046
+ requirements = aggregateUseCommitmentSystemMessages(requirements, filteredCommitments);
30047
+ requirements = await augmentAgentModelRequirementsFromSource(requirements, parseResult, agentSource);
30048
+ requirements = await materializeInlineKnowledgeSources(requirements, options === null || options === void 0 ? void 0 : options.inlineKnowledgeSourceUploader);
30049
+ return finalizeRequirements(requirements);
30050
+ }
30051
+ /**
30052
+ * Creates the initial requirements object with the parsed agent name stored in metadata and an optional model override.
30053
+ *
30054
+ * @param agentName - Parsed agent name from the source prelude.
30055
+ * @param modelName - Optional explicit model name override.
30056
+ * @returns Initial requirements before any commitment is applied.
30057
+ *
30058
+ * @private internal utility of `createAgentModelRequirementsWithCommitments`
30059
+ */
30060
+ function createInitialAgentModelRequirements(agentName, modelName) {
30061
+ const initialRequirements = createBasicAgentModelRequirements(agentName);
30062
+ const requirementsWithMetadata = {
30063
+ ...initialRequirements,
30064
+ _metadata: {
30065
+ ...initialRequirements._metadata,
30066
+ agentName,
30067
+ },
30068
+ };
30069
+ if (!modelName) {
30070
+ return requirementsWithMetadata;
30093
30071
  }
30072
+ return {
30073
+ ...requirementsWithMetadata,
30074
+ modelName,
30075
+ };
30094
30076
  }
30095
30077
  /**
30096
- * Checks whether the given MIME type belongs to a binary file.
30078
+ * Performs the final system-message cleanup pass after all other augmentation steps are complete.
30097
30079
  *
30098
- * @param mimeType - The MIME type to check.
30099
- * @returns `true` when the MIME type is treated as binary.
30080
+ * @param requirements - Fully built requirements before final cleanup.
30081
+ * @returns Requirements with comment lines removed from the final system message.
30100
30082
  *
30101
- * @private internal utility of `createImportedFileSystemMessage`
30083
+ * @private internal utility of `createAgentModelRequirementsWithCommitments`
30102
30084
  */
30103
- function isBinaryMimeType(mimeType) {
30104
- return BINARY_MIME_TYPE_PREFIXES.some((prefix) => mimeType.startsWith(prefix));
30085
+ function finalizeRequirements(requirements) {
30086
+ return {
30087
+ ...requirements,
30088
+ systemMessage: removeCommentsFromSystemMessage(requirements.systemMessage),
30089
+ };
30105
30090
  }
30106
30091
 
30107
30092
  /**