@infinityi/engine-lib 1.3.1 → 1.4.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.
- package/README.md +81 -445
- package/dist/agent/index.js +14 -8
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +8 -5
- package/dist/context/providers.d.ts +3 -3
- package/dist/context/types.d.ts +16 -1
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +6 -1
- package/dist/events/index.js +2 -1
- package/dist/execution/index.js +9 -4
- package/dist/execution/types.d.ts +14 -0
- package/dist/index-37x76zdn.js +4 -0
- package/dist/index-4c15ysa8.js +84 -0
- package/dist/{index-pwr8179t.js → index-7nb9qwa1.js} +23 -14
- package/dist/{index-jxgj4z08.js → index-9egrqxkf.js} +4 -0
- package/dist/index-9rr5dkzh.js +0 -0
- package/dist/{index-w34cbktd.js → index-a67ej96j.js} +1 -0
- package/dist/{index-64tt9696.js → index-aed6fe4z.js} +3 -3
- package/dist/{index-7690reng.js → index-ajr3nk10.js} +15 -1
- package/dist/index-c6kgts41.js +0 -0
- package/dist/{index-xsv43c5j.js → index-e14g2e48.js} +2 -2
- package/dist/index-k0q7x4mz.js +54 -0
- package/dist/index-mnx5mqbs.js +102 -0
- package/dist/index-mr1hs98z.js +661 -0
- package/dist/{index-yrqrxwjt.js → index-nvdsr51v.js} +4 -38
- package/dist/{index-jp2b31xs.js → index-vwcyawfk.js} +4 -4
- package/dist/index-ycjsqfpq.js +39 -0
- package/dist/{index-bqg01r42.js → index-zdggff0y.js} +183 -180
- package/dist/index.d.ts +2 -2
- package/dist/index.js +49 -38
- package/dist/lifecycle/index.js +2 -0
- package/dist/messages/index.js +1 -0
- package/dist/providers/index.js +5 -4
- package/dist/retrieval/chunking.d.ts +8 -0
- package/dist/retrieval/context.d.ts +4 -0
- package/dist/retrieval/index.d.ts +19 -0
- package/dist/retrieval/index.js +747 -0
- package/dist/retrieval/loaders.d.ts +8 -0
- package/dist/retrieval/memory.d.ts +29 -0
- package/dist/retrieval/retriever.d.ts +8 -0
- package/dist/retrieval/types.d.ts +253 -0
- package/dist/retrieval/utils.d.ts +11 -0
- package/dist/retrieval/vector-store.d.ts +13 -0
- package/dist/runtime/index.js +2 -1
- package/dist/schema/index.js +10 -4
- package/dist/session/index.js +1 -0
- package/dist/session-stores/codec.d.ts +8 -0
- package/dist/session-stores/forge-data.d.ts +43 -0
- package/dist/session-stores/hooks.d.ts +4 -0
- package/dist/session-stores/ids.d.ts +3 -0
- package/dist/session-stores/index.d.ts +20 -0
- package/dist/session-stores/index.js +1382 -0
- package/dist/session-stores/jsonl.d.ts +26 -0
- package/dist/session-stores/redis.d.ts +45 -0
- package/dist/session-stores/types.d.ts +45 -0
- package/dist/session-stores/versioning.d.ts +6 -0
- package/dist/testing/conformance.js +5 -4
- package/dist/testing/index.js +1 -0
- package/dist/tools/index.js +5 -3
- package/dist/tools-fs/define.d.ts +2 -0
- package/dist/tools-fs/files.d.ts +40 -0
- package/dist/tools-fs/git.d.ts +14 -0
- package/dist/tools-fs/index.d.ts +19 -0
- package/dist/tools-fs/index.js +1695 -0
- package/dist/tools-fs/policy.d.ts +32 -0
- package/dist/tools-fs/schemas.d.ts +31 -0
- package/dist/tools-fs/search.d.ts +45 -0
- package/dist/tools-fs/symbols.d.ts +12 -0
- package/dist/tools-fs/types.d.ts +151 -0
- package/dist/tools-http/client.d.ts +12 -0
- package/dist/tools-http/define.d.ts +12 -0
- package/dist/tools-http/events.d.ts +22 -0
- package/dist/tools-http/index.d.ts +24 -0
- package/dist/tools-http/index.js +18 -0
- package/dist/tools-http/policy.d.ts +52 -0
- package/dist/tools-http/types.d.ts +116 -0
- package/dist/tools-shell/define.d.ts +23 -0
- package/dist/tools-shell/events.d.ts +38 -0
- package/dist/tools-shell/exec.d.ts +37 -0
- package/dist/tools-shell/index.d.ts +30 -0
- package/dist/tools-shell/index.js +327 -0
- package/dist/tools-shell/policy.d.ts +42 -0
- package/dist/tools-shell/types.d.ts +121 -0
- package/dist/tools-web/define.d.ts +11 -0
- package/dist/tools-web/html.d.ts +22 -0
- package/dist/tools-web/index.d.ts +21 -0
- package/dist/tools-web/index.js +472 -0
- package/dist/tools-web/types.d.ts +81 -0
- package/docs/README.md +58 -10
- package/docs/api/.nojekyll +1 -0
- package/docs/api/assets/hierarchy.js +1 -0
- package/docs/api/assets/highlight.css +99 -0
- package/docs/api/assets/icons.js +18 -0
- package/docs/api/assets/icons.svg +1 -0
- package/docs/api/assets/main.js +60 -0
- package/docs/api/assets/navigation.js +1 -0
- package/docs/api/assets/search.js +1 -0
- package/docs/api/assets/style.css +1633 -0
- package/docs/api/classes/errors.AgentError.html +47 -0
- package/docs/api/classes/errors.CancelledError.html +46 -0
- package/docs/api/classes/errors.ContextWindowError.html +48 -0
- package/docs/api/classes/errors.ExecutionError.html +46 -0
- package/docs/api/classes/errors.FilesystemPolicyError.html +48 -0
- package/docs/api/classes/errors.MaxHandoffsExceededError.html +47 -0
- package/docs/api/classes/errors.MaxStepsExceededError.html +47 -0
- package/docs/api/classes/errors.ProviderError.html +47 -0
- package/docs/api/classes/errors.SchemaValidationError.html +47 -0
- package/docs/api/classes/errors.ShellPolicyError.html +50 -0
- package/docs/api/classes/errors.ToolError.html +47 -0
- package/docs/api/classes/errors.ToolValidationError.html +48 -0
- package/docs/api/classes/index.InMemorySessionStore.html +11 -0
- package/docs/api/classes/index.Secret.html +20 -0
- package/docs/api/classes/providers.StreamAccumulator.html +8 -0
- package/docs/api/classes/session-stores.FilesystemJsonlSessionStore.html +13 -0
- package/docs/api/classes/session-stores.ForgeDataSessionStore.html +14 -0
- package/docs/api/classes/session-stores.RedisSessionStore.html +12 -0
- package/docs/api/classes/tools-http.HttpPolicyError.html +41 -0
- package/docs/api/functions/agent.createToolRegistry.html +3 -0
- package/docs/api/functions/agent.handoffProviderTools.html +3 -0
- package/docs/api/functions/agent.handoffToolName.html +2 -0
- package/docs/api/functions/agent.resolveHandoffTargets.html +8 -0
- package/docs/api/functions/context.applyContextWindow.html +5 -0
- package/docs/api/functions/context.estimateTokens.html +3 -0
- package/docs/api/functions/context.resolveContext.html +5 -0
- package/docs/api/functions/events.createRunTelemetry.html +3 -0
- package/docs/api/functions/events.eventFields.html +4 -0
- package/docs/api/functions/events.eventPayload.html +5 -0
- package/docs/api/functions/execution.addUsage.html +2 -0
- package/docs/api/functions/execution.emptyUsage.html +2 -0
- package/docs/api/functions/index.asSchema.html +4 -0
- package/docs/api/functions/index.asTool.html +8 -0
- package/docs/api/functions/index.assistant.html +2 -0
- package/docs/api/functions/index.createAgentRegistry.html +5 -0
- package/docs/api/functions/index.createAnthropic.html +5 -0
- package/docs/api/functions/index.createEventHub.html +2 -0
- package/docs/api/functions/index.createGoogle.html +5 -0
- package/docs/api/functions/index.createOpenAI.html +5 -0
- package/docs/api/functions/index.createOpenAICompatible.html +7 -0
- package/docs/api/functions/index.createSession.html +3 -0
- package/docs/api/functions/index.defineAgent.html +7 -0
- package/docs/api/functions/index.defineTool.html +7 -0
- package/docs/api/functions/index.dynamicContext.html +2 -0
- package/docs/api/functions/index.fromJsonSchema.html +3 -0
- package/docs/api/functions/index.isSecret.html +4 -0
- package/docs/api/functions/index.loggingSubscriber.html +4 -0
- package/docs/api/functions/index.messageBusSubscriber.html +6 -0
- package/docs/api/functions/index.normalizeContent.html +2 -0
- package/docs/api/functions/index.resolveSecret.html +4 -0
- package/docs/api/functions/index.runAgent.html +19 -0
- package/docs/api/functions/index.staticContext.html +3 -0
- package/docs/api/functions/index.summarizeOldest.html +4 -0
- package/docs/api/functions/index.system.html +2 -0
- package/docs/api/functions/index.text.html +2 -0
- package/docs/api/functions/index.toJsonSchema.html +2 -0
- package/docs/api/functions/index.toolResult.html +2 -0
- package/docs/api/functions/index.truncateOldest.html +5 -0
- package/docs/api/functions/index.user.html +2 -0
- package/docs/api/functions/index.validateJsonSchema.html +3 -0
- package/docs/api/functions/lifecycle.agentRuntimeComponent.html +5 -0
- package/docs/api/functions/providers.collectStream.html +2 -0
- package/docs/api/functions/providers.createProvider.html +4 -0
- package/docs/api/functions/providers.createProviderHttp.html +3 -0
- package/docs/api/functions/providers.defaultProviderResilience.html +3 -0
- package/docs/api/functions/providers.openSseStream.html +6 -0
- package/docs/api/functions/providers.parseSse.html +2 -0
- package/docs/api/functions/providers.toProviderError.html +2 -0
- package/docs/api/functions/session-stores.createPostgresSessionStore.html +1 -0
- package/docs/api/functions/session-stores.createSqliteSessionStore.html +1 -0
- package/docs/api/functions/session-stores.isCloseableSessionStore.html +1 -0
- package/docs/api/functions/session-stores.isVersionedSessionStore.html +1 -0
- package/docs/api/functions/session-stores.migrateSessionStore.html +1 -0
- package/docs/api/functions/session-stores.withSessionStoreHooks.html +2 -0
- package/docs/api/functions/testing.byteStreamOf.html +2 -0
- package/docs/api/functions/testing.collectProviderStream.html +2 -0
- package/docs/api/functions/testing.conversation.html +2 -0
- package/docs/api/functions/testing.expectValid.html +3 -0
- package/docs/api/functions/testing.inMemorySessionStore.html +2 -0
- package/docs/api/functions/testing.jsonFetch.html +3 -0
- package/docs/api/functions/testing.mockProvider.html +3 -0
- package/docs/api/functions/testing.scriptedProvider.html +4 -0
- package/docs/api/functions/testing.sseFetch.html +3 -0
- package/docs/api/functions/testing.textResult.html +3 -0
- package/docs/api/functions/testing.toolCallResult.html +3 -0
- package/docs/api/functions/testing_conformance.runProviderConformance.html +3 -0
- package/docs/api/functions/tools-fs.filesystemTools.html +1 -0
- package/docs/api/functions/tools-http.createHttpToolClient.html +2 -0
- package/docs/api/functions/tools-http.httpTools.html +2 -0
- package/docs/api/functions/tools-shell.shellTools.html +4 -0
- package/docs/api/functions/tools-web.webTools.html +2 -0
- package/docs/api/functions/tools.renderToolContent.html +6 -0
- package/docs/api/functions/tools.toProviderTool.html +3 -0
- package/docs/api/functions/tools.toToolResultMessage.html +4 -0
- package/docs/api/hierarchy.html +1 -0
- package/docs/api/index.html +1 -0
- package/docs/api/interfaces/agent.ToolRegistry.html +8 -0
- package/docs/api/interfaces/errors.SchemaIssue.html +4 -0
- package/docs/api/interfaces/events.RunTelemetry.html +10 -0
- package/docs/api/interfaces/events.SpanHandle.html +6 -0
- package/docs/api/interfaces/index.AgentDefinition.html +16 -0
- package/docs/api/interfaces/index.AgentHooks.html +21 -0
- package/docs/api/interfaces/index.AgentRegistry.html +16 -0
- package/docs/api/interfaces/index.AnthropicOptions.html +13 -0
- package/docs/api/interfaces/index.AsToolOptions.html +13 -0
- package/docs/api/interfaces/index.CompletionRequest.html +30 -0
- package/docs/api/interfaces/index.CompletionResult.html +14 -0
- package/docs/api/interfaces/index.ContextItem.html +6 -0
- package/docs/api/interfaces/index.ContextProvider.html +5 -0
- package/docs/api/interfaces/index.ContextStrategy.html +8 -0
- package/docs/api/interfaces/index.ContextStrategyContext.html +8 -0
- package/docs/api/interfaces/index.ContextWindowOptions.html +8 -0
- package/docs/api/interfaces/index.CreateSessionOptions.html +10 -0
- package/docs/api/interfaces/index.EngineContext.html +10 -0
- package/docs/api/interfaces/index.EventHub.html +4 -0
- package/docs/api/interfaces/index.EventHubOptions.html +8 -0
- package/docs/api/interfaces/index.GenerationSettings.html +12 -0
- package/docs/api/interfaces/index.GoogleOptions.html +11 -0
- package/docs/api/interfaces/index.ImagePart.html +5 -0
- package/docs/api/interfaces/index.InstructionContext.html +9 -0
- package/docs/api/interfaces/index.JsonSchema.html +18 -0
- package/docs/api/interfaces/index.LoggingSubscriberOptions.html +4 -0
- package/docs/api/interfaces/index.Message.html +8 -0
- package/docs/api/interfaces/index.MessageBusSubscriberOptions.html +4 -0
- package/docs/api/interfaces/index.OpenAICompatibleOptions.html +16 -0
- package/docs/api/interfaces/index.OpenAIOptions.html +16 -0
- package/docs/api/interfaces/index.Provider.html +11 -0
- package/docs/api/interfaces/index.ProviderCapabilities.html +9 -0
- package/docs/api/interfaces/index.ProviderTool.html +6 -0
- package/docs/api/interfaces/index.ResponseSchema.html +6 -0
- package/docs/api/interfaces/index.RunBridge.html +10 -0
- package/docs/api/interfaces/index.RunOptions.html +39 -0
- package/docs/api/interfaces/index.RunResult.html +20 -0
- package/docs/api/interfaces/index.Schema.html +13 -0
- package/docs/api/interfaces/index.Session.html +13 -0
- package/docs/api/interfaces/index.SessionState.html +5 -0
- package/docs/api/interfaces/index.SessionStore.html +15 -0
- package/docs/api/interfaces/index.TextPart.html +4 -0
- package/docs/api/interfaces/index.ToolCall.html +9 -0
- package/docs/api/interfaces/index.ToolCallPart.html +6 -0
- package/docs/api/interfaces/index.ToolContext.html +21 -0
- package/docs/api/interfaces/index.ToolDefinition.html +14 -0
- package/docs/api/interfaces/index.ToolFailure.html +9 -0
- package/docs/api/interfaces/index.ToolResultPart.html +8 -0
- package/docs/api/interfaces/index.ToolSpec.html +6 -0
- package/docs/api/interfaces/index.ToolSuccess.html +6 -0
- package/docs/api/interfaces/index.Usage.html +9 -0
- package/docs/api/interfaces/lifecycle.AgentRuntimeOptions.html +17 -0
- package/docs/api/interfaces/providers.AdapterSpec.html +17 -0
- package/docs/api/interfaces/providers.ProviderHttpOptions.html +14 -0
- package/docs/api/interfaces/providers.SseMessage.html +6 -0
- package/docs/api/interfaces/providers.SseRequest.html +8 -0
- package/docs/api/interfaces/runtime.Logger.html +22 -0
- package/docs/api/interfaces/runtime.Telemetry.html +9 -0
- package/docs/api/interfaces/schema.OptionalSchema.html +13 -0
- package/docs/api/interfaces/session-stores.CloseableSessionStore.html +11 -0
- package/docs/api/interfaces/session-stores.CreatePostgresSessionStoreOptions.html +6 -0
- package/docs/api/interfaces/session-stores.CreateSqliteSessionStoreOptions.html +7 -0
- package/docs/api/interfaces/session-stores.FilesystemJsonlSessionStoreOptions.html +3 -0
- package/docs/api/interfaces/session-stores.ForgeDataSessionStoreOptions.html +5 -0
- package/docs/api/interfaces/session-stores.RedisSessionStoreClient.html +9 -0
- package/docs/api/interfaces/session-stores.RedisSessionStoreOptions.html +4 -0
- package/docs/api/interfaces/session-stores.RedisSessionStoreTransaction.html +6 -0
- package/docs/api/interfaces/session-stores.SessionArchiveRecord.html +7 -0
- package/docs/api/interfaces/session-stores.SessionArchiver.html +2 -0
- package/docs/api/interfaces/session-stores.SessionCompactionResult.html +3 -0
- package/docs/api/interfaces/session-stores.SessionCompactor.html +3 -0
- package/docs/api/interfaces/session-stores.SessionStoreCodec.html +6 -0
- package/docs/api/interfaces/session-stores.SessionStoreHookContext.html +3 -0
- package/docs/api/interfaces/session-stores.SessionStoreHooks.html +3 -0
- package/docs/api/interfaces/session-stores.VersionedSessionStore.html +11 -0
- package/docs/api/interfaces/testing.MockProviderOptions.html +12 -0
- package/docs/api/interfaces/testing.RecordedCall.html +4 -0
- package/docs/api/interfaces/testing.RecordingFetch.html +4 -0
- package/docs/api/interfaces/testing_conformance.ConformanceFixtures.html +12 -0
- package/docs/api/interfaces/testing_conformance.ConformanceOptions.html +10 -0
- package/docs/api/interfaces/testing_conformance.ConformanceTestApi.html +4 -0
- package/docs/api/interfaces/testing_conformance.ProviderIO.html +7 -0
- package/docs/api/interfaces/tools-fs.ApplyPatchArgs.html +6 -0
- package/docs/api/interfaces/tools-fs.DiffStatusArgs.html +5 -0
- package/docs/api/interfaces/tools-fs.EditRangeArgs.html +7 -0
- package/docs/api/interfaces/tools-fs.EditReplaceArgs.html +7 -0
- package/docs/api/interfaces/tools-fs.FilesystemTools.html +13 -0
- package/docs/api/interfaces/tools-fs.FilesystemToolsConfig.html +12 -0
- package/docs/api/interfaces/tools-fs.FindFilesArgs.html +7 -0
- package/docs/api/interfaces/tools-fs.OpenWindowArgs.html +5 -0
- package/docs/api/interfaces/tools-fs.ReadArgs.html +9 -0
- package/docs/api/interfaces/tools-fs.RepoMapArgs.html +7 -0
- package/docs/api/interfaces/tools-fs.SearchSemanticArgs.html +8 -0
- package/docs/api/interfaces/tools-fs.SearchTextArgs.html +11 -0
- package/docs/api/interfaces/tools-fs.SymbolInfo.html +7 -0
- package/docs/api/interfaces/tools-fs.SymbolsArgs.html +5 -0
- package/docs/api/interfaces/tools-fs.ValidationCommandRequest.html +4 -0
- package/docs/api/interfaces/tools-fs.ValidationCommandResult.html +6 -0
- package/docs/api/interfaces/tools-fs.ValidationOptions.html +4 -0
- package/docs/api/interfaces/tools-fs.WriteFileArgs.html +6 -0
- package/docs/api/interfaces/tools-http.HeaderEntry.html +4 -0
- package/docs/api/interfaces/tools-http.HttpClientRequest.html +11 -0
- package/docs/api/interfaces/tools-http.HttpPolicy.html +13 -0
- package/docs/api/interfaces/tools-http.HttpRequestResult.html +17 -0
- package/docs/api/interfaces/tools-http.HttpRetryOptions.html +10 -0
- package/docs/api/interfaces/tools-http.HttpToolClient.html +5 -0
- package/docs/api/interfaces/tools-http.HttpTools.html +4 -0
- package/docs/api/interfaces/tools-http.HttpToolsConfig.html +38 -0
- package/docs/api/interfaces/tools-shell.ApprovalDecision.html +5 -0
- package/docs/api/interfaces/tools-shell.CommandRequest.html +14 -0
- package/docs/api/interfaces/tools-shell.CommandResult.html +21 -0
- package/docs/api/interfaces/tools-shell.EnvPolicy.html +9 -0
- package/docs/api/interfaces/tools-shell.ShellPolicy.html +7 -0
- package/docs/api/interfaces/tools-shell.ShellTools.html +6 -0
- package/docs/api/interfaces/tools-shell.ShellToolsConfig.html +26 -0
- package/docs/api/interfaces/tools-web.Citation.html +6 -0
- package/docs/api/interfaces/tools-web.SearchProvider.html +3 -0
- package/docs/api/interfaces/tools-web.SearchRequest.html +4 -0
- package/docs/api/interfaces/tools-web.SearchResult.html +7 -0
- package/docs/api/interfaces/tools-web.SourceMetadata.html +10 -0
- package/docs/api/interfaces/tools-web.WebTools.html +6 -0
- package/docs/api/interfaces/tools-web.WebToolsConfig.html +56 -0
- package/docs/api/modules/agent.html +5 -0
- package/docs/api/modules/context.html +5 -0
- package/docs/api/modules/errors.html +8 -0
- package/docs/api/modules/events.html +16 -0
- package/docs/api/modules/execution.html +4 -0
- package/docs/api/modules/index.html +16 -0
- package/docs/api/modules/lifecycle.html +6 -0
- package/docs/api/modules/messages.html +3 -0
- package/docs/api/modules/providers.html +10 -0
- package/docs/api/modules/runtime.html +4 -0
- package/docs/api/modules/schema.html +5 -0
- package/docs/api/modules/session-stores.html +6 -0
- package/docs/api/modules/session.html +4 -0
- package/docs/api/modules/testing.html +4 -0
- package/docs/api/modules/testing_conformance.html +21 -0
- package/docs/api/modules/tools-fs.html +9 -0
- package/docs/api/modules/tools-http.html +8 -0
- package/docs/api/modules/tools-shell.html +12 -0
- package/docs/api/modules/tools-web.html +7 -0
- package/docs/api/modules/tools.html +4 -0
- package/docs/api/types/events.Attrs.html +2 -0
- package/docs/api/types/index.AnyRunOptions.html +3 -0
- package/docs/api/types/index.BufferedRunOptions.html +2 -0
- package/docs/api/types/index.ContentPart.html +2 -0
- package/docs/api/types/index.FinishReason.html +2 -0
- package/docs/api/types/index.Infer.html +2 -0
- package/docs/api/types/index.Instructions.html +5 -0
- package/docs/api/types/index.LogLevel.html +2 -0
- package/docs/api/types/index.Role.html +2 -0
- package/docs/api/types/index.RunEvent.html +30 -0
- package/docs/api/types/index.RunHandle.html +7 -0
- package/docs/api/types/index.RunInput.html +2 -0
- package/docs/api/types/index.RunSubscriber.html +4 -0
- package/docs/api/types/index.SafeParseResult.html +2 -0
- package/docs/api/types/index.StreamEvent.html +8 -0
- package/docs/api/types/index.StreamingRunOptions.html +2 -0
- package/docs/api/types/index.TelemetryHandle.html +2 -0
- package/docs/api/types/index.TokenCounter.html +2 -0
- package/docs/api/types/index.ToolChoice.html +2 -0
- package/docs/api/types/index.ToolResult.html +2 -0
- package/docs/api/types/lifecycle.ProviderProbe.html +2 -0
- package/docs/api/types/session-stores.SessionStoreHookOperation.html +1 -0
- package/docs/api/types/testing_conformance.MakeProvider.html +2 -0
- package/docs/api/types/tools-fs.SymbolKind.html +1 -0
- package/docs/api/types/tools-http.HostPattern.html +2 -0
- package/docs/api/types/tools-shell.CommandPattern.html +2 -0
- package/docs/api/types/tools-web.RobotsPolicy.html +2 -0
- package/docs/api/variables/events.SPAN_PROVIDER.html +2 -0
- package/docs/api/variables/events.SPAN_RUN.html +2 -0
- package/docs/api/variables/events.SPAN_TOOL.html +2 -0
- package/docs/api/variables/execution.DEFAULT_MAX_HANDOFFS.html +2 -0
- package/docs/api/variables/execution.DEFAULT_MAX_STEPS.html +2 -0
- package/docs/api/variables/index.s.html +11 -0
- package/docs/api/variables/providers.DEFAULT_TIMEOUT_MS.html +2 -0
- package/docs/api/variables/session-stores.SESSION_STORE_SCHEMA_VERSION.html +1 -0
- package/docs/api/variables/session-stores.jsonSessionStoreCodec.html +2 -0
- package/docs/api/variables/tools-http.HTTP_EVENT.html +2 -0
- package/docs/api/variables/tools-shell.SHELL_EVENT.html +2 -0
- package/docs/events-and-telemetry.md +68 -0
- package/docs/execution.md +63 -0
- package/docs/getting-started.md +73 -0
- package/docs/multi-agent.md +52 -0
- package/docs/optional-tool-packs.md +93 -0
- package/docs/providers.md +68 -0
- package/docs/retrieval.md +83 -0
- package/docs/sessions-and-context.md +82 -0
- package/docs/testing-and-lifecycle.md +60 -0
- package/docs/tools.md +69 -0
- package/examples/01-minimal-agent.ts +19 -0
- package/examples/02-custom-tool.ts +32 -0
- package/examples/03-streaming.ts +46 -0
- package/examples/04-sessions-context.ts +40 -0
- package/examples/05-events-subscribers.ts +35 -0
- package/examples/06-multi-agent-handoff.ts +27 -0
- package/examples/07-sub-agent-tool.ts +26 -0
- package/examples/08-testing-agent.ts +31 -0
- package/examples/09-tools-filesystem.ts +49 -0
- package/examples/10-tools-http-web.ts +74 -0
- package/examples/11-shell-tools.ts +39 -0
- package/examples/12-provider-openai.ts +24 -0
- package/examples/13-lifecycle.ts +37 -0
- package/examples/14-retrieval.ts +65 -0
- package/examples/incident-analysis.ts +52 -0
- package/package.json +78 -4
- package/dist/index-02s1fjxr.js +0 -226
|
@@ -0,0 +1,747 @@
|
|
|
1
|
+
import {
|
|
2
|
+
estimateTokens
|
|
3
|
+
} from "../index-nvdsr51v.js";
|
|
4
|
+
import"../index-1p6mb2vz.js";
|
|
5
|
+
import {
|
|
6
|
+
CancelledError
|
|
7
|
+
} from "../index-ajr3nk10.js";
|
|
8
|
+
import"../index-37x76zdn.js";
|
|
9
|
+
|
|
10
|
+
// src/retrieval/utils.ts
|
|
11
|
+
function throwIfAborted(ctx) {
|
|
12
|
+
if (ctx === undefined)
|
|
13
|
+
return;
|
|
14
|
+
const signal = ctx.engine?.signal ?? ctx.signal;
|
|
15
|
+
if (signal?.aborted)
|
|
16
|
+
throw new CancelledError("retrieval cancelled");
|
|
17
|
+
}
|
|
18
|
+
function assertPositiveInteger(name, value) {
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
return;
|
|
21
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
|
|
22
|
+
throw new TypeError(`${name} must be a positive integer`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function assertNonNegativeInteger(name, value) {
|
|
26
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {
|
|
27
|
+
throw new TypeError(`${name} must be a non-negative integer`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/retrieval/chunking.ts
|
|
32
|
+
var DEFAULT_SEPARATORS = [`
|
|
33
|
+
|
|
34
|
+
`, `
|
|
35
|
+
`, ". ", " "];
|
|
36
|
+
function lineStarts(text) {
|
|
37
|
+
const starts = [0];
|
|
38
|
+
for (let index = 0;index < text.length; index += 1) {
|
|
39
|
+
if (text.charCodeAt(index) === 10)
|
|
40
|
+
starts.push(index + 1);
|
|
41
|
+
}
|
|
42
|
+
return starts;
|
|
43
|
+
}
|
|
44
|
+
function lineNumberAt(starts, offset) {
|
|
45
|
+
let low = 0;
|
|
46
|
+
let high = starts.length - 1;
|
|
47
|
+
while (low <= high) {
|
|
48
|
+
const mid = Math.floor((low + high) / 2);
|
|
49
|
+
const start = starts[mid] ?? 0;
|
|
50
|
+
const next = starts[mid + 1] ?? Number.POSITIVE_INFINITY;
|
|
51
|
+
if (offset >= start && offset < next)
|
|
52
|
+
return mid + 1;
|
|
53
|
+
if (offset < start)
|
|
54
|
+
high = mid - 1;
|
|
55
|
+
else
|
|
56
|
+
low = mid + 1;
|
|
57
|
+
}
|
|
58
|
+
return Math.max(1, starts.length);
|
|
59
|
+
}
|
|
60
|
+
function trimRange(text, start, end) {
|
|
61
|
+
let trimmedStart = start;
|
|
62
|
+
let trimmedEnd = end;
|
|
63
|
+
while (trimmedStart < trimmedEnd && /\s/.test(text[trimmedStart] ?? ""))
|
|
64
|
+
trimmedStart += 1;
|
|
65
|
+
while (trimmedEnd > trimmedStart && /\s/.test(text[trimmedEnd - 1] ?? ""))
|
|
66
|
+
trimmedEnd -= 1;
|
|
67
|
+
return { start: trimmedStart, end: trimmedEnd };
|
|
68
|
+
}
|
|
69
|
+
function findChunkEnd(text, start, maxChars, separators) {
|
|
70
|
+
const maxEnd = Math.min(text.length, start + maxChars);
|
|
71
|
+
if (maxEnd >= text.length)
|
|
72
|
+
return text.length;
|
|
73
|
+
const minBreak = start + Math.floor(maxChars / 2);
|
|
74
|
+
for (const separator of separators) {
|
|
75
|
+
if (separator === "")
|
|
76
|
+
continue;
|
|
77
|
+
const index = text.lastIndexOf(separator, maxEnd);
|
|
78
|
+
if (index > minBreak)
|
|
79
|
+
return Math.min(text.length, index + separator.length);
|
|
80
|
+
}
|
|
81
|
+
return maxEnd;
|
|
82
|
+
}
|
|
83
|
+
function fixedRanges(text, offset, maxChars) {
|
|
84
|
+
const ranges = [];
|
|
85
|
+
for (let start = 0;start < text.length; start += maxChars) {
|
|
86
|
+
ranges.push({ start: offset + start, end: offset + Math.min(text.length, start + maxChars) });
|
|
87
|
+
}
|
|
88
|
+
return ranges;
|
|
89
|
+
}
|
|
90
|
+
function splitBySeparator(text, offset, separator) {
|
|
91
|
+
const ranges = [];
|
|
92
|
+
let start = 0;
|
|
93
|
+
while (start < text.length) {
|
|
94
|
+
const index = text.indexOf(separator, start);
|
|
95
|
+
const end = index === -1 ? text.length : index + separator.length;
|
|
96
|
+
ranges.push({ start: offset + start, end: offset + end });
|
|
97
|
+
start = end;
|
|
98
|
+
}
|
|
99
|
+
return ranges;
|
|
100
|
+
}
|
|
101
|
+
function recursiveUnits(text, offset, maxChars, separators, separatorIndex) {
|
|
102
|
+
if (text.length <= maxChars)
|
|
103
|
+
return [{ start: offset, end: offset + text.length }];
|
|
104
|
+
const separator = separators[separatorIndex];
|
|
105
|
+
if (separator === undefined || separator === "")
|
|
106
|
+
return fixedRanges(text, offset, maxChars);
|
|
107
|
+
const split = splitBySeparator(text, offset, separator);
|
|
108
|
+
if (split.length <= 1)
|
|
109
|
+
return recursiveUnits(text, offset, maxChars, separators, separatorIndex + 1);
|
|
110
|
+
const out = [];
|
|
111
|
+
for (const range of split) {
|
|
112
|
+
const length = range.end - range.start;
|
|
113
|
+
if (length <= maxChars)
|
|
114
|
+
out.push(range);
|
|
115
|
+
else
|
|
116
|
+
out.push(...recursiveUnits(text.slice(range.start - offset, range.end - offset), range.start, maxChars, separators, separatorIndex + 1));
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
function mergeRanges(ranges, maxChars) {
|
|
121
|
+
const merged = [];
|
|
122
|
+
let current;
|
|
123
|
+
for (const range of ranges) {
|
|
124
|
+
if (current === undefined) {
|
|
125
|
+
current = range;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (range.end - current.start <= maxChars) {
|
|
129
|
+
current = { start: current.start, end: range.end };
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
merged.push(current);
|
|
133
|
+
current = range;
|
|
134
|
+
}
|
|
135
|
+
if (current !== undefined)
|
|
136
|
+
merged.push(current);
|
|
137
|
+
return merged;
|
|
138
|
+
}
|
|
139
|
+
function sourceForChunk(document, location) {
|
|
140
|
+
return {
|
|
141
|
+
...document.source ?? {},
|
|
142
|
+
...document.id !== undefined && document.source?.id === undefined ? { id: document.id } : {},
|
|
143
|
+
location
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function chunkId(document, documentIndex, chunkIndex) {
|
|
147
|
+
const sourceId = document.id ?? document.source?.id ?? document.source?.uri ?? `document-${documentIndex + 1}`;
|
|
148
|
+
return `${sourceId}#chunk-${chunkIndex + 1}`;
|
|
149
|
+
}
|
|
150
|
+
function chunkFromRange(document, documentIndex, chunkIndex, starts, range) {
|
|
151
|
+
const trimmed = trimRange(document.content, range.start, range.end);
|
|
152
|
+
if (trimmed.end <= trimmed.start)
|
|
153
|
+
return;
|
|
154
|
+
const location = {
|
|
155
|
+
startOffset: trimmed.start,
|
|
156
|
+
endOffset: trimmed.end,
|
|
157
|
+
startLine: lineNumberAt(starts, trimmed.start),
|
|
158
|
+
endLine: lineNumberAt(starts, Math.max(trimmed.start, trimmed.end - 1))
|
|
159
|
+
};
|
|
160
|
+
return {
|
|
161
|
+
id: chunkId(document, documentIndex, chunkIndex),
|
|
162
|
+
text: document.content.slice(trimmed.start, trimmed.end),
|
|
163
|
+
source: sourceForChunk(document, location),
|
|
164
|
+
...document.metadata !== undefined ? { metadata: document.metadata } : {}
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function createChunker(name, options, recursive) {
|
|
168
|
+
const maxChars = options.maxChars;
|
|
169
|
+
const overlapChars = options.overlapChars ?? 0;
|
|
170
|
+
assertPositiveInteger("maxChars", maxChars);
|
|
171
|
+
assertNonNegativeInteger("overlapChars", overlapChars);
|
|
172
|
+
if (overlapChars >= maxChars)
|
|
173
|
+
throw new TypeError("overlapChars must be smaller than maxChars");
|
|
174
|
+
const separators = options.separators ?? DEFAULT_SEPARATORS;
|
|
175
|
+
return {
|
|
176
|
+
name,
|
|
177
|
+
chunk(document, ctx) {
|
|
178
|
+
throwIfAborted(ctx);
|
|
179
|
+
const text = document.content;
|
|
180
|
+
if (text.trim() === "")
|
|
181
|
+
return [];
|
|
182
|
+
const starts = lineStarts(text);
|
|
183
|
+
const baseRanges = recursive ? mergeRanges(recursiveUnits(text, 0, maxChars, separators, 0), maxChars) : (() => {
|
|
184
|
+
const ranges2 = [];
|
|
185
|
+
let start = 0;
|
|
186
|
+
while (start < text.length) {
|
|
187
|
+
const end = findChunkEnd(text, start, maxChars, separators);
|
|
188
|
+
ranges2.push({ start, end });
|
|
189
|
+
if (end >= text.length)
|
|
190
|
+
break;
|
|
191
|
+
start = Math.max(start + 1, end - overlapChars);
|
|
192
|
+
}
|
|
193
|
+
return ranges2;
|
|
194
|
+
})();
|
|
195
|
+
const ranges = recursive ? baseRanges.map((range, index) => ({
|
|
196
|
+
start: index === 0 ? range.start : Math.max(0, range.end - maxChars, range.start - overlapChars),
|
|
197
|
+
end: range.end
|
|
198
|
+
})) : baseRanges;
|
|
199
|
+
const chunks = [];
|
|
200
|
+
for (const range of ranges) {
|
|
201
|
+
throwIfAborted(ctx);
|
|
202
|
+
const chunk = chunkFromRange(document, ctx?.documentIndex ?? 0, chunks.length, starts, range);
|
|
203
|
+
if (chunk !== undefined)
|
|
204
|
+
chunks.push(chunk);
|
|
205
|
+
}
|
|
206
|
+
return chunks;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function createTextChunker(options) {
|
|
211
|
+
return createChunker("text-chunker", options, false);
|
|
212
|
+
}
|
|
213
|
+
function recursiveTextChunker(options) {
|
|
214
|
+
return createChunker("recursive-text-chunker", options, true);
|
|
215
|
+
}
|
|
216
|
+
// src/retrieval/context.ts
|
|
217
|
+
function textOf(message) {
|
|
218
|
+
return message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
219
|
+
}
|
|
220
|
+
function latestUserText(messages) {
|
|
221
|
+
if (messages === undefined)
|
|
222
|
+
return;
|
|
223
|
+
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
224
|
+
const message = messages[index];
|
|
225
|
+
if (message?.role !== "user")
|
|
226
|
+
continue;
|
|
227
|
+
const text = textOf(message).trim();
|
|
228
|
+
if (text !== "")
|
|
229
|
+
return text;
|
|
230
|
+
}
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
async function resolveQuery(options, ctx, run) {
|
|
234
|
+
if (typeof options.query === "string")
|
|
235
|
+
return options.query.trim() === "" ? undefined : options.query;
|
|
236
|
+
if (typeof options.query === "function") {
|
|
237
|
+
const query = await options.query(ctx, run);
|
|
238
|
+
return query === undefined || query.trim() === "" ? undefined : query;
|
|
239
|
+
}
|
|
240
|
+
return latestUserText(run?.input) ?? latestUserText(run?.messages);
|
|
241
|
+
}
|
|
242
|
+
function messageForCount(text) {
|
|
243
|
+
return { role: "system", content: [{ type: "text", text }] };
|
|
244
|
+
}
|
|
245
|
+
function countText(text, countTokens) {
|
|
246
|
+
return countTokens([messageForCount(text)]);
|
|
247
|
+
}
|
|
248
|
+
function locationLabel(location) {
|
|
249
|
+
if (location === undefined)
|
|
250
|
+
return;
|
|
251
|
+
if (location.startLine !== undefined && location.endLine !== undefined) {
|
|
252
|
+
return location.startLine === location.endLine ? `line ${location.startLine}` : `lines ${location.startLine}-${location.endLine}`;
|
|
253
|
+
}
|
|
254
|
+
if (location.startOffset !== undefined && location.endOffset !== undefined) {
|
|
255
|
+
return `offsets ${location.startOffset}-${location.endOffset}`;
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
function sourceLabel(source) {
|
|
260
|
+
const name = source?.title ?? source?.uri ?? source?.id ?? "unknown source";
|
|
261
|
+
const location = locationLabel(source?.location);
|
|
262
|
+
return location === undefined ? name : `${name}, ${location}`;
|
|
263
|
+
}
|
|
264
|
+
function renderResult(result, citation, includeScores, text = result.text) {
|
|
265
|
+
const score = includeScores ? ` score=${result.score.toFixed(3)}` : "";
|
|
266
|
+
return `[${citation}] ${sourceLabel(result.source)}${score}
|
|
267
|
+
${text}`;
|
|
268
|
+
}
|
|
269
|
+
function joinBlocks(blocks) {
|
|
270
|
+
return blocks.join(`
|
|
271
|
+
|
|
272
|
+
`);
|
|
273
|
+
}
|
|
274
|
+
function appendBlock(content, block) {
|
|
275
|
+
return content === "" ? block : `${content}
|
|
276
|
+
|
|
277
|
+
${block}`;
|
|
278
|
+
}
|
|
279
|
+
function availableBudget(options, run, countTokens) {
|
|
280
|
+
if (options.maxContextTokens !== undefined)
|
|
281
|
+
return Math.max(0, options.maxContextTokens);
|
|
282
|
+
if (run?.contextWindow === undefined)
|
|
283
|
+
return;
|
|
284
|
+
const reserveTokens = options.reserveTokens ?? Math.min(512, Math.floor(run.contextWindow.maxTokens * 0.1));
|
|
285
|
+
const used = countTokens(run.messages);
|
|
286
|
+
return Math.max(0, run.contextWindow.maxTokens - used - reserveTokens);
|
|
287
|
+
}
|
|
288
|
+
function truncateToFit(prefixContent, result, citation, budget, countTokens, includeScores) {
|
|
289
|
+
let low = 1;
|
|
290
|
+
let high = result.text.length;
|
|
291
|
+
let best;
|
|
292
|
+
while (low <= high) {
|
|
293
|
+
const mid = Math.floor((low + high) / 2);
|
|
294
|
+
const text = `${result.text.slice(0, mid).trimEnd()}
|
|
295
|
+
[truncated]`;
|
|
296
|
+
const block = renderResult(result, citation, includeScores, text);
|
|
297
|
+
const candidate = appendBlock(prefixContent, block);
|
|
298
|
+
if (countText(candidate, countTokens) <= budget) {
|
|
299
|
+
best = block;
|
|
300
|
+
low = mid + 1;
|
|
301
|
+
} else {
|
|
302
|
+
high = mid - 1;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return best;
|
|
306
|
+
}
|
|
307
|
+
function selectResults(results, budget, countTokens, includeScores) {
|
|
308
|
+
if (budget === undefined) {
|
|
309
|
+
return {
|
|
310
|
+
content: joinBlocks(results.map((result, index) => renderResult(result, index + 1, includeScores))),
|
|
311
|
+
selected: results
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
if (budget <= 0)
|
|
315
|
+
return { content: "", selected: [] };
|
|
316
|
+
let content = "";
|
|
317
|
+
const selected = [];
|
|
318
|
+
for (let index = 0;index < results.length; index += 1) {
|
|
319
|
+
const result = results[index];
|
|
320
|
+
if (result === undefined)
|
|
321
|
+
continue;
|
|
322
|
+
const citation = selected.length + 1;
|
|
323
|
+
const block = renderResult(result, citation, includeScores);
|
|
324
|
+
const candidate = appendBlock(content, block);
|
|
325
|
+
if (countText(candidate, countTokens) <= budget) {
|
|
326
|
+
content = candidate;
|
|
327
|
+
selected.push(result);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
const truncated = truncateToFit(content, result, citation, budget, countTokens, includeScores);
|
|
331
|
+
if (truncated !== undefined) {
|
|
332
|
+
content = appendBlock(content, truncated);
|
|
333
|
+
selected.push(result);
|
|
334
|
+
}
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
return { content, selected };
|
|
338
|
+
}
|
|
339
|
+
function retrieverContext(options) {
|
|
340
|
+
return {
|
|
341
|
+
name: options.name ?? `retriever:${options.retriever.name}`,
|
|
342
|
+
async resolve(ctx, run) {
|
|
343
|
+
const query = await resolveQuery(options, ctx, run);
|
|
344
|
+
if (query === undefined)
|
|
345
|
+
return [];
|
|
346
|
+
const results = await options.retriever.retrieve({
|
|
347
|
+
query,
|
|
348
|
+
...options.topK !== undefined ? { topK: options.topK } : {},
|
|
349
|
+
...options.minScore !== undefined ? { minScore: options.minScore } : {}
|
|
350
|
+
}, ctx);
|
|
351
|
+
if (results.length === 0)
|
|
352
|
+
return [];
|
|
353
|
+
const countTokens = options.countTokens ?? run?.contextWindow?.countTokens ?? estimateTokens;
|
|
354
|
+
const budget = availableBudget(options, run, countTokens);
|
|
355
|
+
const rendered = selectResults(results, budget, countTokens, options.includeScores ?? false);
|
|
356
|
+
if (rendered.content === "")
|
|
357
|
+
return [];
|
|
358
|
+
await options.onResults?.(rendered.selected, query, ctx, run);
|
|
359
|
+
return [{ title: options.title ?? "Retrieved Context", content: rendered.content }];
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
// src/retrieval/loaders.ts
|
|
364
|
+
function isAsyncIterable(value) {
|
|
365
|
+
return Symbol.asyncIterator in Object(value);
|
|
366
|
+
}
|
|
367
|
+
function isIterable(value) {
|
|
368
|
+
return Symbol.iterator in Object(value);
|
|
369
|
+
}
|
|
370
|
+
async function collect(output, ctx) {
|
|
371
|
+
const documents = [];
|
|
372
|
+
if (isAsyncIterable(output)) {
|
|
373
|
+
for await (const document of output) {
|
|
374
|
+
throwIfAborted(ctx);
|
|
375
|
+
documents.push(document);
|
|
376
|
+
}
|
|
377
|
+
return documents;
|
|
378
|
+
}
|
|
379
|
+
if (isIterable(output)) {
|
|
380
|
+
for (const document of output) {
|
|
381
|
+
throwIfAborted(ctx);
|
|
382
|
+
documents.push(document);
|
|
383
|
+
}
|
|
384
|
+
return documents;
|
|
385
|
+
}
|
|
386
|
+
return documents;
|
|
387
|
+
}
|
|
388
|
+
function createDocumentLoader(name, load) {
|
|
389
|
+
return { name, load };
|
|
390
|
+
}
|
|
391
|
+
function staticDocumentLoader(documents, name = "static-documents") {
|
|
392
|
+
return createDocumentLoader(name, () => documents.map((document) => ({ ...document })));
|
|
393
|
+
}
|
|
394
|
+
async function loadDocuments(loaders, ctx) {
|
|
395
|
+
const documents = [];
|
|
396
|
+
for (const loader of loaders) {
|
|
397
|
+
throwIfAborted(ctx);
|
|
398
|
+
const output = await loader.load(ctx);
|
|
399
|
+
const loaded = await collect(output, ctx);
|
|
400
|
+
documents.push(...loaded);
|
|
401
|
+
}
|
|
402
|
+
return { documents, loaders: loaders.length };
|
|
403
|
+
}
|
|
404
|
+
// src/retrieval/vector-store.ts
|
|
405
|
+
function assertVector(vector, label = "vector") {
|
|
406
|
+
if (vector.length === 0)
|
|
407
|
+
throw new TypeError(`${label} must not be empty`);
|
|
408
|
+
for (let index = 0;index < vector.length; index += 1) {
|
|
409
|
+
const value = vector[index];
|
|
410
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
411
|
+
throw new TypeError(`${label} contains a non-finite value at index ${index}`);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function dotProduct(a, b) {
|
|
416
|
+
let score = 0;
|
|
417
|
+
for (let index = 0;index < a.length; index += 1)
|
|
418
|
+
score += (a[index] ?? 0) * (b[index] ?? 0);
|
|
419
|
+
return score;
|
|
420
|
+
}
|
|
421
|
+
function cosineSimilarity(a, b) {
|
|
422
|
+
let aNorm = 0;
|
|
423
|
+
let bNorm = 0;
|
|
424
|
+
for (let index = 0;index < a.length; index += 1) {
|
|
425
|
+
const av = a[index] ?? 0;
|
|
426
|
+
const bv = b[index] ?? 0;
|
|
427
|
+
aNorm += av * av;
|
|
428
|
+
bNorm += bv * bv;
|
|
429
|
+
}
|
|
430
|
+
if (aNorm === 0 || bNorm === 0)
|
|
431
|
+
return 0;
|
|
432
|
+
return dotProduct(a, b) / (Math.sqrt(aNorm) * Math.sqrt(bNorm));
|
|
433
|
+
}
|
|
434
|
+
function euclideanSimilarity(a, b) {
|
|
435
|
+
let sum = 0;
|
|
436
|
+
for (let index = 0;index < a.length; index += 1) {
|
|
437
|
+
const delta = (a[index] ?? 0) - (b[index] ?? 0);
|
|
438
|
+
sum += delta * delta;
|
|
439
|
+
}
|
|
440
|
+
return 1 / (1 + Math.sqrt(sum));
|
|
441
|
+
}
|
|
442
|
+
function scoreVectors(a, b, similarity) {
|
|
443
|
+
switch (similarity) {
|
|
444
|
+
case "cosine":
|
|
445
|
+
return cosineSimilarity(a, b);
|
|
446
|
+
case "dot":
|
|
447
|
+
return dotProduct(a, b);
|
|
448
|
+
case "euclidean":
|
|
449
|
+
return euclideanSimilarity(a, b);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// src/retrieval/memory.ts
|
|
454
|
+
function cloneVector(vector) {
|
|
455
|
+
return vector.map((value) => value);
|
|
456
|
+
}
|
|
457
|
+
function cloneRecord(record) {
|
|
458
|
+
return {
|
|
459
|
+
id: record.id,
|
|
460
|
+
vector: cloneVector(record.vector),
|
|
461
|
+
text: record.text,
|
|
462
|
+
...record.source !== undefined ? { source: record.source } : {},
|
|
463
|
+
...record.metadata !== undefined ? { metadata: record.metadata } : {}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
class InMemoryVectorStore {
|
|
468
|
+
name;
|
|
469
|
+
records = new Map;
|
|
470
|
+
similarity;
|
|
471
|
+
recordDimensions;
|
|
472
|
+
constructor(options = {}) {
|
|
473
|
+
assertPositiveInteger("dimensions", options.dimensions);
|
|
474
|
+
this.name = options.name ?? "memory-vector-store";
|
|
475
|
+
this.recordDimensions = options.dimensions;
|
|
476
|
+
this.similarity = options.similarity ?? "cosine";
|
|
477
|
+
}
|
|
478
|
+
get dimensions() {
|
|
479
|
+
return this.recordDimensions;
|
|
480
|
+
}
|
|
481
|
+
ensureDimensions(vector, label) {
|
|
482
|
+
assertVector(vector, label);
|
|
483
|
+
if (this.recordDimensions === undefined) {
|
|
484
|
+
this.recordDimensions = vector.length;
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (vector.length !== this.recordDimensions) {
|
|
488
|
+
throw new TypeError(`${label} has ${vector.length} dimensions; expected ${this.recordDimensions}`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
ensureQueryDimensions(vector) {
|
|
492
|
+
assertVector(vector, "query vector");
|
|
493
|
+
if (this.recordDimensions !== undefined && vector.length !== this.recordDimensions) {
|
|
494
|
+
throw new TypeError(`query vector has ${vector.length} dimensions; expected ${this.recordDimensions}`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
async upsert(records, ctx) {
|
|
498
|
+
for (const record of records) {
|
|
499
|
+
throwIfAborted(ctx);
|
|
500
|
+
if (record.id === "")
|
|
501
|
+
throw new TypeError("record id must not be empty");
|
|
502
|
+
this.ensureDimensions(record.vector, `record ${record.id} vector`);
|
|
503
|
+
this.records.set(record.id, cloneRecord(record));
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async query(query, ctx) {
|
|
507
|
+
throwIfAborted(ctx);
|
|
508
|
+
this.ensureQueryDimensions(query.vector);
|
|
509
|
+
const topK = query.topK ?? 10;
|
|
510
|
+
assertPositiveInteger("topK", topK);
|
|
511
|
+
const hits = [];
|
|
512
|
+
for (const record of this.records.values()) {
|
|
513
|
+
throwIfAborted(ctx);
|
|
514
|
+
if (query.filter !== undefined && !query.filter(record))
|
|
515
|
+
continue;
|
|
516
|
+
const score = scoreVectors(query.vector, record.vector, this.similarity);
|
|
517
|
+
if (query.minScore !== undefined && score < query.minScore)
|
|
518
|
+
continue;
|
|
519
|
+
hits.push({
|
|
520
|
+
id: record.id,
|
|
521
|
+
score,
|
|
522
|
+
text: record.text,
|
|
523
|
+
...record.source !== undefined ? { source: record.source } : {},
|
|
524
|
+
...record.metadata !== undefined ? { metadata: record.metadata } : {},
|
|
525
|
+
...query.includeVectors === true ? { vector: cloneVector(record.vector) } : {}
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
hits.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
529
|
+
return hits.slice(0, topK);
|
|
530
|
+
}
|
|
531
|
+
async delete(ids, ctx) {
|
|
532
|
+
for (const id of ids) {
|
|
533
|
+
throwIfAborted(ctx);
|
|
534
|
+
this.records.delete(id);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async clear(ctx) {
|
|
538
|
+
throwIfAborted(ctx);
|
|
539
|
+
this.records.clear();
|
|
540
|
+
}
|
|
541
|
+
async stats(ctx) {
|
|
542
|
+
throwIfAborted(ctx);
|
|
543
|
+
return {
|
|
544
|
+
records: this.records.size,
|
|
545
|
+
...this.recordDimensions !== undefined ? { dimensions: this.recordDimensions } : {}
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
// src/retrieval/retriever.ts
|
|
550
|
+
function defaultModel(provider, model) {
|
|
551
|
+
return model ?? provider.defaultModel;
|
|
552
|
+
}
|
|
553
|
+
function assertEmbeddingCount(expected, actual) {
|
|
554
|
+
if (actual.length !== expected) {
|
|
555
|
+
throw new Error(`embedding provider returned ${actual.length} vectors for ${expected} inputs`);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
function fromVectorHit(hit, index) {
|
|
559
|
+
return {
|
|
560
|
+
id: hit.id,
|
|
561
|
+
rank: index + 1,
|
|
562
|
+
score: hit.score,
|
|
563
|
+
scores: { vector: hit.score },
|
|
564
|
+
text: hit.text,
|
|
565
|
+
...hit.source !== undefined ? { source: hit.source } : {},
|
|
566
|
+
...hit.metadata !== undefined ? { metadata: hit.metadata } : {}
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
function normalizeScore(score, min, max) {
|
|
570
|
+
if (max === min)
|
|
571
|
+
return score > 0 ? 1 : 0;
|
|
572
|
+
return (score - min) / (max - min);
|
|
573
|
+
}
|
|
574
|
+
function scoreBounds(results) {
|
|
575
|
+
if (results.length === 0)
|
|
576
|
+
return { min: 0, max: 0 };
|
|
577
|
+
let min = Number.POSITIVE_INFINITY;
|
|
578
|
+
let max = Number.NEGATIVE_INFINITY;
|
|
579
|
+
for (const result of results) {
|
|
580
|
+
min = Math.min(min, result.score);
|
|
581
|
+
max = Math.max(max, result.score);
|
|
582
|
+
}
|
|
583
|
+
return { min, max };
|
|
584
|
+
}
|
|
585
|
+
function mergeHybridResults(vectorResults, keywordResults, options = {}) {
|
|
586
|
+
const inferredTopK = Math.max(vectorResults.length, keywordResults.length);
|
|
587
|
+
if (options.topK === undefined && inferredTopK === 0)
|
|
588
|
+
return [];
|
|
589
|
+
const topK = options.topK ?? inferredTopK;
|
|
590
|
+
assertPositiveInteger("topK", topK);
|
|
591
|
+
const vectorWeight = options.vectorWeight ?? 0.7;
|
|
592
|
+
const keywordWeight = options.keywordWeight ?? 0.3;
|
|
593
|
+
const vectorBounds = scoreBounds(vectorResults);
|
|
594
|
+
const keywordBounds = scoreBounds(keywordResults);
|
|
595
|
+
const entries = new Map;
|
|
596
|
+
for (const result of vectorResults) {
|
|
597
|
+
const previous = entries.get(result.id);
|
|
598
|
+
entries.set(result.id, {
|
|
599
|
+
id: result.id,
|
|
600
|
+
text: previous?.text ?? result.text,
|
|
601
|
+
...previous?.source !== undefined || result.source !== undefined ? { source: previous?.source ?? result.source } : {},
|
|
602
|
+
...previous?.metadata !== undefined || result.metadata !== undefined ? { metadata: previous?.metadata ?? result.metadata } : {},
|
|
603
|
+
...previous?.keywordRaw !== undefined ? { keywordRaw: previous.keywordRaw } : {},
|
|
604
|
+
...previous?.keywordNormalized !== undefined ? { keywordNormalized: previous.keywordNormalized } : {},
|
|
605
|
+
vectorRaw: result.score,
|
|
606
|
+
vectorNormalized: normalizeScore(result.score, vectorBounds.min, vectorBounds.max)
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
for (const result of keywordResults) {
|
|
610
|
+
const previous = entries.get(result.id);
|
|
611
|
+
const text = previous?.text === undefined || previous.text === "" ? result.text : previous.text;
|
|
612
|
+
entries.set(result.id, {
|
|
613
|
+
id: result.id,
|
|
614
|
+
text,
|
|
615
|
+
...previous?.source !== undefined || result.source !== undefined ? { source: previous?.source ?? result.source } : {},
|
|
616
|
+
...previous?.metadata !== undefined || result.metadata !== undefined ? { metadata: previous?.metadata ?? result.metadata } : {},
|
|
617
|
+
...previous?.vectorRaw !== undefined ? { vectorRaw: previous.vectorRaw } : {},
|
|
618
|
+
...previous?.vectorNormalized !== undefined ? { vectorNormalized: previous.vectorNormalized } : {},
|
|
619
|
+
keywordRaw: result.score,
|
|
620
|
+
keywordNormalized: normalizeScore(result.score, keywordBounds.min, keywordBounds.max)
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
const merged = [...entries.values()].map((entry) => {
|
|
624
|
+
const combined = (entry.vectorNormalized ?? 0) * vectorWeight + (entry.keywordNormalized ?? 0) * keywordWeight;
|
|
625
|
+
return {
|
|
626
|
+
id: entry.id,
|
|
627
|
+
rank: 0,
|
|
628
|
+
score: combined,
|
|
629
|
+
scores: {
|
|
630
|
+
...entry.vectorRaw !== undefined ? { vector: entry.vectorRaw } : {},
|
|
631
|
+
...entry.keywordRaw !== undefined ? { keyword: entry.keywordRaw } : {},
|
|
632
|
+
combined
|
|
633
|
+
},
|
|
634
|
+
text: entry.text,
|
|
635
|
+
...entry.source !== undefined ? { source: entry.source } : {},
|
|
636
|
+
...entry.metadata !== undefined ? { metadata: entry.metadata } : {}
|
|
637
|
+
};
|
|
638
|
+
}).filter((result) => options.minScore === undefined || result.score >= options.minScore).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, topK);
|
|
639
|
+
return merged.map((result, index) => ({ ...result, rank: index + 1 }));
|
|
640
|
+
}
|
|
641
|
+
async function indexDocuments(options, ctx) {
|
|
642
|
+
const batchSize = options.batchSize ?? 64;
|
|
643
|
+
assertPositiveInteger("batchSize", batchSize);
|
|
644
|
+
const loaded = await loadDocuments(options.loaders, ctx);
|
|
645
|
+
const chunks = [];
|
|
646
|
+
for (let documentIndex = 0;documentIndex < loaded.documents.length; documentIndex += 1) {
|
|
647
|
+
throwIfAborted(ctx);
|
|
648
|
+
const document = loaded.documents[documentIndex];
|
|
649
|
+
if (document === undefined)
|
|
650
|
+
continue;
|
|
651
|
+
const documentChunks = await options.chunker.chunk(document, { documentIndex, ...ctx !== undefined ? { engine: ctx } : {} });
|
|
652
|
+
chunks.push(...documentChunks);
|
|
653
|
+
}
|
|
654
|
+
let records = 0;
|
|
655
|
+
let model;
|
|
656
|
+
let dimensions;
|
|
657
|
+
for (let start = 0;start < chunks.length; start += batchSize) {
|
|
658
|
+
throwIfAborted(ctx);
|
|
659
|
+
const batch = chunks.slice(start, start + batchSize);
|
|
660
|
+
const result = await options.embeddings.embed({
|
|
661
|
+
input: batch.map((chunk) => chunk.text),
|
|
662
|
+
...defaultModel(options.embeddings, options.embeddingModel) !== undefined ? { model: defaultModel(options.embeddings, options.embeddingModel) } : {}
|
|
663
|
+
}, ctx);
|
|
664
|
+
assertEmbeddingCount(batch.length, result.vectors);
|
|
665
|
+
model = result.model;
|
|
666
|
+
if (result.dimensions !== undefined)
|
|
667
|
+
dimensions = result.dimensions;
|
|
668
|
+
const vectorRecords = [];
|
|
669
|
+
for (let index = 0;index < batch.length; index += 1) {
|
|
670
|
+
const chunk = batch[index];
|
|
671
|
+
const vector = result.vectors[index];
|
|
672
|
+
if (chunk === undefined || vector === undefined)
|
|
673
|
+
continue;
|
|
674
|
+
assertVector(vector, `embedding ${chunk.id}`);
|
|
675
|
+
if (dimensions === undefined)
|
|
676
|
+
dimensions = vector.length;
|
|
677
|
+
vectorRecords.push({
|
|
678
|
+
id: chunk.id,
|
|
679
|
+
vector,
|
|
680
|
+
text: chunk.text,
|
|
681
|
+
...chunk.source !== undefined ? { source: chunk.source } : {},
|
|
682
|
+
...chunk.metadata !== undefined ? { metadata: chunk.metadata } : {}
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
await options.store.upsert(vectorRecords, ctx);
|
|
686
|
+
records += vectorRecords.length;
|
|
687
|
+
}
|
|
688
|
+
return {
|
|
689
|
+
documents: loaded.documents.length,
|
|
690
|
+
chunks: chunks.length,
|
|
691
|
+
records,
|
|
692
|
+
...model !== undefined ? { model } : {},
|
|
693
|
+
...dimensions !== undefined ? { dimensions } : {}
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
function createVectorRetriever(options) {
|
|
697
|
+
assertPositiveInteger("topK", options.topK);
|
|
698
|
+
return {
|
|
699
|
+
name: options.name ?? `vector:${options.store.name}`,
|
|
700
|
+
async retrieve(query, ctx) {
|
|
701
|
+
throwIfAborted(ctx);
|
|
702
|
+
const topK = query.topK ?? options.hybrid?.topK ?? options.topK ?? 5;
|
|
703
|
+
assertPositiveInteger("topK", topK);
|
|
704
|
+
const embed = await options.embeddings.embed({
|
|
705
|
+
input: [query.query],
|
|
706
|
+
...defaultModel(options.embeddings, options.model) !== undefined ? { model: defaultModel(options.embeddings, options.model) } : {}
|
|
707
|
+
}, ctx);
|
|
708
|
+
assertEmbeddingCount(1, embed.vectors);
|
|
709
|
+
const vector = embed.vectors[0];
|
|
710
|
+
if (vector === undefined)
|
|
711
|
+
throw new Error("embedding provider returned no query vector");
|
|
712
|
+
assertVector(vector, "query embedding");
|
|
713
|
+
const vectorHits = await options.store.query({
|
|
714
|
+
vector,
|
|
715
|
+
topK,
|
|
716
|
+
...query.filter !== undefined || options.filter !== undefined ? { filter: query.filter ?? options.filter } : {},
|
|
717
|
+
...query.minScore !== undefined || options.minScore !== undefined ? { minScore: query.minScore ?? options.minScore } : {}
|
|
718
|
+
}, ctx);
|
|
719
|
+
const vectorResults = vectorHits.map(fromVectorHit);
|
|
720
|
+
if (options.keyword === undefined)
|
|
721
|
+
return vectorResults.map((result, index) => ({ ...result, rank: index + 1 }));
|
|
722
|
+
const keywordResults = await options.keyword.retrieve({ ...query, topK }, ctx);
|
|
723
|
+
return mergeHybridResults(vectorResults, keywordResults, {
|
|
724
|
+
...options.hybrid,
|
|
725
|
+
topK,
|
|
726
|
+
...query.minScore !== undefined || options.hybrid?.minScore !== undefined ? { minScore: query.minScore ?? options.hybrid?.minScore } : {}
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
export {
|
|
732
|
+
staticDocumentLoader,
|
|
733
|
+
scoreVectors,
|
|
734
|
+
retrieverContext,
|
|
735
|
+
recursiveTextChunker,
|
|
736
|
+
mergeHybridResults,
|
|
737
|
+
loadDocuments,
|
|
738
|
+
indexDocuments,
|
|
739
|
+
euclideanSimilarity,
|
|
740
|
+
dotProduct,
|
|
741
|
+
createVectorRetriever,
|
|
742
|
+
createTextChunker,
|
|
743
|
+
createDocumentLoader,
|
|
744
|
+
cosineSimilarity,
|
|
745
|
+
assertVector,
|
|
746
|
+
InMemoryVectorStore
|
|
747
|
+
};
|