@byfriends/agent-core 0.3.1 → 0.3.2

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.
@@ -2,16 +2,16 @@ import { CacheHitRate, ChatProvider, ContentPart, FinishReason, Message, ModelCa
2
2
  import { z } from "zod";
3
3
  import { OAuthClientProvider, OAuthDiscoveryState } from "@modelcontextprotocol/sdk/client/auth.js";
4
4
  import { Kaos, KaosProcess } from "@byfriends/kaos";
5
- import { ActivateSkillPayload, AgentAPI, AgentEvent, SDKAgentRPC, SDKSessionRPC, UsageStatus } from "./index-CZA_2ux5.mjs";
5
+ import { ActivateSkillPayload, AgentAPI, AgentEvent, SDKAgentRPC, SDKSessionRPC, UsageStatus } from "./index-BNApCprm.mjs";
6
6
  import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
7
- import { ByfConfig, ByfConfigPatch, OAuthRef } from "./index-CZA_2ux5.mjs";
8
- import { AgentConfigData, AgentConfigUpdateData } from "./index-CZA_2ux5.mjs";
9
- import { AgentContextData, ContextMessage } from "./index-CZA_2ux5.mjs";
10
- import { PermissionApprovalResultRecord, PermissionData, PermissionMode } from "./index-CZA_2ux5.mjs";
11
- import { ToolInfo } from "./index-CZA_2ux5.mjs";
12
- import { AgentType } from "./index-CZA_2ux5.mjs";
13
- import { SessionMeta } from "./index-CZA_2ux5.mjs";
14
- import { BackgroundTaskInfo } from "./index-CZA_2ux5.mjs";
7
+ import { ByfConfig, ByfConfigPatch, OAuthRef } from "./index-BNApCprm.mjs";
8
+ import { AgentConfigData, AgentConfigUpdateData } from "./index-BNApCprm.mjs";
9
+ import { AgentContextData, ContextMessage } from "./index-BNApCprm.mjs";
10
+ import { PermissionApprovalResultRecord, PermissionData, PermissionMode } from "./index-BNApCprm.mjs";
11
+ import { ToolInfo } from "./index-BNApCprm.mjs";
12
+ import { AgentType } from "./index-BNApCprm.mjs";
13
+ import { SessionMeta } from "./index-BNApCprm.mjs";
14
+ import { BackgroundTaskInfo } from "./index-BNApCprm.mjs";
15
15
  //#region src/logging/types.d.ts
16
16
  type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug';
17
17
  type LogContext = Record<string, unknown>;
@@ -1102,98 +1102,6 @@ declare function transformTomlData(data: Record<string, unknown>): Record<string
1102
1102
  declare function writeConfigFile(filePath: string, config: ByfConfig$1): Promise<void>;
1103
1103
  declare function configToTomlData(config: ByfConfig$1): Record<string, unknown>;
1104
1104
  //#endregion
1105
- //#region src/config/update-rules.d.ts
1106
- /**
1107
- * Update-rules for `byf update-config`.
1108
- *
1109
- * Each rule corresponds to a deprecated / renamed / migrated field that
1110
- * `analyzeConfig` can detect in `config.raw` and (where applicable) that
1111
- * `applyFixes` can clean up.
1112
- *
1113
- * **Principles** (from PRD-0013 grill decisions):
1114
- * - G2 — Whitelist approach: only fields explicitly registered here are removed.
1115
- * - Every rule carries a `deprecatedSince` version annotation so the report
1116
- * tells the user *when* the field became obsolete.
1117
- */
1118
- interface Finding {
1119
- kind: 'removed' | 'renamed' | 'migrated' | 'dangling' | 'unknown' | 'invalid-value';
1120
- /** TOML dotted path, e.g. `'services.byf_search'`, `'loop_control.max_steps_per_run'`. */
1121
- path: string;
1122
- /** Human-readable description of what was found and what will happen. */
1123
- detail: string;
1124
- /** Version when this field was deprecated (optional — may be unknown for very old fields). */
1125
- deprecatedSince?: string;
1126
- }
1127
- interface DeprecatedFieldRule {
1128
- /** TOML dotted path, same format as `Finding.path`. */
1129
- path: string;
1130
- /** Path split into segments for traversing `config.raw`. */
1131
- pathParts: readonly string[];
1132
- /** Which kind of Finding this rule produces. */
1133
- kind: Finding['kind'];
1134
- /** Human-readable description. */
1135
- detail: string;
1136
- deprecatedSince?: string;
1137
- }
1138
- /**
1139
- * Combined list of all deprecated-field rules.
1140
- *
1141
- * Order within the list does not affect correctness (the CLI groups by kind
1142
- * at display time), but a stable order helps test expectations.
1143
- */
1144
- declare const DEPRECATED_FIELD_RULES: readonly DeprecatedFieldRule[];
1145
- //#endregion
1146
- //#region src/config/update.d.ts
1147
- /**
1148
- * Minimal config shape accepted by {@link analyzeConfig}.
1149
- *
1150
- * All fields are optional so callers — especially tests — don't need to
1151
- * construct a full `ByfConfig`. Backward-compatible: every `ByfConfig` is
1152
- * a valid `UpdateAnalyzeInput`.
1153
- */
1154
- interface UpdateAnalyzeInput {
1155
- readonly raw?: Record<string, unknown>;
1156
- readonly thinking?: {
1157
- readonly mode?: string;
1158
- readonly effort?: string;
1159
- };
1160
- readonly models?: Record<string, {
1161
- readonly provider: string;
1162
- readonly capabilities?: readonly string[];
1163
- }>;
1164
- readonly providers?: Record<string, unknown>;
1165
- readonly defaultProvider?: string;
1166
- readonly defaultModel?: string;
1167
- }
1168
- /**
1169
- * Scan a parsed config (including `config.raw`) and return all Findings
1170
- * for deprecated / renamed / migrated / dangling / unknown / invalid-value
1171
- * fields.
1172
- *
1173
- * This is a **pure** function — no file I/O, no side effects.
1174
- *
1175
- * Detection is based on `config.raw` (the clone of the original TOML data),
1176
- * not on the parsed camelCase schema. This matches the PRD's observation
1177
- * that `raw` is both the protection layer (preserving unknown fields) and
1178
- * the blind spot (retaining stale keys through read→write cycles).
1179
- */
1180
- declare function analyzeConfig(config: UpdateAnalyzeInput): Finding[];
1181
- /**
1182
- * Apply automatic fixes to a `ByfConfig` by deleting every path registered in
1183
- * `DEPRECATED_FIELD_RULES` from `config.raw`.
1184
- *
1185
- * The `_findings` parameter is intentionally **not consulted** — deletion is
1186
- * driven exclusively by the whitelist in `DEPRECATED_FIELD_RULES`. This ensures
1187
- * that a call to `applyFixes` always produces a clean config regardless of
1188
- * what analysis step previously ran.
1189
- *
1190
- * This is a **pure** function — it returns a new config object without
1191
- * mutating the input.
1192
- */
1193
- declare function applyFixes(config: ByfConfig$1, findings: readonly Finding[]): ByfConfig$1 & {
1194
- raw: Record<string, unknown>;
1195
- };
1196
- //#endregion
1197
1105
  //#region src/providers/request-auth.d.ts
1198
1106
  interface ProviderRequestAuthOptions {
1199
1107
  readonly forceRefresh?: boolean;
@@ -4240,5 +4148,5 @@ declare function resolveLoggingConfig(input: ResolveLoggingInput): LoggingConfig
4240
4148
  //#region src/prompt-plan/builder.d.ts
4241
4149
  declare function buildPromptPlan(renderedSystemPrompt: string, providerCacheCapability: ProviderCacheCapability): PromptPlan;
4242
4150
  //#endregion
4243
- export { CreateSessionPayload as $, RootLogger as $i, TelemetryProperties as $n, ResolveConfigValueInput as $r, CompactionCancelledEvent as $t, QuestionAnswers as A, PermissionRuleSchema as Ai, TurnStepStartedEvent as An, LoopToolResultEvent as Ar, SetThinkingPayload as At, SDKSessionAPI as B, WebSearchConfig as Bi, BYF_ERROR_INFO as Bn, OAuthTokenProviderResolver as Br, WithAgentId as Bt, SDKRPCClient as C, ModelAliasSchema as Ci, ToolUpdate as Cn, UserPromptOrigin as Cr, SessionMetadataPatch as Ct, ApprovalResponse as D, PermissionConfigSchema as Di, TurnStepCompletedEvent as Dn, LoopStepBeginEvent as Dr, SetModelPayload as Dt, ApprovalRequest as E, PermissionConfig as Ei, TurnStartedEvent as En, LoopRecordedEvent as Er, SetByfConfigPayload as Et, QuestionResult as F, ProviderTypeSchema as Fi, isByfError as Fn, BackgroundLifecycleEvent as Fr, StopBackgroundPayload as Ft, AgentAPI$1 as G, getDefaultConfig as Gi, SessionSubagentHost as Gn, DeprecatedFieldRule as Gr, ResumedAgentState as Gt, ToolCallRequest as H, WebSearchProviderConfig as Hi, ByfErrorInfo as Hn, analyzeConfig as Hr, proxyWithExtraPayload as Ht, SDKAPI as I, ServicesConfig as Ii, makeErrorPayload as In, BackgroundTaskInfo$1 as Ir, TextPromptPart as It, ByfConfigPatch as J, LogEntry as Ji, Session as Jn, ensureConfigFile as Jr, AssistantDeltaEvent as Jt, BeginCompactionPayload as K, validateConfig as Ki, SubagentHandle as Kn, Finding as Kr, AgentEvent$1 as Kt, SDKAgentAPI as L, ServicesConfigSchema as Li, toByfErrorPayload as Ln, BackgroundTaskKind as Lr, UnregisterToolPayload as Lt, QuestionOption as M, ProviderConfig$1 as Mi, WarningEvent as Mn, ExecutableToolResult as Mr, ShellExecResult as Mt, QuestionRequest as N, ProviderConfigSchema as Ni, ByfErrorPayload as Nn, ExecutableToolSuccessResult as Nr, SkillSummary as Nt, ApprovalScope as O, PermissionModeSchema as Oi, TurnStepInterruptedEvent as On, LoopStepEndEvent as Or, SetModelResult as Ot, QuestionResponse as P, ProviderType as Pi, fromByfErrorPayload as Pn, ToolInputDisplay as Pr, SteerPayload as Pt, CoreInfo as Q, LoggingConfig as Qi, TelemetryClient as Qn, writeConfigFile as Qr, CompactionBlockedEvent as Qt, SDKAgentRPC$1 as R, ThinkingConfig as Ri, ByfError as Rn, BackgroundTaskStatus as Rr, Unsubscribe as Rt, RPCMethods as S, ModelAlias as Si, ToolResultEvent as Sn, USER_PROMPT_ORIGIN as Sr, SessionAPI as St, ApprovalDecision as T, OAuthRefSchema as Ti, TurnEndedEvent as Tn, LoopContentPartEvent as Tr, SetActiveToolsPayload as Tt, ToolCallResponse as U, WebSearchProviderConfigSchema as Ui, ErrorCodes as Un, applyFixes as Ur, AgentReplayRecord as Ut, SDKSessionRPC$1 as V, WebSearchConfigSchema as Vi, ByfErrorCode as Vn, UpdateAnalyzeInput as Vr, WithSessionId as Vt, ActivateSkillPayload$1 as W, formatConfigValidationError as Wi, RuntimeConfig as Wn, DEPRECATED_FIELD_RULES as Wr, ResumeSessionResult as Wt, CloseSessionPayload as X, LogPayload as Xi, SessionMeta$1 as Xn, readConfigFile as Xr, BackgroundTaskTerminatedEvent as Xt, CancelPayload as Y, LogLevel as Yi, SessionConfig as Yn, parseConfigString as Yr, BackgroundTaskStartedEvent as Yt, CoreAPI as Z, Logger as Zi, SessionSkillConfig as Zn, transformTomlData as Zr, BackgroundTaskUpdatedEvent as Zt, ByfCoreOptions as _, McpServerConfigSchema as _i, ToolCallDeltaEvent as _n, CompactionBeginData as _r, ReconnectMcpServerPayload as _t, collectFilesRecursive as a, mergeConfigPatch as ai, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE as an, BuiltinTool as ar, GetBackgroundOutputPathPayload as at, RPCCallOptions as b, McpServerStdioConfig as bi, ToolListUpdatedReason as bn, ContextMessage$1 as br, RenameSessionPayload as bt, WIRE_PROTOCOL_VERSION as c, ByfConfigPatchSchema as ci, McpServerStatusPayload as cn, UserToolRegistration as cr, JsonObject as ct, normalizeTimestampMs as d, ByfServiceConfigSchema as di, SessionMetaUpdatedEvent as dn, AgentRecordOf as dr, ListSessionsPayload as dt, SessionAttachInput as ea, parseBooleanEnv as ei, CompactionCompletedEvent as en, flushDiagnosticLogs as er, EmptyPayload as et, scanSessionWire as f, HookDefConfig as fi, SkillActivatedEvent as fn, AgentRecordPersistence as fr, McpServerInfo as ft, ByfCore as g, McpServerConfig as gi, ThinkingDeltaEvent as gn, AgentConfigUpdateData$1 as gr, PromptPayload as gt, AgentType$1 as h, LoopControlSchema as hi, SubagentSpawnedEvent as hn, PermissionMode$1 as hr, PromptPart as ht, ExtraZipEntry as i, resolveConfigPath as ii, HookResultEvent as in, resolveGlobalLogPath as ir, ForkSessionPayload as it, QuestionItem as j, PermissionRuleScopeSchema as ji, UsageStatus$1 as jn, ExecutableToolErrorResult as jr, ShellExecPayload as jt, QuestionAnswerMethod as k, PermissionRuleDecisionSchema as ki, TurnStepRetryingEvent as kn, LoopToolCallEvent as kr, SetPermissionPayload as kt, buildExportManifest as l, ByfConfigSchema as li, ObservationMaskingAppliedEvent as ln, AgentRecord as lr, JsonPrimitive as lt, AgentConfig as m, LoopControl as mi, SubagentFailedEvent as mn, PermissionApprovalResultRecord$1 as mr, PromptInput as mt, ResolveLoggingInput as n, ensureByfHome as ni, ErrorEvent as nn, log as nr, ExportSessionPayload as nt, writeExportZip as o, BackgroundConfig as oi, McpOAuthAuthorizationUrlUpdateData as on, ToolInfo$1 as or, GetBackgroundOutputPayload as ot, Agent as p, HookDefSchema as pi, SubagentCompletedEvent as pn, UsageRecordScope as pr, McpStartupMetrics as pt, ByfConfig as q, LogContext as qi, AgentMeta as qn, configToTomlData as qr, AgentStatusUpdatedEvent as qt, resolveLoggingConfig as r, resolveByfHome as ri, Event as rn, redact as rr, ExportSessionResult as rt, exportSessionDirectory as s, BackgroundConfigSchema as si, McpServerStatusEvent as sn, ToolSource as sr, GetBackgroundPayload as st, buildPromptPlan as t, SessionLogHandle as ta, resolveConfigValue as ti, CompactionStartedEvent as tn, getRootLogger as tr, ExportSessionManifest as tt, SessionWireScan as u, ByfServiceConfig as ui, PruningAppliedEvent as un, AgentRecordEvents as ur, JsonValue as ut, CoreRPC as v, McpServerHttpConfig as vi, ToolCallStartedEvent as vn, CompactionResult$1 as vr, RegisterToolPayload as vt, createRPC as w, OAuthRef$1 as wi, TurnEndReason as wn, ToolStoreUpdate as wr, SessionSummary as wt, RPCClient as x, McpServerStdioConfigSchema as xi, ToolProgressEvent as xn, PromptOrigin as xr, ResumeSessionPayload as xt, CoreRPCClient as y, McpServerHttpConfigSchema as yi, ToolListUpdatedEvent as yn, AgentContextData$1 as yr, RemoveByfProviderPayload as yt, SDKRPC as z, ThinkingConfigSchema as zi, ByfErrorOptions as zn, BearerTokenProvider as zr, UpdateSessionMetadataPayload as zt };
4151
+ export { CreateSessionPayload as $, TelemetryProperties as $n, mergeConfigPatch as $r, CompactionCancelledEvent as $t, QuestionAnswers as A, ServicesConfig as Ai, TurnStepStartedEvent as An, LoopToolResultEvent as Ar, SetThinkingPayload as At, SDKSessionAPI as B, validateConfig as Bi, BYF_ERROR_INFO as Bn, OAuthTokenProviderResolver as Br, WithAgentId as Bt, SDKRPCClient as C, PermissionRuleDecisionSchema as Ci, ToolUpdate as Cn, UserPromptOrigin as Cr, SessionMetadataPatch as Ct, ApprovalResponse as D, ProviderConfigSchema as Di, TurnStepCompletedEvent as Dn, LoopStepBeginEvent as Dr, SetModelPayload as Dt, ApprovalRequest as E, ProviderConfig$1 as Ei, TurnStartedEvent as En, LoopRecordedEvent as Er, SetByfConfigPayload as Et, QuestionResult as F, WebSearchConfigSchema as Fi, isByfError as Fn, BackgroundLifecycleEvent as Fr, StopBackgroundPayload as Ft, AgentAPI$1 as G, Logger as Gi, SessionSubagentHost as Gn, transformTomlData as Gr, ResumedAgentState as Gt, ToolCallRequest as H, LogEntry as Hi, ByfErrorInfo as Hn, ensureConfigFile as Hr, proxyWithExtraPayload as Ht, SDKAPI as I, WebSearchProviderConfig as Ii, makeErrorPayload as In, BackgroundTaskInfo$1 as Ir, TextPromptPart as It, ByfConfigPatch as J, SessionAttachInput as Ji, Session as Jn, parseBooleanEnv as Jr, AssistantDeltaEvent as Jt, BeginCompactionPayload as K, LoggingConfig as Ki, SubagentHandle as Kn, writeConfigFile as Kr, AgentEvent$1 as Kt, SDKAgentAPI as L, WebSearchProviderConfigSchema as Li, toByfErrorPayload as Ln, BackgroundTaskKind as Lr, UnregisterToolPayload as Lt, QuestionOption as M, ThinkingConfig as Mi, WarningEvent as Mn, ExecutableToolResult as Mr, ShellExecResult as Mt, QuestionRequest as N, ThinkingConfigSchema as Ni, ByfErrorPayload as Nn, ExecutableToolSuccessResult as Nr, SkillSummary as Nt, ApprovalScope as O, ProviderType as Oi, TurnStepInterruptedEvent as On, LoopStepEndEvent as Or, SetModelResult as Ot, QuestionResponse as P, WebSearchConfig as Pi, fromByfErrorPayload as Pn, ToolInputDisplay as Pr, SteerPayload as Pt, CoreInfo as Q, TelemetryClient as Qn, resolveConfigPath as Qr, CompactionBlockedEvent as Qt, SDKAgentRPC$1 as R, formatConfigValidationError as Ri, ByfError as Rn, BackgroundTaskStatus as Rr, Unsubscribe as Rt, RPCMethods as S, PermissionModeSchema as Si, ToolResultEvent as Sn, USER_PROMPT_ORIGIN as Sr, SessionAPI as St, ApprovalDecision as T, PermissionRuleScopeSchema as Ti, TurnEndedEvent as Tn, LoopContentPartEvent as Tr, SetActiveToolsPayload as Tt, ToolCallResponse as U, LogLevel as Ui, ErrorCodes as Un, parseConfigString as Ur, AgentReplayRecord as Ut, SDKSessionRPC$1 as V, LogContext as Vi, ByfErrorCode as Vn, configToTomlData as Vr, WithSessionId as Vt, ActivateSkillPayload$1 as W, LogPayload as Wi, RuntimeConfig as Wn, readConfigFile as Wr, ResumeSessionResult as Wt, CloseSessionPayload as X, SessionMeta$1 as Xn, ensureByfHome as Xr, BackgroundTaskTerminatedEvent as Xt, CancelPayload as Y, SessionLogHandle as Yi, SessionConfig as Yn, resolveConfigValue as Yr, BackgroundTaskStartedEvent as Yt, CoreAPI as Z, SessionSkillConfig as Zn, resolveByfHome as Zr, BackgroundTaskUpdatedEvent as Zt, ByfCoreOptions as _, ModelAliasSchema as _i, ToolCallDeltaEvent as _n, CompactionBeginData as _r, ReconnectMcpServerPayload as _t, collectFilesRecursive as a, ByfServiceConfigSchema as ai, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE as an, BuiltinTool as ar, GetBackgroundOutputPathPayload as at, RPCCallOptions as b, PermissionConfig as bi, ToolListUpdatedReason as bn, ContextMessage$1 as br, RenameSessionPayload as bt, WIRE_PROTOCOL_VERSION as c, LoopControl as ci, McpServerStatusPayload as cn, UserToolRegistration as cr, JsonObject as ct, normalizeTimestampMs as d, McpServerConfigSchema as di, SessionMetaUpdatedEvent as dn, AgentRecordOf as dr, ListSessionsPayload as dt, BackgroundConfig as ei, CompactionCompletedEvent as en, flushDiagnosticLogs as er, EmptyPayload as et, scanSessionWire as f, McpServerHttpConfig as fi, SkillActivatedEvent as fn, AgentRecordPersistence as fr, McpServerInfo as ft, ByfCore as g, ModelAlias as gi, ThinkingDeltaEvent as gn, AgentConfigUpdateData$1 as gr, PromptPayload as gt, AgentType$1 as h, McpServerStdioConfigSchema as hi, SubagentSpawnedEvent as hn, PermissionMode$1 as hr, PromptPart as ht, ExtraZipEntry as i, ByfServiceConfig as ii, HookResultEvent as in, resolveGlobalLogPath as ir, ForkSessionPayload as it, QuestionItem as j, ServicesConfigSchema as ji, UsageStatus$1 as jn, ExecutableToolErrorResult as jr, ShellExecPayload as jt, QuestionAnswerMethod as k, ProviderTypeSchema as ki, TurnStepRetryingEvent as kn, LoopToolCallEvent as kr, SetPermissionPayload as kt, buildExportManifest as l, LoopControlSchema as li, ObservationMaskingAppliedEvent as ln, AgentRecord as lr, JsonPrimitive as lt, AgentConfig as m, McpServerStdioConfig as mi, SubagentFailedEvent as mn, PermissionApprovalResultRecord$1 as mr, PromptInput as mt, ResolveLoggingInput as n, ByfConfigPatchSchema as ni, ErrorEvent as nn, log as nr, ExportSessionPayload as nt, writeExportZip as o, HookDefConfig as oi, McpOAuthAuthorizationUrlUpdateData as on, ToolInfo$1 as or, GetBackgroundOutputPayload as ot, Agent as p, McpServerHttpConfigSchema as pi, SubagentCompletedEvent as pn, UsageRecordScope as pr, McpStartupMetrics as pt, ByfConfig as q, RootLogger as qi, AgentMeta as qn, ResolveConfigValueInput as qr, AgentStatusUpdatedEvent as qt, resolveLoggingConfig as r, ByfConfigSchema as ri, Event as rn, redact as rr, ExportSessionResult as rt, exportSessionDirectory as s, HookDefSchema as si, McpServerStatusEvent as sn, ToolSource as sr, GetBackgroundPayload as st, buildPromptPlan as t, BackgroundConfigSchema as ti, CompactionStartedEvent as tn, getRootLogger as tr, ExportSessionManifest as tt, SessionWireScan as u, McpServerConfig as ui, PruningAppliedEvent as un, AgentRecordEvents as ur, JsonValue as ut, CoreRPC as v, OAuthRef$1 as vi, ToolCallStartedEvent as vn, CompactionResult$1 as vr, RegisterToolPayload as vt, createRPC as w, PermissionRuleSchema as wi, TurnEndReason as wn, ToolStoreUpdate as wr, SessionSummary as wt, RPCClient as x, PermissionConfigSchema as xi, ToolProgressEvent as xn, PromptOrigin as xr, ResumeSessionPayload as xt, CoreRPCClient as y, OAuthRefSchema as yi, ToolListUpdatedEvent as yn, AgentContextData$1 as yr, RemoveByfProviderPayload as yt, SDKRPC as z, getDefaultConfig as zi, ByfErrorOptions as zn, BearerTokenProvider as zr, UpdateSessionMetadataPayload as zt };
4244
4152
  export { ActivateSkillPayload$1 as ActivateSkillPayload, AgentAPI$1 as AgentAPI, AgentEvent$1 as AgentEvent, SDKAgentRPC$1 as SDKAgentRPC, SDKSessionRPC$1 as SDKSessionRPC, UsageStatus$1 as UsageStatus, ByfConfig$1 as ByfConfig, ByfConfigPatch$1 as ByfConfigPatch, OAuthRef$1 as OAuthRef, AgentConfigData$1 as AgentConfigData, AgentConfigUpdateData$1 as AgentConfigUpdateData, AgentContextData$1 as AgentContextData, ContextMessage$1 as ContextMessage, PermissionApprovalResultRecord$1 as PermissionApprovalResultRecord, PermissionData$1 as PermissionData, PermissionMode$1 as PermissionMode, ToolInfo$1 as ToolInfo, AgentType$1 as AgentType, SessionMeta$1 as SessionMeta, BackgroundTaskInfo$1 as BackgroundTaskInfo };
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { t as AGENT_WIRE_PROTOCOL_VERSION } from "./index-DitEeLHK.mjs";
2
- import { $ as CreateSessionPayload, $i as RootLogger, $n as TelemetryProperties, $r as ResolveConfigValueInput, $t as CompactionCancelledEvent, A as QuestionAnswers, Ai as PermissionRuleSchema, An as TurnStepStartedEvent, Ar as LoopToolResultEvent, At as SetThinkingPayload, B as SDKSessionAPI, Bi as WebSearchConfig, Bn as BYF_ERROR_INFO, Br as OAuthTokenProviderResolver, Bt as WithAgentId, C as SDKRPCClient, Ci as ModelAliasSchema, Cn as ToolUpdate, Cr as UserPromptOrigin, Ct as SessionMetadataPatch, D as ApprovalResponse, Di as PermissionConfigSchema, Dn as TurnStepCompletedEvent, Dr as LoopStepBeginEvent, Dt as SetModelPayload, E as ApprovalRequest, Ei as PermissionConfig, En as TurnStartedEvent, Er as LoopRecordedEvent, Et as SetByfConfigPayload, F as QuestionResult, Fi as ProviderTypeSchema, Fn as isByfError, Fr as BackgroundLifecycleEvent, Ft as StopBackgroundPayload, G as AgentAPI, Gi as getDefaultConfig, Gn as SessionSubagentHost, Gr as DeprecatedFieldRule, Gt as ResumedAgentState, H as ToolCallRequest, Hi as WebSearchProviderConfig, Hn as ByfErrorInfo, Hr as analyzeConfig, Ht as proxyWithExtraPayload, I as SDKAPI, Ii as ServicesConfig, In as makeErrorPayload, Ir as BackgroundTaskInfo, It as TextPromptPart, J as ByfConfigPatch, Ji as LogEntry, Jn as Session, Jr as ensureConfigFile, Jt as AssistantDeltaEvent, K as BeginCompactionPayload, Ki as validateConfig, Kn as SubagentHandle, Kr as Finding, Kt as AgentEvent, L as SDKAgentAPI, Li as ServicesConfigSchema, Ln as toByfErrorPayload, Lr as BackgroundTaskKind, Lt as UnregisterToolPayload, M as QuestionOption, Mi as ProviderConfig, Mn as WarningEvent, Mr as ExecutableToolResult, Mt as ShellExecResult, N as QuestionRequest, Ni as ProviderConfigSchema, Nn as ByfErrorPayload, Nr as ExecutableToolSuccessResult, Nt as SkillSummary, O as ApprovalScope, Oi as PermissionModeSchema, On as TurnStepInterruptedEvent, Or as LoopStepEndEvent, Ot as SetModelResult, P as QuestionResponse, Pi as ProviderType, Pn as fromByfErrorPayload, Pr as ToolInputDisplay, Pt as SteerPayload, Q as CoreInfo, Qi as LoggingConfig, Qn as TelemetryClient, Qr as writeConfigFile, Qt as CompactionBlockedEvent, R as SDKAgentRPC, Ri as ThinkingConfig, Rn as ByfError, Rr as BackgroundTaskStatus, Rt as Unsubscribe, S as RPCMethods, Si as ModelAlias, Sn as ToolResultEvent, Sr as USER_PROMPT_ORIGIN, St as SessionAPI, T as ApprovalDecision, Ti as OAuthRefSchema, Tn as TurnEndedEvent, Tr as LoopContentPartEvent, Tt as SetActiveToolsPayload, U as ToolCallResponse, Ui as WebSearchProviderConfigSchema, Un as ErrorCodes, Ur as applyFixes, Ut as AgentReplayRecord, V as SDKSessionRPC, Vi as WebSearchConfigSchema, Vn as ByfErrorCode, Vr as UpdateAnalyzeInput, Vt as WithSessionId, W as ActivateSkillPayload, Wi as formatConfigValidationError, Wn as RuntimeConfig, Wr as DEPRECATED_FIELD_RULES, Wt as ResumeSessionResult, X as CloseSessionPayload, Xi as LogPayload, Xn as SessionMeta, Xr as readConfigFile, Xt as BackgroundTaskTerminatedEvent, Y as CancelPayload, Yi as LogLevel, Yn as SessionConfig, Yr as parseConfigString, Yt as BackgroundTaskStartedEvent, Z as CoreAPI, Zi as Logger, Zn as SessionSkillConfig, Zr as transformTomlData, Zt as BackgroundTaskUpdatedEvent, _ as ByfCoreOptions, _i as McpServerConfigSchema, _n as ToolCallDeltaEvent, _r as CompactionBeginData, _t as ReconnectMcpServerPayload, a as collectFilesRecursive, ai as mergeConfigPatch, an as MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, ar as BuiltinTool, at as GetBackgroundOutputPathPayload, b as RPCCallOptions, bi as McpServerStdioConfig, bn as ToolListUpdatedReason, br as ContextMessage, bt as RenameSessionPayload, c as WIRE_PROTOCOL_VERSION, ci as ByfConfigPatchSchema, cn as McpServerStatusPayload, cr as UserToolRegistration, ct as JsonObject, d as normalizeTimestampMs, di as ByfServiceConfigSchema, dn as SessionMetaUpdatedEvent, dr as AgentRecordOf, dt as ListSessionsPayload, ea as SessionAttachInput, ei as parseBooleanEnv, en as CompactionCompletedEvent, er as flushDiagnosticLogs, et as EmptyPayload, f as scanSessionWire, fi as HookDefConfig, fn as SkillActivatedEvent, fr as AgentRecordPersistence, ft as McpServerInfo, g as ByfCore, gi as McpServerConfig, gn as ThinkingDeltaEvent, gr as AgentConfigUpdateData, gt as PromptPayload, h as AgentType, hi as LoopControlSchema, hn as SubagentSpawnedEvent, hr as PermissionMode, ht as PromptPart, i as ExtraZipEntry, ii as resolveConfigPath, in as HookResultEvent, ir as resolveGlobalLogPath, it as ForkSessionPayload, j as QuestionItem, ji as PermissionRuleScopeSchema, jn as UsageStatus, jr as ExecutableToolErrorResult, jt as ShellExecPayload, k as QuestionAnswerMethod, ki as PermissionRuleDecisionSchema, kn as TurnStepRetryingEvent, kr as LoopToolCallEvent, kt as SetPermissionPayload, l as buildExportManifest, li as ByfConfigSchema, ln as ObservationMaskingAppliedEvent, lr as AgentRecord, lt as JsonPrimitive, m as AgentConfig, mi as LoopControl, mn as SubagentFailedEvent, mr as PermissionApprovalResultRecord, mt as PromptInput, n as ResolveLoggingInput, ni as ensureByfHome, nn as ErrorEvent, nr as log, nt as ExportSessionPayload, o as writeExportZip, oi as BackgroundConfig, on as McpOAuthAuthorizationUrlUpdateData, or as ToolInfo, ot as GetBackgroundOutputPayload, p as Agent, pi as HookDefSchema, pn as SubagentCompletedEvent, pr as UsageRecordScope, pt as McpStartupMetrics, q as ByfConfig, qi as LogContext, qn as AgentMeta, qr as configToTomlData, qt as AgentStatusUpdatedEvent, r as resolveLoggingConfig, ri as resolveByfHome, rn as Event, rr as redact, rt as ExportSessionResult, s as exportSessionDirectory, si as BackgroundConfigSchema, sn as McpServerStatusEvent, sr as ToolSource, st as GetBackgroundPayload, t as buildPromptPlan, ta as SessionLogHandle, ti as resolveConfigValue, tn as CompactionStartedEvent, tr as getRootLogger, tt as ExportSessionManifest, u as SessionWireScan, ui as ByfServiceConfig, un as PruningAppliedEvent, ur as AgentRecordEvents, ut as JsonValue, v as CoreRPC, vi as McpServerHttpConfig, vn as ToolCallStartedEvent, vr as CompactionResult, vt as RegisterToolPayload, w as createRPC, wi as OAuthRef, wn as TurnEndReason, wr as ToolStoreUpdate, wt as SessionSummary, x as RPCClient, xi as McpServerStdioConfigSchema, xn as ToolProgressEvent, xr as PromptOrigin, xt as ResumeSessionPayload, y as CoreRPCClient, yi as McpServerHttpConfigSchema, yn as ToolListUpdatedEvent, yr as AgentContextData, yt as RemoveByfProviderPayload, z as SDKRPC, zi as ThinkingConfigSchema, zn as ByfErrorOptions, zr as BearerTokenProvider, zt as UpdateSessionMetadataPayload } from "./index-CZA_2ux5.mjs";
3
- export { AGENT_WIRE_PROTOCOL_VERSION, ActivateSkillPayload, Agent, AgentAPI, AgentConfig, type AgentConfigUpdateData, type AgentContextData, AgentEvent, AgentMeta, type AgentRecord, type AgentRecordEvents, type AgentRecordOf, type AgentRecordPersistence, AgentReplayRecord, AgentStatusUpdatedEvent, AgentType, ApprovalDecision, ApprovalRequest, ApprovalResponse, ApprovalScope, AssistantDeltaEvent, BYF_ERROR_INFO, BackgroundConfig, BackgroundConfigSchema, type BackgroundLifecycleEvent, type BackgroundTaskInfo, type BackgroundTaskKind, BackgroundTaskStartedEvent, type BackgroundTaskStatus, BackgroundTaskTerminatedEvent, BackgroundTaskUpdatedEvent, type BearerTokenProvider, BeginCompactionPayload, type BuiltinTool, ByfConfigPatchSchema, ByfConfigSchema, ByfCore, ByfCoreOptions, ByfError, type ByfErrorCode, type ByfErrorInfo, type ByfErrorOptions, type ByfErrorPayload, ByfServiceConfig, ByfServiceConfigSchema, CancelPayload, CloseSessionPayload, type CompactionBeginData, CompactionBlockedEvent, CompactionCancelledEvent, CompactionCompletedEvent, CompactionResult, CompactionStartedEvent, type ContextMessage, CoreAPI, CoreInfo, CoreRPC, CoreRPCClient, CreateSessionPayload, DEPRECATED_FIELD_RULES, DeprecatedFieldRule, EmptyPayload, ErrorCodes, ErrorEvent, Event, type ExecutableToolErrorResult, type ExecutableToolResult, type ExecutableToolSuccessResult, ExportSessionManifest, ExportSessionPayload, ExportSessionResult, ExtraZipEntry, Finding, ForkSessionPayload, GetBackgroundOutputPathPayload, GetBackgroundOutputPayload, GetBackgroundPayload, HookDefConfig, HookDefSchema, HookResultEvent, JsonObject, JsonPrimitive, JsonValue, ListSessionsPayload, type LogContext, type LogEntry, type LogLevel, type LogPayload, type Logger, type LoggingConfig, type LoopContentPartEvent, LoopControl, LoopControlSchema, type LoopRecordedEvent, type LoopStepBeginEvent, type LoopStepEndEvent, type LoopToolCallEvent, type LoopToolResultEvent, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, McpOAuthAuthorizationUrlUpdateData, McpServerConfig, McpServerConfigSchema, McpServerHttpConfig, McpServerHttpConfigSchema, McpServerInfo, McpServerStatusEvent, McpServerStatusPayload, McpServerStdioConfig, McpServerStdioConfigSchema, McpStartupMetrics, ModelAlias, ModelAliasSchema, OAuthRef, OAuthRefSchema, type OAuthTokenProviderResolver, ObservationMaskingAppliedEvent, type PermissionApprovalResultRecord, PermissionConfig, PermissionConfigSchema, type PermissionMode, PermissionModeSchema, PermissionRuleDecisionSchema, PermissionRuleSchema, PermissionRuleScopeSchema, PromptInput, type PromptOrigin, PromptPart, PromptPayload, ProviderConfig, ProviderConfigSchema, ProviderType, ProviderTypeSchema, PruningAppliedEvent, QuestionAnswerMethod, QuestionAnswers, QuestionItem, QuestionOption, QuestionRequest, QuestionResponse, QuestionResult, RPCCallOptions, RPCClient, RPCMethods, ReconnectMcpServerPayload, RegisterToolPayload, RemoveByfProviderPayload, RenameSessionPayload, ResolveConfigValueInput, type ResolveLoggingInput, ResumeSessionPayload, ResumeSessionResult, ResumedAgentState, type RootLogger, type RuntimeConfig, SDKAPI, SDKAgentAPI, SDKAgentRPC, SDKRPC, SDKRPCClient, SDKSessionAPI, SDKSessionRPC, ServicesConfig, ServicesConfigSchema, Session, SessionAPI, type SessionAttachInput, SessionConfig, type SessionLogHandle, SessionMeta, SessionMetaUpdatedEvent, SessionMetadataPatch, SessionSkillConfig, SessionSubagentHost, SessionSummary, SessionWireScan, SetActiveToolsPayload, SetByfConfigPayload, SetModelPayload, SetModelResult, SetPermissionPayload, SetThinkingPayload, ShellExecPayload, ShellExecResult, SkillActivatedEvent, SkillSummary, SteerPayload, StopBackgroundPayload, SubagentCompletedEvent, SubagentFailedEvent, SubagentHandle, SubagentSpawnedEvent, type TelemetryClient, type TelemetryProperties, TextPromptPart, ThinkingConfig, ThinkingConfigSchema, ThinkingDeltaEvent, ToolCallDeltaEvent, ToolCallRequest, ToolCallResponse, ToolCallStartedEvent, type ToolInfo, type ToolInputDisplay, ToolListUpdatedEvent, ToolListUpdatedReason, ToolProgressEvent, ToolResultEvent, type ToolSource, type ToolStoreUpdate, ToolUpdate, TurnEndReason, TurnEndedEvent, TurnStartedEvent, TurnStepCompletedEvent, TurnStepInterruptedEvent, TurnStepRetryingEvent, TurnStepStartedEvent, USER_PROMPT_ORIGIN, UnregisterToolPayload, Unsubscribe, UpdateAnalyzeInput, UpdateSessionMetadataPayload, type UsageRecordScope, UsageStatus, type UserPromptOrigin, type UserToolRegistration, WIRE_PROTOCOL_VERSION, WarningEvent, WebSearchConfig, WebSearchConfigSchema, WebSearchProviderConfig, WebSearchProviderConfigSchema, WithAgentId, WithSessionId, analyzeConfig, applyFixes, buildExportManifest, buildPromptPlan, collectFilesRecursive, configToTomlData, createRPC, ensureByfHome, ensureConfigFile, exportSessionDirectory, flushDiagnosticLogs, formatConfigValidationError, fromByfErrorPayload, getDefaultConfig, getRootLogger, isByfError, log, makeErrorPayload, mergeConfigPatch, normalizeTimestampMs, parseBooleanEnv, parseConfigString, proxyWithExtraPayload, readConfigFile, redact, resolveByfHome, resolveConfigPath, resolveConfigValue, resolveGlobalLogPath, resolveLoggingConfig, scanSessionWire, toByfErrorPayload, transformTomlData, validateConfig, writeConfigFile, writeExportZip };
2
+ import { $ as CreateSessionPayload, $n as TelemetryProperties, $r as mergeConfigPatch, $t as CompactionCancelledEvent, A as QuestionAnswers, Ai as ServicesConfig, An as TurnStepStartedEvent, Ar as LoopToolResultEvent, At as SetThinkingPayload, B as SDKSessionAPI, Bi as validateConfig, Bn as BYF_ERROR_INFO, Br as OAuthTokenProviderResolver, Bt as WithAgentId, C as SDKRPCClient, Ci as PermissionRuleDecisionSchema, Cn as ToolUpdate, Cr as UserPromptOrigin, Ct as SessionMetadataPatch, D as ApprovalResponse, Di as ProviderConfigSchema, Dn as TurnStepCompletedEvent, Dr as LoopStepBeginEvent, Dt as SetModelPayload, E as ApprovalRequest, Ei as ProviderConfig, En as TurnStartedEvent, Er as LoopRecordedEvent, Et as SetByfConfigPayload, F as QuestionResult, Fi as WebSearchConfigSchema, Fn as isByfError, Fr as BackgroundLifecycleEvent, Ft as StopBackgroundPayload, G as AgentAPI, Gi as Logger, Gn as SessionSubagentHost, Gr as transformTomlData, Gt as ResumedAgentState, H as ToolCallRequest, Hi as LogEntry, Hn as ByfErrorInfo, Hr as ensureConfigFile, Ht as proxyWithExtraPayload, I as SDKAPI, Ii as WebSearchProviderConfig, In as makeErrorPayload, Ir as BackgroundTaskInfo, It as TextPromptPart, J as ByfConfigPatch, Ji as SessionAttachInput, Jn as Session, Jr as parseBooleanEnv, Jt as AssistantDeltaEvent, K as BeginCompactionPayload, Ki as LoggingConfig, Kn as SubagentHandle, Kr as writeConfigFile, Kt as AgentEvent, L as SDKAgentAPI, Li as WebSearchProviderConfigSchema, Ln as toByfErrorPayload, Lr as BackgroundTaskKind, Lt as UnregisterToolPayload, M as QuestionOption, Mi as ThinkingConfig, Mn as WarningEvent, Mr as ExecutableToolResult, Mt as ShellExecResult, N as QuestionRequest, Ni as ThinkingConfigSchema, Nn as ByfErrorPayload, Nr as ExecutableToolSuccessResult, Nt as SkillSummary, O as ApprovalScope, Oi as ProviderType, On as TurnStepInterruptedEvent, Or as LoopStepEndEvent, Ot as SetModelResult, P as QuestionResponse, Pi as WebSearchConfig, Pn as fromByfErrorPayload, Pr as ToolInputDisplay, Pt as SteerPayload, Q as CoreInfo, Qn as TelemetryClient, Qr as resolveConfigPath, Qt as CompactionBlockedEvent, R as SDKAgentRPC, Ri as formatConfigValidationError, Rn as ByfError, Rr as BackgroundTaskStatus, Rt as Unsubscribe, S as RPCMethods, Si as PermissionModeSchema, Sn as ToolResultEvent, Sr as USER_PROMPT_ORIGIN, St as SessionAPI, T as ApprovalDecision, Ti as PermissionRuleScopeSchema, Tn as TurnEndedEvent, Tr as LoopContentPartEvent, Tt as SetActiveToolsPayload, U as ToolCallResponse, Ui as LogLevel, Un as ErrorCodes, Ur as parseConfigString, Ut as AgentReplayRecord, V as SDKSessionRPC, Vi as LogContext, Vn as ByfErrorCode, Vr as configToTomlData, Vt as WithSessionId, W as ActivateSkillPayload, Wi as LogPayload, Wn as RuntimeConfig, Wr as readConfigFile, Wt as ResumeSessionResult, X as CloseSessionPayload, Xn as SessionMeta, Xr as ensureByfHome, Xt as BackgroundTaskTerminatedEvent, Y as CancelPayload, Yi as SessionLogHandle, Yn as SessionConfig, Yr as resolveConfigValue, Yt as BackgroundTaskStartedEvent, Z as CoreAPI, Zn as SessionSkillConfig, Zr as resolveByfHome, Zt as BackgroundTaskUpdatedEvent, _ as ByfCoreOptions, _i as ModelAliasSchema, _n as ToolCallDeltaEvent, _r as CompactionBeginData, _t as ReconnectMcpServerPayload, a as collectFilesRecursive, ai as ByfServiceConfigSchema, an as MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, ar as BuiltinTool, at as GetBackgroundOutputPathPayload, b as RPCCallOptions, bi as PermissionConfig, bn as ToolListUpdatedReason, br as ContextMessage, bt as RenameSessionPayload, c as WIRE_PROTOCOL_VERSION, ci as LoopControl, cn as McpServerStatusPayload, cr as UserToolRegistration, ct as JsonObject, d as normalizeTimestampMs, di as McpServerConfigSchema, dn as SessionMetaUpdatedEvent, dr as AgentRecordOf, dt as ListSessionsPayload, ei as BackgroundConfig, en as CompactionCompletedEvent, er as flushDiagnosticLogs, et as EmptyPayload, f as scanSessionWire, fi as McpServerHttpConfig, fn as SkillActivatedEvent, fr as AgentRecordPersistence, ft as McpServerInfo, g as ByfCore, gi as ModelAlias, gn as ThinkingDeltaEvent, gr as AgentConfigUpdateData, gt as PromptPayload, h as AgentType, hi as McpServerStdioConfigSchema, hn as SubagentSpawnedEvent, hr as PermissionMode, ht as PromptPart, i as ExtraZipEntry, ii as ByfServiceConfig, in as HookResultEvent, ir as resolveGlobalLogPath, it as ForkSessionPayload, j as QuestionItem, ji as ServicesConfigSchema, jn as UsageStatus, jr as ExecutableToolErrorResult, jt as ShellExecPayload, k as QuestionAnswerMethod, ki as ProviderTypeSchema, kn as TurnStepRetryingEvent, kr as LoopToolCallEvent, kt as SetPermissionPayload, l as buildExportManifest, li as LoopControlSchema, ln as ObservationMaskingAppliedEvent, lr as AgentRecord, lt as JsonPrimitive, m as AgentConfig, mi as McpServerStdioConfig, mn as SubagentFailedEvent, mr as PermissionApprovalResultRecord, mt as PromptInput, n as ResolveLoggingInput, ni as ByfConfigPatchSchema, nn as ErrorEvent, nr as log, nt as ExportSessionPayload, o as writeExportZip, oi as HookDefConfig, on as McpOAuthAuthorizationUrlUpdateData, or as ToolInfo, ot as GetBackgroundOutputPayload, p as Agent, pi as McpServerHttpConfigSchema, pn as SubagentCompletedEvent, pr as UsageRecordScope, pt as McpStartupMetrics, q as ByfConfig, qi as RootLogger, qn as AgentMeta, qr as ResolveConfigValueInput, qt as AgentStatusUpdatedEvent, r as resolveLoggingConfig, ri as ByfConfigSchema, rn as Event, rr as redact, rt as ExportSessionResult, s as exportSessionDirectory, si as HookDefSchema, sn as McpServerStatusEvent, sr as ToolSource, st as GetBackgroundPayload, t as buildPromptPlan, ti as BackgroundConfigSchema, tn as CompactionStartedEvent, tr as getRootLogger, tt as ExportSessionManifest, u as SessionWireScan, ui as McpServerConfig, un as PruningAppliedEvent, ur as AgentRecordEvents, ut as JsonValue, v as CoreRPC, vi as OAuthRef, vn as ToolCallStartedEvent, vr as CompactionResult, vt as RegisterToolPayload, w as createRPC, wi as PermissionRuleSchema, wn as TurnEndReason, wr as ToolStoreUpdate, wt as SessionSummary, x as RPCClient, xi as PermissionConfigSchema, xn as ToolProgressEvent, xr as PromptOrigin, xt as ResumeSessionPayload, y as CoreRPCClient, yi as OAuthRefSchema, yn as ToolListUpdatedEvent, yr as AgentContextData, yt as RemoveByfProviderPayload, z as SDKRPC, zi as getDefaultConfig, zn as ByfErrorOptions, zr as BearerTokenProvider, zt as UpdateSessionMetadataPayload } from "./index-BNApCprm.mjs";
3
+ export { AGENT_WIRE_PROTOCOL_VERSION, ActivateSkillPayload, Agent, AgentAPI, AgentConfig, type AgentConfigUpdateData, type AgentContextData, AgentEvent, AgentMeta, type AgentRecord, type AgentRecordEvents, type AgentRecordOf, type AgentRecordPersistence, AgentReplayRecord, AgentStatusUpdatedEvent, AgentType, ApprovalDecision, ApprovalRequest, ApprovalResponse, ApprovalScope, AssistantDeltaEvent, BYF_ERROR_INFO, BackgroundConfig, BackgroundConfigSchema, type BackgroundLifecycleEvent, type BackgroundTaskInfo, type BackgroundTaskKind, BackgroundTaskStartedEvent, type BackgroundTaskStatus, BackgroundTaskTerminatedEvent, BackgroundTaskUpdatedEvent, type BearerTokenProvider, BeginCompactionPayload, type BuiltinTool, ByfConfigPatchSchema, ByfConfigSchema, ByfCore, ByfCoreOptions, ByfError, type ByfErrorCode, type ByfErrorInfo, type ByfErrorOptions, type ByfErrorPayload, ByfServiceConfig, ByfServiceConfigSchema, CancelPayload, CloseSessionPayload, type CompactionBeginData, CompactionBlockedEvent, CompactionCancelledEvent, CompactionCompletedEvent, CompactionResult, CompactionStartedEvent, type ContextMessage, CoreAPI, CoreInfo, CoreRPC, CoreRPCClient, CreateSessionPayload, EmptyPayload, ErrorCodes, ErrorEvent, Event, type ExecutableToolErrorResult, type ExecutableToolResult, type ExecutableToolSuccessResult, ExportSessionManifest, ExportSessionPayload, ExportSessionResult, ExtraZipEntry, ForkSessionPayload, GetBackgroundOutputPathPayload, GetBackgroundOutputPayload, GetBackgroundPayload, HookDefConfig, HookDefSchema, HookResultEvent, JsonObject, JsonPrimitive, JsonValue, ListSessionsPayload, type LogContext, type LogEntry, type LogLevel, type LogPayload, type Logger, type LoggingConfig, type LoopContentPartEvent, LoopControl, LoopControlSchema, type LoopRecordedEvent, type LoopStepBeginEvent, type LoopStepEndEvent, type LoopToolCallEvent, type LoopToolResultEvent, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, McpOAuthAuthorizationUrlUpdateData, McpServerConfig, McpServerConfigSchema, McpServerHttpConfig, McpServerHttpConfigSchema, McpServerInfo, McpServerStatusEvent, McpServerStatusPayload, McpServerStdioConfig, McpServerStdioConfigSchema, McpStartupMetrics, ModelAlias, ModelAliasSchema, OAuthRef, OAuthRefSchema, type OAuthTokenProviderResolver, ObservationMaskingAppliedEvent, type PermissionApprovalResultRecord, PermissionConfig, PermissionConfigSchema, type PermissionMode, PermissionModeSchema, PermissionRuleDecisionSchema, PermissionRuleSchema, PermissionRuleScopeSchema, PromptInput, type PromptOrigin, PromptPart, PromptPayload, ProviderConfig, ProviderConfigSchema, ProviderType, ProviderTypeSchema, PruningAppliedEvent, QuestionAnswerMethod, QuestionAnswers, QuestionItem, QuestionOption, QuestionRequest, QuestionResponse, QuestionResult, RPCCallOptions, RPCClient, RPCMethods, ReconnectMcpServerPayload, RegisterToolPayload, RemoveByfProviderPayload, RenameSessionPayload, ResolveConfigValueInput, type ResolveLoggingInput, ResumeSessionPayload, ResumeSessionResult, ResumedAgentState, type RootLogger, type RuntimeConfig, SDKAPI, SDKAgentAPI, SDKAgentRPC, SDKRPC, SDKRPCClient, SDKSessionAPI, SDKSessionRPC, ServicesConfig, ServicesConfigSchema, Session, SessionAPI, type SessionAttachInput, SessionConfig, type SessionLogHandle, SessionMeta, SessionMetaUpdatedEvent, SessionMetadataPatch, SessionSkillConfig, SessionSubagentHost, SessionSummary, SessionWireScan, SetActiveToolsPayload, SetByfConfigPayload, SetModelPayload, SetModelResult, SetPermissionPayload, SetThinkingPayload, ShellExecPayload, ShellExecResult, SkillActivatedEvent, SkillSummary, SteerPayload, StopBackgroundPayload, SubagentCompletedEvent, SubagentFailedEvent, SubagentHandle, SubagentSpawnedEvent, type TelemetryClient, type TelemetryProperties, TextPromptPart, ThinkingConfig, ThinkingConfigSchema, ThinkingDeltaEvent, ToolCallDeltaEvent, ToolCallRequest, ToolCallResponse, ToolCallStartedEvent, type ToolInfo, type ToolInputDisplay, ToolListUpdatedEvent, ToolListUpdatedReason, ToolProgressEvent, ToolResultEvent, type ToolSource, type ToolStoreUpdate, ToolUpdate, TurnEndReason, TurnEndedEvent, TurnStartedEvent, TurnStepCompletedEvent, TurnStepInterruptedEvent, TurnStepRetryingEvent, TurnStepStartedEvent, USER_PROMPT_ORIGIN, UnregisterToolPayload, Unsubscribe, UpdateSessionMetadataPayload, type UsageRecordScope, UsageStatus, type UserPromptOrigin, type UserToolRegistration, WIRE_PROTOCOL_VERSION, WarningEvent, WebSearchConfig, WebSearchConfigSchema, WebSearchProviderConfig, WebSearchProviderConfigSchema, WithAgentId, WithSessionId, buildExportManifest, buildPromptPlan, collectFilesRecursive, configToTomlData, createRPC, ensureByfHome, ensureConfigFile, exportSessionDirectory, flushDiagnosticLogs, formatConfigValidationError, fromByfErrorPayload, getDefaultConfig, getRootLogger, isByfError, log, makeErrorPayload, mergeConfigPatch, normalizeTimestampMs, parseBooleanEnv, parseConfigString, proxyWithExtraPayload, readConfigFile, redact, resolveByfHome, resolveConfigPath, resolveConfigValue, resolveGlobalLogPath, resolveLoggingConfig, scanSessionWire, toByfErrorPayload, transformTomlData, validateConfig, writeConfigFile, writeExportZip };
package/dist/index.mjs CHANGED
@@ -3032,7 +3032,7 @@ function parseSkillText(options) {
3032
3032
  throw error;
3033
3033
  }
3034
3034
  const frontmatter = parsed.data ?? {};
3035
- if (!isRecord$2(frontmatter)) throw new SkillParseError(`Frontmatter in ${options.skillMdPath} must be a mapping at the top level`);
3035
+ if (!isRecord$1(frontmatter)) throw new SkillParseError(`Frontmatter in ${options.skillMdPath} must be a mapping at the top level`);
3036
3036
  const metadata = normalizeMetadata(frontmatter);
3037
3037
  if (!isSupportedSkillType(metadata.type)) throw new UnsupportedSkillTypeError(metadata.type ?? String(frontmatter["type"]));
3038
3038
  const name = nonEmptyString$2(metadata.name);
@@ -3145,7 +3145,7 @@ function tokenizeArgs(raw) {
3145
3145
  function nonEmptyString$2(value) {
3146
3146
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
3147
3147
  }
3148
- function isRecord$2(value) {
3148
+ function isRecord$1(value) {
3149
3149
  return typeof value === "object" && value !== null && !Array.isArray(value);
3150
3150
  }
3151
3151
  //#endregion
@@ -3153,14 +3153,36 @@ function isRecord$2(value) {
3153
3153
  var mcp_config_default = "---\nname: mcp-config\ndescription: Configure MCP servers and handle MCP OAuth login.\n---\n\n# Interactive MCP server configuration\n\nThe user invoked this skill through `/mcp-config` or `/skill:mcp-config`.\nEither they want to log into an MCP server that asked for OAuth, or they\nwant to edit the `mcp.json` that lists MCP servers. The work is small and\nlocal — handle it on this turn yourself, no agents or planning todos.\n\nPick the flow from the user's message and your tool list:\n\n- An `mcp__<server>__authenticate` tool is in your list, the user says\n \"log in\" / \"auth\" / \"sign in\", they invoke `/mcp-config login\n <server>`, or they quote a `needs-auth` status → **Login**.\n- Add / edit / remove / list of an `mcp.json` entry → **Config edit**.\n- Bare `/mcp-config` with no `authenticate` tool in your list →\n **Config edit**. If there were a pending login, the authenticate tool\n would be in your list.\n\n## Login\n\nEach MCP server in `needs-auth` exposes one `mcp__<server>__authenticate`\ntool. Call it for the server the user means — its own description owns\nthe OAuth UX (printing the URL, blocking on the callback, reconnecting on\nsuccess). Surface its output verbatim, including the authorization URL\nunchanged; the URL contains state and PKCE parameters that break if\nedited.\n\nIf the user named a server that has no authenticate tool, say so in one\nsentence and stop — do **not** fall into config edit. They're trying to\nlog in to a server that isn't currently waiting for login; quietly\nrewriting `mcp.json` would be the wrong fix. If multiple authenticate\ntools exist and the user didn't name one, ask which.\n\n## Config edit\n\nConfig lives in two files; on key collision the project file overrides\nthe user-global one:\n\n- User-global: `~/.byf/mcp.json` (or `$BYF_HOME/mcp.json` if\n set). Use for servers you want everywhere.\n- Project-local: `<cwd>/.byf/mcp.json`. Mention once that stdio\n entries spawn commands at session start, so this should only live in\n trusted repos.\n\nBoth files wrap their entries the same way:\n\n```json\n{ \"mcpServers\": { \"<name>\": { /* entry */ } } }\n```\n\nA minimal stdio entry needs `command` (+ optional `args`, `env`, `cwd`).\nA minimal http entry needs `url`; add `bearerTokenEnvVar: \"ENV_NAME\"` for\nservers that authenticate with a static bearer token from the\nenvironment. Servers that use OAuth take no token field — the login flow\nabove handles them. `transport` is inferred from `command` vs `url`, so\nomit it. For less common fields (`enabled`, `startupTimeoutMs`,\n`toolTimeoutMs`, `enabledTools`, `disabledTools`, `headers`) the source of\ntruth is `McpServerStdioConfigSchema` / `McpServerHttpConfigSchema` in\n`packages/agent-core/src/config/schema.ts`.\n\nIf the user only wants to **see** what's configured, read both files,\nshow a merged view, and stop — no scope prompt, no write.\n\nFor changes, the flow is:\n\n1. **Pick a scope.** Infer it from the user's words when you can\n (project / repo / this checkout / cwd → project; global / everywhere /\n all projects → user-global). When the request is genuinely scope-less,\n use one `AskUserQuestion` to ask user-global vs project-local, defaulting\n to user-global. Use plain text for every other question — `AskUserQuestion`\n is a poor fit for free-form input. If the user dismisses the scope\n question, stop; you can't safely guess where they wanted the change.\n2. **Read and announce.** Read the target file (a missing or empty file\n is fine; you'll create `{ \"mcpServers\": {} }`). If JSON parsing fails,\n surface the error verbatim and stop — silently overwriting a broken\n file could destroy work. Then show the user the target path, what's\n currently in it, and the entry you're about to write or delete. This\n is for transparency, not a confirmation gate — the Edit/Write\n permission prompt is the real gate, and your message is what gives\n the user context when that prompt appears. In yolo / afk modes there\n is no prompt, which is those modes' explicit contract.\n3. **Write and tell them how to reload MCP servers.** Preserve unrelated\n entries and the `mcpServers` wrapper. MCP servers load at session\n start, so tell the user to start a new session (for example `/new`) or\n restart BYF for the change to take effect.\n\n## Secrets\n\nDon't store secrets (tokens, keys, passwords) as literals in\n`mcp.json` — it's a plain config file on disk. http servers should use\n`bearerTokenEnvVar` to reference an env var instead; if a stdio entry\nmust inline one in `env`, warn the user before writing.\n";
3154
3154
  //#endregion
3155
3155
  //#region src/skill/builtin/mcp-config.ts
3156
- const PSEUDO_PATH = "builtin://mcp-config";
3157
- const parsed = parseSkillText({
3156
+ const PSEUDO_PATH$1 = "builtin://mcp-config";
3157
+ const parsed$1 = parseSkillText({
3158
3158
  skillMdPath: "/builtin/skills/mcp-config.md",
3159
3159
  skillDirName: "mcp-config",
3160
3160
  source: "builtin",
3161
3161
  text: mcp_config_default
3162
3162
  });
3163
3163
  const MCP_CONFIG_SKILL = {
3164
+ ...parsed$1,
3165
+ path: PSEUDO_PATH$1,
3166
+ dir: PSEUDO_PATH$1,
3167
+ metadata: {
3168
+ ...parsed$1.metadata,
3169
+ type: parsed$1.metadata.type ?? "inline",
3170
+ disableModelInvocation: true
3171
+ }
3172
+ };
3173
+ //#endregion
3174
+ //#region src/skill/builtin/update-config.md
3175
+ var update_config_default = "---\nname: update-config\ndescription: Audit and fix ~/.byf/config.toml — remove deprecated fields, migrate legacy settings, and flag semantic conflicts.\n---\n\n# Audit and fix config.toml\n\nThe user invoked this skill via `/update-config` or `/skill:update-config`.\nThe goal is to bring `~/.byf/config.toml` in line with the current BYF schema:\nremove deprecated fields, migrate legacy settings, and point out semantic\nconflicts that a deterministic linter cannot catch. The work is small and\nlocal — handle it on this turn yourself, no agents or planning todos.\n\n## Read the config\n\n1. **Resolve the path.** Default: `~/.byf/config.toml` (or\n `$BYF_HOME/config.toml` if that env var is set). If the user passed a path\n as an argument, use that instead.\n2. **Read the file.** If it does not exist, say so and stop — there is nothing\n to update. If the TOML fails to parse, surface the parse error verbatim and\n **stop** — do not overwrite a broken file, that could destroy the user's\n work.\n3. **Never echo secrets.** `config.toml` stores `api_key` secret values, and\n `oauth` references (a `{ storage, key }` handle that points at a\n file/keyring entry — not the token itself). When you describe what you\n found or plan to change, state only that a credential is present or\n absent — never quote the `api_key` value itself, not even partially.\n\n## What to check for\n\nField-level validity (which keys exist, what types and enums are allowed) is\n**not** something to reproduce here. The single source of truth is\n`ByfConfigSchema` in `packages/agent-core/src/config/schema.ts` — read it when\nyou need to confirm whether a field is recognized and what values it accepts.\n\nThe checks below fall into three groups. Report findings from all three before\nmaking any change.\n\n### 1. Deprecated, renamed, and migrated fields\n\nThese are historical fields that the schema no longer accepts or has replaced.\nDelete them, except where the table says to rename or migrate:\n\n| Field | Action |\n|---|---|\n| `default_yolo` / `defaultYolo` (top-level) | Remove. Use `yolo` instead. |\n| `services.byf_search` | Remove. (Legacy service, superseded by `[services.web_search]`.) |\n| `services.byf_fetch` | Remove. Use `[services.fetch_url]` instead. |\n| `loop_control.max_steps_per_run` | **Rename** to `max_steps_per_turn`, preserving the value. First check whether `max_steps_per_turn` is already present: if so, the old key is a stale duplicate — just delete it; if not, write `max_steps_per_turn` with the old value, then delete `max_steps_per_run`. (The runtime auto-copies the value on read, but this skill edits the file directly and skips that roundtrip — so you must perform the rename yourself to avoid losing the limit.) |\n| `default_thinking` (top-level boolean) | Migrate — see below. |\n\n**`default_thinking` migration** (matches the runtime precedence in\n`byf-tui.ts`: a `[thinking]` block wins over `default_thinking`):\n\n- If `[thinking]` already has `mode` or `effort` set, `default_thinking` was\n never effective — just remove it.\n- Otherwise migrate by value: `true` → write `[thinking]` with\n `mode = \"on\"` and `effort = \"high\"`; `false` → `[thinking]` with\n `mode = \"off\"`. Then remove `default_thinking`.\n\n> **Raw-passthrough blind spot.** Fields stripped by the schema (like\n> `byf_search`, `byf_fetch`) survive inside `config.raw` and get written back\n> on every read→write roundtrip, so they linger in the file even though they\n> have no effect. Deleting them here is the only way to clear them — that is\n> the core value of this skill.\n\n### 2. Semantic conflicts (the part a linter cannot enumerate)\n\nLook for cross-field problems that require understanding intent:\n\n- A provider with **both** `api_key` and `oauth` configured — these are\n mutually exclusive; ask which one the user meant.\n- `thinking.mode = \"off\"` **and** a non-empty `thinking.effort` — the effort\n is ignored; suggest removing it or flipping the mode.\n- `models.<alias>.capabilities` containing a value not in the valid set. The\n valid set is the single source of truth: read `CAPABILITY_DEFINITIONS` (or\n the derived `VALID_CAPABILITIES`) in\n `packages/agent-core/src/providers/runtime-provider.ts`. Comparison is\n case-insensitive at runtime, so flag only genuine mismatches.\n- A model alias, `default_provider`, or `default_model` that points at a\n provider or model that does not exist — a dangling reference. Report it; do\n **not** delete it, the user may be mid-edit.\n\n### 3. Housekeeping\n\n- Top-level keys that are not in `ByfConfigSchema` (and not a deprecated key\n above) — likely typos or leftovers from an old version. Report them; only\n remove with user confirmation. Note that legitimate unknown keys (e.g.\n `theme`, `notifications`) are preserved by design through `config.raw`, so\n do not touch keys the user clearly added on purpose.\n- **Nested keys inside containers** (`[providers.<name>]`, `[models.<alias>]`,\n `[services]`, `[background]`, `[loop_control]`, `[thinking]`,\n `[permission]`). A key that the corresponding section of `ByfConfigSchema`\n does not recognize is silently dropped by the parser and has no effect — a\n common cause is a typo (e.g. `max_context_tokns` instead of\n `max_context_size`). Cross-check each sub-key against the schema and flag\n any mismatch; fix only with user confirmation. Note that `[permission]`\n still accepts the legacy `deny`/`allow`/`ask` array shorthand, so do not\n report those as unknown.\n\n## Make changes\n\nFor each change, show the user **what is currently there → what you plan to\nwrite** before editing. Then apply edits with Write/Edit. The Edit/Write\npermission prompt is the real safety gate — your summary is what gives the\nuser context when that prompt appears. There is no automatic backup; if the\nuser wants one, suggest they copy the file first.\n\nAfter editing, tell the user to start a new session (e.g. `/new`) or restart\nBYF for the config change to take effect.\n";
3176
+ //#endregion
3177
+ //#region src/skill/builtin/update-config.ts
3178
+ const PSEUDO_PATH = "builtin://update-config";
3179
+ const parsed = parseSkillText({
3180
+ skillMdPath: "/builtin/skills/update-config.md",
3181
+ skillDirName: "update-config",
3182
+ source: "builtin",
3183
+ text: update_config_default
3184
+ });
3185
+ const UPDATE_CONFIG_SKILL = {
3164
3186
  ...parsed,
3165
3187
  path: PSEUDO_PATH,
3166
3188
  dir: PSEUDO_PATH,
@@ -3174,6 +3196,7 @@ const MCP_CONFIG_SKILL = {
3174
3196
  //#region src/skill/builtin/index.ts
3175
3197
  function registerBuiltinSkills(registry) {
3176
3198
  registry.registerBuiltinSkill(MCP_CONFIG_SKILL);
3199
+ registry.registerBuiltinSkill(UPDATE_CONFIG_SKILL);
3177
3200
  }
3178
3201
  //#endregion
3179
3202
  //#region src/skill/scanner.ts
@@ -8221,7 +8244,7 @@ const OptionalStringSchema = z.preprocess((value) => {
8221
8244
  if (typeof value === "string") return value;
8222
8245
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
8223
8246
  }, z.string().optional());
8224
- const HookSpecificOutputSchema = z.preprocess((value) => isRecord$1(value) ? value : void 0, z.looseObject({
8247
+ const HookSpecificOutputSchema = z.preprocess((value) => isRecord(value) ? value : void 0, z.looseObject({
8225
8248
  message: OptionalStringSchema,
8226
8249
  permissionDecision: z.unknown().optional(),
8227
8250
  permissionDecisionReason: OptionalStringSchema
@@ -8381,7 +8404,7 @@ function tryKillProcess(child, signal) {
8381
8404
  } catch {}
8382
8405
  }
8383
8406
  }
8384
- function isRecord$1(value) {
8407
+ function isRecord(value) {
8385
8408
  return typeof value === "object" && value !== null && !Array.isArray(value);
8386
8409
  }
8387
8410
  function errorMessage(error) {
@@ -11049,6 +11072,7 @@ const YoloOutsideWorkspacePermissionPolicy = {
11049
11072
  evaluate({ agent, mode, toolCallContext }) {
11050
11073
  if (mode !== "yolo") return void 0;
11051
11074
  const toolName = toolCallContext.toolCall.name;
11075
+ if (isDefaultAutoAllowTool(toolName)) return void 0;
11052
11076
  const toolAccess = FILE_ACCESS_TOOLS[toolName];
11053
11077
  if (toolAccess === void 0) return void 0;
11054
11078
  const [operation, displayOperation] = toolAccess;
@@ -15908,655 +15932,66 @@ function isFileExistsError(error) {
15908
15932
  return typeof error === "object" && error !== null && error.code === "EEXIST";
15909
15933
  }
15910
15934
  //#endregion
15911
- //#region src/config/update-rules.ts
15912
- const REMOVED_RULES = [
15913
- {
15914
- path: "default_yolo",
15915
- pathParts: ["default_yolo"],
15916
- kind: "removed",
15917
- detail: "Top-level field default_yolo is removed. Use yolo instead.",
15918
- deprecatedSince: "pre-0.1.0"
15919
- },
15920
- {
15921
- path: "defaultYolo",
15922
- pathParts: ["defaultYolo"],
15923
- kind: "removed",
15924
- detail: "Top-level field defaultYolo is removed. Use yolo instead.",
15925
- deprecatedSince: "pre-0.1.0"
15926
- },
15927
- {
15928
- path: "services.byf_search",
15929
- pathParts: ["services", "byf_search"],
15930
- kind: "removed",
15931
- detail: "Deprecated service byf_search is removed.",
15932
- deprecatedSince: "pre-0.1.0"
15933
- },
15934
- {
15935
- path: "services.byf_fetch",
15936
- pathParts: ["services", "byf_fetch"],
15937
- kind: "removed",
15938
- detail: "Deprecated service byf_fetch is removed. Use services.fetch_url instead.",
15939
- deprecatedSince: "pre-0.1.0"
15935
+ //#region src/version.ts
15936
+ function getCoreVersion() {
15937
+ try {
15938
+ const raw = readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf-8");
15939
+ const pkg = JSON.parse(raw);
15940
+ return typeof pkg.version === "string" ? pkg.version : "0.0.0";
15941
+ } catch {
15942
+ return "0.0.0";
15940
15943
  }
15941
- ];
15942
- const RENAMED_RULES = [{
15943
- path: "loop_control.max_steps_per_run",
15944
- pathParts: ["loop_control", "max_steps_per_run"],
15945
- kind: "renamed",
15946
- detail: "Renamed to max_steps_per_turn.",
15947
- deprecatedSince: "pre-0.1.0"
15948
- }];
15949
- const MIGRATED_RULES = [{
15950
- path: "default_thinking",
15951
- pathParts: ["default_thinking"],
15952
- kind: "migrated",
15953
- detail: "Migrate default_thinking to [thinking] block.",
15954
- deprecatedSince: "pre-0.1.0"
15955
- }];
15944
+ }
15945
+ //#endregion
15946
+ //#region src/mcp/client-shared.ts
15947
+ const BYF_MCP_CLIENT_VERSION = getCoreVersion();
15956
15948
  /**
15957
- * Combined list of all deprecated-field rules.
15958
- *
15959
- * Order within the list does not affect correctness (the CLI groups by kind
15960
- * at display time), but a stable order helps test expectations.
15949
+ * Build the `RequestOptions` object accepted by the MCP SDK's `callTool`,
15950
+ * including either the configured tool-call timeout, an in-flight abort
15951
+ * signal, both, or neither. Returns `undefined` when nothing needs to be
15952
+ * passed so the SDK falls back to its defaults.
15961
15953
  */
15962
- const DEPRECATED_FIELD_RULES = [
15963
- ...REMOVED_RULES,
15964
- ...RENAMED_RULES,
15965
- ...MIGRATED_RULES
15966
- ];
15967
- //#endregion
15968
- //#region src/providers/runtime-provider.ts
15969
- function resolveRuntimeProvider(input) {
15970
- const modelName = input.model ?? input.config.defaultModel;
15971
- if (modelName === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, "No model is selected. Set default_model in config.toml or pass a configured model alias.");
15972
- const alias = input.config.models?.[modelName];
15973
- if (alias === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Model "${modelName}" is not configured in config.toml. Add a [models."${modelName}"] entry with max_context_size.`);
15974
- const resolvedModel = alias.model;
15975
- const providerName = alias.provider ?? input.config.defaultProvider;
15976
- const providerConfig = providerName === void 0 ? void 0 : input.config.providers[providerName];
15977
- if (providerName === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Model "${modelName}" must define a provider in config.toml.`);
15978
- if (providerConfig === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Provider "${providerName}" for model "${modelName}" is not configured.`);
15979
- if (!Number.isInteger(alias.maxContextSize) || alias.maxContextSize <= 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Model "${modelName}" must define a positive max_context_size in config.toml.`);
15980
- if (input.validateCredentials !== false && providerConfig.type !== "vertexai" && providerConfig.oauth === void 0 && providerApiKey(providerConfig) === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Provider "${providerName}" has no credentials configured. Set apiKey, oauth, or a provider env API key in config.toml.`);
15981
- const provider = toKosongProviderConfig(providerConfig, resolvedModel, input.byfRequestHeaders, alias.maxOutputSize, alias.reasoningKey, input.promptCacheKey);
15954
+ function buildRequestOptions(toolCallTimeoutMs, signal) {
15955
+ if (toolCallTimeoutMs === void 0 && signal === void 0) return void 0;
15982
15956
  return {
15983
- modelName,
15984
- providerName,
15985
- modelCapabilities: resolveModelCapabilities(alias, provider),
15986
- provider
15957
+ timeout: toolCallTimeoutMs,
15958
+ signal
15987
15959
  };
15988
15960
  }
15989
- async function resolveRuntimeProviderWithOAuth(input) {
15990
- const resolved = resolveRuntimeProvider(input);
15991
- const resolveAuth = createRuntimeProviderAuthResolver(input, resolved);
15992
- if (resolveAuth === void 0) return resolved;
15993
- await resolveAuth();
15961
+ function toMcpToolDefinition(tool) {
15994
15962
  return {
15995
- ...resolved,
15996
- resolveAuth
15997
- };
15998
- }
15999
- function createRuntimeProviderAuthResolver(input, resolved = resolveRuntimeProvider(input)) {
16000
- const providerName = resolved.providerName;
16001
- if (providerName === void 0) return void 0;
16002
- const providerConfig = input.config.providers[providerName];
16003
- if (providerConfig?.oauth === void 0) return void 0;
16004
- if (providerApiKey(providerConfig) !== void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Provider "${providerName}" has both apiKey and oauth set in config.toml — they are mutually exclusive. Remove one.`);
16005
- const tokenProvider = input.resolveOAuthTokenProvider?.(providerName, providerConfig.oauth);
16006
- if (tokenProvider === void 0) return async () => {
16007
- throw new ByfError(ErrorCodes.AUTH_LOGIN_REQUIRED, `OAuth provider "${providerName}" requires login before it can be used.`);
16008
- };
16009
- return async (options) => {
16010
- let apiKey;
16011
- try {
16012
- apiKey = await tokenProvider.getAccessToken(options?.forceRefresh === true ? { force: true } : void 0);
16013
- } catch (error) {
16014
- if (!isAuthLoginRequired(error)) (input.log ?? log).warn("oauth token fetch failed", {
16015
- providerName,
16016
- error
16017
- });
16018
- throw new ByfError(ErrorCodes.AUTH_LOGIN_REQUIRED, `OAuth provider "${providerName}" requires login before it can be used.`, { cause: error });
16019
- }
16020
- if (apiKey.trim().length === 0) throw new ByfError(ErrorCodes.AUTH_LOGIN_REQUIRED, `OAuth provider "${providerName}" requires login before it can be used.`);
16021
- return { apiKey };
15963
+ name: tool.name,
15964
+ description: tool.description ?? "",
15965
+ inputSchema: tool.inputSchema
16022
15966
  };
16023
15967
  }
16024
- function isAuthLoginRequired(error) {
16025
- return isByfError(error) && error.code === ErrorCodes.AUTH_LOGIN_REQUIRED;
16026
- }
16027
- const CAPABILITY_DEFINITIONS = [
16028
- {
16029
- name: "image_in",
16030
- returnKey: "image_in"
16031
- },
16032
- {
16033
- name: "video_in",
16034
- returnKey: "video_in"
16035
- },
16036
- {
16037
- name: "audio_in",
16038
- returnKey: "audio_in"
16039
- },
16040
- {
16041
- name: "thinking",
16042
- returnKey: "thinking"
16043
- },
16044
- {
16045
- name: "always_thinking",
16046
- returnKey: "thinking"
16047
- },
16048
- {
16049
- name: "tool_use",
16050
- returnKey: "tool_use"
16051
- },
16052
- {
16053
- name: "thinking_effort",
16054
- returnKey: "thinking_effort"
16055
- },
16056
- {
16057
- name: "thinking_xhigh",
16058
- returnKey: "thinking_xhigh"
16059
- },
16060
- {
16061
- name: "thinking_max",
16062
- returnKey: "thinking_max"
16063
- }
16064
- ];
16065
15968
  /**
16066
- * The list of every valid capability name that can appear in a model
16067
- * alias's `capabilities` array.
16068
- *
16069
- * Derives directly from {@link CAPABILITY_DEFINITIONS} so that adding a
16070
- * new capability in one place automatically keeps both the validation
16071
- * gate (`update-config`) and the runtime resolver in sync.
15969
+ * Normalise the SDK's `callTool` return into kosong's {@link MCPToolResult}.
15970
+ * The SDK can return either the modern `{ content, isError }` shape or a
15971
+ * legacy `{ toolResult }` shape; we collapse the legacy shape to a single
15972
+ * text content block.
16072
15973
  */
16073
- const VALID_CAPABILITIES = CAPABILITY_DEFINITIONS.map((d) => d.name);
16074
- function resolveModelCapabilities(alias, provider) {
16075
- const capabilities = new Set((alias.capabilities ?? []).map((capability) => capability.trim().toLowerCase()));
16076
- const has = (capability) => capabilities.has(capability);
16077
- const providerCapability = createProvider(providerForCapabilityProbe(provider)).getCapability?.(provider.model) ?? UNKNOWN_CAPABILITY;
16078
- const returnKeyToNames = /* @__PURE__ */ new Map();
16079
- for (const def of CAPABILITY_DEFINITIONS) {
16080
- const names = returnKeyToNames.get(def.returnKey) ?? [];
16081
- names.push(def.name);
16082
- returnKeyToNames.set(def.returnKey, names);
16083
- }
16084
- const resolved = {};
16085
- for (const [returnKey, names] of returnKeyToNames) resolved[returnKey] = names.some((n) => has(n)) || Boolean(providerCapability[returnKey]);
16086
- return {
16087
- ...resolved,
16088
- max_context_tokens: alias.maxContextSize
16089
- };
16090
- }
16091
- function toKosongProviderConfig(provider, model, byfRequestHeaders, maxOutputSize, reasoningKey, promptCacheKey) {
16092
- switch (provider.type) {
16093
- case "anthropic": return {
16094
- type: "anthropic",
16095
- model,
16096
- baseUrl: providerValue(provider.baseUrl, provider.env, "ANTHROPIC_BASE_URL"),
16097
- apiKey: providerApiKey(provider),
16098
- ...maxOutputSize !== void 0 ? { defaultMaxTokens: maxOutputSize } : {},
16099
- ...defaultHeadersField(provider.customHeaders)
16100
- };
16101
- case "openai-completions": {
16102
- const defaultHeaders = {
16103
- ...byfRequestHeaders,
16104
- ...provider.customHeaders
16105
- };
16106
- const generationKwargs = {
16107
- prompt_cache_key: promptCacheKey,
16108
- extra_body: provider.extraBody
16109
- };
16110
- if (Object.keys(defaultHeaders).length === 0) return {
16111
- type: "openai-completions",
16112
- model,
16113
- baseUrl: providerValue(provider.baseUrl, provider.env, "BYF_BASE_URL"),
16114
- reasoningKey,
16115
- thinkingEffortKey: provider.thinkingEffortKey,
16116
- generationKwargs,
16117
- apiKey: providerApiKey(provider)
16118
- };
16119
- return {
16120
- type: "openai-completions",
16121
- model,
16122
- baseUrl: providerValue(provider.baseUrl, provider.env, "BYF_BASE_URL"),
16123
- reasoningKey,
16124
- thinkingEffortKey: provider.thinkingEffortKey,
16125
- generationKwargs,
16126
- defaultHeaders,
16127
- apiKey: providerApiKey(provider)
16128
- };
16129
- }
16130
- case "google-genai": return {
16131
- type: "google-genai",
16132
- model,
16133
- apiKey: providerApiKey(provider)
16134
- };
16135
- case "openai_responses": return {
16136
- type: "openai_responses",
16137
- model,
16138
- baseUrl: providerValue(provider.baseUrl, provider.env, "OPENAI_BASE_URL"),
16139
- apiKey: providerApiKey(provider),
16140
- ...defaultHeadersField(provider.customHeaders)
15974
+ function toMcpToolResult(result) {
15975
+ if (typeof result === "object" && result !== null && "content" in result) {
15976
+ const typed = result;
15977
+ if (Array.isArray(typed.content)) return {
15978
+ content: typed.content,
15979
+ isError: typed.isError === true
16141
15980
  };
16142
- case "vertexai": return {
16143
- type: "vertexai",
16144
- model,
16145
- vertexai: hasVertexAIServiceEnv(provider),
16146
- apiKey: hasVertexAIServiceEnv(provider) ? void 0 : providerApiKey(provider),
16147
- project: vertexAIProject(provider),
16148
- location: vertexAILocation(provider)
15981
+ }
15982
+ if (typeof result === "object" && result !== null && "toolResult" in result) {
15983
+ const legacy = result.toolResult;
15984
+ return {
15985
+ content: [{
15986
+ type: "text",
15987
+ text: typeof legacy === "string" ? legacy : JSON.stringify(legacy)
15988
+ }],
15989
+ isError: false
16149
15990
  };
16150
- default: {
16151
- const exhaustive = provider.type;
16152
- throw new ByfError(ErrorCodes.MODEL_CONFIG_INVALID, `Unsupported provider type: ${String(exhaustive)}`);
16153
- }
16154
15991
  }
16155
- }
16156
- function defaultHeadersField(headers) {
16157
- if (headers === void 0 || Object.keys(headers).length === 0) return {};
16158
- return { defaultHeaders: { ...headers } };
16159
- }
16160
- function providerForCapabilityProbe(provider) {
16161
- if (provider.type === "vertexai") return {
16162
- ...provider,
16163
- vertexai: false,
16164
- project: void 0,
16165
- location: void 0,
16166
- apiKey: provider.apiKey === void 0 || provider.apiKey.length === 0 ? "capability-probe" : provider.apiKey
16167
- };
16168
- if (provider.apiKey !== void 0 && provider.apiKey.length > 0) return provider;
16169
15992
  return {
16170
- ...provider,
16171
- apiKey: "capability-probe"
16172
- };
16173
- }
16174
- function providerApiKey(provider) {
16175
- switch (provider.type) {
16176
- case "anthropic": return providerValue(provider.apiKey, provider.env, "ANTHROPIC_API_KEY");
16177
- case "openai_responses": return providerValue(provider.apiKey, provider.env, "OPENAI_API_KEY");
16178
- case "openai-completions": return providerValue(provider.apiKey, provider.env, "BYF_API_KEY");
16179
- case "google-genai": return providerValue(provider.apiKey, provider.env, "GOOGLE_API_KEY");
16180
- case "vertexai": return nonEmptyString$1(provider.apiKey) ?? envValue(provider.env, "VERTEXAI_API_KEY") ?? envValue(provider.env, "GOOGLE_API_KEY");
16181
- default: {
16182
- const exhaustive = provider.type;
16183
- throw new ByfError(ErrorCodes.MODEL_CONFIG_INVALID, `Unsupported provider type: ${String(exhaustive)}`);
16184
- }
16185
- }
16186
- }
16187
- function hasVertexAIServiceEnv(provider) {
16188
- return vertexAIProject(provider) !== void 0 && vertexAILocation(provider) !== void 0;
16189
- }
16190
- function vertexAIProject(provider) {
16191
- return envValue(provider.env, "GOOGLE_CLOUD_PROJECT");
16192
- }
16193
- function vertexAILocation(provider) {
16194
- return envValue(provider.env, "GOOGLE_CLOUD_LOCATION") ?? locationFromVertexAIBaseUrl(provider.baseUrl);
16195
- }
16196
- function providerValue(configured, env, envKey) {
16197
- return nonEmptyString$1(configured) ?? envValue(env, envKey);
16198
- }
16199
- function envValue(env, key) {
16200
- return nonEmptyString$1(env?.[key]);
16201
- }
16202
- function nonEmptyString$1(value) {
16203
- const trimmed = value?.trim();
16204
- return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
16205
- }
16206
- function locationFromVertexAIBaseUrl(baseUrl) {
16207
- const url = nonEmptyString$1(baseUrl);
16208
- if (url === void 0) return void 0;
16209
- try {
16210
- const host = new URL(url).hostname;
16211
- return host.endsWith("-aiplatform.googleapis.com") ? nonEmptyString$1(host.slice(0, -26)) : void 0;
16212
- } catch {
16213
- return;
16214
- }
16215
- }
16216
- //#endregion
16217
- //#region src/config/update.ts
16218
- /**
16219
- * Scan a parsed config (including `config.raw`) and return all Findings
16220
- * for deprecated / renamed / migrated / dangling / unknown / invalid-value
16221
- * fields.
16222
- *
16223
- * This is a **pure** function — no file I/O, no side effects.
16224
- *
16225
- * Detection is based on `config.raw` (the clone of the original TOML data),
16226
- * not on the parsed camelCase schema. This matches the PRD's observation
16227
- * that `raw` is both the protection layer (preserving unknown fields) and
16228
- * the blind spot (retaining stale keys through read→write cycles).
16229
- */
16230
- function analyzeConfig(config) {
16231
- const raw = config.raw;
16232
- const findings = [];
16233
- if (isRecord(raw)) {
16234
- for (const rule of DEPRECATED_FIELD_RULES) if (pathExistsInRaw(raw, rule.pathParts)) findings.push({
16235
- kind: rule.kind,
16236
- path: rule.path,
16237
- detail: rule.detail,
16238
- deprecatedSince: rule.deprecatedSince
16239
- });
16240
- const defaultThinkingFinding = findings.find((f) => f.path === "default_thinking");
16241
- if (defaultThinkingFinding) {
16242
- const thinking = config.thinking;
16243
- if (thinking && (thinking.mode !== void 0 || thinking.effort !== void 0)) {
16244
- defaultThinkingFinding.kind = "removed";
16245
- defaultThinkingFinding.detail = "Already superseded by [thinking] block.";
16246
- }
16247
- }
16248
- const UNKNOWN_SKIP_PATHS = new Set(DEPRECATED_FIELD_RULES.map((r) => r.pathParts.join(".")));
16249
- const byfShapeKeys = /* @__PURE__ */ new Set();
16250
- for (const key of Object.keys(ByfConfigSchema.shape)) {
16251
- byfShapeKeys.add(key);
16252
- byfShapeKeys.add(camelToSnakeStatic(key));
16253
- }
16254
- for (const rawKey of Object.keys(raw)) {
16255
- if (rawKey === "raw") continue;
16256
- if (UNKNOWN_SKIP_PATHS.has(rawKey)) continue;
16257
- const camelKey = snakeToCamelStatic(rawKey);
16258
- if (!byfShapeKeys.has(camelKey) && !byfShapeKeys.has(rawKey)) findings.push({
16259
- kind: "unknown",
16260
- path: rawKey,
16261
- detail: `Field "${rawKey}" is not recognized by the current schema. Its value has been ignored. This may be a typo or a field from a previous version.`
16262
- });
16263
- }
16264
- const nestedFindings = scanNestedUnknowns(raw, UNKNOWN_SKIP_PATHS);
16265
- findings.push(...nestedFindings);
16266
- }
16267
- if (config.models) {
16268
- const validCapsLower = new Set(VALID_CAPABILITIES.map((c) => c.toLowerCase()));
16269
- for (const [alias, modelConfig] of Object.entries(config.models)) if (modelConfig.capabilities) for (let i = 0; i < modelConfig.capabilities.length; i++) {
16270
- const cap = modelConfig.capabilities[i];
16271
- if (cap === void 0) continue;
16272
- if (!validCapsLower.has(cap.toLowerCase())) findings.push({
16273
- kind: "invalid-value",
16274
- path: `models.${alias}.capabilities[${i}]`,
16275
- detail: `"${cap}" is not a valid capability. Valid values: ${VALID_CAPABILITIES.join(", ")}.`
16276
- });
16277
- }
16278
- }
16279
- const providerKeys = Object.keys(config.providers ?? {});
16280
- if (config.models) {
16281
- for (const [alias, modelConfig] of Object.entries(config.models)) if (!providerKeys.includes(modelConfig.provider)) findings.push({
16282
- kind: "dangling",
16283
- path: `models.${alias}.provider`,
16284
- detail: `Model alias "${alias}" references provider "${modelConfig.provider}", which does not exist in [providers].`
16285
- });
16286
- }
16287
- if (config.defaultProvider !== void 0 && !providerKeys.includes(config.defaultProvider)) findings.push({
16288
- kind: "dangling",
16289
- path: "default_provider",
16290
- detail: `Default provider "${config.defaultProvider}" does not exist in [providers].`
16291
- });
16292
- const modelKeys = Object.keys(config.models ?? {});
16293
- if (config.defaultModel !== void 0 && !modelKeys.includes(config.defaultModel)) findings.push({
16294
- kind: "dangling",
16295
- path: "default_model",
16296
- detail: `Default model "${config.defaultModel}" does not exist in [models].`
16297
- });
16298
- return findings;
16299
- }
16300
- /**
16301
- * Apply automatic fixes to a `ByfConfig` by deleting every path registered in
16302
- * `DEPRECATED_FIELD_RULES` from `config.raw`.
16303
- *
16304
- * The `_findings` parameter is intentionally **not consulted** — deletion is
16305
- * driven exclusively by the whitelist in `DEPRECATED_FIELD_RULES`. This ensures
16306
- * that a call to `applyFixes` always produces a clean config regardless of
16307
- * what analysis step previously ran.
16308
- *
16309
- * This is a **pure** function — it returns a new config object without
16310
- * mutating the input.
16311
- */
16312
- function applyFixes(config, findings) {
16313
- const newRaw = rawShallowClone(config.raw);
16314
- for (const rule of DEPRECATED_FIELD_RULES) deletePath(newRaw, rule.pathParts);
16315
- let newConfig = {
16316
- ...config,
16317
- raw: newRaw
16318
- };
16319
- if (findings.find((f) => f.kind === "migrated" && f.path === "default_thinking")) {
16320
- const rawValue = config.raw?.["default_thinking"];
16321
- const isTruthy = rawValue === true || rawValue === "true" || rawValue === 1;
16322
- newConfig = {
16323
- ...newConfig,
16324
- thinking: isTruthy ? {
16325
- mode: "on",
16326
- effort: "high"
16327
- } : { mode: "off" }
16328
- };
16329
- }
16330
- return newConfig;
16331
- }
16332
- /** Convert snake_case to camelCase (static helper for unknown detection). */
16333
- function snakeToCamelStatic(str) {
16334
- return str.replaceAll(/_([a-z])/g, (_, ch) => ch.toUpperCase());
16335
- }
16336
- /** Convert camelCase to snake_case (static helper for unknown detection). */
16337
- function camelToSnakeStatic(str) {
16338
- return str.replaceAll(/[A-Z]/g, (ch) => `_${ch.toLowerCase()}`);
16339
- }
16340
- /** True when `value` is a non-null, non-array object. */
16341
- function isRecord(value) {
16342
- return typeof value === "object" && value !== null && !Array.isArray(value);
16343
- }
16344
- /**
16345
- * Walk `root` along `pathParts` checking that **every** segment exists.
16346
- *
16347
- * Returns `true` iff all parts exist as own keys (or inherited keys — TOML
16348
- * parse results are plain objects so the distinction doesn't matter here).
16349
- */
16350
- function pathExistsInRaw(root, pathParts) {
16351
- let current = root;
16352
- for (const part of pathParts) {
16353
- if (!isRecord(current) || !(part in current)) return false;
16354
- current = current[part];
16355
- }
16356
- return true;
16357
- }
16358
- /**
16359
- * Delete a leaf (or entire sub-tree) from `root` following `pathParts`.
16360
- *
16361
- * If the parent after deletion becomes empty it is cleaned up as well
16362
- * (recursive upward), so that a service table cleared of all deprecated
16363
- * keys does not leave behind an empty `{}`.
16364
- */
16365
- function deletePath(root, pathParts) {
16366
- if (pathParts.length === 0) return;
16367
- const parentParts = pathParts.slice(0, -1);
16368
- const leafKey = pathParts.at(-1);
16369
- let current;
16370
- if (parentParts.length === 0) current = root;
16371
- else current = traverseTo(root, parentParts);
16372
- if (current === void 0) return;
16373
- const keyExisted = leafKey in current;
16374
- delete current[leafKey];
16375
- if (keyExisted && parentParts.length > 0 && Object.keys(current).length === 0) deletePath(root, parentParts);
16376
- }
16377
- /**
16378
- * Walk `root` along `pathParts` returning the penultimate record, or
16379
- * `undefined` if any segment is missing.
16380
- */
16381
- function traverseTo(root, pathParts) {
16382
- let current = root;
16383
- for (const part of pathParts) {
16384
- if (!isRecord(current) || !(part in current)) return void 0;
16385
- current = current[part];
16386
- }
16387
- return isRecord(current) ? current : void 0;
16388
- }
16389
- /**
16390
- * Shallow-clone `raw`: each nested record is also shallow-cloned so that
16391
- * mutations in `applyFixes` do not affect the original object.
16392
- */
16393
- function rawShallowClone(raw) {
16394
- if (!isRecord(raw)) return {};
16395
- const clone = {};
16396
- for (const [key, value] of Object.entries(raw)) clone[key] = isRecord(value) ? { ...value } : value;
16397
- return clone;
16398
- }
16399
- /**
16400
- * Build a set of all valid keys (camelCase + snake_case) from a zod
16401
- * object schema's `.shape`.
16402
- */
16403
- function getShapeKeySet(schema) {
16404
- const keys = /* @__PURE__ */ new Set();
16405
- for (const key of Object.keys(schema.shape)) {
16406
- keys.add(key);
16407
- keys.add(camelToSnakeStatic(key));
16408
- }
16409
- return keys;
16410
- }
16411
- /**
16412
- * Scan known container keys in `raw` for sub-keys that don't match the
16413
- * corresponding schema shape. Unknown paths that overlap with
16414
- * `skipPaths` (e.g. already reported deprecated fields) are skipped.
16415
- *
16416
- * Detects e.g. `models.gpt4.max_context_tokns` (typo) or
16417
- * `providers.anthropic.api_kei` (typo).
16418
- */
16419
- function scanNestedUnknowns(raw, skipPaths) {
16420
- const findings = [];
16421
- const containers = [
16422
- {
16423
- rawKey: "models",
16424
- isRecord: true,
16425
- schema: ModelAliasSchema
16426
- },
16427
- {
16428
- rawKey: "providers",
16429
- isRecord: true,
16430
- schema: ProviderConfigSchema
16431
- },
16432
- {
16433
- rawKey: "services",
16434
- isRecord: false,
16435
- schema: ServicesConfigSchema
16436
- },
16437
- {
16438
- rawKey: "background",
16439
- isRecord: false,
16440
- schema: BackgroundConfigSchema
16441
- },
16442
- {
16443
- rawKey: "loop_control",
16444
- isRecord: false,
16445
- schema: LoopControlSchema
16446
- },
16447
- {
16448
- rawKey: "thinking",
16449
- isRecord: false,
16450
- schema: ThinkingConfigSchema
16451
- },
16452
- {
16453
- rawKey: "permission",
16454
- isRecord: false,
16455
- schema: PermissionConfigSchema,
16456
- legacyKeys: [
16457
- "deny",
16458
- "allow",
16459
- "ask"
16460
- ]
16461
- }
16462
- ];
16463
- const schemaKeySets = /* @__PURE__ */ new Map();
16464
- containers.forEach((entry, index) => {
16465
- const base = getShapeKeySet(entry.schema);
16466
- if (entry.legacyKeys) for (const k of entry.legacyKeys) base.add(k);
16467
- schemaKeySets.set(index, base);
16468
- });
16469
- for (const [entryIndex, entry] of containers.entries()) {
16470
- if (!(entry.rawKey in raw)) continue;
16471
- const rawValue = raw[entry.rawKey];
16472
- if (!isRecord(rawValue)) continue;
16473
- if (entry.isRecord) for (const [itemKey, itemValue] of Object.entries(rawValue)) {
16474
- if (!isRecord(itemValue)) continue;
16475
- const validKeys = schemaKeySets.get(entryIndex);
16476
- for (const subKey of Object.keys(itemValue)) if (!validKeys.has(subKey)) {
16477
- const path = `${entry.rawKey}.${itemKey}.${subKey}`;
16478
- if (!skipPaths.has(path)) findings.push({
16479
- kind: "unknown",
16480
- path,
16481
- detail: `Field "${subKey}" is not recognized in ${entry.rawKey}.${itemKey}. This may be a typo or a field from a previous version.`
16482
- });
16483
- }
16484
- }
16485
- else {
16486
- const validKeys = schemaKeySets.get(entryIndex);
16487
- for (const subKey of Object.keys(rawValue)) if (!validKeys.has(subKey)) {
16488
- const path = `${entry.rawKey}.${subKey}`;
16489
- if (!skipPaths.has(path)) findings.push({
16490
- kind: "unknown",
16491
- path,
16492
- detail: `Field "${subKey}" is not recognized in [${entry.rawKey}]. This may be a typo or a field from a previous version.`
16493
- });
16494
- }
16495
- }
16496
- }
16497
- return findings;
16498
- }
16499
- //#endregion
16500
- //#region src/version.ts
16501
- function getCoreVersion() {
16502
- try {
16503
- const raw = readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf-8");
16504
- const pkg = JSON.parse(raw);
16505
- return typeof pkg.version === "string" ? pkg.version : "0.0.0";
16506
- } catch {
16507
- return "0.0.0";
16508
- }
16509
- }
16510
- //#endregion
16511
- //#region src/mcp/client-shared.ts
16512
- const BYF_MCP_CLIENT_VERSION = getCoreVersion();
16513
- /**
16514
- * Build the `RequestOptions` object accepted by the MCP SDK's `callTool`,
16515
- * including either the configured tool-call timeout, an in-flight abort
16516
- * signal, both, or neither. Returns `undefined` when nothing needs to be
16517
- * passed so the SDK falls back to its defaults.
16518
- */
16519
- function buildRequestOptions(toolCallTimeoutMs, signal) {
16520
- if (toolCallTimeoutMs === void 0 && signal === void 0) return void 0;
16521
- return {
16522
- timeout: toolCallTimeoutMs,
16523
- signal
16524
- };
16525
- }
16526
- function toMcpToolDefinition(tool) {
16527
- return {
16528
- name: tool.name,
16529
- description: tool.description ?? "",
16530
- inputSchema: tool.inputSchema
16531
- };
16532
- }
16533
- /**
16534
- * Normalise the SDK's `callTool` return into kosong's {@link MCPToolResult}.
16535
- * The SDK can return either the modern `{ content, isError }` shape or a
16536
- * legacy `{ toolResult }` shape; we collapse the legacy shape to a single
16537
- * text content block.
16538
- */
16539
- function toMcpToolResult(result) {
16540
- if (typeof result === "object" && result !== null && "content" in result) {
16541
- const typed = result;
16542
- if (Array.isArray(typed.content)) return {
16543
- content: typed.content,
16544
- isError: typed.isError === true
16545
- };
16546
- }
16547
- if (typeof result === "object" && result !== null && "toolResult" in result) {
16548
- const legacy = result.toolResult;
16549
- return {
16550
- content: [{
16551
- type: "text",
16552
- text: typeof legacy === "string" ? legacy : JSON.stringify(legacy)
16553
- }],
16554
- isError: false
16555
- };
16556
- }
16557
- return {
16558
- content: [],
16559
- isError: false
15993
+ content: [],
15994
+ isError: false
16560
15995
  };
16561
15996
  }
16562
15997
  //#endregion
@@ -20048,6 +19483,247 @@ async function readOptionalFile(path) {
20048
19483
  }
20049
19484
  }
20050
19485
  //#endregion
19486
+ //#region src/providers/runtime-provider.ts
19487
+ function resolveRuntimeProvider(input) {
19488
+ const modelName = input.model ?? input.config.defaultModel;
19489
+ if (modelName === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, "No model is selected. Set default_model in config.toml or pass a configured model alias.");
19490
+ const alias = input.config.models?.[modelName];
19491
+ if (alias === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Model "${modelName}" is not configured in config.toml. Add a [models."${modelName}"] entry with max_context_size.`);
19492
+ const resolvedModel = alias.model;
19493
+ const providerName = alias.provider ?? input.config.defaultProvider;
19494
+ const providerConfig = providerName === void 0 ? void 0 : input.config.providers[providerName];
19495
+ if (providerName === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Model "${modelName}" must define a provider in config.toml.`);
19496
+ if (providerConfig === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Provider "${providerName}" for model "${modelName}" is not configured.`);
19497
+ if (!Number.isInteger(alias.maxContextSize) || alias.maxContextSize <= 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Model "${modelName}" must define a positive max_context_size in config.toml.`);
19498
+ if (input.validateCredentials !== false && providerConfig.type !== "vertexai" && providerConfig.oauth === void 0 && providerApiKey(providerConfig) === void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Provider "${providerName}" has no credentials configured. Set apiKey, oauth, or a provider env API key in config.toml.`);
19499
+ const provider = toKosongProviderConfig(providerConfig, resolvedModel, input.byfRequestHeaders, alias.maxOutputSize, alias.reasoningKey, input.promptCacheKey);
19500
+ return {
19501
+ modelName,
19502
+ providerName,
19503
+ modelCapabilities: resolveModelCapabilities(alias, provider),
19504
+ provider
19505
+ };
19506
+ }
19507
+ async function resolveRuntimeProviderWithOAuth(input) {
19508
+ const resolved = resolveRuntimeProvider(input);
19509
+ const resolveAuth = createRuntimeProviderAuthResolver(input, resolved);
19510
+ if (resolveAuth === void 0) return resolved;
19511
+ await resolveAuth();
19512
+ return {
19513
+ ...resolved,
19514
+ resolveAuth
19515
+ };
19516
+ }
19517
+ function createRuntimeProviderAuthResolver(input, resolved = resolveRuntimeProvider(input)) {
19518
+ const providerName = resolved.providerName;
19519
+ if (providerName === void 0) return void 0;
19520
+ const providerConfig = input.config.providers[providerName];
19521
+ if (providerConfig?.oauth === void 0) return void 0;
19522
+ if (providerApiKey(providerConfig) !== void 0) throw new ByfError(ErrorCodes.CONFIG_INVALID, `Provider "${providerName}" has both apiKey and oauth set in config.toml — they are mutually exclusive. Remove one.`);
19523
+ const tokenProvider = input.resolveOAuthTokenProvider?.(providerName, providerConfig.oauth);
19524
+ if (tokenProvider === void 0) return async () => {
19525
+ throw new ByfError(ErrorCodes.AUTH_LOGIN_REQUIRED, `OAuth provider "${providerName}" requires login before it can be used.`);
19526
+ };
19527
+ return async (options) => {
19528
+ let apiKey;
19529
+ try {
19530
+ apiKey = await tokenProvider.getAccessToken(options?.forceRefresh === true ? { force: true } : void 0);
19531
+ } catch (error) {
19532
+ if (!isAuthLoginRequired(error)) (input.log ?? log).warn("oauth token fetch failed", {
19533
+ providerName,
19534
+ error
19535
+ });
19536
+ throw new ByfError(ErrorCodes.AUTH_LOGIN_REQUIRED, `OAuth provider "${providerName}" requires login before it can be used.`, { cause: error });
19537
+ }
19538
+ if (apiKey.trim().length === 0) throw new ByfError(ErrorCodes.AUTH_LOGIN_REQUIRED, `OAuth provider "${providerName}" requires login before it can be used.`);
19539
+ return { apiKey };
19540
+ };
19541
+ }
19542
+ function isAuthLoginRequired(error) {
19543
+ return isByfError(error) && error.code === ErrorCodes.AUTH_LOGIN_REQUIRED;
19544
+ }
19545
+ const CAPABILITY_DEFINITIONS = [
19546
+ {
19547
+ name: "image_in",
19548
+ returnKey: "image_in"
19549
+ },
19550
+ {
19551
+ name: "video_in",
19552
+ returnKey: "video_in"
19553
+ },
19554
+ {
19555
+ name: "audio_in",
19556
+ returnKey: "audio_in"
19557
+ },
19558
+ {
19559
+ name: "thinking",
19560
+ returnKey: "thinking"
19561
+ },
19562
+ {
19563
+ name: "always_thinking",
19564
+ returnKey: "thinking"
19565
+ },
19566
+ {
19567
+ name: "tool_use",
19568
+ returnKey: "tool_use"
19569
+ },
19570
+ {
19571
+ name: "thinking_effort",
19572
+ returnKey: "thinking_effort"
19573
+ },
19574
+ {
19575
+ name: "thinking_xhigh",
19576
+ returnKey: "thinking_xhigh"
19577
+ },
19578
+ {
19579
+ name: "thinking_max",
19580
+ returnKey: "thinking_max"
19581
+ }
19582
+ ];
19583
+ CAPABILITY_DEFINITIONS.map((d) => d.name);
19584
+ function resolveModelCapabilities(alias, provider) {
19585
+ const capabilities = new Set((alias.capabilities ?? []).map((capability) => capability.trim().toLowerCase()));
19586
+ const has = (capability) => capabilities.has(capability);
19587
+ const providerCapability = createProvider(providerForCapabilityProbe(provider)).getCapability?.(provider.model) ?? UNKNOWN_CAPABILITY;
19588
+ const returnKeyToNames = /* @__PURE__ */ new Map();
19589
+ for (const def of CAPABILITY_DEFINITIONS) {
19590
+ const names = returnKeyToNames.get(def.returnKey) ?? [];
19591
+ names.push(def.name);
19592
+ returnKeyToNames.set(def.returnKey, names);
19593
+ }
19594
+ const resolved = {};
19595
+ for (const [returnKey, names] of returnKeyToNames) resolved[returnKey] = names.some((n) => has(n)) || Boolean(providerCapability[returnKey]);
19596
+ return {
19597
+ ...resolved,
19598
+ max_context_tokens: alias.maxContextSize
19599
+ };
19600
+ }
19601
+ function toKosongProviderConfig(provider, model, byfRequestHeaders, maxOutputSize, reasoningKey, promptCacheKey) {
19602
+ switch (provider.type) {
19603
+ case "anthropic": return {
19604
+ type: "anthropic",
19605
+ model,
19606
+ baseUrl: providerValue(provider.baseUrl, provider.env, "ANTHROPIC_BASE_URL"),
19607
+ apiKey: providerApiKey(provider),
19608
+ ...maxOutputSize !== void 0 ? { defaultMaxTokens: maxOutputSize } : {},
19609
+ ...defaultHeadersField(provider.customHeaders)
19610
+ };
19611
+ case "openai-completions": {
19612
+ const defaultHeaders = {
19613
+ ...byfRequestHeaders,
19614
+ ...provider.customHeaders
19615
+ };
19616
+ const generationKwargs = {
19617
+ prompt_cache_key: promptCacheKey,
19618
+ extra_body: provider.extraBody
19619
+ };
19620
+ if (Object.keys(defaultHeaders).length === 0) return {
19621
+ type: "openai-completions",
19622
+ model,
19623
+ baseUrl: providerValue(provider.baseUrl, provider.env, "BYF_BASE_URL"),
19624
+ reasoningKey,
19625
+ thinkingEffortKey: provider.thinkingEffortKey,
19626
+ generationKwargs,
19627
+ apiKey: providerApiKey(provider)
19628
+ };
19629
+ return {
19630
+ type: "openai-completions",
19631
+ model,
19632
+ baseUrl: providerValue(provider.baseUrl, provider.env, "BYF_BASE_URL"),
19633
+ reasoningKey,
19634
+ thinkingEffortKey: provider.thinkingEffortKey,
19635
+ generationKwargs,
19636
+ defaultHeaders,
19637
+ apiKey: providerApiKey(provider)
19638
+ };
19639
+ }
19640
+ case "google-genai": return {
19641
+ type: "google-genai",
19642
+ model,
19643
+ apiKey: providerApiKey(provider)
19644
+ };
19645
+ case "openai_responses": return {
19646
+ type: "openai_responses",
19647
+ model,
19648
+ baseUrl: providerValue(provider.baseUrl, provider.env, "OPENAI_BASE_URL"),
19649
+ apiKey: providerApiKey(provider),
19650
+ ...defaultHeadersField(provider.customHeaders)
19651
+ };
19652
+ case "vertexai": return {
19653
+ type: "vertexai",
19654
+ model,
19655
+ vertexai: hasVertexAIServiceEnv(provider),
19656
+ apiKey: hasVertexAIServiceEnv(provider) ? void 0 : providerApiKey(provider),
19657
+ project: vertexAIProject(provider),
19658
+ location: vertexAILocation(provider)
19659
+ };
19660
+ default: {
19661
+ const exhaustive = provider.type;
19662
+ throw new ByfError(ErrorCodes.MODEL_CONFIG_INVALID, `Unsupported provider type: ${String(exhaustive)}`);
19663
+ }
19664
+ }
19665
+ }
19666
+ function defaultHeadersField(headers) {
19667
+ if (headers === void 0 || Object.keys(headers).length === 0) return {};
19668
+ return { defaultHeaders: { ...headers } };
19669
+ }
19670
+ function providerForCapabilityProbe(provider) {
19671
+ if (provider.type === "vertexai") return {
19672
+ ...provider,
19673
+ vertexai: false,
19674
+ project: void 0,
19675
+ location: void 0,
19676
+ apiKey: provider.apiKey === void 0 || provider.apiKey.length === 0 ? "capability-probe" : provider.apiKey
19677
+ };
19678
+ if (provider.apiKey !== void 0 && provider.apiKey.length > 0) return provider;
19679
+ return {
19680
+ ...provider,
19681
+ apiKey: "capability-probe"
19682
+ };
19683
+ }
19684
+ function providerApiKey(provider) {
19685
+ switch (provider.type) {
19686
+ case "anthropic": return providerValue(provider.apiKey, provider.env, "ANTHROPIC_API_KEY");
19687
+ case "openai_responses": return providerValue(provider.apiKey, provider.env, "OPENAI_API_KEY");
19688
+ case "openai-completions": return providerValue(provider.apiKey, provider.env, "BYF_API_KEY");
19689
+ case "google-genai": return providerValue(provider.apiKey, provider.env, "GOOGLE_API_KEY");
19690
+ case "vertexai": return nonEmptyString$1(provider.apiKey) ?? envValue(provider.env, "VERTEXAI_API_KEY") ?? envValue(provider.env, "GOOGLE_API_KEY");
19691
+ default: {
19692
+ const exhaustive = provider.type;
19693
+ throw new ByfError(ErrorCodes.MODEL_CONFIG_INVALID, `Unsupported provider type: ${String(exhaustive)}`);
19694
+ }
19695
+ }
19696
+ }
19697
+ function hasVertexAIServiceEnv(provider) {
19698
+ return vertexAIProject(provider) !== void 0 && vertexAILocation(provider) !== void 0;
19699
+ }
19700
+ function vertexAIProject(provider) {
19701
+ return envValue(provider.env, "GOOGLE_CLOUD_PROJECT");
19702
+ }
19703
+ function vertexAILocation(provider) {
19704
+ return envValue(provider.env, "GOOGLE_CLOUD_LOCATION") ?? locationFromVertexAIBaseUrl(provider.baseUrl);
19705
+ }
19706
+ function providerValue(configured, env, envKey) {
19707
+ return nonEmptyString$1(configured) ?? envValue(env, envKey);
19708
+ }
19709
+ function envValue(env, key) {
19710
+ return nonEmptyString$1(env?.[key]);
19711
+ }
19712
+ function nonEmptyString$1(value) {
19713
+ const trimmed = value?.trim();
19714
+ return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
19715
+ }
19716
+ function locationFromVertexAIBaseUrl(baseUrl) {
19717
+ const url = nonEmptyString$1(baseUrl);
19718
+ if (url === void 0) return void 0;
19719
+ try {
19720
+ const host = new URL(url).hostname;
19721
+ return host.endsWith("-aiplatform.googleapis.com") ? nonEmptyString$1(host.slice(0, -26)) : void 0;
19722
+ } catch {
19723
+ return;
19724
+ }
19725
+ }
19726
+ //#endregion
20051
19727
  //#region src/providers/provider-manager.ts
20052
19728
  var ProviderManager = class ProviderManager {
20053
19729
  options;
@@ -20616,4 +20292,4 @@ function parsePositiveInt(value) {
20616
20292
  return n;
20617
20293
  }
20618
20294
  //#endregion
20619
- export { AGENT_WIRE_PROTOCOL_VERSION, Agent, BYF_ERROR_INFO, BackgroundConfigSchema, ByfConfigPatchSchema, ByfConfigSchema, ByfCore, ByfError, ByfServiceConfigSchema, DEPRECATED_FIELD_RULES, ErrorCodes, HookDefSchema, LoopControlSchema, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, McpServerConfigSchema, McpServerHttpConfigSchema, McpServerStdioConfigSchema, ModelAliasSchema, OAuthRefSchema, PermissionConfigSchema, PermissionModeSchema, PermissionRuleDecisionSchema, PermissionRuleSchema, PermissionRuleScopeSchema, ProviderConfigSchema, ProviderTypeSchema, ServicesConfigSchema, Session, SessionSubagentHost, ThinkingConfigSchema, USER_PROMPT_ORIGIN, WIRE_PROTOCOL_VERSION, WebSearchConfigSchema, WebSearchProviderConfigSchema, analyzeConfig, applyFixes, buildExportManifest, buildPromptPlan, collectFilesRecursive, configToTomlData, createRPC, ensureByfHome, ensureConfigFile, exportSessionDirectory, flushDiagnosticLogs, formatConfigValidationError, fromByfErrorPayload, getDefaultConfig, getRootLogger, isByfError, log, makeErrorPayload, mergeConfigPatch, normalizeTimestampMs, parseBooleanEnv, parseConfigString, proxyWithExtraPayload, readConfigFile, redact, resolveByfHome, resolveConfigPath, resolveConfigValue, resolveGlobalLogPath, resolveLoggingConfig, scanSessionWire, toByfErrorPayload, transformTomlData, validateConfig, writeConfigFile, writeExportZip };
20295
+ export { AGENT_WIRE_PROTOCOL_VERSION, Agent, BYF_ERROR_INFO, BackgroundConfigSchema, ByfConfigPatchSchema, ByfConfigSchema, ByfCore, ByfError, ByfServiceConfigSchema, ErrorCodes, HookDefSchema, LoopControlSchema, MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, McpServerConfigSchema, McpServerHttpConfigSchema, McpServerStdioConfigSchema, ModelAliasSchema, OAuthRefSchema, PermissionConfigSchema, PermissionModeSchema, PermissionRuleDecisionSchema, PermissionRuleSchema, PermissionRuleScopeSchema, ProviderConfigSchema, ProviderTypeSchema, ServicesConfigSchema, Session, SessionSubagentHost, ThinkingConfigSchema, USER_PROMPT_ORIGIN, WIRE_PROTOCOL_VERSION, WebSearchConfigSchema, WebSearchProviderConfigSchema, buildExportManifest, buildPromptPlan, collectFilesRecursive, configToTomlData, createRPC, ensureByfHome, ensureConfigFile, exportSessionDirectory, flushDiagnosticLogs, formatConfigValidationError, fromByfErrorPayload, getDefaultConfig, getRootLogger, isByfError, log, makeErrorPayload, mergeConfigPatch, normalizeTimestampMs, parseBooleanEnv, parseConfigString, proxyWithExtraPayload, readConfigFile, redact, resolveByfHome, resolveConfigPath, resolveConfigValue, resolveGlobalLogPath, resolveLoggingConfig, scanSessionWire, toByfErrorPayload, transformTomlData, validateConfig, writeConfigFile, writeExportZip };
@@ -1,4 +1,4 @@
1
- import { ct as JsonObject, dt as ListSessionsPayload, wt as SessionSummary } from "../../index-CZA_2ux5.mjs";
1
+ import { ct as JsonObject, dt as ListSessionsPayload, wt as SessionSummary } from "../../index-BNApCprm.mjs";
2
2
 
3
3
  //#region src/session/store/session-store.d.ts
4
4
  interface CreateSessionRecordInput {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byfriends/agent-core",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Unified agent engine for BYF",
5
5
  "license": "Proprietary",
6
6
  "author": "ByronFinn",
@@ -69,8 +69,8 @@
69
69
  "undici": "^8.4.1",
70
70
  "yauzl": "^3.3.0",
71
71
  "zod": "^4.3.6",
72
- "@byfriends/kaos": "^0.2.2",
73
- "@byfriends/kosong": "^0.2.3"
72
+ "@byfriends/kaos": "^0.3.2",
73
+ "@byfriends/kosong": "^0.3.2"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/js-yaml": "^4.0.9",