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

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