@intelliweave/embedded 1.8.63 → 1.9.65-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,8 @@
1
1
  import * as onnxruntime_web from 'onnxruntime-web';
2
2
  import { InferenceSession, Tensor } from 'onnxruntime-web';
3
- import { Optional } from 'utility-types';
4
3
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
+ import { Optional } from 'utility-types';
5
+ import Anthropic from '@anthropic-ai/sdk';
5
6
 
6
7
  /**
7
8
  * This is a utility class for dealing with the ONNX runtime and model loading.
@@ -387,771 +388,754 @@ function int16ToFloat32BitPCM(input) {
387
388
  }
388
389
 
389
390
  /**
390
- * This class helps organize groups of tokenized text along with removing items when the window is full.
391
+ * Speech output
392
+ *
393
+ * - event `speechstart` - When the speech starts
394
+ * - event `speechend` - When the speech ends
391
395
  */
392
- declare class TokenWindow {
393
- /** Token window size */
394
- size: number;
395
- /** Token groups */
396
- groups: TokenWindowGroup<any>[];
397
- /** Create a new group */
398
- createGroup(id: string): TokenWindowGroup<unknown>;
399
- /** Get a group */
400
- group<CustomDataType>(id: string): TokenWindowGroup<CustomDataType> | undefined;
401
- /** Calculate current tokens in all groups */
402
- countTokens(): number;
403
- /** Remove overflow from all groups. */
404
- removeOverflow(): void;
405
- /** Remove one overflow item. Returns null if no items were able to be removed. */
406
- private removeOneItem;
396
+ declare class WebWeaverSpeechOutput extends EventTarget {
397
+ /** Reference to the AI */
398
+ private ai?;
399
+ /** Constructor */
400
+ constructor(ai: IntelliWeave);
401
+ /** Called when the AI speaks */
402
+ onTextOutputFromAI(e: CustomEvent): void;
403
+ /** Current player vars */
404
+ private currentPlayerVolume?;
405
+ private currentPlayer?;
406
+ /** The audio analyser node */
407
+ private analyserNode?;
408
+ /** The audio analyser buffer */
409
+ private analyserBuffer?;
410
+ /** @private Maximum volume heard this session */
411
+ private maxVolumeHeard;
412
+ /** Get current (realtime) audio output volume level, from 0 to 1 */
413
+ get volumeLevel(): number;
414
+ /** Speak the text */
415
+ speak(text: string): Promise<void>;
416
+ private _speakWithLock;
417
+ /** True if currently playing audio */
418
+ get isSpeaking(): boolean;
419
+ /** Interrupt the previously playing audio */
420
+ interrupt(): Promise<void>;
421
+ /** Called when the speech output ends */
422
+ onSpeechEnd(): void;
407
423
  }
408
- /** A token group. */
409
- declare class TokenWindowGroup<CustomDataType> {
410
- /** Group ID */
411
- id: string;
412
- /** List of items */
413
- items: TokenWindowGroupItem<CustomDataType>[];
424
+
425
+ /**
426
+ * An AudioWorklet module that records data from input and sends it to the host.
427
+ *
428
+ * - event `data` - Fired when data is available to be read.
429
+ */
430
+ declare class PCMReceiverNode extends AudioWorkletNode {
431
+ /** @type {'int16' | 'float32'} The output data format */
432
+ format: string;
414
433
  /**
415
- * Weight controls how many items from this group should be kept in relation to the entire window. For example if all
416
- * groups have a weight of 1, each group remove items equally if full. If one has a weight of 2 while the rest are 1,
417
- * that group will be allowed to keep double the amount of items.
434
+ * Creates a new PCMRecorderNode ready to receive PCM data.
435
+ *
436
+ * @param context - The audio context to use.
437
+ * @param sampleRate - The sample rate of the output data stream.
438
+ * @param format - The format of the output data stream.
439
+ * @param bufferSize - The size of the output buffer in elements (Int16Array or Float32Array items, depending on `format`).
418
440
  */
419
- weight: number;
420
- /** Current total token count, computed automatically. Don't update this value manually. */
421
- tokenCount: number;
422
- /** Group item separator */
423
- separator: string;
424
- /** Token count padding added to each item. */
425
- private itemPadding;
426
- /** Sets the token count padding added to each item. Useful if you don't know exactly what will be added by the LLM host. */
427
- setItemPadding(padding: number): this;
428
- /** Sort function */
429
- private sortFunction;
430
- /** Set sort function */
431
- sortBy(sortFunction: (a: TokenWindowGroupItem<CustomDataType>, b: TokenWindowGroupItem<CustomDataType>) => number): this;
432
- /** Set separator */
433
- setSeparator(separator: string): this;
434
- /** Set weight */
435
- setWeight(weight: number): this;
436
- /** Recalculate all tokens. Note this may take a while. */
437
- recalculateTokens(): void;
438
- /** Add an item to the group */
439
- add(item: string | Omit<Optional<TokenWindowGroupItem<CustomDataType>, 'id' | 'dateAdded' | 'sortOrder'>, 'tokenCount'>): TokenWindowGroupItem<CustomDataType>;
440
- /** Get all items as a string */
441
- getAllAsString(): string;
442
- /** Get all items. Doesn't return disabled items. */
443
- getAll(): TokenWindowGroupItem<CustomDataType>[];
444
- /** Remove all items from this group */
445
- empty(): void;
446
- }
447
- /** Token group item */
448
- interface TokenWindowGroupItem<CustomDataType> {
449
- /** Each item must have a unique ID. */
450
- id: string;
451
- /** The string content of the item */
452
- content: string;
453
- /** True if this item should never be removed */
454
- cannotRemove?: boolean;
455
- /** Sorting order. If not specified, uses dateAdded instead. */
456
- sortOrder: number;
457
- /** Date this item was added */
458
- dateAdded: number;
459
- /** Token count in the content */
460
- tokenCount: number;
461
- /** Anything to attach to this item */
462
- customData?: CustomDataType;
463
- /** If disabled, this item will not be included and will not add tot he token count. */
464
- disabled?: boolean;
441
+ constructor(context: AudioContext, sampleRate: number, format: 'int16' | 'int64' | 'float32', bufferSize: number);
442
+ /** @private Called when a message is received from the worklet */
443
+ onWorkletMessage(e: MessageEvent): void;
444
+ /** Called when data is received */
445
+ onData(buffer: Float32Array | Int16Array | BigInt64Array): void;
465
446
  }
466
447
 
467
- // ==================================================================================================
468
- // JSON Schema Draft 07
469
- // ==================================================================================================
470
- // https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
471
- // --------------------------------------------------------------------------------------------------
472
-
473
448
  /**
474
- * Primitive type
475
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
449
+ * An AudioNode which sends events for when speech is detected
450
+ *
451
+ * - event `speechstart` - Fired when speech is detected
452
+ * - event `speechend` - Fired when speech ends
476
453
  */
477
- type JSONSchema7TypeName =
478
- | "string" //
479
- | "number"
480
- | "integer"
481
- | "boolean"
482
- | "object"
483
- | "array"
484
- | "null";
454
+ declare class VoiceDetectionNode extends PCMReceiverNode {
455
+ /** True if voice is currently being detected */
456
+ isVoiceActive: boolean;
457
+ /** True if voice is active but may be ending soon */
458
+ get isVoicePossiblyEnding(): boolean;
459
+ /** Last date that voice was detected */
460
+ lastVoiceActiveDate: number;
461
+ /** Amount of time to wait after voice detection to detect that it has ended */
462
+ voiceEndTimeout: number;
463
+ /** Detection sensitivity, if the detection model outputs a number bigger than this it will be considered voice */
464
+ sensitivity: number;
465
+ /** Sensitivity threshold to end speaking */
466
+ sentivityEnd: number;
467
+ /** VAD model */
468
+ static vadModelURL: string;
469
+ /** Loaded VAD model */
470
+ private vad?;
471
+ /** Sample rate */
472
+ get sampleRate(): 16000 | 8000;
473
+ /** Number of samples */
474
+ get numberOfSamples(): number;
475
+ /** Number of sample chunks */
476
+ get numberOfSampleChunks(): number;
477
+ /** Output buffer size */
478
+ get outputBufferSize(): number;
479
+ /** True if the VAD model has been loaded */
480
+ get isModelLoaded(): boolean;
481
+ /** The time when to next reset the VAD model */
482
+ nextVadReset: number;
483
+ /** The current probability of active voice */
484
+ currentProbability: number;
485
+ /** Constructor */
486
+ constructor(audioContext: AudioContext);
487
+ /** Start loading */
488
+ loadModel(): Promise<void>;
489
+ private _lastVoiceActive;
490
+ /** Called when data is received */
491
+ onData(buffer: Float32Array): Promise<void>;
492
+ /** Called when speech is detected */
493
+ onSpeechStart(): void;
494
+ /** Called when speech ends */
495
+ onSpeechEnd(): void;
496
+ }
485
497
 
486
498
  /**
487
- * Primitive type
488
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
499
+ * An AudioNode which isolates speech and outputs the audio data. Since we are reusing the VAD model node,
500
+ * output data is in 8000Hz Float32 format.
501
+ *
502
+ * - event `voicedata` - Fired when a chunk of voice is detected. `data` contains the recorded chunk of voice in a Float32Array.
503
+ * - event `voicedataend` - Fired when this chunk of voice ends. `data` contains an array of Float32Array containing the entirety of the recorded voice.
489
504
  */
490
- type JSONSchema7Type =
491
- | string //
492
- | number
493
- | boolean
494
- | JSONSchema7Object
495
- | JSONSchema7Array
496
- | null;
497
-
498
- // Workaround for infinite type recursion
499
- interface JSONSchema7Object {
500
- [key: string]: JSONSchema7Type;
505
+ declare class VoiceChunkOutputNode extends VoiceDetectionNode {
506
+ /** Stored buffers */
507
+ buffers: Float32Array[];
508
+ /** Recorded audio chunks with voice in it */
509
+ recordedBuffers: Float32Array[];
510
+ /** Last active state */
511
+ _voiceRecording: boolean;
512
+ /** Amount of audio data in the buffer, in seconds */
513
+ get bufferDuration(): number;
514
+ /** Amount of data to keep from before the user started speaking */
515
+ backBufferDurationSeconds: number;
516
+ /** Called when data is received */
517
+ onData(buffer: Float32Array): Promise<void>;
518
+ /** Called when a chunk of voice is recorded */
519
+ onVoiceChunk(buffer: Float32Array): void;
520
+ /** Called when the voice recording ends */
521
+ onVoiceEnd(buffers: Float32Array[]): void;
501
522
  }
502
523
 
503
- // Workaround for infinite type recursion
504
- // https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
505
- interface JSONSchema7Array extends Array<JSONSchema7Type> {}
506
-
507
524
  /**
508
- * Meta schema
509
- *
510
- * Recommended values:
511
- * - 'http://json-schema.org/schema#'
512
- * - 'http://json-schema.org/hyper-schema#'
513
- * - 'http://json-schema.org/draft-07/schema#'
514
- * - 'http://json-schema.org/draft-07/hyper-schema#'
525
+ * This AudioNode uses OpenAI's Whisper model to transcribe spoken speech to text.
515
526
  *
516
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
527
+ * - event `transcription` - Fired when a transcription is ready. `text` contains the transcribed text.
517
528
  */
518
- type JSONSchema7Version = string;
529
+ declare class OpenAITranscriptionNode extends VoiceChunkOutputNode {
530
+ /** OpenAI API key */
531
+ apiKey: string;
532
+ /** Pending buffers */
533
+ private pendingBuffers;
534
+ /** Last request */
535
+ private lastRequestAbortController?;
536
+ /** True if currently transcribing */
537
+ isTranscribing: boolean;
538
+ /** Constructor */
539
+ constructor(audioContext: AudioContext, apiKey: string);
540
+ /** Called when the voice recording ends */
541
+ onVoiceEnd(buffers: Float32Array[]): Promise<void>;
542
+ /** Called when a transcription is ready */
543
+ onVoiceTranscription(text: string): void;
544
+ }
519
545
 
520
546
  /**
521
- * JSON Schema v7
522
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
523
- */
524
- type JSONSchema7Definition = JSONSchema7 | boolean;
525
- interface JSONSchema7 {
526
- $id?: string | undefined;
527
- $ref?: string | undefined;
528
- $schema?: JSONSchema7Version | undefined;
529
- $comment?: string | undefined;
530
-
531
- /**
532
- * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4
533
- * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A
534
- */
535
- $defs?: {
536
- [key: string]: JSONSchema7Definition;
537
- } | undefined;
538
-
539
- /**
540
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1
541
- */
542
- type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined;
543
- enum?: JSONSchema7Type[] | undefined;
544
- const?: JSONSchema7Type | undefined;
545
-
546
- /**
547
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2
548
- */
549
- multipleOf?: number | undefined;
550
- maximum?: number | undefined;
551
- exclusiveMaximum?: number | undefined;
552
- minimum?: number | undefined;
553
- exclusiveMinimum?: number | undefined;
554
-
555
- /**
556
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3
557
- */
558
- maxLength?: number | undefined;
559
- minLength?: number | undefined;
560
- pattern?: string | undefined;
561
-
562
- /**
563
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4
564
- */
565
- items?: JSONSchema7Definition | JSONSchema7Definition[] | undefined;
566
- additionalItems?: JSONSchema7Definition | undefined;
567
- maxItems?: number | undefined;
568
- minItems?: number | undefined;
569
- uniqueItems?: boolean | undefined;
570
- contains?: JSONSchema7Definition | undefined;
571
-
572
- /**
573
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5
574
- */
575
- maxProperties?: number | undefined;
576
- minProperties?: number | undefined;
577
- required?: string[] | undefined;
578
- properties?: {
579
- [key: string]: JSONSchema7Definition;
580
- } | undefined;
581
- patternProperties?: {
582
- [key: string]: JSONSchema7Definition;
583
- } | undefined;
584
- additionalProperties?: JSONSchema7Definition | undefined;
585
- dependencies?: {
586
- [key: string]: JSONSchema7Definition | string[];
587
- } | undefined;
588
- propertyNames?: JSONSchema7Definition | undefined;
589
-
590
- /**
591
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6
592
- */
593
- if?: JSONSchema7Definition | undefined;
594
- then?: JSONSchema7Definition | undefined;
595
- else?: JSONSchema7Definition | undefined;
596
-
597
- /**
598
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7
599
- */
600
- allOf?: JSONSchema7Definition[] | undefined;
601
- anyOf?: JSONSchema7Definition[] | undefined;
602
- oneOf?: JSONSchema7Definition[] | undefined;
603
- not?: JSONSchema7Definition | undefined;
604
-
605
- /**
606
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7
607
- */
608
- format?: string | undefined;
609
-
610
- /**
611
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8
612
- */
613
- contentMediaType?: string | undefined;
614
- contentEncoding?: string | undefined;
615
-
616
- /**
617
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9
618
- */
619
- definitions?: {
620
- [key: string]: JSONSchema7Definition;
621
- } | undefined;
622
-
623
- /**
624
- * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10
625
- */
626
- title?: string | undefined;
627
- description?: string | undefined;
628
- default?: JSONSchema7Type | undefined;
629
- readOnly?: boolean | undefined;
630
- writeOnly?: boolean | undefined;
631
- examples?: JSONSchema7Type | undefined;
632
- }
633
-
634
- /** ChatGPT config options */
635
- interface ChatGPTConfig {
636
- /** API key */
637
- apiKey: string;
638
- /** Provider ID */
639
- providerID?: string;
640
- /** Endpoint URL if using a custom URL */
641
- endpoint: string;
642
- /** LLM model to use */
643
- model: string;
644
- /** System message to describe to the AI how to behave. */
645
- systemMessage: string;
646
- /** User ID used to uniquely identify users in ChatGPT's API */
647
- userID: string;
648
- /** If true, streams the text responses from the API */
649
- stream: boolean;
650
- /** Amount of estimated tokens to keep when trimming */
651
- maxTokens: number;
652
- /** Callback before the AI sends info to the LLM */
653
- onBeforeMessageProcessing?: () => void;
654
- /** Callback when a message from the AI is returned. If isChunk is true, it may be incomplete and be called again with more updates. */
655
- onAIMessage?: (text: string, isChunk: boolean) => void;
656
- /** Callback when the AI starts performing an action */
657
- onAIToolStart?: (toolName: string, input: any) => void;
658
- }
659
- /** ChatGPT tool config */
660
- interface ChatGPTToolConfig {
661
- /** Name of the tool */
662
- name: string;
663
- /** Description of the tool */
664
- description: string;
665
- /** Parameters for the tool */
666
- params: JSONSchema7;
667
- /** Callback function to process the tool */
668
- callback: (params: any) => any;
669
- /** If true, this tool call will be removed from the message history after it is executed. */
670
- removeFromMessageHistory?: boolean;
671
- /** If true, this item can be removed if there's not enough context available. */
672
- canRemove?: boolean;
673
- /** Misc app context */
674
- [key: string]: any;
675
- }
676
- /** ChatGPT message */
677
- interface ChatGPTMessage {
678
- /** Role of the message */
679
- role: 'user' | 'assistant' | 'system' | 'tool';
680
- /** Content of the message */
681
- content: string;
682
- /** Tool call ID */
683
- tool_call_id?: string;
684
- /** Tool calls made by the AI */
685
- tool_calls?: any[];
686
- }
687
- /**
688
- * API for interacting with ChatGPT APIs.
547
+ * This AudioNode uses IntelliWeave's servers to transcribe spoken speech to text.
548
+ *
549
+ * - event `transcription` - Fired when a transcription is ready. `text` contains the transcribed text.
689
550
  */
690
- declare class ChatGPT {
691
- /** ID */
692
- id: string;
693
- /** Metadata */
694
- metadata: any;
695
- /** Config */
696
- config: ChatGPTConfig;
697
- /** The maximum tool calls in sequence the AI can make before an error is thrown. */
698
- maxToolCallsPerMessage: number;
699
- /** Statistics */
700
- stats: {
701
- /** Total tokens used this session */
702
- tokensUsed: number;
703
- };
704
- /** Token window management */
705
- tokenWindow: TokenWindow;
706
- /** Token window group used for the context message */
707
- get contextGroup(): TokenWindowGroup<any>;
708
- /** Token window group used for tools / actions */
709
- get toolGroup(): TokenWindowGroup<ChatGPTToolConfig>;
710
- /** Token window group used for messages */
711
- get messageGroup(): TokenWindowGroup<ChatGPTMessage>;
551
+ declare class IntelliWeaveTranscriptionNode extends VoiceChunkOutputNode {
552
+ /** Debug: Export each recording as a wav file for download */
553
+ static debugExportWav: boolean;
554
+ /** Server address for transcription */
555
+ apiAddress: string;
556
+ /** OpenAI API key */
557
+ apiKey: string;
558
+ /** WebSocket connection */
559
+ private ws?;
560
+ /** True if currently transcribing */
561
+ isTranscribing: boolean;
562
+ /** WebSocket shutdown timer */
563
+ private shutdownTimer?;
712
564
  /** Constructor */
713
- constructor(config: ChatGPTConfig);
714
- /** Send a message, and get the response */
715
- sendMessage(message: string): Promise<string>;
716
- /** Insert a message as if the assistant has written it */
717
- addAssistantMessage(message: string): void;
718
- /** Insert a message sent from a user. Note that doing this instead of using `sendMessage()` means you'll need to manually call `await processMessages()` and then `getLatestMessage()` to get the response. */
719
- addUserMessage(message: string): void;
720
- /** Get all messages */
721
- getMessages(): ChatGPTMessage[];
722
- /** Get latest message */
723
- getLatestMessage(): ChatGPTMessage | undefined;
724
- /** @private Process messages in the chat history */
725
- processMessages(): Promise<void>;
726
- /** Trim message list */
727
- trimMessages(): Promise<void>;
728
- /** @private Send message list to the API and store the response */
729
- sendToAPI(generatePayloadOnly?: boolean): Promise<any>;
730
- /** Process incoming message from the AI. Can be used to respond to encoded actions in the text response. */
731
- processIncomingMessage(message: string): void;
732
- /** Register a tool. */
733
- registerTool(tool: ChatGPTToolConfig): void;
734
- /** @private Process a tool call request from the AI */
735
- processToolCall(toolCall: any): Promise<void>;
736
- /** Reset the conversation */
737
- resetConversation(): void;
565
+ constructor(audioContext: AudioContext, apiKey: string);
566
+ /** Called when a voice chunk is received */
567
+ onVoiceChunk(buffer: Float32Array): Promise<void>;
568
+ /** Called when the voice recording ends */
569
+ onVoiceEnd(buffers: Float32Array[]): Promise<void>;
570
+ /** Called when a transcription is ready */
571
+ onVoiceTranscription(text: string): void;
572
+ /** Called when the WebSocket is closed */
573
+ onSocketClose(): void;
738
574
  }
739
575
 
740
576
  /**
741
- * Speech output
577
+ * Handles speech recognition from the microphone
742
578
  *
743
- * - event `speechstart` - When the speech starts
744
- * - event `speechend` - When the speech ends
579
+ * - event `speechstart` - We have detected the user started speaking
580
+ * - event `speechend` - We have detected the user stopped speaking
581
+ * - event `speech` - Speech recognition result
582
+ * - event `start` - Speech recognition started
583
+ * - event `end` - Speech recognition ended
745
584
  */
746
- declare class WebWeaverSpeechOutput extends EventTarget {
585
+ declare class WebWeaverSpeechRecognition extends EventTarget {
747
586
  /** Reference to the AI */
748
- private ai?;
749
- /** Constructor */
750
- constructor(ai: IntelliWeave);
751
- /** Called when the AI speaks */
752
- onTextOutputFromAI(e: CustomEvent): void;
753
- /** Current player vars */
754
- private currentPlayerVolume?;
755
- private currentPlayer?;
587
+ ai?: IntelliWeave;
588
+ /** True if recognition is running */
589
+ isRunning: boolean;
756
590
  /** The audio analyser node */
757
591
  private analyserNode?;
758
592
  /** The audio analyser buffer */
759
593
  private analyserBuffer?;
594
+ /** The microphone stream */
595
+ micStream?: MediaStream;
596
+ /** Recording start time for tracking duration */
597
+ private recordingStartTime?;
598
+ /** Returns true if speech recognition is supported by this persona and browser */
599
+ get isSupported(): boolean;
600
+ /** Currently active voice detection node */
601
+ voiceDetection?: IntelliWeaveTranscriptionNode | OpenAITranscriptionNode;
602
+ /** Constructor */
603
+ constructor(ai: IntelliWeave);
604
+ private _skipEvents;
605
+ /** Start recognition */
606
+ start(): Promise<void>;
607
+ /** Stop recognition */
608
+ stop(): void;
760
609
  /** @private Maximum volume heard this session */
761
- private maxVolumeHeard;
762
- /** Get current (realtime) audio output volume level, from 0 to 1 */
610
+ maxVolumeHeard: number;
611
+ /** Get current (realtime) microphone volume level, from 0 to 1 */
763
612
  get volumeLevel(): number;
764
- /** Speak the text */
765
- speak(text: string): Promise<void>;
766
- private _speakWithLock;
767
- /** True if currently playing audio */
768
- get isSpeaking(): boolean;
769
- /** Interrupt the previously playing audio */
770
- interrupt(): Promise<void>;
771
- /** Called when the speech output ends */
772
- onSpeechEnd(): void;
613
+ /** True if currently detecting words being spoken */
614
+ get wordsCurrentlyBeingSpoken(): boolean;
615
+ /** True if currently transcribing voice to text */
616
+ get isTranscribing(): boolean;
617
+ /** Called when speech has been recorded */
618
+ onTranscription(e: CustomEvent): void;
619
+ /** Called to reset the speech recognizer */
620
+ reset(): Promise<void>;
621
+ }
622
+
623
+ /** Handles creating and managing the AudioContext */
624
+ declare class AudioSystem {
625
+ /** Reference to the AI */
626
+ private ai?;
627
+ /** The speech recognition module. */
628
+ speechRecognition: WebWeaverSpeechRecognition;
629
+ /** The speech output module. */
630
+ speechOutput: WebWeaverSpeechOutput;
631
+ /** The audio context */
632
+ context?: AudioContext;
633
+ /** List of active named locks */
634
+ locks: string[];
635
+ /** Returns true if speech recognition and output is supported by this persona and browser */
636
+ static get isSupported(): boolean;
637
+ /** Constructor */
638
+ constructor(ai: IntelliWeave);
639
+ /** Create a named lock to enable the audio system */
640
+ beginAccess(namedLock: string): Promise<void>;
641
+ /** Stop accessing the audio system */
642
+ endAccess(namedLock: string): void;
773
643
  }
774
644
 
775
645
  /**
776
- * An AudioWorklet module that records data from input and sends it to the host.
777
- *
778
- * - event `data` - Fired when data is available to be read.
646
+ * This class allows you to use the AI as a logic engine, data extractor, etc.
779
647
  */
780
- declare class PCMReceiverNode extends AudioWorkletNode {
781
- /** @type {'int16' | 'float32'} The output data format */
782
- format: string;
648
+ declare class AILogic {
649
+ /** Reference to the AI */
650
+ private ai?;
651
+ /** Constructor */
652
+ constructor(ai: IntelliWeave);
653
+ /** Ask the AI a yes/no question associated with the specified data. Data must be JSON-serializable, or a string of any kind of data. */
654
+ boolean(config: IntelliWeaveInstructConfig): Promise<boolean>;
655
+ /** Ask the AI to select a choice from a list of options. */
656
+ choose(config: IntelliWeaveInstructConfig & {
657
+ /** List of choices the AI can pick from. */
658
+ options: string[];
659
+ }): Promise<string | undefined>;
660
+ /**
661
+ * Ask the AI to extract data from input data. The AI will return the extracted data. Possibly an array of multiple extractions.
662
+ */
663
+ extract<T = any>(config: IntelliWeaveInstructConfig & {
664
+ /** Allow multiple items to be returned. If true, returns an array instead of an object. */
665
+ allowMultiple?: boolean;
666
+ /** Fields to extract in each object. */
667
+ extractions: {
668
+ /** Field name */
669
+ name: string;
670
+ /** Field data type */
671
+ type: 'string' | 'number' | 'boolean' | 'date' | 'email' | 'phone' | 'address';
672
+ /** Describe to the AI what data to put in this field. */
673
+ description?: string;
674
+ }[];
675
+ }): Promise<T[]>;
783
676
  /**
784
- * Creates a new PCMRecorderNode ready to receive PCM data.
677
+ * Generate a Markdown document based on the data from the user.
785
678
  *
786
- * @param context - The audio context to use.
787
- * @param sampleRate - The sample rate of the output data stream.
788
- * @param format - The format of the output data stream.
789
- * @param bufferSize - The size of the output buffer in elements (Int16Array or Float32Array items, depending on `format`).
679
+ * @param config Instruct config.
680
+ * @returns A markdown document.
790
681
  */
791
- constructor(context: AudioContext, sampleRate: number, format: 'int16' | 'int64' | 'float32', bufferSize: number);
792
- /** @private Called when a message is received from the worklet */
793
- onWorkletMessage(e: MessageEvent): void;
794
- /** Called when data is received */
795
- onData(buffer: Float32Array | Int16Array | BigInt64Array): void;
682
+ generateMarkdown(config: Omit<IntelliWeaveInstructConfig, 'instruction'>): Promise<string>;
683
+ /**
684
+ * Perform an instruction.
685
+ *
686
+ * @param config Instruct config.
687
+ * @returns The final response from the AI.
688
+ */
689
+ instruct(config: IntelliWeaveInstructConfig): Promise<string>;
690
+ }
691
+ /** Config for any instruct call */
692
+ interface IntelliWeaveInstructConfig {
693
+ /** Instruction */
694
+ instruction: string;
695
+ /** Input data or query to process */
696
+ data: any;
697
+ /** Whether to allow the AI to use the knowledge base or not. If false, the AI will not use the knowledge base. */
698
+ allowKB?: boolean;
699
+ /** Callback that will be called when streaming the response. Each call will contain the full text that has been generated so far. */
700
+ callback?: (txt: string) => void;
796
701
  }
797
702
 
798
703
  /**
799
- * An AudioNode which sends events for when speech is detected
800
- *
801
- * - event `speechstart` - Fired when speech is detected
802
- * - event `speechend` - Fired when speech ends
704
+ * Allows an MCP server to be used as a knowledge source for IntelliWeave.
803
705
  */
804
- declare class VoiceDetectionNode extends PCMReceiverNode {
805
- /** True if voice is currently being detected */
806
- isVoiceActive: boolean;
807
- /** True if voice is active but may be ending soon */
808
- get isVoicePossiblyEnding(): boolean;
809
- /** Last date that voice was detected */
810
- lastVoiceActiveDate: number;
811
- /** Amount of time to wait after voice detection to detect that it has ended */
812
- voiceEndTimeout: number;
813
- /** Detection sensitivity, if the detection model outputs a number bigger than this it will be considered voice */
814
- sensitivity: number;
815
- /** Sensitivity threshold to end speaking */
816
- sentivityEnd: number;
817
- /** VAD model */
818
- static vadModelURL: string;
819
- /** Loaded VAD model */
820
- private vad?;
821
- /** Sample rate */
822
- get sampleRate(): 8000 | 16000;
823
- /** Number of samples */
824
- get numberOfSamples(): number;
825
- /** Number of sample chunks */
826
- get numberOfSampleChunks(): number;
827
- /** Output buffer size */
828
- get outputBufferSize(): number;
829
- /** True if the VAD model has been loaded */
830
- get isModelLoaded(): boolean;
831
- /** The time when to next reset the VAD model */
832
- nextVadReset: number;
833
- /** The current probability of active voice */
834
- currentProbability: number;
706
+ declare class MCPKnowledgeClient {
707
+ /** MCP client */
708
+ client?: Client;
709
+ /** All tools discovered on the MCP server. Only available after connect() has completed. */
710
+ tools: Awaited<ReturnType<Client['listTools']>>['tools'];
711
+ /** All toold discovered, mapped to IntelliWeave knowledge base actions */
712
+ iwActions: KnowledgeBaseItem[];
713
+ /** Statistics */
714
+ stats: {
715
+ toolsCalled: number;
716
+ };
717
+ /** Configuration */
718
+ config: {
719
+ /** Source ID */
720
+ id?: string;
721
+ /** URL to the MCP server endpoint */
722
+ baseURL?: string;
723
+ /** Custom connection function. If specified, baseURL is optional. */
724
+ connect?: () => Promise<Client>;
725
+ /**
726
+ * The name of the tool which provides knowledge searching. If specified, the search() will exclude this function and instead
727
+ * call it and show returned results. If not specified, the search() will just return all tools.
728
+ */
729
+ searchToolName?: string;
730
+ /** Keep search function available for the AI to use. */
731
+ searchToolVisible?: boolean;
732
+ };
835
733
  /** Constructor */
836
- constructor(audioContext: AudioContext);
837
- /** Start loading */
838
- loadModel(): Promise<void>;
839
- private _lastVoiceActive;
840
- /** Called when data is received */
841
- onData(buffer: Float32Array): Promise<void>;
842
- /** Called when speech is detected */
843
- onSpeechStart(): void;
844
- /** Called when speech ends */
845
- onSpeechEnd(): void;
734
+ constructor(config: MCPKnowledgeClient['config']);
735
+ /** In-progress connection attempt */
736
+ private connectionPromise?;
737
+ /** Connect to the client */
738
+ connect(): Promise<Client<{
739
+ method: string;
740
+ params?: {
741
+ [x: string]: unknown;
742
+ _meta?: {
743
+ [x: string]: unknown;
744
+ progressToken?: string | number | undefined;
745
+ } | undefined;
746
+ } | undefined;
747
+ }, {
748
+ method: string;
749
+ params?: {
750
+ [x: string]: unknown;
751
+ _meta?: {
752
+ [x: string]: unknown;
753
+ } | undefined;
754
+ } | undefined;
755
+ }, {
756
+ [x: string]: unknown;
757
+ _meta?: {
758
+ [x: string]: unknown;
759
+ } | undefined;
760
+ }>>;
761
+ connectInternal(): Promise<Client<{
762
+ method: string;
763
+ params?: {
764
+ [x: string]: unknown;
765
+ _meta?: {
766
+ [x: string]: unknown;
767
+ progressToken?: string | number | undefined;
768
+ } | undefined;
769
+ } | undefined;
770
+ }, {
771
+ method: string;
772
+ params?: {
773
+ [x: string]: unknown;
774
+ _meta?: {
775
+ [x: string]: unknown;
776
+ } | undefined;
777
+ } | undefined;
778
+ }, {
779
+ [x: string]: unknown;
780
+ _meta?: {
781
+ [x: string]: unknown;
782
+ } | undefined;
783
+ }>>;
784
+ /** Disconnect from server */
785
+ disconnect(): Promise<void>;
786
+ /** Fetch list of tools from the MCP server */
787
+ private fetchTools;
788
+ /** Cache last search result */
789
+ lastSearchQuery: string;
790
+ lastSearchResults: KnowledgeBaseItem[];
791
+ /** Perform a search query */
792
+ search(query: string): Promise<KnowledgeBaseItem[]>;
793
+ /** Perform search using the configured search function */
794
+ private performSearchCall;
795
+ /** Perform tool call. */
796
+ private performToolCall;
846
797
  }
847
798
 
848
799
  /**
849
- * An AudioNode which isolates speech and outputs the audio data. Since we are reusing the VAD model node,
850
- * output data is in 8000Hz Float32 format.
851
- *
852
- * - event `voicedata` - Fired when a chunk of voice is detected. `data` contains the recorded chunk of voice in a Float32Array.
853
- * - event `voicedataend` - Fired when this chunk of voice ends. `data` contains an array of Float32Array containing the entirety of the recorded voice.
800
+ * This class helps organize groups of tokenized text along with removing items when the window is full.
854
801
  */
855
- declare class VoiceChunkOutputNode extends VoiceDetectionNode {
856
- /** Stored buffers */
857
- buffers: Float32Array[];
858
- /** Recorded audio chunks with voice in it */
859
- recordedBuffers: Float32Array[];
860
- /** Last active state */
861
- _voiceRecording: boolean;
862
- /** Amount of audio data in the buffer, in seconds */
863
- get bufferDuration(): number;
864
- /** Amount of data to keep from before the user started speaking */
865
- backBufferDurationSeconds: number;
866
- /** Called when data is received */
867
- onData(buffer: Float32Array): Promise<void>;
868
- /** Called when a chunk of voice is recorded */
869
- onVoiceChunk(buffer: Float32Array): void;
870
- /** Called when the voice recording ends */
871
- onVoiceEnd(buffers: Float32Array[]): void;
802
+ declare class TokenWindow {
803
+ /** Token window size */
804
+ size: number;
805
+ /** Token groups */
806
+ groups: TokenWindowGroup<any>[];
807
+ /** Create a new group */
808
+ createGroup(id: string): TokenWindowGroup<unknown>;
809
+ /** Get a group */
810
+ group<CustomDataType>(id: string): TokenWindowGroup<CustomDataType> | undefined;
811
+ /** Calculate current tokens in all groups */
812
+ countTokens(): number;
813
+ /** Remove overflow from all groups. */
814
+ removeOverflow(): void;
815
+ /** Remove one overflow item. Returns null if no items were able to be removed. */
816
+ private removeOneItem;
817
+ }
818
+ /** A token group. */
819
+ declare class TokenWindowGroup<CustomDataType> {
820
+ /** Group ID */
821
+ id: string;
822
+ /** List of items */
823
+ items: TokenWindowGroupItem<CustomDataType>[];
824
+ /**
825
+ * Weight controls how many items from this group should be kept in relation to the entire window. For example if all
826
+ * groups have a weight of 1, each group remove items equally if full. If one has a weight of 2 while the rest are 1,
827
+ * that group will be allowed to keep double the amount of items.
828
+ */
829
+ weight: number;
830
+ /** Current total token count, computed automatically. Don't update this value manually. */
831
+ tokenCount: number;
832
+ /** Group item separator */
833
+ separator: string;
834
+ /** Token count padding added to each item. */
835
+ private itemPadding;
836
+ /** Sets the token count padding added to each item. Useful if you don't know exactly what will be added by the LLM host. */
837
+ setItemPadding(padding: number): this;
838
+ /** Sort function */
839
+ private sortFunction;
840
+ /** Set sort function */
841
+ sortBy(sortFunction: (a: TokenWindowGroupItem<CustomDataType>, b: TokenWindowGroupItem<CustomDataType>) => number): this;
842
+ /** Set separator */
843
+ setSeparator(separator: string): this;
844
+ /** Set weight */
845
+ setWeight(weight: number): this;
846
+ /** Recalculate all tokens. Note this may take a while. */
847
+ recalculateTokens(): void;
848
+ /** Add an item to the group */
849
+ add(item: string | Omit<Optional<TokenWindowGroupItem<CustomDataType>, 'id' | 'dateAdded' | 'sortOrder'>, 'tokenCount'>): TokenWindowGroupItem<CustomDataType>;
850
+ /** Get all items as a string */
851
+ getAllAsString(): string;
852
+ /** Get all items. Doesn't return disabled items. */
853
+ getAll(): TokenWindowGroupItem<CustomDataType>[];
854
+ /** Remove all items from this group */
855
+ empty(): void;
856
+ }
857
+ /** Token group item */
858
+ interface TokenWindowGroupItem<CustomDataType> {
859
+ /** Each item must have a unique ID. */
860
+ id: string;
861
+ /** The string content of the item */
862
+ content: string;
863
+ /** True if this item should never be removed */
864
+ cannotRemove?: boolean;
865
+ /** Sorting order. If not specified, uses dateAdded instead. */
866
+ sortOrder: number;
867
+ /** Date this item was added */
868
+ dateAdded: number;
869
+ /** Token count in the content */
870
+ tokenCount: number;
871
+ /** Anything to attach to this item */
872
+ customData?: CustomDataType;
873
+ /** If disabled, this item will not be included and will not add tot he token count. */
874
+ disabled?: boolean;
872
875
  }
873
876
 
877
+ // ==================================================================================================
878
+ // JSON Schema Draft 07
879
+ // ==================================================================================================
880
+ // https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
881
+ // --------------------------------------------------------------------------------------------------
882
+
874
883
  /**
875
- * This AudioNode uses OpenAI's Whisper model to transcribe spoken speech to text.
876
- *
877
- * - event `transcription` - Fired when a transcription is ready. `text` contains the transcribed text.
884
+ * Primitive type
885
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
878
886
  */
879
- declare class OpenAITranscriptionNode extends VoiceChunkOutputNode {
880
- /** OpenAI API key */
881
- apiKey: string;
882
- /** Pending buffers */
883
- private pendingBuffers;
884
- /** Last request */
885
- private lastRequestAbortController?;
886
- /** True if currently transcribing */
887
- isTranscribing: boolean;
888
- /** Constructor */
889
- constructor(audioContext: AudioContext, apiKey: string);
890
- /** Called when the voice recording ends */
891
- onVoiceEnd(buffers: Float32Array[]): Promise<void>;
892
- /** Called when a transcription is ready */
893
- onVoiceTranscription(text: string): void;
894
- }
887
+ type JSONSchema7TypeName =
888
+ | "string" //
889
+ | "number"
890
+ | "integer"
891
+ | "boolean"
892
+ | "object"
893
+ | "array"
894
+ | "null";
895
895
 
896
896
  /**
897
- * This AudioNode uses IntelliWeave's servers to transcribe spoken speech to text.
898
- *
899
- * - event `transcription` - Fired when a transcription is ready. `text` contains the transcribed text.
897
+ * Primitive type
898
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
900
899
  */
901
- declare class IntelliWeaveTranscriptionNode extends VoiceChunkOutputNode {
902
- /** Debug: Export each recording as a wav file for download */
903
- static debugExportWav: boolean;
904
- /** Server address for transcription */
905
- apiAddress: string;
906
- /** OpenAI API key */
907
- apiKey: string;
908
- /** WebSocket connection */
909
- private ws?;
910
- /** True if currently transcribing */
911
- isTranscribing: boolean;
912
- /** WebSocket shutdown timer */
913
- private shutdownTimer?;
914
- /** Constructor */
915
- constructor(audioContext: AudioContext, apiKey: string);
916
- /** Called when a voice chunk is received */
917
- onVoiceChunk(buffer: Float32Array): Promise<void>;
918
- /** Called when the voice recording ends */
919
- onVoiceEnd(buffers: Float32Array[]): Promise<void>;
920
- /** Called when a transcription is ready */
921
- onVoiceTranscription(text: string): void;
922
- /** Called when the WebSocket is closed */
923
- onSocketClose(): void;
900
+ type JSONSchema7Type =
901
+ | string //
902
+ | number
903
+ | boolean
904
+ | JSONSchema7Object
905
+ | JSONSchema7Array
906
+ | null;
907
+
908
+ // Workaround for infinite type recursion
909
+ interface JSONSchema7Object {
910
+ [key: string]: JSONSchema7Type;
924
911
  }
925
912
 
913
+ // Workaround for infinite type recursion
914
+ // https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
915
+ interface JSONSchema7Array extends Array<JSONSchema7Type> {}
916
+
926
917
  /**
927
- * Handles speech recognition from the microphone
918
+ * Meta schema
928
919
  *
929
- * - event `speechstart` - We have detected the user started speaking
930
- * - event `speechend` - We have detected the user stopped speaking
931
- * - event `speech` - Speech recognition result
932
- * - event `start` - Speech recognition started
933
- * - event `end` - Speech recognition ended
920
+ * Recommended values:
921
+ * - 'http://json-schema.org/schema#'
922
+ * - 'http://json-schema.org/hyper-schema#'
923
+ * - 'http://json-schema.org/draft-07/schema#'
924
+ * - 'http://json-schema.org/draft-07/hyper-schema#'
925
+ *
926
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
934
927
  */
935
- declare class WebWeaverSpeechRecognition extends EventTarget {
936
- /** Reference to the AI */
937
- ai?: IntelliWeave;
938
- /** True if recognition is running */
939
- isRunning: boolean;
940
- /** The audio analyser node */
941
- private analyserNode?;
942
- /** The audio analyser buffer */
943
- private analyserBuffer?;
944
- /** The microphone stream */
945
- micStream?: MediaStream;
946
- /** Recording start time for tracking duration */
947
- private recordingStartTime?;
948
- /** Returns true if speech recognition is supported by this persona and browser */
949
- get isSupported(): boolean;
950
- /** Currently active voice detection node */
951
- voiceDetection?: IntelliWeaveTranscriptionNode | OpenAITranscriptionNode;
952
- /** Constructor */
953
- constructor(ai: IntelliWeave);
954
- private _skipEvents;
955
- /** Start recognition */
956
- start(): Promise<void>;
957
- /** Stop recognition */
958
- stop(): void;
959
- /** @private Maximum volume heard this session */
960
- maxVolumeHeard: number;
961
- /** Get current (realtime) microphone volume level, from 0 to 1 */
962
- get volumeLevel(): number;
963
- /** True if currently detecting words being spoken */
964
- get wordsCurrentlyBeingSpoken(): boolean;
965
- /** True if currently transcribing voice to text */
966
- get isTranscribing(): boolean;
967
- /** Called when speech has been recorded */
968
- onTranscription(e: CustomEvent): void;
969
- /** Called to reset the speech recognizer */
970
- reset(): Promise<void>;
971
- }
972
-
973
- /** Handles creating and managing the AudioContext */
974
- declare class AudioSystem {
975
- /** Reference to the AI */
976
- private ai?;
977
- /** The speech recognition module. */
978
- speechRecognition: WebWeaverSpeechRecognition;
979
- /** The speech output module. */
980
- speechOutput: WebWeaverSpeechOutput;
981
- /** The audio context */
982
- context?: AudioContext;
983
- /** List of active named locks */
984
- locks: string[];
985
- /** Returns true if speech recognition and output is supported by this persona and browser */
986
- static get isSupported(): boolean;
987
- /** Constructor */
988
- constructor(ai: IntelliWeave);
989
- /** Create a named lock to enable the audio system */
990
- beginAccess(namedLock: string): Promise<void>;
991
- /** Stop accessing the audio system */
992
- endAccess(namedLock: string): void;
993
- }
928
+ type JSONSchema7Version = string;
994
929
 
995
930
  /**
996
- * This class allows you to use the AI as a logic engine, data extractor, etc.
931
+ * JSON Schema v7
932
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
997
933
  */
998
- declare class AILogic {
999
- /** Reference to the AI */
1000
- private ai?;
1001
- /** Constructor */
1002
- constructor(ai: IntelliWeave);
1003
- /** Ask the AI a yes/no question associated with the specified data. Data must be JSON-serializable, or a string of any kind of data. */
1004
- boolean(config: IntelliWeaveInstructConfig): Promise<boolean>;
1005
- /** Ask the AI to select a choice from a list of options. */
1006
- choose(config: IntelliWeaveInstructConfig & {
1007
- /** List of choices the AI can pick from. */
1008
- options: string[];
1009
- }): Promise<string | undefined>;
934
+ type JSONSchema7Definition = JSONSchema7 | boolean;
935
+ interface JSONSchema7 {
936
+ $id?: string | undefined;
937
+ $ref?: string | undefined;
938
+ $schema?: JSONSchema7Version | undefined;
939
+ $comment?: string | undefined;
940
+
941
+ /**
942
+ * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4
943
+ * @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A
944
+ */
945
+ $defs?: {
946
+ [key: string]: JSONSchema7Definition;
947
+ } | undefined;
948
+
949
+ /**
950
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1
951
+ */
952
+ type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined;
953
+ enum?: JSONSchema7Type[] | undefined;
954
+ const?: JSONSchema7Type | undefined;
955
+
956
+ /**
957
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2
958
+ */
959
+ multipleOf?: number | undefined;
960
+ maximum?: number | undefined;
961
+ exclusiveMaximum?: number | undefined;
962
+ minimum?: number | undefined;
963
+ exclusiveMinimum?: number | undefined;
964
+
965
+ /**
966
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3
967
+ */
968
+ maxLength?: number | undefined;
969
+ minLength?: number | undefined;
970
+ pattern?: string | undefined;
971
+
972
+ /**
973
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4
974
+ */
975
+ items?: JSONSchema7Definition | JSONSchema7Definition[] | undefined;
976
+ additionalItems?: JSONSchema7Definition | undefined;
977
+ maxItems?: number | undefined;
978
+ minItems?: number | undefined;
979
+ uniqueItems?: boolean | undefined;
980
+ contains?: JSONSchema7Definition | undefined;
981
+
982
+ /**
983
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5
984
+ */
985
+ maxProperties?: number | undefined;
986
+ minProperties?: number | undefined;
987
+ required?: string[] | undefined;
988
+ properties?: {
989
+ [key: string]: JSONSchema7Definition;
990
+ } | undefined;
991
+ patternProperties?: {
992
+ [key: string]: JSONSchema7Definition;
993
+ } | undefined;
994
+ additionalProperties?: JSONSchema7Definition | undefined;
995
+ dependencies?: {
996
+ [key: string]: JSONSchema7Definition | string[];
997
+ } | undefined;
998
+ propertyNames?: JSONSchema7Definition | undefined;
999
+
1000
+ /**
1001
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6
1002
+ */
1003
+ if?: JSONSchema7Definition | undefined;
1004
+ then?: JSONSchema7Definition | undefined;
1005
+ else?: JSONSchema7Definition | undefined;
1006
+
1007
+ /**
1008
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7
1009
+ */
1010
+ allOf?: JSONSchema7Definition[] | undefined;
1011
+ anyOf?: JSONSchema7Definition[] | undefined;
1012
+ oneOf?: JSONSchema7Definition[] | undefined;
1013
+ not?: JSONSchema7Definition | undefined;
1014
+
1010
1015
  /**
1011
- * Ask the AI to extract data from input data. The AI will return the extracted data. Possibly an array of multiple extractions.
1016
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7
1012
1017
  */
1013
- extract<T = any>(config: IntelliWeaveInstructConfig & {
1014
- /** Allow multiple items to be returned. If true, returns an array instead of an object. */
1015
- allowMultiple?: boolean;
1016
- /** Fields to extract in each object. */
1017
- extractions: {
1018
- /** Field name */
1019
- name: string;
1020
- /** Field data type */
1021
- type: 'string' | 'number' | 'boolean' | 'date' | 'email' | 'phone' | 'address';
1022
- /** Describe to the AI what data to put in this field. */
1023
- description?: string;
1024
- }[];
1025
- }): Promise<T[]>;
1018
+ format?: string | undefined;
1019
+
1026
1020
  /**
1027
- * Generate a Markdown document based on the data from the user.
1028
- *
1029
- * @param config Instruct config.
1030
- * @returns A markdown document.
1021
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8
1031
1022
  */
1032
- generateMarkdown(config: Omit<IntelliWeaveInstructConfig, 'instruction'>): Promise<string>;
1023
+ contentMediaType?: string | undefined;
1024
+ contentEncoding?: string | undefined;
1025
+
1033
1026
  /**
1034
- * Perform an instruction.
1035
- *
1036
- * @param config Instruct config.
1037
- * @returns The final response from the AI.
1027
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9
1038
1028
  */
1039
- instruct(config: IntelliWeaveInstructConfig): Promise<string>;
1040
- }
1041
- /** Config for any instruct call */
1042
- interface IntelliWeaveInstructConfig {
1043
- /** Instruction */
1044
- instruction: string;
1045
- /** Input data or query to process */
1046
- data: any;
1047
- /** Whether to allow the AI to use the knowledge base or not. If false, the AI will not use the knowledge base. */
1048
- allowKB?: boolean;
1049
- /** Callback that will be called when streaming the response. Each call will contain the full text that has been generated so far. */
1050
- callback?: (txt: string) => void;
1029
+ definitions?: {
1030
+ [key: string]: JSONSchema7Definition;
1031
+ } | undefined;
1032
+
1033
+ /**
1034
+ * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10
1035
+ */
1036
+ title?: string | undefined;
1037
+ description?: string | undefined;
1038
+ default?: JSONSchema7Type | undefined;
1039
+ readOnly?: boolean | undefined;
1040
+ writeOnly?: boolean | undefined;
1041
+ examples?: JSONSchema7Type | undefined;
1051
1042
  }
1052
1043
 
1044
+ /** Chat config options */
1045
+ interface ChatBaseConfig {
1046
+ /** API key */
1047
+ apiKey: string;
1048
+ /** Provider ID */
1049
+ providerID?: string;
1050
+ /** Endpoint URL if using a custom URL */
1051
+ endpoint: string;
1052
+ /** LLM model to use */
1053
+ model: string;
1054
+ /** System message to describe to the AI how to behave. */
1055
+ systemMessage: string;
1056
+ /** User ID used to uniquely identify users in ChatGPT's API */
1057
+ userID: string;
1058
+ /** If true, streams the text responses from the API */
1059
+ stream: boolean;
1060
+ /** Amount of estimated tokens to keep when trimming */
1061
+ maxTokens: number;
1062
+ /** Callback before the AI sends info to the LLM */
1063
+ onBeforeMessageProcessing?: () => void;
1064
+ /** Callback when a message from the AI is returned. If isChunk is true, it may be incomplete and be called again with more updates. */
1065
+ onAIMessage?: (text: string, isChunk: boolean) => void;
1066
+ /** Callback when the AI starts performing an action */
1067
+ onAIToolStart?: (toolName: string, input: any) => void;
1068
+ }
1069
+ /** Chat tool config */
1070
+ interface ChatBaseToolConfig {
1071
+ /** Name of the tool, eg "perform_search" */
1072
+ name: string;
1073
+ /** Description of the tool */
1074
+ description: string;
1075
+ /** Parameters for the tool */
1076
+ params: JSONSchema7;
1077
+ /** Callback function to process the tool */
1078
+ callback: (params: any) => any;
1079
+ /** If true, this tool call will be removed from the message history after it is executed. */
1080
+ removeFromMessageHistory?: boolean;
1081
+ /** If true, this item can be removed if there's not enough context available. */
1082
+ canRemove?: boolean;
1083
+ /** Misc app context */
1084
+ [key: string]: any;
1085
+ }
1053
1086
  /**
1054
- * Allows an MCP server to be used as a knowledge source for IntelliWeave.
1087
+ * API for interacting with chat APIs.
1055
1088
  */
1056
- declare class MCPKnowledgeClient {
1057
- /** MCP client */
1058
- client?: Client;
1059
- /** All tools discovered on the MCP server. Only available after connect() has completed. */
1060
- tools: Awaited<ReturnType<Client['listTools']>>['tools'];
1061
- /** All toold discovered, mapped to IntelliWeave knowledge base actions */
1062
- iwActions: KnowledgeBaseItem[];
1089
+ declare class ChatBase<
1090
+ /** Format for messages in the token window */
1091
+ MessageFormat = any,
1092
+ /** Optional extended config */
1093
+ ConfigFormat extends ChatBaseConfig = ChatBaseConfig> {
1094
+ /** ID */
1095
+ id: string;
1096
+ /** Metadata */
1097
+ metadata: any;
1098
+ /** Config */
1099
+ config: ConfigFormat;
1100
+ /** The maximum tool calls in sequence the AI can make before an error is thrown. */
1101
+ maxToolCallsPerMessage: number;
1063
1102
  /** Statistics */
1064
1103
  stats: {
1065
- toolsCalled: number;
1066
- };
1067
- /** Configuration */
1068
- config: {
1069
- /** Source ID */
1070
- id?: string;
1071
- /** URL to the MCP server endpoint */
1072
- baseURL?: string;
1073
- /** Custom connection function. If specified, baseURL is optional. */
1074
- connect?: () => Promise<Client>;
1075
- /**
1076
- * The name of the tool which provides knowledge searching. If specified, the search() will exclude this function and instead
1077
- * call it and show returned results. If not specified, the search() will just return all tools.
1078
- */
1079
- searchToolName?: string;
1080
- /** Keep search function available for the AI to use. */
1081
- searchToolVisible?: boolean;
1104
+ /** Total tokens used this session */
1105
+ tokensUsed: number;
1082
1106
  };
1107
+ /** Token window management */
1108
+ tokenWindow: TokenWindow;
1109
+ /** Token window group used for the context message */
1110
+ get contextGroup(): TokenWindowGroup<any>;
1111
+ /** Token window group used for tools / actions */
1112
+ get toolGroup(): TokenWindowGroup<ChatBaseToolConfig>;
1113
+ /** Token window group used for messages */
1114
+ get messageGroup(): TokenWindowGroup<MessageFormat>;
1083
1115
  /** Constructor */
1084
- constructor(config: MCPKnowledgeClient['config']);
1085
- /** In-progress connection attempt */
1086
- private connectionPromise?;
1087
- /** Connect to the client */
1088
- connect(): Promise<Client<{
1089
- method: string;
1090
- params?: {
1091
- [x: string]: unknown;
1092
- _meta?: {
1093
- [x: string]: unknown;
1094
- progressToken?: string | number | undefined;
1095
- } | undefined;
1096
- } | undefined;
1097
- }, {
1098
- method: string;
1099
- params?: {
1100
- [x: string]: unknown;
1101
- _meta?: {
1102
- [x: string]: unknown;
1103
- } | undefined;
1104
- } | undefined;
1105
- }, {
1106
- [x: string]: unknown;
1107
- _meta?: {
1108
- [x: string]: unknown;
1109
- } | undefined;
1110
- }>>;
1111
- connectInternal(): Promise<Client<{
1112
- method: string;
1113
- params?: {
1114
- [x: string]: unknown;
1115
- _meta?: {
1116
- [x: string]: unknown;
1117
- progressToken?: string | number | undefined;
1118
- } | undefined;
1119
- } | undefined;
1120
- }, {
1121
- method: string;
1122
- params?: {
1123
- [x: string]: unknown;
1124
- _meta?: {
1125
- [x: string]: unknown;
1126
- } | undefined;
1127
- } | undefined;
1128
- }, {
1129
- [x: string]: unknown;
1130
- _meta?: {
1131
- [x: string]: unknown;
1132
- } | undefined;
1133
- }>>;
1134
- /** Disconnect from server */
1135
- disconnect(): Promise<void>;
1136
- /** Fetch list of tools from the MCP server */
1137
- private fetchTools;
1138
- /** Cache last search result */
1139
- lastSearchQuery: string;
1140
- lastSearchResults: KnowledgeBaseItem[];
1141
- /** Perform a search query */
1142
- search(query: string): Promise<KnowledgeBaseItem[]>;
1143
- /** Perform search using the configured search function */
1144
- private performSearchCall;
1145
- /** Perform tool call. */
1146
- private performToolCall;
1116
+ constructor(config: ConfigFormat);
1117
+ /** Send a message, and get the response */
1118
+ sendMessage(message: string): Promise<string>;
1119
+ /** Add a user message to the message history */
1120
+ addUserMessage(message: string): void;
1121
+ /** Add an assistant message to the message history */
1122
+ addAssistantMessage(message: string): void;
1123
+ /** Process incoming message from the AI. Can be used to respond to encoded actions in the text response. */
1124
+ onBeforeIncomingMessage(message: MessageFormat): void;
1125
+ /** Reset the conversation */
1126
+ resetConversation(): void;
1127
+ /** Trim message list */
1128
+ trimMessages(): Promise<void>;
1129
+ /** Register a tool. */
1130
+ registerTool(tool: ChatBaseToolConfig): TokenWindowGroupItem<ChatBaseToolConfig>;
1147
1131
  }
1148
1132
 
1149
1133
  /** Persona config received from the hub */
1150
1134
  interface WebWeaverGPTConfig {
1151
1135
  /** ID */
1152
1136
  id: string;
1153
- /** ChatGPT config */
1154
- model: ChatGPTConfig;
1137
+ /** Chat API config */
1138
+ model: ChatBaseConfig;
1155
1139
  /** If true, message history will be sent to the IntelliWeave hub for analysis */
1156
1140
  analytics?: boolean;
1157
1141
  /** Persona name */
@@ -1198,7 +1182,7 @@ interface WebWeaverGPTConfig {
1198
1182
  * - event `webweaver_loaded` - Fired when the AI is loaded with a new configuration. This is a global event that is fired on the window object.
1199
1183
  * - event `webweaver_error` - Fired when an error occurs during loading. This is a global event that is fired on the window object.
1200
1184
  * - event `input` - Fired when the user sends a message to the AI.
1201
- * - event `output` - Fired when the AI sends a message back to the user. If `event.detail.isChunk` is true, the message is incomplete and will be followed by more chunks.
1185
+ * - event `output` - Fired when the AI sends a message back to the user. If `event.detail.isChunk` is true, the message is incomplete and will be followed by more events.
1202
1186
  * - event `toolstart` - Fired when the AI starts performing an action.
1203
1187
  * - event `tool` - Fired when the AI finishes performing an action.
1204
1188
  */
@@ -1208,7 +1192,7 @@ declare class IntelliWeave extends EventTarget {
1208
1192
  /** Callback when a message from the AI is returned. If isChunk is true, it may be incomplete and be called again with more updates. */
1209
1193
  onAIMessage?: (text: string, isChunk: boolean) => void;
1210
1194
  /** Callback when the AI starts performing an action */
1211
- onAIToolStart?: ChatGPTConfig['onAIToolStart'];
1195
+ onAIToolStart?: ChatBaseConfig['onAIToolStart'];
1212
1196
  /** Current conversation ID */
1213
1197
  conversationID: string;
1214
1198
  /** Knowledge database interface */
@@ -1224,11 +1208,11 @@ declare class IntelliWeave extends EventTarget {
1224
1208
  /** Available LLMs */
1225
1209
  models: {
1226
1210
  id: string;
1227
- config: ChatGPTConfig;
1211
+ config: ChatBaseConfig;
1228
1212
  priority?: number;
1229
1213
  }[];
1230
1214
  /** Current LLM */
1231
- currentModel?: ChatGPT;
1215
+ currentModel?: ChatBase;
1232
1216
  /** The audio system. Set this to a new instance of AudioSystem to enable audio support */
1233
1217
  audio: AudioSystem | null;
1234
1218
  /** Silero VAD model blob */
@@ -1258,7 +1242,6 @@ declare class IntelliWeave extends EventTarget {
1258
1242
  getContextPrefix(): Promise<string>;
1259
1243
  /** Get system message to send to the AI */
1260
1244
  onBeforeMessageProcessing(): Promise<void>;
1261
- private _lastOutput?;
1262
1245
  /** @private Process incoming message from the AI. Can be used to respond to encoded actions in the text response. */
1263
1246
  processIncomingMessage(message: string, isChunk?: boolean): void;
1264
1247
  /** True if currently processing a message */
@@ -1279,7 +1262,7 @@ declare class IntelliWeave extends EventTarget {
1279
1262
  exportState(): {
1280
1263
  type: string;
1281
1264
  conversationID: string;
1282
- messages: (ChatGPTMessage | undefined)[] | undefined;
1265
+ messages: any[] | undefined;
1283
1266
  };
1284
1267
  /** Import conversation state from JSON */
1285
1268
  importState(state: any): void;
@@ -1532,6 +1515,8 @@ declare class WebWeaverEmbed extends BaseComponent {
1532
1515
  resetConversation(): void;
1533
1516
  /** True if busy processing */
1534
1517
  private _isProcessing;
1518
+ /** The element which will receive the current message from the AI */
1519
+ currentOutputElement?: HTMLElement;
1535
1520
  /** Process input text from the user */
1536
1521
  processInput(inputText: string): Promise<void>;
1537
1522
  /** Called when the AI responds with some text */
@@ -1583,6 +1568,59 @@ declare function getDefaultUserID(): string;
1583
1568
  /** Convert an IntelliWeave parameter list to JSON schema. Does not modify if it's already a JSON schema. */
1584
1569
  declare function convertParamsToJSONSchema(params: KnowledgeBaseActionParameterSchema): JSONSchema7;
1585
1570
 
1571
+ /** ChatGPT message */
1572
+ interface ChatGPTMessage {
1573
+ /** Role of the message */
1574
+ role: 'user' | 'assistant' | 'system' | 'tool';
1575
+ /** Content of the message */
1576
+ content: string;
1577
+ /** Tool call ID */
1578
+ tool_call_id?: string;
1579
+ /** Tool calls made by the AI */
1580
+ tool_calls?: any[];
1581
+ }
1582
+ /**
1583
+ * API for interacting with ChatGPT APIs.
1584
+ */
1585
+ declare class ChatGPT extends ChatBase<ChatGPTMessage> {
1586
+ /** Send a message, and get the response */
1587
+ sendMessage(message: string): Promise<string>;
1588
+ /** Insert a message as if the assistant has written it */
1589
+ addAssistantMessage(message: string): void;
1590
+ /** Insert a message sent from a user. Note that doing this instead of using `sendMessage()` means you'll need to manually call `await processMessages()` and then `getLatestMessage()` to get the response. */
1591
+ addUserMessage(message: string): void;
1592
+ /** Get all messages */
1593
+ getMessages(): ChatGPTMessage[];
1594
+ /** Get latest message */
1595
+ getLatestMessage(): ChatGPTMessage | undefined;
1596
+ /** @private Process messages in the chat history */
1597
+ processMessages(): Promise<void>;
1598
+ /** Trim message list */
1599
+ trimMessages(): Promise<void>;
1600
+ /** @private Send HTTP request to the API and return the response */
1601
+ sendRequest(payload: any): Promise<Response>;
1602
+ /** @private Send message list to the API and store the response */
1603
+ sendToAPI(generatePayloadOnly?: boolean): Promise<any>;
1604
+ /** @private Process a tool call request from the AI */
1605
+ processToolCall(toolCall: any): Promise<void>;
1606
+ }
1607
+
1608
+ /**
1609
+ * API for interacting with Anthropic APIs.
1610
+ */
1611
+ declare class AnthropicChat extends ChatBase<Anthropic.Messages.MessageParam> {
1612
+ /** Add a user message to the message history */
1613
+ addUserMessage(message: string): void;
1614
+ /** Add an assistant message to the message history */
1615
+ addAssistantMessage(message: string): void;
1616
+ /** Send a message, and get the response */
1617
+ sendMessage(message: string): Promise<string>;
1618
+ /** Calls the specified tool and returns a tool_result block */
1619
+ protected performToolCall(toolUse: Anthropic.Messages.ToolUseBlockParam): Promise<Anthropic.Messages.ToolResultBlockParam>;
1620
+ /** Trim message list */
1621
+ trimMessages(): Promise<void>;
1622
+ }
1623
+
1586
1624
  /** Class to help with logging */
1587
1625
  declare class Logging {
1588
1626
  /** Current module */
@@ -1658,4 +1696,4 @@ interface IntelliWeaveStreamTextOutputEvent extends IntelliWeaveStreamEvent {
1658
1696
  text: string;
1659
1697
  }
1660
1698
 
1661
- export { type BufferType, BufferedWebSocket, ChatGPT, type ChatGPTConfig, type ChatGPTMessage, type ChatGPTToolConfig, FixedBufferStream, IntelliWeave, type IntelliWeaveGlobalConfig, type IntelliWeaveParameterDefinition, IntelliWeaveStream, type IntelliWeaveStreamErrorEvent, type IntelliWeaveStreamEvent, type IntelliWeaveStreamTextOutputEvent, KnowledgeBase, type KnowledgeBaseActionParameterSchema, type KnowledgeBaseItem, type KnowledgeBaseSource, type KnowledgeBaseWebhookActionResponse, type KnowledgeBaseWebhookRequest, type KnowledgeBaseWebhookSearchResponse, type KnowledgeFetcher, Logging, MCPKnowledgeClient, ONNXModel, type ONNXTensors, Resampler, type SupportedArrayBuffers, TokenWindow, TokenWindowGroup, type TokenWindowGroupItem, type WebWeaverGPTConfig, audioToWav, convertParamsToJSONSchema, floatTo16BitPCM, floatTo64BitPCM, getDefaultUserID, int16ToFloat32BitPCM, intelliweaveConfig, intelliweaveGlobalThis, sseEvents, trimWhitespaceInText };
1699
+ export { AnthropicChat, type BufferType, BufferedWebSocket, ChatBase, type ChatBaseConfig, type ChatBaseToolConfig, ChatGPT, type ChatGPTMessage, FixedBufferStream, IntelliWeave, type IntelliWeaveGlobalConfig, type IntelliWeaveParameterDefinition, IntelliWeaveStream, type IntelliWeaveStreamErrorEvent, type IntelliWeaveStreamEvent, type IntelliWeaveStreamTextOutputEvent, KnowledgeBase, type KnowledgeBaseActionParameterSchema, type KnowledgeBaseItem, type KnowledgeBaseSource, type KnowledgeBaseWebhookActionResponse, type KnowledgeBaseWebhookRequest, type KnowledgeBaseWebhookSearchResponse, type KnowledgeFetcher, Logging, MCPKnowledgeClient, ONNXModel, type ONNXTensors, Resampler, type SupportedArrayBuffers, TokenWindow, TokenWindowGroup, type TokenWindowGroupItem, type WebWeaverGPTConfig, audioToWav, convertParamsToJSONSchema, floatTo16BitPCM, floatTo64BitPCM, getDefaultUserID, int16ToFloat32BitPCM, intelliweaveConfig, intelliweaveGlobalThis, sseEvents, trimWhitespaceInText };