@faapi/faapi 6.1.0 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AppRegistries, R as RouteManifest, F as FaapiContext, C as CorsOptions, H as HelmetOptions, L as LoggerOptions, a as FaapiMiddleware, I as InjectorMap, T as ToolMetadata, b as AgentCore, c as AgentMetadata, W as WsRouteManifest } from './routeTypes-Bm--uTbm.js';
2
- export { d as AgentHandleFactory, e as AgentHandleStore, f as AgentPathMeta, g as AgentRegistry, h as AgentToolDescriptor, i as FaapiContextConfig, j as FailOptions, k as Injector, l as RouteInfo, m as RouteInputSchema, n as RouteOutputSchema, o as RouteParamSchema, S as SkillRegistry, p as SseEvent, q as SseWriter, r as ToolCore, s as ToolPathMeta, t as ToolRegistry, u as cors, v as createAppRegistries, w as helmet, x as logger } from './routeTypes-Bm--uTbm.js';
1
+ import { A as AppRegistries, R as RouteManifest, F as FaapiContext, C as CorsOptions, T as TaskClient, H as HelmetOptions, L as LoggerOptions, a as FaapiMiddleware, I as InjectorMap, b as TaskQueueDeps, c as TaskQueue, d as TaskDriver, e as TaskRegistry, f as TaskManifest, g as ToolMetadata, h as AgentCore, i as AgentMetadata, W as WsRouteManifest } from './routeTypes-CCveqSnY.js';
2
+ export { j as AgentHandleFactory, k as AgentHandleStore, l as AgentPathMeta, m as AgentRegistry, n as AgentToolDescriptor, o as FaapiContextConfig, p as FaapiTaskMeta, q as FailOptions, r as Injector, s as RouteInfo, t as RouteInputSchema, u as RouteOutputSchema, v as RouteParamSchema, S as SkillRegistry, w as SseEvent, x as SseWriter, y as TaskContext, z as TaskDriverJob, B as TaskDriverProcess, D as TaskJob, E as TaskJobStatus, G as TaskMetadata, J as TaskModule, K as ToolCore, M as ToolPathMeta, N as ToolRegistry, O as cors, P as createAppRegistries, Q as createTaskRegistry, U as helmet, V as logger } from './routeTypes-CCveqSnY.js';
3
3
  import * as node_http from 'node:http';
4
4
  import { Server, IncomingMessage, ServerResponse } from 'node:http';
5
5
  import { Socket } from 'node:net';
@@ -156,6 +156,24 @@ interface LifecycleHooks {
156
156
  */
157
157
  onError?: (error: unknown, ctx: FaapiContext) => Promise<void> | void;
158
158
  }
159
+ /**
160
+ * 任务子系统配置(config.task,全部字段可选)
161
+ *
162
+ * 第一版为进程内内存队列(重启丢任务、多实例不防重跑——部署职责见 task 子系统文档)。
163
+ */
164
+ interface TaskConfig {
165
+ /** 队列驱动,当前仅 'memory'(默认) */
166
+ driver?: 'memory';
167
+ /**
168
+ * 是否启动任务队列(默认 true)
169
+ *
170
+ * 多实例部署时可在非 worker 节点设 `FAAPI_TASKS_DISABLED=1` 或 `task.enabled: false`,
171
+ * API 节点照常入队(入队能力保留),但不消费执行。
172
+ */
173
+ enabled?: boolean;
174
+ /** 优雅停机时等待在跑任务的最长时间(毫秒,默认 10000;超时 abort) */
175
+ shutdownTimeoutMs?: number;
176
+ }
159
177
  /**
160
178
  * 生命周期上下文
161
179
  */
@@ -168,6 +186,8 @@ interface LifecycleContext {
168
186
  server: node_http.Server;
169
187
  /** app 级注册表——skill 等运行时动态注册路径(`registries.skill.upsert(...)`) */
170
188
  registries: AppRegistries;
189
+ /** 任务客户端——onBoot/onReady 中投递异步任务(`tasks.enqueue(name, payload)`) */
190
+ tasks: TaskClient;
171
191
  }
172
192
  /**
173
193
  * 统一响应包装配置
@@ -617,6 +637,19 @@ interface FaapiConfig {
617
637
  * 详见 `src/config/configTypes.md` agent 配置块章节。
618
638
  */
619
639
  agent?: AgentConfig;
640
+ /**
641
+ * 任务子系统全局配置(队列驱动、启停、停机超时)
642
+ *
643
+ * ```ts
644
+ * import type { FaapiConfig } from '@faapi/faapi';
645
+ * export default {
646
+ * task: { enabled: true, shutdownTimeoutMs: 10_000 },
647
+ * } satisfies FaapiConfig;
648
+ * ```
649
+ *
650
+ * 详见 `src/task/README.md`。
651
+ */
652
+ task?: TaskConfig;
620
653
  /**
621
654
  * 扩展 ctx:在每次请求创建上下文后调用,可挂载自定义方法(如 ctx.xml、ctx.stream)
622
655
  *
@@ -1048,6 +1081,82 @@ declare function collectRouteSchemaSources(routes: RouteManifest, rootDir?: stri
1048
1081
  resolversByFile: Map<string, LazyTypeResolver>;
1049
1082
  };
1050
1083
 
1084
+ /**
1085
+ * 任务队列语义层
1086
+ *
1087
+ * 职责边界(driverTypes.md):
1088
+ * - 本层:任务存在性检查 → payload zod 校验 → 驱动入队;worker 执行包装
1089
+ * (模块加载 + run 调用 + 任务记录更新);start/stop/reload 生命周期编排
1090
+ * - 驱动层(deps.driver,默认 memoryDriver):入队存储、worker 消费、重试策略、停机 drain
1091
+ *
1092
+ * 任务记录(list)由本层维护:enqueue 写 pending,每次 process 写 attempts/running,
1093
+ * 返回写 done,抛错写 failed——对任何驱动语义一致。
1094
+ */
1095
+ declare function createTaskQueue(deps: TaskQueueDeps): TaskQueue;
1096
+
1097
+ /**
1098
+ * 进程内内存驱动(TaskDriver 默认实现,零依赖)
1099
+ *
1100
+ * 行为与第一版内存队列一致(taskQueue 重构前的原始语义):
1101
+ * - 入队进每任务 FIFO 数组;延迟任务由 runAt 控制
1102
+ * - 每任务最多 concurrency 个并行(startWorker 注册时给定)
1103
+ * - 失败按 retries 指数退避重试(500ms * 2^(n-1),封顶 30s);耗尽后丢弃(失败记录由语义层在最后一次 process 抛错时写入)
1104
+ * - stop(timeoutMs):停止出队 + 停接受新任务,等在跑任务,超时 abort;重试等待中的任务取消(视为失败)
1105
+ *
1106
+ * 取舍不变:重启即丢、多实例不防重跑(fallback.md)。
1107
+ */
1108
+ declare function createMemoryDriver(): TaskDriver;
1109
+
1110
+ /**
1111
+ * 按 config.task.driver 解析并加载任务队列驱动
1112
+ *
1113
+ * - 未设置 / `'memory'` → 内置 memoryDriver(零依赖)
1114
+ * - `'pgboss'` → 动态加载子包 `@faapi/task-pgboss` 的 `createPgBossDriver(options)`
1115
+ * - `'bullmq'` → 动态加载子包 `@faapi/task-bullmq` 的 `createBullMQDriver(options)`
1116
+ * - TaskDriver 对象 → 直接使用(编程式自定义驱动)
1117
+ * - 其他值 → 显式抛错,不静默降级
1118
+ *
1119
+ * 子包 specifier 用变量拼接(`'@faapi/task-' + name`)而非字面量——主包不依赖
1120
+ * 驱动子包,运行时从业务方 node_modules 解析(与 zod peerDependency 同策略)。
1121
+ * 未安装时抛出带安装指引的错误,不静默回退 memory。
1122
+ */
1123
+ declare function loadTaskDriver(driver: string | TaskDriver | undefined, driverOptions: unknown): Promise<TaskDriver>;
1124
+
1125
+ /**
1126
+ * cron 定时入队调度器
1127
+ *
1128
+ * 为注册表中声明了 `cron` 的任务建立 croner 定时器,到点调用 `enqueue(name)`
1129
+ * 投递空 payload——定时只是"自动投递者",复用队列的重试/并发/停机语义。
1130
+ * 详见 cronScheduler.md。
1131
+ */
1132
+ interface CronScheduler {
1133
+ /** 建立全部 cron 定时器(幂等——重复调用先清理旧定时器) */
1134
+ start(): void;
1135
+ /** 停止全部定时器(幂等) */
1136
+ stop(): void;
1137
+ }
1138
+ declare function createCronScheduler(registry: TaskRegistry, enqueue: (name: string) => Promise<unknown>): CronScheduler;
1139
+
1140
+ /**
1141
+ * 任务扫描 patterns(框架约定,非用户可配置项)
1142
+ *
1143
+ * 与路由的 src/api、tool 的 src/tools 对称——任务文件约定放在
1144
+ * `src/tasks` 下任意层级子目录的 task.ts(与 handler.ts 同构的一文件一任务约定)。
1145
+ */
1146
+ declare const TASK_PATTERNS: string[];
1147
+ /**
1148
+ * 扫描 tasks 目录,生成任务清单
1149
+ *
1150
+ * Vite 风格:只读源码 + 正则提取 meta 字面量,不 import 任务模块。
1151
+ * 任务模块的编译与加载延后到运行时(队列派发时 import 产物路径)。
1152
+ *
1153
+ * 重名检测:不同文件推导出同名任务时抛错。
1154
+ *
1155
+ * @param rootDir 项目根目录
1156
+ * @param patterns glob patterns(匹配 src/tasks 下的 task.ts)
1157
+ */
1158
+ declare function scanTasks(rootDir: string, patterns: string[]): Promise<TaskManifest[]>;
1159
+
1051
1160
  /**
1052
1161
  * 加载后的 agent 模块
1053
1162
  *
@@ -1443,6 +1552,8 @@ interface AppBase {
1443
1552
  wsRoutes: WsRouteManifest;
1444
1553
  /** 项目根目录 */
1445
1554
  rootDir: string;
1555
+ /** 任务队列客户端(入队/查询;app 实例级,close 时随队列停机) */
1556
+ tasks: TaskClient;
1446
1557
  /** 启动 HTTP server,打印路由表,执行 onReady 钩子 */
1447
1558
  listen(port?: number): Promise<Server>;
1448
1559
  /** 关闭 server,执行 onClose 钩子 */
@@ -1467,6 +1578,8 @@ interface DevApp extends AppBase {
1467
1578
  reloadTools(): Promise<void>;
1468
1579
  /** 重新扫描 agents + 重生成 faapi-agents.js + 清缓存(dev 热替换用) */
1469
1580
  reloadAgents(): Promise<void>;
1581
+ /** 重新扫描 tasks + 重编译任务源码 + 重生成 faapi-tasks.js + 清队列缓存(dev 热替换用) */
1582
+ reloadTasks(): Promise<void>;
1470
1583
  }
1471
1584
  /**
1472
1585
  * dev 模式应用启动 API
@@ -1513,4 +1626,4 @@ type ProdApp = AppBase;
1513
1626
  */
1514
1627
  declare function createProdApp(options?: CreateAppOptions): Promise<ProdApp>;
1515
1628
 
1516
- export { type AgentConfig, AgentCore, AgentMetadata, type AgentModule, type ProdApp as App, AppRegistries, CorsOptions, type CreateAppOptions, type DevApp, type FaapiConfig, FaapiContext, FaapiError, FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, HelmetOptions, type InjectOptions, type InjectResponse, InjectorMap, InternalError, type LifecycleContext, type LifecycleHooks, type LlmConfig, type LlmModelConfig, LoggerOptions, MethodNotAllowedError, ModuleLoadError, type PluginContext, type PluginDeclaration, type ProdApp, type PropertyType, type RequestHandler, type ResponseConfig, RouteManifest, RouteNotFoundError, type RouteSchemaSource, type RuntimeType, SchemaExtractionError, ToolMetadata, type ToolModule, type ToolSchemaModule, type TypeConstraint, type UpgradeHandler, ValidationError, type ValidationErrorCode, type ValidationIssue, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, clearAgentHandleFactory, collectRouteSchemaSources, createProdApp as createApp, createDevApp, createProdApp, createProgram, createPrograms, extractTypeInfo, getAgent, getAgentEntry, getApp, getInputTypeForMethod, getSkill, getTool, getToolSchemaPath, hydrateSkillRegistry, invalidateProgramCache, listSkills, loadAgentModule, loadConfig, loadEnv, loadToolModule, loadToolSchema, registerAgentHandleFactory, removeSkill, resolveAgentTools, resolveSubAgents, resolveTypeNode, upsertSkill };
1629
+ export { type AgentConfig, AgentCore, AgentMetadata, type AgentModule, type ProdApp as App, AppRegistries, CorsOptions, type CreateAppOptions, type CronScheduler, type DevApp, type FaapiConfig, FaapiContext, FaapiError, FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, HelmetOptions, type InjectOptions, type InjectResponse, InjectorMap, InternalError, type LifecycleContext, type LifecycleHooks, type LlmConfig, type LlmModelConfig, LoggerOptions, MethodNotAllowedError, ModuleLoadError, type PluginContext, type PluginDeclaration, type ProdApp, type PropertyType, type RequestHandler, type ResponseConfig, RouteManifest, RouteNotFoundError, type RouteSchemaSource, type RuntimeType, SchemaExtractionError, TASK_PATTERNS, TaskClient, TaskDriver, TaskManifest, TaskQueue, TaskRegistry, ToolMetadata, type ToolModule, type ToolSchemaModule, type TypeConstraint, type UpgradeHandler, ValidationError, type ValidationErrorCode, type ValidationIssue, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, clearAgentHandleFactory, collectRouteSchemaSources, createProdApp as createApp, createCronScheduler, createDevApp, createMemoryDriver, createProdApp, createProgram, createPrograms, createTaskQueue, extractTypeInfo, getAgent, getAgentEntry, getApp, getInputTypeForMethod, getSkill, getTool, getToolSchemaPath, hydrateSkillRegistry, invalidateProgramCache, listSkills, loadAgentModule, loadConfig, loadEnv, loadTaskDriver, loadToolModule, loadToolSchema, registerAgentHandleFactory, removeSkill, resolveAgentTools, resolveSubAgents, resolveTypeNode, scanTasks, upsertSkill };