@tbox.cn/app-module-activity-play 0.0.0-stage → 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.
Files changed (49) hide show
  1. package/INTEGRATION.md +94 -0
  2. package/LICENSE +21 -0
  3. package/README.md +30 -2
  4. package/dist/chunk-CM4OEPC3.js +689 -0
  5. package/dist/chunk-HUBEOW44.js +98 -0
  6. package/dist/client/index.css +107 -0
  7. package/dist/client/index.d.ts +11 -0
  8. package/dist/client/index.js +6 -0
  9. package/dist/index.css +107 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +46 -0
  12. package/dist/server/index.d.ts +309 -0
  13. package/dist/server/index.js +42 -0
  14. package/package.json +67 -3
  15. package/skills/activity-play/SKILL.md +55 -0
  16. package/src/client/cards/activity-play/ActivityPlayCard.tsx +77 -0
  17. package/src/client/cards/activity-play/index.ts +1 -0
  18. package/src/client/cards/view.ts +42 -0
  19. package/src/client/index.ts +22 -0
  20. package/src/client/styles/activity-play.css +136 -0
  21. package/src/index.ts +6 -0
  22. package/src/server/cards/activity-play/meta.ts +26 -0
  23. package/src/server/cards/activity-play/samples.ts +116 -0
  24. package/src/server/cards/activity-play-prize-detail/meta.ts +29 -0
  25. package/src/server/cards/activity-play-prize-detail/samples.ts +54 -0
  26. package/src/server/cards/activity-play-prize-list/meta.ts +41 -0
  27. package/src/server/cards/activity-play-prize-list/samples.ts +78 -0
  28. package/src/server/cards/index.ts +7 -0
  29. package/src/server/errors.ts +101 -0
  30. package/src/server/index.ts +72 -0
  31. package/src/server/ports.ts +50 -0
  32. package/src/server/prizes/cards.ts +79 -0
  33. package/src/server/prizes/errors.ts +88 -0
  34. package/src/server/prizes/query.ts +101 -0
  35. package/src/server/prizes/subject.ts +29 -0
  36. package/src/server/query.ts +98 -0
  37. package/src/server/routes.ts +371 -0
  38. package/src/server/tools.ts +187 -0
  39. package/tbox.module.json +65 -0
  40. package/tests/cards-capture.test.ts +110 -0
  41. package/tests/entry.test.ts +458 -0
  42. package/tests/ports.test.ts +83 -0
  43. package/tests/prizes.test.ts +357 -0
  44. package/tests/routes.test.ts +271 -0
  45. package/tests/samples.test.ts +53 -0
  46. package/tests/smoke.test.ts +27 -0
  47. package/tests/tools.test.ts +251 -0
  48. package/tsconfig.json +8 -0
  49. package/tsup.config.ts +27 -0
@@ -0,0 +1,371 @@
1
+ /**
2
+ * 活动玩法 HTTP 接口(挂载 /api/m/activity-play,鉴权归平台 /api 中间件)。
3
+ * 仅承载 HTTP 出入口形态:query 单值提取 / 错误信封 / 404 映射;查询语义与校验
4
+ * 单源在 ./query.ts(task-02 起与工具共用——工具/HTTP 对同参数同错误分类)。
5
+ *
6
+ * GET /activities?mallId&keyword&limit → {"data":{"items":[活动对象]}}
7
+ * GET /activities/:activityRef?mallId → {"data":活动对象}
8
+ *
9
+ * 语义钉死(任务 01 查询闭环):
10
+ * - mallId 必填;请求商圈与已绑定上下文冲突 → 403 SCOPE_MISMATCH(可信上下文不可被
11
+ * 客户端静默覆盖);无任何商圈(上下文缺商圈且 query 无 mallId)→ 400 SCOPE_REQUIRED;
12
+ * - 用户身份恒取可信请求上下文(getRequestContext),不解析/不信任任何客户端
13
+ * userId/openid/会员号类参数——loginRequired 仅为活动描述字段,本模块不据此拦截;
14
+ * - limit 缺省 20、合法域 1—50(normalizeListLimit 单源——非法/越界 400,不静默钳制);
15
+ * - 活动引用不存在 → 404 ACTIVITY_NOT_FOUND;供给未配置/实例缺席/禁用 → 503
16
+ * NOT_CONFIGURED;供给配置非法或执行异常 → 502 PROVIDER_ERROR(不回退演示数据)。
17
+ */
18
+ import { Router } from 'express';
19
+ import type { Request, Response } from 'express';
20
+ import { getRequestContext } from '@tbox.cn/app-agent-sdk-server';
21
+ import {
22
+ parseMallScope,
23
+ toMallQueryContext,
24
+ withMallScopeFromQuery,
25
+ mallScopeOf,
26
+ ACTIVITY_PLAY_QUERY_SERVICE,
27
+ ACTIVITY_PLAY_ENTRY_SERVICE,
28
+ activityPlayActivitySchema,
29
+ activityPlayEntrySchema,
30
+ ACTIVITY_PLAY_ENTRY_PROTOCOL_VERSION,
31
+ } from '@tbox.cn/app-contracts-mall';
32
+ import type {
33
+ ActivityPlayActivity,
34
+ ActivityPlayEntryRecord,
35
+ ActivityPlaySupplyBinding,
36
+ } from '@tbox.cn/app-contracts-mall';
37
+ import type { RequestContext } from '@tbox.cn/app-contracts';
38
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
39
+ import {
40
+ normalizeActivityRef,
41
+ normalizeKeyword,
42
+ normalizeListLimit,
43
+ queryActivityPlayList,
44
+ } from './query';
45
+ import { resolveActivityPlayEntryPort, resolveActivityPlayQueryPort } from './ports';
46
+ import { ActivityPlayHttpError, toActivityPlayHttpError } from './errors';
47
+
48
+ /** mallId 形状守卫(与 provider adapter 同则,防注入类字符) */
49
+ const MALL_ID_RE = /^[\w-]{1,32}$/;
50
+
51
+ /**
52
+ * query 单值提取(keyword/mallId):非字符串(数组/对象)直接抛 400;trim 后空串按缺省。
53
+ * 不使用任何哨兵返回值——普通字符串(如 "invalid")是合法输入字面量。
54
+ * limit **不走本口**:空串/空白是非法值而非缺省(见 queryValue 原样转交 normalize 裁定)。
55
+ */
56
+ function queryText(req: Request, key: string, label: string): string | undefined {
57
+ const raw: unknown = req.query[key];
58
+ if (raw === undefined) return undefined;
59
+ if (typeof raw !== 'string') {
60
+ throw ActivityPlayHttpError.invalidRequest(`${label} 参数非法(须为单值字符串)`);
61
+ }
62
+ const trimmed = raw.trim();
63
+ return trimmed.length > 0 ? trimmed : undefined;
64
+ }
65
+
66
+ /** limit 原样单值提取:缺席 = undefined;空串/空白保留原样→normalize 显性拒绝 */
67
+ function queryValue(req: Request, key: string, label: string): string | undefined {
68
+ const raw: unknown = req.query[key];
69
+ if (raw === undefined) return undefined;
70
+ if (typeof raw !== 'string') {
71
+ throw ActivityPlayHttpError.invalidRequest(`${label} 参数非法(须为单值字符串)`);
72
+ }
73
+ return raw;
74
+ }
75
+
76
+ /** 商圈解析:query mallId(唯一注入面)与已绑定上下文核对——冲突显式拒绝 */
77
+ function resolveScopedRequestContext(req: Request): RequestContext {
78
+ const reqCtx = getRequestContext(req);
79
+ if (!reqCtx) {
80
+ // 平台鉴权中间件恒在场(/api 全挂 auth——401 通常由上层统一响应);此分支为装配旁路防御
81
+ throw new ActivityPlayHttpError('LOGIN_REQUIRED', 401, '缺少可信请求上下文');
82
+ }
83
+ const boundMallId = parseMallScope(reqCtx.attributes)?.mallId;
84
+ const queryMallId = queryText(req, 'mallId', 'mallId');
85
+ if (queryMallId && boundMallId && queryMallId !== boundMallId) {
86
+ throw ActivityPlayHttpError.scopeMismatch(
87
+ `请求商圈与已绑定上下文冲突(query=${queryMallId}, bound=${boundMallId})`,
88
+ );
89
+ }
90
+ if (queryMallId) {
91
+ if (!MALL_ID_RE.test(queryMallId)) {
92
+ throw ActivityPlayHttpError.invalidRequest('mallId 形状非法');
93
+ }
94
+ return withMallScopeFromQuery(reqCtx, req.query);
95
+ }
96
+ if (boundMallId) {
97
+ if (!MALL_ID_RE.test(boundMallId)) {
98
+ throw ActivityPlayHttpError.invalidRequest('已绑定商圈标识非法');
99
+ }
100
+ return reqCtx;
101
+ }
102
+ throw ActivityPlayHttpError.scopeRequired('缺少商圈(mallId 必填或上下文未绑定商圈)');
103
+ }
104
+
105
+ /** 统一错误收口:映射守门 + logger 留痕(原始供给细节不透传响应) */
106
+ function sendError(res: Response, err: unknown, opts?: {
107
+ logger?: { warn?: (msg: string, ...meta: unknown[]) => void };
108
+ fields?: { activityRef?: string; mallId?: string };
109
+ }): void {
110
+ const httpError = toActivityPlayHttpError(err);
111
+ if (httpError.httpStatus >= 500) {
112
+ // 日志安全纪律(评审返修):只记安全 code 与定位字段——不拼供给 err.message
113
+ //(实测其可能携带配置/参数细节;HTTP 响应零细节早有断言)
114
+ const where = opts?.fields;
115
+ opts?.logger?.warn?.(
116
+ `[activity-play] 供给异常 code=${httpError.code}`
117
+ + (where?.activityRef ? ` ref=${where.activityRef}` : '')
118
+ + (where?.mallId ? ` mallId=${where.mallId}` : ''),
119
+ );
120
+ }
121
+ res.status(httpError.httpStatus).json({ error: { code: httpError.code, message: httpError.message } });
122
+ }
123
+
124
+
125
+ /** 日志取值护甲:activityRef/mallId 仅在过形状守卫后进日志(拒绝注入面写日志) */
126
+ function rawActivityRefOf(req: Request): string | undefined {
127
+ const raw = typeof req.params['activityRef'] === 'string' ? req.params['activityRef'] : '';
128
+ return /^[\w:.-]{1,128}$/.test(raw) ? raw : undefined;
129
+ }
130
+
131
+ function safeMallIdOf(req: Request): string | undefined {
132
+ const raw = typeof req.query['mallId'] === 'string' ? req.query['mallId'] : '';
133
+ return /^[\w-]{1,32}$/.test(raw) ? raw : undefined;
134
+ }
135
+
136
+ /**
137
+ * 两槽一致性内容级比对(task-03):query 活动对象 vs entry 供给侧活动快照——全字段
138
+ *(含 status/loginRequired:不能用 A 目录的状态/登录要求放行 B 目录的入口)。
139
+ * 状态在两次读取的毫秒临界差会表现为 ENTRY_UNAVAILABLE(fail-closed——重试即恢复)。
140
+ */
141
+ export function activityMatchesForEntry(a: ActivityPlayActivity, b: ActivityPlayActivity): boolean {
142
+ return a.activityRef === b.activityRef
143
+ && a.title === b.title
144
+ && a.status === b.status
145
+ && a.loginRequired === b.loginRequired
146
+ && (a.description ?? undefined) === (b.description ?? undefined)
147
+ && (a.imageUrl ?? undefined) === (b.imageUrl ?? undefined)
148
+ && a.startsAt === b.startsAt
149
+ && a.endsAt === b.endsAt;
150
+ }
151
+
152
+ /**
153
+ * 供给侧活动对象契约校验(评审返修:非法活动数据不得通过状态/登录检查):
154
+ * 过 activityPlayActivitySchema(status/loginRequired 形状——'paused'/缺 loginRequired
155
+ * 直接 502)+ 引用必须与请求一致(供给返回另一 activityRef 时不得以请求引用包装输出)。
156
+ * query 侧活动与 entry 快照两侧同规则。
157
+ */
158
+ function assertSupplyActivity(activity: ActivityPlayActivity, expectedRef: string): void {
159
+ const parsed = activityPlayActivitySchema.safeParse(activity);
160
+ if (!parsed.success || activity.activityRef !== expectedRef) {
161
+ throw ActivityPlayHttpError.providerError('活动供给数据非法');
162
+ }
163
+ }
164
+
165
+ /**
166
+ * 两槽供给一致性联检(评审返修两轮):
167
+ * 1) 自报签名比对:两侧 Port 的 supplyBinding(绑定双键 + 归一目录指纹)完全相等——
168
+ * 目录任何差异(含 entry 目标)即不等;签名缺席(供给未实现联检口)→ fail-closed。
169
+ * **仅自报不足**:同一工厂被复用绑到别槽时,实现按自身常量生成签名(自报口径可谎报
170
+ * 一致)——因此:
171
+ * 2) registry 实绑点查:用 SDK 既有 `hasProviderBinding` 在当前 scope 对两槽分别核对
172
+ * 「实际有效绑定 === 该侧自报签名」;任一不符或点查能力缺席(旧 SDK)→ 不可证一致
173
+ * → fail-closed ENTRY_UNAVAILABLE。
174
+ */
175
+ async function assertSupplyConsistency(
176
+ ctx: ServerContext,
177
+ queryPort: { supplyBinding?: ActivityPlaySupplyBinding },
178
+ entryPort: { supplyBinding?: ActivityPlaySupplyBinding },
179
+ scope: Record<string, string>,
180
+ ): Promise<void> {
181
+ const qb = queryPort.supplyBinding;
182
+ const eb = entryPort.supplyBinding;
183
+ if (!qb || !eb
184
+ || qb.provider !== eb.provider
185
+ || qb.implementation !== eb.implementation
186
+ || qb.directoryHash !== eb.directoryHash) {
187
+ throw ActivityPlayHttpError.entryUnavailable('入口供给与活动目录供给不一致');
188
+ }
189
+ const integrations = ctx.integrations as {
190
+ hasProviderBinding?: (
191
+ service: string,
192
+ scope: Record<string, string>,
193
+ provider: string,
194
+ implementation: string,
195
+ ) => boolean;
196
+ } | undefined;
197
+ const check = integrations?.hasProviderBinding?.bind(integrations);
198
+ const queryBound = check?.(ACTIVITY_PLAY_QUERY_SERVICE, scope, qb.provider, qb.implementation);
199
+ const entryBound = check?.(ACTIVITY_PLAY_ENTRY_SERVICE, scope, eb.provider, eb.implementation);
200
+ if (queryBound !== true || entryBound !== true) {
201
+ throw ActivityPlayHttpError.entryUnavailable('入口供给与活动目录供给不一致');
202
+ }
203
+ }
204
+
205
+ /** 入口异常安全日志(评审返修:不拼供给 err.message——只记安全 code 与定位字段) */
206
+ function logEntryIssue(
207
+ logger: { warn?: (msg: string, ...meta: unknown[]) => void } | undefined,
208
+ fields: { code: string; activityRef?: string; mallId?: string },
209
+ ): void {
210
+ logger?.warn?.(
211
+ `[activity-play] entry 异常 code=${fields.code}`
212
+ + (fields.activityRef ? ` ref=${fields.activityRef}` : '')
213
+ + (fields.mallId ? ` mallId=${fields.mallId}` : ''),
214
+ );
215
+ }
216
+
217
+ /**
218
+ * 入口准备业务体校验:空对象或省略合法;平台保留 body.context(上层中间件消费转
219
+ * 请求上下文——本模块忽略该键,不重复实现解析)之外的任何非空字段 INVALID_REQUEST
220
+ *(不容目标/身份/插件参数覆盖入口)。
221
+ */
222
+ function validateEntryBody(req: Request): void {
223
+ const body: unknown = req.body;
224
+ if (body === undefined) return;
225
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
226
+ throw ActivityPlayHttpError.invalidRequest('入口请求业务体须为空对象或省略');
227
+ }
228
+ for (const [key, value] of Object.entries(body as Record<string, unknown>)) {
229
+ if (key === 'context') continue; // 平台保留键(上层鉴权中间件摄入——接口文档说明)
230
+ if (value !== undefined) {
231
+ throw ActivityPlayHttpError.invalidRequest('入口请求业务体须为空对象或省略(不接受目标/身份/参数覆盖)');
232
+ }
233
+ }
234
+ }
235
+
236
+ /** 步骤 4:本系统登录要求检查(身份唯一直读可信 RequestContext——guest/local/external 均有效) */
237
+ function requireEntryLogin(reqCtx: RequestContext, activity: ActivityPlayActivity): void {
238
+ if (!activity.loginRequired) return;
239
+ const identity = reqCtx.identity;
240
+ if (!identity || identity.source === 'anonymous') {
241
+ throw new ActivityPlayHttpError('LOGIN_REQUIRED', 401, '该活动要求先登录');
242
+ }
243
+ }
244
+
245
+ export function createActivityPlayRouter(ctx: ServerContext): Router {
246
+ const router = Router();
247
+
248
+ // GET /api/m/activity-play/activities?mallId=…&keyword=…&limit=…
249
+ router.get('/activities', async (req: Request, res: Response) => {
250
+ try {
251
+ const scopedReqCtx = resolveScopedRequestContext(req);
252
+ const limit = normalizeListLimit(queryValue(req, 'limit', 'limit'));
253
+ const keyword = normalizeKeyword(queryText(req, 'keyword', 'keyword'));
254
+ const page = await queryActivityPlayList(scopedReqCtx, ctx, {
255
+ ...(keyword ? { keyword } : {}),
256
+ limit,
257
+ });
258
+ res.json({ data: { items: page.items } });
259
+ } catch (err) {
260
+ sendError(res, err, {
261
+ logger: ctx.logger,
262
+ fields: { activityRef: rawActivityRefOf(req), mallId: safeMallIdOf(req) },
263
+ });
264
+ }
265
+ });
266
+
267
+ // POST /api/m/activity-play/activities/:activityRef/entry?mallId=…(task-03 准备参与入口)
268
+ // 检查序:输入与可信商圈 → 当前活动(404 + 双侧供给对象校验 502)→ 状态门(409 族)
269
+ // → 本系统登录要求(401)→ entry 供给与两槽一致性(绑定签名/供给对象校验/内容比对
270
+ // 三道联检)→ 出站 schema 自证。成功与业务错误均 no-store;异常日志只记安全 code 与
271
+ // 定位字段。
272
+ router.post('/activities/:activityRef/entry', async (req: Request, res: Response) => {
273
+ try {
274
+ const activityRefRaw = typeof req.params['activityRef'] === 'string' ? req.params['activityRef'] : '';
275
+ const activityRef = normalizeActivityRef(activityRefRaw);
276
+ validateEntryBody(req);
277
+ const scopedReqCtx = resolveScopedRequestContext(req);
278
+ const q = toMallQueryContext(scopedReqCtx); // 空 scope 兜底 + 主体归一(契约组合子单源)
279
+
280
+ // 2. 重新读当前活动(不读卡片旧状态/客户端身份)——供给对象先过公开 schema 且
281
+ // 引用一致(评审返修:'paused'/缺 loginRequired 等非法供给数据不得通过状态与
282
+ // 登录检查——直接 502;供给返回另一 activityRef 也不得以请求引用包装输出)
283
+ const queryPort = await resolveActivityPlayQueryPort(scopedReqCtx, ctx);
284
+ const activity = await queryPort.getActivity(q, activityRef);
285
+ if (!activity) {
286
+ throw ActivityPlayHttpError.notFound(`活动不存在: ${activityRef}`);
287
+ }
288
+ assertSupplyActivity(activity, activityRef);
289
+
290
+ // 3. 服务端时间状态门(disabled 优先——statusOf 单源结果位;'paused' 等非法枚举
291
+ // 已在步骤 2 拒 502——只有 active 前进)
292
+ if (activity.status === 'disabled') {
293
+ throw ActivityPlayHttpError.activityDisabled('活动已停用');
294
+ }
295
+ if (activity.status === 'not_started') {
296
+ throw ActivityPlayHttpError.activityNotStarted('活动尚未开始');
297
+ }
298
+ if (activity.status === 'ended') {
299
+ throw ActivityPlayHttpError.activityEnded('活动已结束');
300
+ }
301
+
302
+ // 4. 本系统登录要求(loginRequired 只表示本系统登录——不判会员资格/插件登录)
303
+ requireEntryLogin(scopedReqCtx, activity);
304
+
305
+ // 5. entry 供给(槽未配置 503 / 异常 502 归 errors 单源)与两槽一致性三道联检:
306
+ // a) supplyBinding(绑定键 provider/implementation + 归一目录指纹)——评审批据
307
+ // 「活动 DTO 相同不足以证明供给一致」:不同目录 entry 目标(query 目录 aPlay/
308
+ // entry 目录 otherPlay)、不同 provider/implementation、签名缺席,均不可证
309
+ // 同源 → fail-closed 409 ENTRY_UNAVAILABLE;
310
+ // b) entry 快照活动对象过公开 schema 且引用一致(同 query 侧——502);
311
+ // c) 内容级全字段比对 activityMatchesForEntry(fail-closed 409)
312
+ const entryPort = await resolveActivityPlayEntryPort(scopedReqCtx, ctx);
313
+ await assertSupplyConsistency(ctx, queryPort, entryPort, mallScopeOf(scopedReqCtx));
314
+ const entryRecord: ActivityPlayEntryRecord | null = await entryPort.getEntry(q, activityRef);
315
+ if (!entryRecord) {
316
+ throw ActivityPlayHttpError.entryUnavailable('该活动暂未登记参与入口');
317
+ }
318
+ assertSupplyActivity(entryRecord.activity, activityRef);
319
+ if (!activityMatchesForEntry(activity, entryRecord.activity)) {
320
+ throw ActivityPlayHttpError.entryUnavailable('入口供给与活动目录不一致');
321
+ }
322
+
323
+ // 6. 出站自证(供给侧非法结构不得未经校验输出 → PROVIDER_ERROR)
324
+ const payload = {
325
+ protocolVersion: ACTIVITY_PLAY_ENTRY_PROTOCOL_VERSION,
326
+ activityRef,
327
+ target: entryRecord.target,
328
+ };
329
+ const parsed = activityPlayEntrySchema.safeParse(payload);
330
+ if (!parsed.success) {
331
+ throw ActivityPlayHttpError.providerError('入口供给数据非法');
332
+ }
333
+ res.setHeader('Cache-Control', 'no-store');
334
+ res.json({ data: parsed.data });
335
+ } catch (err) {
336
+ // 入口业务错误同样 no-store(上层鉴权错误保持平台行为)
337
+ const httpError = toActivityPlayHttpError(err);
338
+ if (httpError.httpStatus >= 500) {
339
+ logEntryIssue(ctx.logger, {
340
+ code: httpError.code,
341
+ activityRef: rawActivityRefOf(req),
342
+ mallId: safeMallIdOf(req),
343
+ });
344
+ }
345
+ res.setHeader('Cache-Control', 'no-store');
346
+ res.status(httpError.httpStatus).json({ error: { code: httpError.code, message: httpError.message } });
347
+ }
348
+ });
349
+
350
+ // GET /api/m/activity-play/activities/:activityRef?mallId=…
351
+ router.get('/activities/:activityRef', async (req: Request, res: Response) => {
352
+ try {
353
+ const activityRefRaw = typeof req.params['activityRef'] === 'string' ? req.params['activityRef'] : '';
354
+ const activityRef = normalizeActivityRef(activityRefRaw);
355
+ const scopedReqCtx = resolveScopedRequestContext(req);
356
+ const queryPort = await resolveActivityPlayQueryPort(scopedReqCtx, ctx);
357
+ const activity = await queryPort.getActivity(toMallQueryContext(scopedReqCtx), activityRef);
358
+ if (!activity) {
359
+ throw ActivityPlayHttpError.notFound(`活动不存在: ${activityRef}`);
360
+ }
361
+ res.json({ data: activity });
362
+ } catch (err) {
363
+ sendError(res, err, {
364
+ logger: ctx.logger,
365
+ fields: { activityRef: rawActivityRefOf(req), mallId: safeMallIdOf(req) },
366
+ });
367
+ }
368
+ });
369
+
370
+ return router;
371
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 活动玩法只读工具集(task-02 服务端出卡)。
3
+ *
4
+ * 上下文统一化:运行上下文 = 工具 execute 第二参(requireToolRequestContext 显式
5
+ * 读取——认证错误沿平台 fail-visible 处理,不吞);商圈与用户恒取该可信上下文
6
+ * (mallId 不在 inputSchema——不声明任何身份/scope/入口覆盖字段)。
7
+ * 查询语义单源 = ./query.ts(与 HTTP 同参同错误分类);本层只做字符串化入参归一、
8
+ * 出卡编排与失败事实组装。无模块级请求态缓存(每次 execute 用各自上下文解析供给)。
9
+ *
10
+ * 出卡语义(任务 02 表格钉死,对齐 cards.md 出卡管线):
11
+ * - 非空结果 → 顶层答话事实 + cards 候选(capture 校验/入池/剥离归平台单点);
12
+ * - 空目录/关键词无匹配 → 明确空结果事实,不产 cards 键(不出卡语义,非错误);
13
+ * - 引用不存在 → ACTIVITY_NOT_FOUND 失败事实;配置缺席/未激活 → NOT_CONFIGURED;
14
+ * 供给异常 → PROVIDER_ERROR——失败路径恒无 cards(不携带其他商圈/先前成功卡片)。
15
+ * - 工具省略 outputSchema(capture 改写出参——协议约定);经 withCardEmissionHint
16
+ * 预告知(注册与 preTool 声明共用 wrapped 实例);失败 message 面向调用方安全文案,
17
+ * 原始异常与配置内容不透出。
18
+ */
19
+ import { z } from 'zod';
20
+ import {
21
+ createTool,
22
+ requireToolRequestContext,
23
+ withCardEmissionHint,
24
+ } from '@tbox.cn/app-agent-sdk-server';
25
+ import type { ServerContext, ToolExecContextLike } from '@tbox.cn/app-agent-sdk-server';
26
+ import type { RequestContext } from '@tbox.cn/app-contracts';
27
+ import type { ActivityPlayActivity } from '@tbox.cn/app-contracts-mall';
28
+ import { activityPlayCardDataSchema } from '@tbox.cn/app-contracts-mall';
29
+ import {
30
+ normalizeActivityRef,
31
+ normalizeKeyword,
32
+ normalizeListLimit,
33
+ queryActivityPlayDetail,
34
+ queryActivityPlayList,
35
+ requireMallIdOf,
36
+ } from './query';
37
+ import { toActivityPlayHttpError } from './errors';
38
+
39
+ export const ACTIVITY_PLAY_CARD_TYPE = 'activity-play';
40
+
41
+ /**
42
+ * 入参不做 JSON 预解析(评审返修二轮):本域三字段(activityRef/keyword/limit)契约恒为
43
+ * string;通用 JSON 转换会先把 '1.20'→1.2、'1e3'→1000 丢成 number——引用恰好撞上另一
44
+ * 目录项造成串答(HTTP 同 ref 却返回不同活动)。引擎级 harden(sanitizeLlmToolInput:
45
+ * null 系键清洗)已在装配期统一承担,模块侧**保留原始字符串**直交归一层单源校验
46
+ * (与 HTTP 同参同果)。
47
+ */
48
+
49
+ /** 工具失败事实(可辨识错误码 + 安全文案;与 HTTP 信封同 code 面——errors.ts 单源分类) */
50
+ function toFailureFact(err: unknown): {
51
+ found: false;
52
+ errorCode: string;
53
+ message: string;
54
+ } {
55
+ const httpError = toActivityPlayHttpError(err);
56
+ return { found: false, errorCode: httpError.code, message: httpError.message };
57
+ }
58
+
59
+ /** 状态中文口径(答话事实与卡片 import 一致——同一活动对象派生) */
60
+ function statusTextOf(status: ActivityPlayActivity['status']): string {
61
+ switch (status) {
62
+ case 'not_started': return '未开始';
63
+ case 'active': return '进行中';
64
+ case 'ended': return '已结束';
65
+ case 'disabled': return '已停用';
66
+ }
67
+ }
68
+
69
+ /** 答话事实条目(capture 剥离 data 后模型答话的完整依据——不及顶层即不完整) */
70
+ function activityFactOf(activity: ActivityPlayActivity) {
71
+ return {
72
+ activityRef: activity.activityRef,
73
+ title: activity.title,
74
+ status: activity.status,
75
+ statusText: statusTextOf(activity.status),
76
+ loginRequired: activity.loginRequired,
77
+ ...(activity.description ? { description: activity.description } : {}),
78
+ ...(activity.startsAt ? { startsAt: activity.startsAt } : {}),
79
+ ...(activity.endsAt ? { endsAt: activity.endsAt } : {}),
80
+ };
81
+ }
82
+
83
+ function cardNoteOf(items: readonly ActivityPlayActivity[]): string {
84
+ // note 内容契约:120 字符内承载主体+关键事实,最重要信息放最前,不复述顶层 facts
85
+ const titles = items.slice(0, 3).map((item) => item.title).join('、');
86
+ const tail = items.length > 3 ? ` 等 ${items.length} 项` : '';
87
+ return `活动玩法 ${items.length} 项 · ${titles}${tail}`.slice(0, 120);
88
+ }
89
+
90
+ export function createActivityPlayTools(opts: { getCtx: () => ServerContext }) {
91
+ const listActivityPlays = createTool({
92
+ id: 'listActivityPlays',
93
+ description:
94
+ '查询当前商场登记的活动玩法目录(大转盘、抽奖、签到、互动游戏等),可用 keyword 按名称或说明过滤、limit 控制返回数量(缺省 20);只读查询,不执行参与或抽奖。',
95
+ inputSchema: z.object({
96
+ keyword: z.string().optional(),
97
+ limit: z.string().optional(),
98
+ }),
99
+ execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
100
+ const reqCtx: RequestContext = requireToolRequestContext(execCtx, 'listActivityPlays');
101
+ const ctx = opts.getCtx();
102
+ try {
103
+ const limit = normalizeListLimit(typeof args.limit === 'string' ? args.limit : undefined);
104
+ const keyword = normalizeKeyword(typeof args.keyword === 'string' ? args.keyword : undefined);
105
+ const page = await queryActivityPlayList(reqCtx, ctx, {
106
+ ...(keyword ? { keyword } : {}),
107
+ limit,
108
+ });
109
+ if (page.items.length === 0) {
110
+ // 空结果事实(目录空或关键词无匹配):不是错误,不产卡片候选
111
+ return {
112
+ found: false as const,
113
+ count: 0,
114
+ ...(keyword ? { keyword } : {}),
115
+ noResultsReason: keyword
116
+ ? `当前商场没有匹配「${keyword}」的活动玩法`
117
+ : '当前商场暂未登记活动玩法',
118
+ };
119
+ }
120
+ const mallId = requireMallIdOf(reqCtx);
121
+ const data = { mallId, mode: 'list' as const, items: page.items };
122
+ activityPlayCardDataSchema.parse(data); // 出卡侧自证(强 schema 签名位,坏数据显性失败而非静默出池)
123
+ const facts = {
124
+ found: true as const,
125
+ mallId,
126
+ mode: 'list' as const,
127
+ count: page.items.length,
128
+ truncated: page.items.length === limit, // 列表被 limit 截断不等同没有更多活动——提示模型勿冒称总数
129
+ items: page.items.map(activityFactOf),
130
+ // loginRequired false 只说明本系统目录不要求先登录——不得引申“参与无需登录/已具备资格”;
131
+ // 活动方/插件侧的实际要求以活动页面为准(评审返修:收紧过度承诺)
132
+ notice: '活动玩法为本地登记目录;参与须在活动页面完成。loginRequired 仅说明本系统是否要求先登录,活动方实际要求(登录/资格)以活动页面为准;查询结果不代表参与资格。',
133
+ };
134
+ return { ...facts, cards: [{ cardType: ACTIVITY_PLAY_CARD_TYPE, data, note: cardNoteOf(page.items) }] };
135
+ } catch (err) {
136
+ return toFailureFact(err);
137
+ }
138
+ },
139
+ });
140
+
141
+ const getActivityPlayDetail = createTool({
142
+ id: 'getActivityPlayDetail',
143
+ description:
144
+ '按 activityRef 查询当前商场指定活动玩法的详情(名称、说明、开始/结束时间与当前状态);用户只说名称时先用 listActivityPlays 拿到 activityRef 再查详情。只读查询,不含参与入口,不代表登录或参与资格。',
145
+ inputSchema: z.object({
146
+ activityRef: z.string(),
147
+ }),
148
+ execute: async (args: Record<string, unknown>, execCtx: ToolExecContextLike) => {
149
+ const reqCtx: RequestContext = requireToolRequestContext(execCtx, 'getActivityPlayDetail');
150
+ const ctx = opts.getCtx();
151
+ try {
152
+ const activityRef = normalizeActivityRef(typeof args.activityRef === 'string' ? args.activityRef : '');
153
+ const activity = await queryActivityPlayDetail(reqCtx, ctx, activityRef);
154
+ if (!activity) {
155
+ return {
156
+ found: false as const,
157
+ errorCode: 'ACTIVITY_NOT_FOUND',
158
+ message: `未找到活动玩法: ${activityRef}`,
159
+ };
160
+ }
161
+ const mallId = requireMallIdOf(reqCtx);
162
+ const data = { mallId, mode: 'detail' as const, items: [activity] };
163
+ activityPlayCardDataSchema.parse(data); // 出卡侧自证(同上——含 detail 恰一约束)
164
+ const facts = {
165
+ found: true as const,
166
+ mallId,
167
+ mode: 'detail' as const,
168
+ ...activityFactOf(activity),
169
+ notice: activity.loginRequired
170
+ ? '本系统目录要求先登录;参与须在活动页面完成。活动方实际要求与参与资格以活动页面为准。'
171
+ : '本系统目录不要求登录;参与须在活动页面完成。活动方是否要求登录或资格以活动页面为准,本结果不代表参与资格。',
172
+ };
173
+ return {
174
+ ...facts,
175
+ cards: [{ cardType: ACTIVITY_PLAY_CARD_TYPE, data, note: `活动详情 · ${activity.title} · ${statusTextOf(activity.status)}` }],
176
+ };
177
+ } catch (err) {
178
+ return toFailureFact(err);
179
+ }
180
+ },
181
+ });
182
+
183
+ return {
184
+ listActivityPlays: withCardEmissionHint(listActivityPlays),
185
+ getActivityPlayDetail: withCardEmissionHint(getActivityPlayDetail),
186
+ };
187
+ }
@@ -0,0 +1,65 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "module-activity-play",
4
+ "name": "活动玩法",
5
+ "description": "查询商圈活动玩法目录(HTTP 列表/详情、只读工具出卡)并准备参与入口(本地插件目标)",
6
+ "version": "0.3.0",
7
+ "kind": "business",
8
+ "risk": {
9
+ "level": "low",
10
+ "writeBoundary": "source"
11
+ },
12
+ "distribution": {
13
+ "defaultMode": "codegen"
14
+ },
15
+ "dependencies": {
16
+ "modules": [
17
+ {
18
+ "id": "contracts-mall",
19
+ "required": true
20
+ }
21
+ ]
22
+ },
23
+ "env": [],
24
+ "declare": {
25
+ "handlers": [],
26
+ "tools": [
27
+ "listActivityPlays",
28
+ "getActivityPlayDetail"
29
+ ],
30
+ "cards": [
31
+ {
32
+ "cardType": "activity-play",
33
+ "schemaVersion": 1
34
+ }
35
+ ],
36
+ "routes": [],
37
+ "pages": [],
38
+ "tabs": [],
39
+ "resources": [],
40
+ "consumes": [
41
+ {
42
+ "service": "activity-play.query",
43
+ "optional": false
44
+ },
45
+ {
46
+ "service": "activity-play.entry",
47
+ "optional": true
48
+ }
49
+ ],
50
+ "owns": [
51
+ {
52
+ "service": "activity-play.query"
53
+ },
54
+ {
55
+ "service": "activity-play.entry"
56
+ },
57
+ {
58
+ "service": "activity-play.prizes"
59
+ }
60
+ ],
61
+ "skills": [
62
+ "activity-play"
63
+ ]
64
+ }
65
+ }