@byfriends/agent-core 0.2.0 → 0.2.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.
@@ -127,6 +127,7 @@ declare const ProviderConfigSchema: z.ZodObject<{
127
127
  }, z.core.$strip>>;
128
128
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
129
129
  customHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
130
+ extraBody: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
130
131
  }, z.core.$strip>;
131
132
  type ProviderConfig$1 = z.infer<typeof ProviderConfigSchema>;
132
133
  declare const ModelAliasSchema: z.ZodObject<{
@@ -358,6 +359,7 @@ declare const ByfConfigSchema: z.ZodObject<{
358
359
  }, z.core.$strip>>;
359
360
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
360
361
  customHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
362
+ extraBody: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
361
363
  }, z.core.$strip>>>;
362
364
  defaultProvider: z.ZodOptional<z.ZodString>;
363
365
  defaultModel: z.ZodOptional<z.ZodString>;
@@ -495,6 +497,7 @@ declare const ByfConfigPatchSchema: z.ZodObject<{
495
497
  }, z.core.$strip>>>;
496
498
  env: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
497
499
  customHeaders: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
500
+ extraBody: z.ZodOptional<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
498
501
  }, z.core.$strip>>>;
499
502
  defaultProvider: z.ZodOptional<z.ZodString>;
500
503
  defaultModel: z.ZodOptional<z.ZodString>;
@@ -824,6 +827,13 @@ interface McpConnectionManagerOptions {
824
827
  * `session.log` so MCP events land in the session log too.
825
828
  */
826
829
  readonly log?: Logger;
830
+ /**
831
+ * Custom fetch function for HTTP MCP transports. When provided, the
832
+ * connection manager passes it to every `HttpMcpClient` so the
833
+ * transport uses it for all HTTP requests — enabling proxy fallback,
834
+ * custom retries, or test doubles.
835
+ */
836
+ readonly fetch?: typeof fetch;
827
837
  }
828
838
  /**
829
839
  * Owns the lifecycle of every configured MCP server for a Session.
@@ -2632,6 +2642,12 @@ interface RuntimeConfig {
2632
2642
  readonly osEnv: Environment;
2633
2643
  readonly urlFetcher?: UrlFetcher | undefined;
2634
2644
  readonly webSearcher?: WebSearchProvider | undefined;
2645
+ /**
2646
+ * ProxiedFetch — a `typeof fetch` wrapper that retries through an
2647
+ * HTTP/SOCKS proxy when the direct attempt fails with a retryable error.
2648
+ * Used by MCP HTTP connections, URL fetcher, and web search.
2649
+ */
2650
+ readonly fetch?: typeof fetch;
2635
2651
  }
2636
2652
  //#endregion
2637
2653
  //#region src/utils/types.d.ts
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 CoreInfo, $n as SessionSkillConfig, $r as resolveByfHome, $t as BackgroundTaskUpdatedEvent, A as QuestionAnswers, Ai as ProviderType, An as TurnStepInterruptedEvent, Ar as LoopStepEndEvent, At as SetModelResult, B as SDKSessionAPI, Bi as LogEntry, Bn as ByfError, Br as BackgroundTaskStatus, Bt as Unsubscribe, C as SDKRPCClient, Ci as PermissionConfigSchema, Cn as ToolProgressEvent, Cr as PromptOrigin, Ct as ResumeSessionPayload, D as ApprovalResponse, Di as PermissionRuleScopeSchema, Dn as TurnEndedEvent, Dr as LoopContentPartEvent, Dt as SetActiveToolsPayload, E as ApprovalRequest, Ei as PermissionRuleSchema, En as TurnEndReason, Er as ToolStoreUpdate, Et as SessionSummary, F as QuestionResult, Fi as ThinkingConfigSchema, Fn as ByfErrorPayload, Fr as ExecutableToolSuccessResult, Ft as SkillSummary, G as AgentAPI, Gi as RootLogger, Gn as ErrorCodes, Gr as parseConfigString, Gt as AgentReplayRecord, H as ToolCallRequest, Hi as LogPayload, Hn as BYF_ERROR_INFO, Hr as OAuthTokenProviderResolver, Ht as WithAgentId, I as SDKAPI, Ii as formatConfigValidationError, In as fromByfErrorPayload, Ir as ToolInputDisplay, It as SteerPayload, J as ByfConfigPatch, Jn as SubagentHandle, Jr as writeConfigFile, Jt as AgentEvent, K as BeginCompactionPayload, Ki as SessionAttachInput, Kn as RuntimeConfig, Kr as readConfigFile, Kt as ResumeSessionResult, L as SDKAgentAPI, Li as getDefaultConfig, Ln as isByfError, Lr as BackgroundLifecycleEvent, Lt as StopBackgroundPayload, M as QuestionOption, Mi as ServicesConfig, Mn as TurnStepStartedEvent, Mr as LoopToolResultEvent, Mt as SetThinkingPayload, N as QuestionRequest, Ni as ServicesConfigSchema, Nn as UsageStatus, Nr as ExecutableToolErrorResult, Nt as ShellExecPayload, O as ApprovalScope, Oi as ProviderConfig, On as TurnStartedEvent, Or as LoopRecordedEvent, Ot as SetByfConfigPayload, P as QuestionResponse, Pi as ThinkingConfig, Pn as WarningEvent, Pr as ExecutableToolResult, Pt as ShellExecResult, Q as CoreAPI, Qn as SessionMeta, Qr as ensureByfHome, Qt as BackgroundTaskTerminatedEvent, R as SDKAgentRPC, Ri as validateConfig, Rn as makeErrorPayload, Rr as BackgroundTaskInfo, Rt as TextPromptPart, S as RPCMethods, Si as PermissionConfig, Sn as ToolListUpdatedReason, Sr as ContextMessage, St as RenameSessionPayload, T as ApprovalDecision, Ti as PermissionRuleDecisionSchema, Tn as ToolUpdate, Tr as UserPromptOrigin, Tt as SessionMetadataPatch, U as ToolCallResponse, Ui as Logger, Un as ByfErrorCode, Ur as configToTomlData, Ut as WithSessionId, V as SDKSessionRPC, Vi as LogLevel, Vn as ByfErrorOptions, Vr as BearerTokenProvider, Vt as UpdateSessionMetadataPayload, W as ActivateSkillPayload, Wi as LoggingConfig, Wn as ByfErrorInfo, Wr as ensureConfigFile, Wt as proxyWithExtraPayload, X as CancelPlanPayload, Xn as Session, Xr as parseBooleanEnv, Xt as AssistantDeltaEvent, Y as CancelPayload, Yn as AgentMeta, Yr as ResolveConfigValueInput, Yt as AgentStatusUpdatedEvent, Z as CloseSessionPayload, Zn as SessionConfig, Zr as resolveConfigValue, Zt as BackgroundTaskStartedEvent, _ as ByfCoreOptions, _i as McpServerStdioConfigSchema, _n as SubagentSpawnedEvent, _r as PermissionMode, _t as PromptPart, a as collectFilesRecursive, ai as ByfConfigSchema, an as Event, ar as redact, at as ForkSessionPayload, b as RPCCallOptions, bi as OAuthRef, bn as ToolCallStartedEvent, br as CompactionResult, bt as RegisterToolPayload, c as WIRE_PROTOCOL_VERSION, ci as HookDefConfig, cn as McpOAuthAuthorizationUrlUpdateData, cr as ToolInfo, ct as GetBackgroundPayload, d as normalizeTimestampMs, di as LoopControlSchema, dn as ObservationMaskingAppliedEvent, dr as AgentRecord, dt as JsonValue, ei as resolveConfigPath, en as CompactionBlockedEvent, er as TelemetryClient, et as CreateSessionPayload, f as scanSessionWire, fi as McpServerConfig, fn as PruningAppliedEvent, fr as AgentRecordEvents, ft as ListSessionsPayload, g as ByfCore, gi as McpServerStdioConfig, gn as SubagentFailedEvent, gr as PermissionApprovalResultRecord, gt as PromptInput, h as AgentType, hi as McpServerHttpConfigSchema, hn as SubagentCompletedEvent, hr as UsageRecordScope, ht as PlanData, i as ExtraZipEntry, ii as ByfConfigPatchSchema, in as ErrorEvent, ir as log, it as ExportSessionResult, j as QuestionItem, ji as ProviderTypeSchema, jn as TurnStepRetryingEvent, jr as LoopToolCallEvent, jt as SetPermissionPayload, k as QuestionAnswerMethod, ki as ProviderConfigSchema, kn as TurnStepCompletedEvent, kr as LoopStepBeginEvent, kt as SetModelPayload, l as buildExportManifest, li as HookDefSchema, ln as McpServerStatusEvent, lr as ToolSource, lt as JsonObject, m as AgentConfig, mi as McpServerHttpConfig, mn as SkillActivatedEvent, mr as AgentRecordPersistence, mt as McpStartupMetrics, n as ResolveLoggingInput, ni as BackgroundConfig, nn as CompactionCompletedEvent, nr as flushDiagnosticLogs, nt as ExportSessionManifest, o as writeExportZip, oi as ByfServiceConfig, on as HookResultEvent, or as resolveGlobalLogPath, ot as GetBackgroundOutputPathPayload, p as Agent, pi as McpServerConfigSchema, pn as SessionMetaUpdatedEvent, pr as AgentRecordOf, pt as McpServerInfo, q as ByfConfig, qi as SessionLogHandle, qn as SessionSubagentHost, qr as transformTomlData, qt as ResumedAgentState, r as resolveLoggingConfig, ri as BackgroundConfigSchema, rn as CompactionStartedEvent, rr as getRootLogger, rt as ExportSessionPayload, s as exportSessionDirectory, si as ByfServiceConfigSchema, sn as MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, sr as BuiltinTool, st as GetBackgroundOutputPayload, t as buildPromptPlan, ti as mergeConfigPatch, tn as CompactionCancelledEvent, tr as TelemetryProperties, tt as EmptyPayload, u as SessionWireScan, ui as LoopControl, un as McpServerStatusPayload, ur as UserToolRegistration, ut as JsonPrimitive, v as CoreRPC, vi as ModelAlias, vn as ThinkingDeltaEvent, vr as AgentConfigUpdateData, vt as PromptPayload, w as createRPC, wi as PermissionModeSchema, wn as ToolResultEvent, wr as USER_PROMPT_ORIGIN, wt as SessionAPI, x as RPCClient, xi as OAuthRefSchema, xn as ToolListUpdatedEvent, xr as AgentContextData, xt as RemoveByfProviderPayload, y as CoreRPCClient, yi as ModelAliasSchema, yn as ToolCallDeltaEvent, yr as CompactionBeginData, yt as ReconnectMcpServerPayload, z as SDKRPC, zi as LogContext, zn as toByfErrorPayload, zr as BackgroundTaskKind, zt as UnregisterToolPayload } from "./index-CSFujlN1.mjs";
2
+ import { $ as CoreInfo, $n as SessionSkillConfig, $r as resolveByfHome, $t as BackgroundTaskUpdatedEvent, A as QuestionAnswers, Ai as ProviderType, An as TurnStepInterruptedEvent, Ar as LoopStepEndEvent, At as SetModelResult, B as SDKSessionAPI, Bi as LogEntry, Bn as ByfError, Br as BackgroundTaskStatus, Bt as Unsubscribe, C as SDKRPCClient, Ci as PermissionConfigSchema, Cn as ToolProgressEvent, Cr as PromptOrigin, Ct as ResumeSessionPayload, D as ApprovalResponse, Di as PermissionRuleScopeSchema, Dn as TurnEndedEvent, Dr as LoopContentPartEvent, Dt as SetActiveToolsPayload, E as ApprovalRequest, Ei as PermissionRuleSchema, En as TurnEndReason, Er as ToolStoreUpdate, Et as SessionSummary, F as QuestionResult, Fi as ThinkingConfigSchema, Fn as ByfErrorPayload, Fr as ExecutableToolSuccessResult, Ft as SkillSummary, G as AgentAPI, Gi as RootLogger, Gn as ErrorCodes, Gr as parseConfigString, Gt as AgentReplayRecord, H as ToolCallRequest, Hi as LogPayload, Hn as BYF_ERROR_INFO, Hr as OAuthTokenProviderResolver, Ht as WithAgentId, I as SDKAPI, Ii as formatConfigValidationError, In as fromByfErrorPayload, Ir as ToolInputDisplay, It as SteerPayload, J as ByfConfigPatch, Jn as SubagentHandle, Jr as writeConfigFile, Jt as AgentEvent, K as BeginCompactionPayload, Ki as SessionAttachInput, Kn as RuntimeConfig, Kr as readConfigFile, Kt as ResumeSessionResult, L as SDKAgentAPI, Li as getDefaultConfig, Ln as isByfError, Lr as BackgroundLifecycleEvent, Lt as StopBackgroundPayload, M as QuestionOption, Mi as ServicesConfig, Mn as TurnStepStartedEvent, Mr as LoopToolResultEvent, Mt as SetThinkingPayload, N as QuestionRequest, Ni as ServicesConfigSchema, Nn as UsageStatus, Nr as ExecutableToolErrorResult, Nt as ShellExecPayload, O as ApprovalScope, Oi as ProviderConfig, On as TurnStartedEvent, Or as LoopRecordedEvent, Ot as SetByfConfigPayload, P as QuestionResponse, Pi as ThinkingConfig, Pn as WarningEvent, Pr as ExecutableToolResult, Pt as ShellExecResult, Q as CoreAPI, Qn as SessionMeta, Qr as ensureByfHome, Qt as BackgroundTaskTerminatedEvent, R as SDKAgentRPC, Ri as validateConfig, Rn as makeErrorPayload, Rr as BackgroundTaskInfo, Rt as TextPromptPart, S as RPCMethods, Si as PermissionConfig, Sn as ToolListUpdatedReason, Sr as ContextMessage, St as RenameSessionPayload, T as ApprovalDecision, Ti as PermissionRuleDecisionSchema, Tn as ToolUpdate, Tr as UserPromptOrigin, Tt as SessionMetadataPatch, U as ToolCallResponse, Ui as Logger, Un as ByfErrorCode, Ur as configToTomlData, Ut as WithSessionId, V as SDKSessionRPC, Vi as LogLevel, Vn as ByfErrorOptions, Vr as BearerTokenProvider, Vt as UpdateSessionMetadataPayload, W as ActivateSkillPayload, Wi as LoggingConfig, Wn as ByfErrorInfo, Wr as ensureConfigFile, Wt as proxyWithExtraPayload, X as CancelPlanPayload, Xn as Session, Xr as parseBooleanEnv, Xt as AssistantDeltaEvent, Y as CancelPayload, Yn as AgentMeta, Yr as ResolveConfigValueInput, Yt as AgentStatusUpdatedEvent, Z as CloseSessionPayload, Zn as SessionConfig, Zr as resolveConfigValue, Zt as BackgroundTaskStartedEvent, _ as ByfCoreOptions, _i as McpServerStdioConfigSchema, _n as SubagentSpawnedEvent, _r as PermissionMode, _t as PromptPart, a as collectFilesRecursive, ai as ByfConfigSchema, an as Event, ar as redact, at as ForkSessionPayload, b as RPCCallOptions, bi as OAuthRef, bn as ToolCallStartedEvent, br as CompactionResult, bt as RegisterToolPayload, c as WIRE_PROTOCOL_VERSION, ci as HookDefConfig, cn as McpOAuthAuthorizationUrlUpdateData, cr as ToolInfo, ct as GetBackgroundPayload, d as normalizeTimestampMs, di as LoopControlSchema, dn as ObservationMaskingAppliedEvent, dr as AgentRecord, dt as JsonValue, ei as resolveConfigPath, en as CompactionBlockedEvent, er as TelemetryClient, et as CreateSessionPayload, f as scanSessionWire, fi as McpServerConfig, fn as PruningAppliedEvent, fr as AgentRecordEvents, ft as ListSessionsPayload, g as ByfCore, gi as McpServerStdioConfig, gn as SubagentFailedEvent, gr as PermissionApprovalResultRecord, gt as PromptInput, h as AgentType, hi as McpServerHttpConfigSchema, hn as SubagentCompletedEvent, hr as UsageRecordScope, ht as PlanData, i as ExtraZipEntry, ii as ByfConfigPatchSchema, in as ErrorEvent, ir as log, it as ExportSessionResult, j as QuestionItem, ji as ProviderTypeSchema, jn as TurnStepRetryingEvent, jr as LoopToolCallEvent, jt as SetPermissionPayload, k as QuestionAnswerMethod, ki as ProviderConfigSchema, kn as TurnStepCompletedEvent, kr as LoopStepBeginEvent, kt as SetModelPayload, l as buildExportManifest, li as HookDefSchema, ln as McpServerStatusEvent, lr as ToolSource, lt as JsonObject, m as AgentConfig, mi as McpServerHttpConfig, mn as SkillActivatedEvent, mr as AgentRecordPersistence, mt as McpStartupMetrics, n as ResolveLoggingInput, ni as BackgroundConfig, nn as CompactionCompletedEvent, nr as flushDiagnosticLogs, nt as ExportSessionManifest, o as writeExportZip, oi as ByfServiceConfig, on as HookResultEvent, or as resolveGlobalLogPath, ot as GetBackgroundOutputPathPayload, p as Agent, pi as McpServerConfigSchema, pn as SessionMetaUpdatedEvent, pr as AgentRecordOf, pt as McpServerInfo, q as ByfConfig, qi as SessionLogHandle, qn as SessionSubagentHost, qr as transformTomlData, qt as ResumedAgentState, r as resolveLoggingConfig, ri as BackgroundConfigSchema, rn as CompactionStartedEvent, rr as getRootLogger, rt as ExportSessionPayload, s as exportSessionDirectory, si as ByfServiceConfigSchema, sn as MCP_OAUTH_AUTHORIZATION_URL_TOOL_UPDATE, sr as BuiltinTool, st as GetBackgroundOutputPayload, t as buildPromptPlan, ti as mergeConfigPatch, tn as CompactionCancelledEvent, tr as TelemetryProperties, tt as EmptyPayload, u as SessionWireScan, ui as LoopControl, un as McpServerStatusPayload, ur as UserToolRegistration, ut as JsonPrimitive, v as CoreRPC, vi as ModelAlias, vn as ThinkingDeltaEvent, vr as AgentConfigUpdateData, vt as PromptPayload, w as createRPC, wi as PermissionModeSchema, wn as ToolResultEvent, wr as USER_PROMPT_ORIGIN, wt as SessionAPI, x as RPCClient, xi as OAuthRefSchema, xn as ToolListUpdatedEvent, xr as AgentContextData, xt as RemoveByfProviderPayload, y as CoreRPCClient, yi as ModelAliasSchema, yn as ToolCallDeltaEvent, yr as CompactionBeginData, yt as ReconnectMcpServerPayload, z as SDKRPC, zi as LogContext, zn as toByfErrorPayload, zr as BackgroundTaskKind, zt as UnregisterToolPayload } from "./index-C2yfSu8d.mjs";
3
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, CancelPlanPayload, 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, PlanData, 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, 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
@@ -23,7 +23,7 @@ import { fromBuffer } from "yauzl";
23
23
  import { StringDecoder } from "node:string_decoder";
24
24
  import { createControlledPromise, objectMap, sleep } from "@antfu/utils";
25
25
  import * as retry from "retry";
26
- import { spawn } from "node:child_process";
26
+ import { execSync, spawn } from "node:child_process";
27
27
  import Ajv from "ajv";
28
28
  import Ajv2019 from "ajv/dist/2019.js";
29
29
  import Ajv2020 from "ajv/dist/2020.js";
@@ -38,6 +38,7 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
38
38
  import { localKaos } from "@byfriends/kaos";
39
39
  import { Readability } from "@mozilla/readability";
40
40
  import { parseHTML } from "linkedom";
41
+ import { ProxyAgent } from "undici";
41
42
  //#region \0rolldown/runtime.js
42
43
  var __create = Object.create;
43
44
  var __defProp = Object.defineProperty;
@@ -7037,7 +7038,8 @@ const DEFAULT_MASKING_CONFIG = {
7037
7038
  function getToolPriority(toolName) {
7038
7039
  switch (toolName) {
7039
7040
  case "Write":
7040
- case "Edit": return "high";
7041
+ case "Edit":
7042
+ case "Agent": return "high";
7041
7043
  case "Bash": return "medium";
7042
7044
  case "Read":
7043
7045
  case "Glob":
@@ -8038,7 +8040,7 @@ var ContextMemory = class {
8038
8040
  }
8039
8041
  case "tool.result": {
8040
8042
  let result = event.result;
8041
- if (!this.agent.records.restoring && this.scratchManager !== void 0 && typeof result.output === "string") {
8043
+ if (!this.agent.records.restoring && this.scratchManager !== void 0 && typeof result.output === "string" && (this.toolCallInfo.get(event.toolCallId)?.name ?? "unknown") !== "Agent") {
8042
8044
  const offloadResult = await offloadOutput(event.toolCallId, this.toolCallInfo.get(event.toolCallId)?.name ?? "unknown", result, this.scratchManager, DEFAULT_OFFLOADING_CONFIG);
8043
8045
  if (offloadResult.offloaded) {
8044
8046
  result = {
@@ -15381,6 +15383,7 @@ const OAuthRefSchema = z.object({
15381
15383
  key: z.string().min(1)
15382
15384
  });
15383
15385
  const StringRecordSchema = z.record(z.string(), z.string());
15386
+ const ExtraBodySchema = z.record(z.string(), z.unknown());
15384
15387
  const ProviderConfigSchema = z.object({
15385
15388
  type: ProviderTypeSchema,
15386
15389
  apiKey: z.string().optional(),
@@ -15389,7 +15392,8 @@ const ProviderConfigSchema = z.object({
15389
15392
  thinkingEffortKey: z.string().optional(),
15390
15393
  oauth: OAuthRefSchema.optional(),
15391
15394
  env: StringRecordSchema.optional(),
15392
- customHeaders: StringRecordSchema.optional()
15395
+ customHeaders: StringRecordSchema.optional(),
15396
+ extraBody: ExtraBodySchema.optional()
15393
15397
  });
15394
15398
  const ModelAliasSchema = z.object({
15395
15399
  provider: z.string(),
@@ -16485,7 +16489,8 @@ var McpConnectionManager = class {
16485
16489
  return new HttpMcpClient(config, {
16486
16490
  toolCallTimeoutMs,
16487
16491
  envLookup: this.options.envLookup,
16488
- oauthProvider: this.resolveOAuthProvider(config, name)
16492
+ oauthProvider: this.resolveOAuthProvider(config, name),
16493
+ fetch: this.options.fetch
16489
16494
  });
16490
16495
  }
16491
16496
  resolveOAuthProvider(config, name) {
@@ -16820,6 +16825,11 @@ var summary_continuation_default = "Your previous response was too brief. Please
16820
16825
  * agent receives a technically complete handoff.
16821
16826
  */
16822
16827
  const SUMMARY_MIN_LENGTH = 200;
16828
+ /**
16829
+ * Soft upper bound (characters) communicated to the subagent via prompt so
16830
+ * it self-regulates summary length. Not enforced at runtime.
16831
+ */
16832
+ const SUMMARY_MAX_LENGTH = 8e3;
16823
16833
  const SUMMARY_CONTINUATION_ATTEMPTS = 1;
16824
16834
  const HOOK_TEXT_PREVIEW_LENGTH = 500;
16825
16835
  const SUBAGENT_MAX_TOKENS_ERROR = "Subagent turn failed before completing its final summary: reason=max_tokens";
@@ -16932,7 +16942,7 @@ var SessionSubagentHost = class {
16932
16942
  options.signal.throwIfAborted();
16933
16943
  await this.triggerSubagentStart(parent, profileName, options.prompt, options.signal);
16934
16944
  options.signal.throwIfAborted();
16935
- let childPrompt = options.prompt;
16945
+ let childPrompt = `${`Summary length constraint: minimum ${SUMMARY_MIN_LENGTH} characters, maximum ${SUMMARY_MAX_LENGTH} characters.`}\n\n${options.prompt}`;
16936
16946
  if (profileName === "explore") {
16937
16947
  const gitContext = await collectGitContext(child.runtime.kaos, child.config.cwd);
16938
16948
  if (gitContext) childPrompt = `${gitContext}\n\n${childPrompt}`;
@@ -17068,7 +17078,8 @@ var Session = class {
17068
17078
  this.skills = new SkillRegistry({ sessionId: config.id });
17069
17079
  this.mcp = new McpConnectionManager({
17070
17080
  oauthService: new McpOAuthService({ byfHomeDir: config.byfHomeDir }),
17071
- log: this.log
17081
+ log: this.log,
17082
+ fetch: config.runtime.fetch
17072
17083
  });
17073
17084
  this.mcp.onStatusChange((entry) => {
17074
17085
  this.onMcpServerStatusChange(entry);
@@ -17540,6 +17551,213 @@ var LocalFetchURLProvider = class {
17540
17551
  }
17541
17552
  };
17542
17553
  //#endregion
17554
+ //#region src/tools/providers/proxied-fetch.ts
17555
+ /**
17556
+ * ProxiedFetch — a `typeof fetch` wrapper with automatic proxy fallback.
17557
+ *
17558
+ * Flow:
17559
+ * 1. Attempt the request with a 60-second timeout (via AbortController,
17560
+ * respecting any external AbortSignal).
17561
+ * 2. If the request succeeds, return the response.
17562
+ * 3. If the request fails with a retryable error and a proxy is detected,
17563
+ * retry through the proxy (also 60-second timeout).
17564
+ * 4. If the request fails with a non-retryable error, or no proxy is
17565
+ * configured, propagate the original error / response.
17566
+ * 5. If the proxy retry also fails, propagate the proxy error in the same
17567
+ * format as a normal fetch error — no special wrapping.
17568
+ *
17569
+ * Proxy detection reads environment variables only (macOS `scutil --proxy`
17570
+ * is added in a separate slice). Env vars take priority over system proxy.
17571
+ */
17572
+ const REQUEST_TIMEOUT_MS = 6e4;
17573
+ const RETRYABLE_HTTP_STATUSES = new Set([
17574
+ 403,
17575
+ 429,
17576
+ 502,
17577
+ 503,
17578
+ 504
17579
+ ]);
17580
+ const RETRYABLE_NETWORK_CODES = new Set([
17581
+ "ECONNREFUSED",
17582
+ "ECONNRESET",
17583
+ "ENOTFOUND",
17584
+ "ETIMEDOUT",
17585
+ "EPIPE",
17586
+ "EAI_AGAIN"
17587
+ ]);
17588
+ const HTTPS_PROXY_KEYS = ["HTTPS_PROXY", "https_proxy"];
17589
+ const HTTP_PROXY_KEYS = ["HTTP_PROXY", "http_proxy"];
17590
+ const ALL_PROXY_KEYS = ["ALL_PROXY", "all_proxy"];
17591
+ const SOCKS_PROXY_KEYS = ["SOCKS_PROXY", "socks_proxy"];
17592
+ const NO_PROXY_KEYS = ["NO_PROXY", "no_proxy"];
17593
+ /**
17594
+ * Determine the proxy URL for a given request URL based on environment
17595
+ * variables and optional system proxy settings.
17596
+ *
17597
+ * Env vars always take priority over system proxy.
17598
+ *
17599
+ * Priority for HTTPS requests:
17600
+ * HTTPS_PROXY → system HTTPS → ALL_PROXY → SOCKS_PROXY → system SOCKS → HTTP_PROXY → system HTTP
17601
+ * Priority for HTTP requests:
17602
+ * HTTP_PROXY → system HTTP → ALL_PROXY → SOCKS_PROXY → system SOCKS
17603
+ */
17604
+ function getProxyForUrl(requestUrl, envLookup, systemProxy) {
17605
+ if (new URL(requestUrl).protocol === "https:") return firstDefined(HTTPS_PROXY_KEYS, envLookup) ?? systemProxy?.httpsProxy ?? firstDefined(ALL_PROXY_KEYS, envLookup) ?? firstDefined(SOCKS_PROXY_KEYS, envLookup) ?? systemProxy?.socksProxy ?? firstDefined(HTTP_PROXY_KEYS, envLookup) ?? systemProxy?.httpProxy;
17606
+ return firstDefined(HTTP_PROXY_KEYS, envLookup) ?? systemProxy?.httpProxy ?? firstDefined(ALL_PROXY_KEYS, envLookup) ?? firstDefined(SOCKS_PROXY_KEYS, envLookup) ?? systemProxy?.socksProxy;
17607
+ }
17608
+ /**
17609
+ * Classify an error or response as retryable (should trigger proxy fallback).
17610
+ *
17611
+ * Retryable: network-level errors (DNS failure, ECONNREFUSED, ECONNRESET,
17612
+ * timeout, abort) and HTTP 403, 429, 502, 503, 504.
17613
+ * Non-retryable: HTTP 4xx (except 403/429) and everything else.
17614
+ */
17615
+ function isRetryableError(error) {
17616
+ if (error instanceof TypeError && error.cause && typeof error.cause === "object") {
17617
+ const code = error.cause.code;
17618
+ if (typeof code === "string" && RETRYABLE_NETWORK_CODES.has(code)) return true;
17619
+ }
17620
+ if (error instanceof DOMException && error.name === "AbortError") return true;
17621
+ if (error instanceof Response) return RETRYABLE_HTTP_STATUSES.has(error.status);
17622
+ return false;
17623
+ }
17624
+ /**
17625
+ * Check whether a hostname matches the NO_PROXY list.
17626
+ *
17627
+ * Entries can be:
17628
+ * - `*` → match everything
17629
+ * - `.example.com` → domain suffix (matches `sub.example.com` and `example.com`)
17630
+ * - `example.com` → exact match + suffix match (matches `sub.example.com`)
17631
+ * - `127.0.0.1` → exact IP/hostname match
17632
+ */
17633
+ function isNoProxyHost(hostname, noProxyValue) {
17634
+ if (noProxyValue === void 0 || noProxyValue.length === 0) return false;
17635
+ const entries = noProxyValue.split(",").map((e) => e.trim()).filter((e) => e.length > 0);
17636
+ const host = hostname.toLowerCase();
17637
+ for (const entry of entries) {
17638
+ if (entry === "*") return true;
17639
+ if (entry.startsWith(".")) {
17640
+ if (host.endsWith(entry) || host === entry.slice(1)) return true;
17641
+ } else if (host === entry || host.endsWith("." + entry)) return true;
17642
+ }
17643
+ return false;
17644
+ }
17645
+ /**
17646
+ * Create a `fetch`-compatible function that adds proxy fallback behaviour.
17647
+ *
17648
+ * - Successful requests are returned as-is.
17649
+ * - Retryable failures (network errors, HTTP 403/429/5xx) trigger a single
17650
+ * retry through the proxy detected from environment variables.
17651
+ * - If no proxy is configured, or the error is non-retryable, the original
17652
+ * error/response is propagated unchanged.
17653
+ */
17654
+ function createProxiedFetch(deps) {
17655
+ const envLookup = deps.envLookup;
17656
+ const innerFetch = deps.innerFetch ?? globalThis.fetch.bind(globalThis);
17657
+ const proxiedFetch = async (input, init) => {
17658
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
17659
+ const noProxy = firstDefined(NO_PROXY_KEYS, envLookup);
17660
+ const hostname = new URL(url).hostname;
17661
+ const sysProxy = deps.systemProxy?.();
17662
+ const proxyUrl = getProxyForUrl(url, envLookup, sysProxy);
17663
+ const noProxyMatch = noProxy !== void 0 && isNoProxyHost(hostname, noProxy);
17664
+ const controller = new AbortController();
17665
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
17666
+ if (init?.signal) if (init.signal.aborted) {
17667
+ clearTimeout(timeoutId);
17668
+ controller.abort();
17669
+ } else init.signal.addEventListener("abort", () => controller.abort(), { once: true });
17670
+ const mergedInit = {
17671
+ ...init,
17672
+ signal: controller.signal
17673
+ };
17674
+ try {
17675
+ const response = await innerFetch(input, mergedInit);
17676
+ clearTimeout(timeoutId);
17677
+ if (!response.ok && isRetryableError(response) && proxyUrl && !noProxyMatch) return await retryViaProxy(input, init, proxyUrl, innerFetch);
17678
+ return response;
17679
+ } catch (error) {
17680
+ clearTimeout(timeoutId);
17681
+ if (isRetryableError(error) && proxyUrl && !noProxyMatch) return await retryViaProxy(input, init, proxyUrl, innerFetch);
17682
+ throw error;
17683
+ }
17684
+ };
17685
+ return proxiedFetch;
17686
+ }
17687
+ async function retryViaProxy(input, init, proxyUrl, innerFetch) {
17688
+ const controller = new AbortController();
17689
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
17690
+ if (init?.signal) if (init.signal.aborted) {
17691
+ clearTimeout(timeoutId);
17692
+ controller.abort();
17693
+ } else init.signal.addEventListener("abort", () => controller.abort(), { once: true });
17694
+ const dispatcher = new ProxyAgent(proxyUrl);
17695
+ const retryInit = {
17696
+ ...init,
17697
+ signal: controller.signal,
17698
+ dispatcher
17699
+ };
17700
+ try {
17701
+ const response = await innerFetch(input, retryInit);
17702
+ clearTimeout(timeoutId);
17703
+ return response;
17704
+ } catch (error) {
17705
+ clearTimeout(timeoutId);
17706
+ throw error;
17707
+ }
17708
+ }
17709
+ function firstDefined(keys, lookup) {
17710
+ for (const key of keys) {
17711
+ const value = lookup(key);
17712
+ if (value !== void 0 && value.length > 0) return value;
17713
+ }
17714
+ }
17715
+ //#endregion
17716
+ //#region src/tools/providers/system-proxy.ts
17717
+ /**
17718
+ * macOS system proxy detection via `scutil --proxy`.
17719
+ *
17720
+ * Parses the scutil output to extract HTTP, HTTPS, and SOCKS proxy settings.
17721
+ * On non-darwin platforms, returns an empty object.
17722
+ */
17723
+ /**
17724
+ * Detect macOS system proxy settings by running `scutil --proxy`.
17725
+ *
17726
+ * On non-darwin platforms, returns `{}` immediately.
17727
+ * If `scutil` fails or produces unparseable output, returns `{}`.
17728
+ */
17729
+ function detectSystemProxy(options) {
17730
+ if ((options?.platform ?? process.platform) !== "darwin") return {};
17731
+ const runCmd = options?.execSync ?? ((cmd) => execSync(cmd, { encoding: "utf-8" }));
17732
+ let raw;
17733
+ try {
17734
+ raw = runCmd("scutil --proxy");
17735
+ } catch {
17736
+ return {};
17737
+ }
17738
+ return parseScutilProxy(raw);
17739
+ }
17740
+ function parseScutilProxy(raw) {
17741
+ const http = extractProxyEntry(raw, "HTTP");
17742
+ const https = extractProxyEntry(raw, "HTTPS");
17743
+ const socks = extractProxyEntry(raw, "SOCKS");
17744
+ return {
17745
+ ...http.enabled ? { httpProxy: `http://${http.host}:${http.port}` } : void 0,
17746
+ ...https.enabled ? { httpsProxy: `http://${https.host}:${https.port}` } : void 0,
17747
+ ...socks.enabled ? { socksProxy: `socks5://${socks.host}:${socks.port}` } : void 0
17748
+ };
17749
+ }
17750
+ function extractProxyEntry(raw, prefix) {
17751
+ const enableMatch = raw.match(new RegExp(`${prefix}Enable\\s*:\\s*(\\d+)`));
17752
+ const hostMatch = raw.match(new RegExp(`${prefix}Proxy\\s*:\\s*(\\S+)`));
17753
+ const portMatch = raw.match(new RegExp(`${prefix}Port\\s*:\\s*(\\d+)`));
17754
+ return {
17755
+ enabled: enableMatch?.[1] === "1",
17756
+ host: hostMatch?.[1] ?? "",
17757
+ port: portMatch?.[1] ? parseInt(portMatch[1], 10) : 0
17758
+ };
17759
+ }
17760
+ //#endregion
17543
17761
  //#region src/tools/providers/remote-fetch-url.ts
17544
17762
  /**
17545
17763
  * RemoteFetchURLProvider — host-side UrlFetcher.
@@ -19248,13 +19466,17 @@ function toKosongProviderConfig(provider, model, byfRequestHeaders, maxOutputSiz
19248
19466
  ...byfRequestHeaders,
19249
19467
  ...provider.customHeaders
19250
19468
  };
19469
+ const generationKwargs = {
19470
+ prompt_cache_key: promptCacheKey,
19471
+ extra_body: provider.extraBody
19472
+ };
19251
19473
  if (Object.keys(defaultHeaders).length === 0) return {
19252
19474
  type: "openai-completions",
19253
19475
  model,
19254
19476
  baseUrl: providerValue(provider.baseUrl, provider.env, "BYF_BASE_URL"),
19255
19477
  reasoningKey,
19256
19478
  thinkingEffortKey: provider.thinkingEffortKey,
19257
- generationKwargs: { prompt_cache_key: promptCacheKey },
19479
+ generationKwargs,
19258
19480
  apiKey: providerApiKey(provider)
19259
19481
  };
19260
19482
  return {
@@ -19263,7 +19485,7 @@ function toKosongProviderConfig(provider, model, byfRequestHeaders, maxOutputSiz
19263
19485
  baseUrl: providerValue(provider.baseUrl, provider.env, "BYF_BASE_URL"),
19264
19486
  reasoningKey,
19265
19487
  thinkingEffortKey: provider.thinkingEffortKey,
19266
- generationKwargs: { prompt_cache_key: promptCacheKey },
19488
+ generationKwargs,
19267
19489
  defaultHeaders,
19268
19490
  apiKey: providerApiKey(provider)
19269
19491
  };
@@ -19819,21 +20041,28 @@ var ByfCore = class {
19819
20041
  }
19820
20042
  };
19821
20043
  async function createRuntimeConfig(input) {
19822
- const localFetcher = new LocalFetchURLProvider();
20044
+ const proxiedFetch = createProxiedFetch({
20045
+ envLookup: (key) => process.env[key],
20046
+ systemProxy: () => detectSystemProxy()
20047
+ });
20048
+ const localFetcher = new LocalFetchURLProvider({ fetchImpl: proxiedFetch });
19823
20049
  const searchService = input.config.services?.byfSearch;
19824
20050
  const fetchService = input.config.services?.byfFetch;
19825
20051
  return {
19826
20052
  kaos: localKaos,
19827
20053
  osEnv: await detectEnvironmentFromNode(),
20054
+ fetch: proxiedFetch,
19828
20055
  urlFetcher: fetchService?.baseUrl === void 0 ? localFetcher : new RemoteFetchURLProvider({
19829
20056
  baseUrl: fetchService.baseUrl,
19830
20057
  localFallback: localFetcher,
19831
20058
  defaultHeaders: input.byfRequestHeaders,
20059
+ fetchImpl: proxiedFetch,
19832
20060
  ...serviceCredentials(fetchService, input.resolveOAuthTokenProvider)
19833
20061
  }),
19834
20062
  webSearcher: searchService?.baseUrl === void 0 ? void 0 : new RemoteWebSearchProvider({
19835
20063
  baseUrl: searchService.baseUrl,
19836
20064
  defaultHeaders: input.byfRequestHeaders,
20065
+ fetchImpl: proxiedFetch,
19837
20066
  ...serviceCredentials(searchService, input.resolveOAuthTokenProvider)
19838
20067
  })
19839
20068
  };
@@ -1,4 +1,4 @@
1
- import { Et as SessionSummary, ft as ListSessionsPayload, lt as JsonObject } from "../../index-CSFujlN1.mjs";
1
+ import { Et as SessionSummary, ft as ListSessionsPayload, lt as JsonObject } from "../../index-C2yfSu8d.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.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Unified agent engine for BYF",
5
5
  "license": "Proprietary",
6
6
  "author": "ByronFinn",
@@ -66,10 +66,11 @@
66
66
  "retry": "0.13.1",
67
67
  "smol-toml": "^1.6.1",
68
68
  "tar": "^7.5.13",
69
+ "undici": "^8.4.1",
69
70
  "yauzl": "^3.3.0",
70
71
  "zod": "^4.3.6",
71
- "@byfriends/kosong": "^0.2.0",
72
- "@byfriends/kaos": "^0.2.0"
72
+ "@byfriends/kaos": "^0.2.2",
73
+ "@byfriends/kosong": "^0.2.2"
73
74
  },
74
75
  "devDependencies": {
75
76
  "@types/js-yaml": "^4.0.9",