@qingflow-tech/qingflow-cli 1.1.46 → 1.1.47-beta.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.
package/README.md CHANGED
@@ -7,7 +7,7 @@ Qingflow CLI 是轻流面向开发者和 AI Agent 的命令行工具。它把轻
7
7
  ## 安装
8
8
 
9
9
  ```bash
10
- npm install @qingflow-tech/qingflow-cli@1.1.46
10
+ npm install @qingflow-tech/qingflow-cli@1.1.47-beta.2
11
11
  ```
12
12
 
13
13
  推荐从官网复制这一条一键安装 Qingflow CLI:
@@ -21,7 +21,7 @@ npx qingflow-cli@latest install
21
21
  ## 运行
22
22
 
23
23
  ```bash
24
- npx -y -p @qingflow-tech/qingflow-cli@1.1.46 qingflow
24
+ npx -y -p @qingflow-tech/qingflow-cli@1.1.47-beta.2 qingflow
25
25
  ```
26
26
 
27
27
  全局安装后可以直接运行:
@@ -62,7 +62,7 @@ qingflow-skills install --agent codex --scope user
62
62
  如果你通过一次性 `npx -p` 执行 skills 安装,建议加 `--copy`,避免 symlink 指向 npm 临时执行缓存:
63
63
 
64
64
  ```bash
65
- npx -y -p @qingflow-tech/qingflow-cli@1.1.46 qingflow-skills install --agent codex --scope user --copy
65
+ npx -y -p @qingflow-tech/qingflow-cli@1.1.47-beta.2 qingflow-skills install --agent codex --scope user --copy
66
66
  ```
67
67
 
68
68
  `qingflow-skills install` 默认使用 symlink,且遇到同名 skill 不会覆盖;只有显式传入 `--force` 才会替换。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qingflow-tech/qingflow-cli",
3
- "version": "1.1.46",
3
+ "version": "1.1.47-beta.2",
4
4
  "description": "Human-friendly Qingflow command line interface for auth, record operations, import, tasks, and stable builder flows.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "qingflow-mcp"
7
- version = "1.1.46"
7
+ version = "1.1.47b2"
8
8
  description = "User-authenticated MCP server for Qingflow"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -124,6 +124,16 @@ qingflow auth login \
124
124
  qingflow --json auth whoami
125
125
  ```
126
126
 
127
+ ### 交付网页资源链接
128
+
129
+ 应用包、应用、视图和安装回执里的 `uri` 是稳定入口。纯查询和中间读取不签发票据。用户需要页面链接时,取该 URI 的 pathname 执行:
130
+
131
+ ```bash
132
+ qingflow auth login-link --redirect-path "/resources/ws/<WS_ID>/app/<APP_KEY>"
133
+ ```
134
+
135
+ 目标浏览器状态未知时,每个要交付的资源分别执行一次,不能复用之前签发或已经消费的链接。只有用户确认目标是同一浏览器、网页域名、账号和工作区且已登录,才直接交付稳定 `uri`。CLI 已登录、自动化浏览器已登录或曾经成功签发票据都不能证明目标浏览器已登录。用户只要链接时不要提前打开;签发失败时说明需要登录,并提供稳定 `uri` 作为备用入口。
136
+
127
137
  常用参数:`--credential-stdin`、`--password-stdin`、`--persist` / `--forget-persisted`;详见 `qingflow auth --help`。
128
138
 
129
139
  ---
@@ -439,14 +449,28 @@ qingflow auth logout --forget-persisted
439
449
 
440
450
  | 分组 | 骨架(细则见上文章节 + 「关联文件」) |
441
451
  | ---- | ------------------------------------ |
442
- | **auth** | `auth whoami` · `auth use-credential --base-url "$QINGFLOW_BASE_URL" --credential-stdin --persist` · `auth login …`(见「失败恢复时的认证方式」)· `auth logout --forget-persisted` |
452
+ | **auth** | `auth whoami` · `auth use-credential --base-url "$QINGFLOW_BASE_URL" --credential-stdin --persist` · `auth login …`(见「失败恢复时的认证方式」)· `auth login-link [--redirect-path PATH]`(临时网页登录链接)· `auth logout --forget-persisted` |
443
453
  | **workspace** | `workspace list` · `workspace get --ws-id` · `workspace select`(慎用,可读数前不必;可能 **59004**) |
444
454
  | **app / portal / view / chart** | `app list [--query 关键词]` → **`app get --app-key`**(`accessible_views` / `view_id`、`import_capability`)· `builder package list [--query 关键词]` → `builder package get --package-id` · `portal list` · `portal get --dash-key` · `view get --view-id`(只读视图元信息;`baseInfo` 或 `viewConfig` 只有 40002 / 40027 / 404 这类权限/缺失边界可用另一侧降级,非权限类后端错误不隐藏;解析 app 仅依赖同源 view/form 与可见应用树,不回退旧应用搜索)· `chart get --chart-id`(图表 `baseInfo` / 数据 / 配置分阶段读取;单个辅助阶段 40002 / 40027 / 404 只作为 warning,非权限类后端错误不隐藏) |
445
455
  | **record** | `record schema insert`(新建记录 insert-ready schema,仅 `--app-key`)· **`browse`/`list`/`access`:`--app-key` + `--view-id`(缺一常 CONFIG)** · `record list --query ... [--query-field FIELD_ID] [--page-size N]` 用于候选定位/样本浏览 · `record get --record-id` 读详情页首屏上下文 · `record logs --record-id` 读完整数据/流程日志 JSONL · `record insert --items-file`(单条也是 items 一行)· `schema update --record-id [--view-id]` / **`update`**(单条 `--fields-file` **或** 批量 `--items-file`/`--dry-run`,二者勿混)· `record delete --app-key --record-id --view-id system:*` / `--record-ids-file` · `export start/direct --view-id` 仅用于明确导出文件 · **大 schema**:先 **[FIELD_DATA_TYPES](./reference/core/QINGFLOW_CLI_FIELD_DATA_TYPES.md)** / **[RECORD_CREATE](./reference/record/QINGFLOW_CLI_RECORD_CREATE_WORKFLOW.md)** / **[RECORD_UPDATE](./reference/record/QINGFLOW_CLI_RECORD_UPDATE_WORKFLOW.md)** / **[RECORD_DELETE](./reference/record/QINGFLOW_CLI_RECORD_DELETE_WORKFLOW.md)**,再 `-h` |
446
456
  | **import** | `record schema import?` · `import template` → `verify` → `repair?` → `start`(**`being-enter-auditing` 必填**)→ `status`(**三者 selector 只选一**);导入权限预检的 `baseInfo` 只有 40002 / 40027 / 404 可降级为 unknown,非权限错误不能当成无导入权或继续执行;**链路与本机目录**只靠本节不够 → **[RECORD_IMPORT](./reference/record/QINGFLOW_CLI_RECORD_IMPORT_WORKFLOW.md)** |
447
- | **builder** | **搭建/系统化配置**:先按 **[INDEX](./reference/00-INDEX.md)** / **[BUILDER](./reference/builder/README.md)** 选主路径,再读 `builder contract`。**完整系统/应用包**:`builder package apply --config-file` → 每个应用依次执行 `builder app-form schema`、更新时 `get --app-key APP_KEY --being-draft`、`validate --schema-version VERSION --file DECLARATION.json`、`apply --file DECLARATION.json`(固定版本、完整声明、记录返回的 `appKey`)→ 视图(按钮随视图 `action_buttons` 写)→ 门户(缺报表时写 `chart`)→ 发布/回读。旧 `schema apply` / `layout apply` 不在当前 CLI parser 中。超时、`partial_success`、`write_executed=true`、`safe_to_retry=false` 或回读不完整时先读取 AppForm draft/published,再恢复,不得重复创建或创建 V2/测试/随机后缀绕过重名。**单应用**:新建和更新遵循同一 AppForm CLI 链路,再按需求配置流程/视图。更新动作归入对应资源文档:AppForm [30](./reference/builder/30-schema-fields.md)、视图 [50](./reference/builder/50-views.md)、报表 [60](./reference/builder/60-charts.md)、门户 [70](./reference/builder/70-portal.md)、关联资源/非主链路按钮维护 [80](./reference/builder/80-buttons-associated-resources.md)、流程 [90](./reference/builder/90-workflow.md)、发布 [99](./reference/builder/99-publish-verify.md)。 |
457
+ | **builder** | **搭建/系统化配置**:先按 **[INDEX](./reference/00-INDEX.md)** / **[BUILDER](./reference/builder/README.md)** 选主路径,再读 `builder contract`。**完整系统/应用包**:`builder package apply --config-file` → 每个应用依次执行 `builder app-form schema`、更新时 `get --app-key APP_KEY --being-draft`、`validate --schema-version VERSION --file DECLARATION.json`、`apply --file DECLARATION.json`(固定版本、完整声明、记录返回的 `appKey`)→ 视图(按钮随视图 `action_buttons` 写)→ 门户(缺报表时写 `chart`)→ 发布/回读。旧 `schema apply` / `layout apply` 不在当前 CLI parser 中。超时、`partial_success`、`write_executed=true`、`safe_to_retry=false` 或回读不完整时先读取 AppForm draft/published,再恢复,不得重复创建或创建 V2/测试/随机后缀绕过重名。**单应用**:新建和更新遵循同一 AppForm CLI 链路,再按需求配置流程/视图。更新动作归入对应资源文档:AppForm [30](./reference/builder/30-schema-fields.md)、视图 [50](./reference/builder/50-views.md)、报表 [60](./reference/builder/60-charts.md)、门户 [70](./reference/builder/70-portal.md)、关联资源/非主链路按钮维护 [80](./reference/builder/80-buttons-associated-resources.md)、流程 [90](./reference/builder/90-workflow.md)、发布 [99](./reference/builder/99-publish-verify.md)。**AI 公式/代码块校验**:`builder app-form validate-formula --app-key KEY --formula '<公式>' --test-case <文件路径>`(`--formula` 内联;`--test-case` **只收文件路径或 `-` stdin,不收内联 JSON**)与 `builder app-form validate-code-block --app-key KEY --code <内联文本|@文件路径> --test-case <文件路径>`(本地静态 + 后端真跑,输出 `staticErrors` / `runResult` / `runError`);两者是公式/代码块生成场景的真实校验命令,校验结论必须来自其真实执行,不得以本地模拟替代。代码内占位符 `qf_field.{字段名$$queId$$}`(**字段名不带引号**,带引号会被 CLI 自动剥离但勿依赖)与 `keyQueId` 均使用**十进制** queId(CLI 真跑前自动编码为运行时形态;错误回显自动还原为十进制,勿逆向编码 id)。test-case values 按类型:文本/电话=字符串、数字=数字字面量、日期=yyyy-MM-dd、附件=URL 字符串数组、单选/下拉/多选=选项文案(CLI 自动译为选项 id)、成员/部门=不可提供(代码判空,覆盖校验豁免)。 |
448
458
  | **task**(须落盘见上文) | `task list [--task-box][--flow-status][--app-key][--query] --page --page-size`(**枚举、`--query`、与 `record` 视图口径勿混**:见上文 SOP · **[TASK_CONTEXT](./reference/task/QINGFLOW_CLI_TASK_CONTEXT_WORKFLOW.md)**)· **`get`/`log`/`report`/`action`**:默认只传 `task list` 返回的 **`data.items[].task_id`**;`report` 另须必选 **`--report-id`**;`action` **无 `--dry-run`** |
449
459
 
460
+ ### 临时网页登录链接
461
+
462
+ 仅在用户需要进入网页查看或继续操作时生成,纯数据查询不自动调用:
463
+
464
+ ```bash
465
+ qingflow --json auth login-link
466
+ qingflow --profile default --json auth login-link --redirect-path "/index/app/123?view=abc"
467
+ ```
468
+
469
+ - 默认使用当前会话和已选工作区;缺失时按实际错误恢复,不额外预查或重新登录。
470
+ - `--redirect-path` 可选,仅接受已确认的站内业务路径,可包含 query/hash;不接受外域或认证入口。示例 ID 仅作格式展示,不得照抄或编造实际目标;省略时进入工作区首页。
471
+ - 将返回的 `url` 作为可点击链接交付,不修改或拼造。链接短时有效且仅可使用一次,失效后重新获取,不写入公共文档或日志。
472
+ - 命令不会自动打开浏览器;用户仅索取链接时不提前打开,明确要求打开时才调用浏览器。
473
+
450
474
  **高发必败**:旧应用搜索入口 · **`record list`/`browse`/`access` 缺 `--view-id`** · **`task report` 缺 `--report-id`** · **`record update` 批量与单条参数混用**。
451
475
 
452
476
  更多成员策略:**[reference/QINGFLOW_CLI_MEMBER_CHEATSHEET.md](./reference/core/QINGFLOW_CLI_MEMBER_CHEATSHEET.md)** · 一次性长模板:**[reference/QINGFLOW_CLI_ONE_SHOT_CHEATSHEET.md](./reference/core/QINGFLOW_CLI_ONE_SHOT_CHEATSHEET.md)** · 对齐说明:**[reference/QINGFLOW_CLI_EXPLORATION_REPORT.md](./reference/core/QINGFLOW_CLI_EXPLORATION_REPORT.md)**。
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: qingflow-common
3
- description: Route Qingflow work through the shared public concepts and choose the matching CLI or MCP package. Use when comparing Qingflow CLI and MCP capabilities, selecting an execution surface, or handing work between record, task, form, workflow, and builder skills.
3
+ description: 解释轻流公共业务概念并选择 CLI 或 MCP 入口。用于能力比较、记录与任务操作、表单与流程搭建的任务分流,以及从 AI 对话进入页面查看结果、继续编辑、处理业务或进入工作区的场景。
4
4
  ---
5
5
 
6
6
  # Qingflow Common Concepts
@@ -31,6 +31,7 @@ Do not require both surfaces. If only one is installed, complete the workflow on
31
31
  | Form schema/read/apply/delete | `qingflow --json builder app-form ...` / `builder app delete` | `app_form_schema`, `app_form_get`, `app_form_apply`, `app_delete` |
32
32
  | AppForm static validation | `qingflow --json builder app-form validate --file ...` | Performed inside `app_form_apply`; no separate tool |
33
33
  | Record and task work | `qingflow --json record ...` / `task ...` | Qingflow MCP record and task tools |
34
+ | 免登录打开网页或指定业务页面 | `qingflow --json auth login-link [--redirect-path PATH]` | `get_login_link` |
34
35
  | Package, view, portal, chart, workflow | `qingflow --json builder ...` | Qingflow MCP configuration tools |
35
36
 
36
37
  The operation names and payload schemas are defined by the public surface. Use the current Schema or tool input schema as the source of truth, not a legacy command name or backend payload.
@@ -42,6 +43,25 @@ The operation names and payload schemas are defined by the public surface. Use t
42
43
 
43
44
  Each package includes this common Skill. The CLI package installs its CLI guidance; the MCP package installs every MCP domain Skill. The source of every packaged Skill is `qingflow-support/mcp-server/skills/`.
44
45
 
46
+ ## 从 AI 对话进入轻流页面
47
+
48
+ 用户需要查看结果、继续编辑、处理业务或进入工作区页面时,优先使用业务输出中的稳定 `uri` 确定目标。纯数据查询和中间读取不自动签发链接。MCP 调用 `get_login_link`;CLI 调用 `qingflow --json auth login-link --redirect-path <资源 pathname>`。
49
+
50
+ - 目标路径使用用户提供或业务工具确认的站内路径,不根据应用、记录标识猜测地址。
51
+ - 用户明确指定页面但路径未知时继续定位或说明限制,不猜测,也不静默替换成首页。搜索未命中时继续搜索 `login` 或查看服务工具列表,不擅自打开固定正式站点;失败时如实说明。
52
+
53
+ - 默认使用当前会话及已选工作区;需要指定会话时使用 MCP 的 `profile` 或 CLI 的 `--profile`。
54
+ - `redirect_path` 可选,默认空:省略时进入工作区首页;传入时仅支持以单个 `/` 开头的站内业务路径,可带 query/hash。不得传完整 URL、外部地址、认证入口或多层编码路径。
55
+ - 示例:`get_login_link({})`;指定目标示例:`get_login_link({"redirect_path":"/index/app/123?view=abc"})`。示例标识仅作格式展示,实际目标必须来自用户提供或已经确认的页面信息,不得编造应用、记录标识。
56
+ - 成功响应仅有 `url` 和毫秒整数 `expires_at`。临近交付时再签发,使用本次返回的完整链接,文案贴合“查看记录”“继续编辑”等上下文,不展示工作区数字 ID 或原始 JSON。
57
+ - CLI 示例:`qingflow --json auth login-link`;指定目标使用 `qingflow --profile default --json auth login-link --redirect-path "/index/app/123?view=abc"`,同样不得编造实际路径。
58
+ - 目标浏览器状态未知时,默认按每个待交付资源分别签发新链接。只有用户确认目标是同一浏览器、网页域名、账号和工作区且已登录,才直接交付稳定 `uri`。调用过票据工具、自动化浏览器已登录或之前签发过票据都不是该事实;已消费链接不可复用。
59
+ - 链接约 5 分钟内只能兑换一次,不作为长期书签;过期或使用后重新调用,不修改票据或拼造链接;只交付给请求用户,不写入公共文档或日志。
60
+ - 用户要求“给我链接”时仅交付,不提前消费;要求“打开”时才使用可用浏览器打开。浏览器不可用时提供可点击链接,不假称已经打开。
61
+ - 签发失败时明确说明需要登录,并提供业务输出中的稳定 `uri` 作为备用入口。
62
+ - 必要的 MFA、密码安全验证仍执行,完成后先切换当前 MCP 工作区,再进入目标页面;业务权限仍由目标页面校验,不因链接而扩大。
63
+ - 工具拒绝非法跳转参数;浏览器收到被篡改的非法目标时忽略目标并进入首页。网页域名由 MCP 配置 `QINGFLOW_MCP_WEB_BASE_URL` 决定,不从目标路径选择其他环境。
64
+
45
65
  ## Route Next
46
66
 
47
67
  Use the installed package's relevant domain Skill. In the unified MCP package, select the Skill by the requested work, not by an assumed user or builder server role. Do not link to or invoke a domain Skill that the current package did not install.
@@ -24,6 +24,8 @@ _INTEGRATION_OUTPUT_TARGET_FIELD_TYPES = {
24
24
  }
25
25
  _Q_LINKER_TEMPLATE_RE = re.compile(r"\{\{(?P<key>[^{}\s]+)\}\}")
26
26
  _FORMULA_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
27
+ #: 公式字段引用正则(#queId_<id>$,支持表格嵌套 <id>.<id>)
28
+ _FORMULA_FIELD_REF_RE = re.compile(r"#queId_([^$]+)\$")
27
29
 
28
30
 
29
31
  class AppFormValidationError(ValueError):
@@ -460,3 +462,305 @@ def validate_declaration(
460
462
  issues = [{"pointer": pointer, "message": message} for pointer, message in sorted(found)]
461
463
  raise AppFormValidationError(issues, schema_version=pinned, api_version=api_version)
462
464
  return {"valid": True, "schemaVersion": pinned, "apiVersion": api_version, "fieldTypes": list(types)}
465
+
466
+
467
+ def validate_formula_expression(
468
+ formula: str,
469
+ fields: list[dict[str, Any]] | None = None,
470
+ ) -> list[dict[str, str]]:
471
+ """校验单条公式表达式:函数名合法 + 字段引用存在性。不依赖整份 AppForm,不调后端。
472
+
473
+ Args:
474
+ formula: 公式文本,如 ``CONCAT(#queId_101$, ":", #queId_102$)``。
475
+ fields: 字段清单 ``[{queId, name}]``(兼容 ``que_id``/``id``);提供时校验字段引用存在性,
476
+ 不提供时跳过字段引用校验。
477
+ Returns:
478
+ 错误列表 ``[{pointer, message}]``,空列表表示本地语法通过。
479
+ """
480
+ errors: list[dict[str, str]] = []
481
+ if not isinstance(formula, str) or not formula.strip():
482
+ errors.append({"pointer": "formula", "message": "formula is empty"})
483
+ return errors
484
+
485
+ # 函数名合法性(复用 AppForm formula Schema 的函数目录)
486
+ supported = _supported_formula_functions("v1alpha1")
487
+ unknown = sorted(
488
+ name for name in _formula_function_calls(formula) if name.upper() not in supported
489
+ )
490
+ for name in unknown:
491
+ errors.append({"pointer": "formula", "message": f"unsupported formula function '{name}'"})
492
+
493
+ # 字段引用存在性(#queId_<id>$,支持表格嵌套 <id>.<id>,按叶子 id 与原始 id 双重匹配)
494
+ if fields:
495
+ known_ids = {
496
+ str(identifier)
497
+ for field in fields
498
+ if isinstance(field, dict)
499
+ for identifier in (
500
+ field.get("queId"),
501
+ field.get("que_id"),
502
+ field.get("id"),
503
+ )
504
+ if identifier is not None and str(identifier) != ""
505
+ }
506
+ for match in _FORMULA_FIELD_REF_RE.finditer(formula):
507
+ raw_id = match.group(1)
508
+ leaf_id = raw_id.split(".")[-1]
509
+ if leaf_id not in known_ids and raw_id not in known_ids:
510
+ errors.append(
511
+ {
512
+ "pointer": "formula",
513
+ "message": f"field reference '{match.group(0)}' refers to unknown queId {raw_id}",
514
+ }
515
+ )
516
+ return errors
517
+
518
+
519
+ def validate_code_block_static(code: str) -> list[dict[str, str]]:
520
+ """校验代码块静态结构:qf_output 赋值 + 基本语法。不调后端。
521
+
522
+ Args:
523
+ code: 代码文本。
524
+ Returns:
525
+ 错误列表 ``[{pointer, message}]``,空列表表示本地静态校验通过。
526
+ """
527
+ errors: list[dict[str, str]] = []
528
+ if not isinstance(code, str) or not code.strip():
529
+ errors.append({"pointer": "code", "message": "code is empty"})
530
+ return errors
531
+
532
+ # qf_output 必须直接赋值(不能用 const/let 声明);仅当代码涉及 outputs 绑定时才提示
533
+ has_qf_output = bool(re.search(r"(^|[^A-Za-z0-9_$])qf_output\s*=(?!=)", code))
534
+ has_outputs_binding = "outputs" in code
535
+ if not has_qf_output and has_outputs_binding:
536
+ errors.append(
537
+ {
538
+ "pointer": "code",
539
+ "message": "code declares outputs but does not assign qf_output; "
540
+ "use 'qf_output = {...}' (not const/let)",
541
+ }
542
+ )
543
+ return errors
544
+
545
+
546
+ # ---------------------------------------------------------------------------
547
+ # 代码块字段占位符编码
548
+ #
549
+ # 后端 codeBlockTest 运行时通过 CustomPushContentConverter.getQueId 解码代码里的
550
+ # ``qf_field.{label$$<encoded>$$}`` 段(私有混淆编码,非十进制),再按解码出的十进制
551
+ # queId 匹配 --test-case 的 keyQueId 填值;匹配不上会静默跳过(占位符原样留跑)。
552
+ # AI 生成的代码按十进制 queId 书写(与 skill/编辑器上下文一致),本模块在真跑前把
553
+ # 纯数字的 ``$$<digits>$$`` 段编码为运行时形态——与后端采纳链路(encryptQueId)同一
554
+ # 编码、同一"纯数字才编码"规则,已编码(含字母)的段原样保留,避免双重编码。
555
+ # ---------------------------------------------------------------------------
556
+
557
+ _ENC_KEY = 1000013
558
+ _INT_TO_HEX = "0123456789ABCDEF"
559
+ _DECIMAL_PLACEHOLDER = re.compile(r"\$\$(-?\d+)\$\$")
560
+
561
+
562
+ def encode_que_id(que_id: int) -> str:
563
+ """Java ``CustomPushContentConverter.encryptQueId`` 的逐行为等价移植。"""
564
+ have_prefix = que_id < 0
565
+ abs_id = abs(que_id)
566
+ ran = abs_id * 17
567
+ inp = str(abs_id)
568
+ seeds: list[int] = []
569
+ salt_sum = 0
570
+ for _ in range(max(0, 4 - len(inp))):
571
+ tmp = (ran % 20) + 71
572
+ ran = ((ran + 13) * 17) % _ENC_KEY
573
+ salt_sum += tmp
574
+ seeds.append(tmp)
575
+ result = [(salt_sum + i + int(ch, 16)) % 15 for i, ch in enumerate(inp)]
576
+ for seed in seeds:
577
+ pos = (ran + seed) % len(result)
578
+ ran = ((ran + 13) * 17) % _ENC_KEY
579
+ result.insert(pos, seed)
580
+ encoded = "".join(chr(value) if value > 15 else _INT_TO_HEX[value] for value in result)
581
+ return ("-" if have_prefix else "") + encoded
582
+
583
+
584
+ def encode_code_block_field_ids(code: str) -> str:
585
+ """把代码里的十进制 queId 占位符段编码为后端运行时形态。
586
+
587
+ 仅处理纯数字(可带负号)的 ``$$...$$`` 段;混有字母的段视为已编码,原样保留。
588
+ """
589
+ if not isinstance(code, str):
590
+ return code
591
+ return _DECIMAL_PLACEHOLDER.sub(
592
+ lambda match: f"$${encode_que_id(int(match.group(1)))}$$", code
593
+ )
594
+
595
+
596
+ def referenced_code_block_field_ids(code: str) -> set[int]:
597
+ """提取代码里以十进制 queId 引用的字段 id 集合(供 test-case 覆盖校验)。
598
+
599
+ 只统计纯数字(可带负号)的 ``$$...$$`` 段;已编码(含字母)段解码依赖后端实现,
600
+ 不在此覆盖校验范围内。
601
+ """
602
+ if not isinstance(code, str):
603
+ return set()
604
+ return {int(match.group(1)) for match in _DECIMAL_PLACEHOLDER.finditer(code)}
605
+
606
+
607
+ # ---------------------------------------------------------------------------
608
+ # 代码块校验的占位符容错与回显还原
609
+ #
610
+ # 现场问题(agent 实测):
611
+ # 1. 模型常把占位符写成 qf_field.{"字段名$$id$$"} —— 字段名带引号。后端替换正则要求
612
+ # 结尾恰为 `$$}`,带引号变成 `$$"}` 匹配失败,占位符原样留在代码里直接语法错误。
613
+ # 这里在编码归一化前剥离字段名两侧引号,带引号写法自动修正。
614
+ # 2. CLI 把 `$$十进制$$` 编码为混淆形态后,校验失败的错误回显里是编码 id,模型认不出
615
+ # 是自己写的 queId,会试图逆向"哈希"浪费大量轮次。这里记录 编码→十进制 映射,
616
+ # 输出前把错误文本里的编码段还原为十进制。
617
+ # ---------------------------------------------------------------------------
618
+
619
+ _QUOTED_PLACEHOLDER = re.compile(r'(qf_field\.\{)["\']([^$\'"{]+?)\$\$(-?\d+)\$\$["\'](\})')
620
+
621
+
622
+ def strip_placeholder_quotes(code: str) -> tuple[str, int]:
623
+ """剥离占位符字段名两侧引号:qf_field.{"名$$id$$"} → qf_field.{名$$id$$}。
624
+
625
+ Returns:
626
+ (修正后的代码, 修正处数)
627
+ """
628
+ if not isinstance(code, str):
629
+ return code, 0
630
+ count = 0
631
+
632
+ def _strip(match: re.Match[str]) -> str:
633
+ nonlocal count
634
+ count += 1
635
+ return f"{match.group(1)}{match.group(2)}$${match.group(3)}$$}}"
636
+
637
+ return _QUOTED_PLACEHOLDER.sub(_strip, code), count
638
+
639
+
640
+ def build_encoded_id_map(code: str) -> dict[str, str]:
641
+ """对代码里的纯数字占位段构建 编码形态→十进制 映射(用于错误回显还原)。"""
642
+ if not isinstance(code, str):
643
+ return {}
644
+ return {
645
+ encode_que_id(int(match.group(1))): match.group(1)
646
+ for match in _DECIMAL_PLACEHOLDER.finditer(code)
647
+ }
648
+
649
+
650
+ def restore_decimal_ids_in_text(text: str, id_map: dict[str, str]) -> str:
651
+ """把文本里出现的 `$$<编码>$$` 还原为 `$$<十进制>$$`(错误回显可读化)。"""
652
+ if not isinstance(text, str) or not id_map:
653
+ return text
654
+ for encoded, decimal in id_map.items():
655
+ text = text.replace(f"$${encoded}$$", f"$${decimal}$$")
656
+ return text
657
+
658
+
659
+ # 选择类字段 test-case 值翻译:后端只认选项 optId(数字),传文案静默变 null;
660
+ # 模型不可能知道 optId,这里按字段定义把"选项文案"翻译成 optId。
661
+ _SELECT_FIELD_TYPES = {"single_choice", "single_select", "multi_select"}
662
+ # 值不可推导的字段类型(成员/部门要 uid/部门id,模型无从得知):覆盖校验跳过。
663
+ _UNDERIVABLE_FIELD_TYPES = {"member", "department"}
664
+
665
+
666
+ def translate_select_test_case_values(
667
+ fields: list[dict] | None, key_que_values: list[dict]
668
+ ) -> tuple[list[dict], list[dict[str, str]], list[str]]:
669
+ """把选择类字段的"选项文案"值翻译为 optId。
670
+
671
+ Args:
672
+ fields: 字段定义清单(含 que_id/type/option_details;可为 None 表示未取到)。
673
+ key_que_values: 已规范化的 test-case。
674
+ Returns:
675
+ (翻译后的 test-case, 翻译记录[{queId, from, to}], 无法翻译的选项错误清单)
676
+ """
677
+ if not fields:
678
+ return key_que_values, [], []
679
+ option_lookup: dict[int, dict[str, object]] = {}
680
+ type_by_que: dict[int, str] = {}
681
+ for field in fields:
682
+ if not isinstance(field, dict):
683
+ continue
684
+ que_id = field.get("que_id") or field.get("queId")
685
+ if not isinstance(que_id, int):
686
+ continue
687
+ field_type = str(field.get("type") or "")
688
+ type_by_que[que_id] = field_type
689
+ details = field.get("option_details")
690
+ if isinstance(details, list):
691
+ by_value = {
692
+ str(item.get("value") or "").strip(): item.get("id")
693
+ for item in details
694
+ if isinstance(item, dict) and item.get("id") is not None
695
+ }
696
+ if by_value:
697
+ option_lookup[que_id] = by_value
698
+
699
+ translated = [dict(item) for item in key_que_values]
700
+ changes: list[dict[str, str]] = []
701
+ errors: list[str] = []
702
+ for item in translated:
703
+ key = item.get("keyQueId")
704
+ if not isinstance(key, int) or key not in option_lookup:
705
+ continue
706
+ by_value = option_lookup[key]
707
+ new_values: list[object] = []
708
+ for value in item.get("values") or []:
709
+ text = str(value).strip()
710
+ if text in by_value:
711
+ new_values.append(by_value[text])
712
+ changes.append({"queId": str(key), "from": text, "to": str(by_value[text])})
713
+ elif str(value).isdigit() and int(value) in set(by_value.values()):
714
+ new_values.append(int(value))
715
+ else:
716
+ errors.append(
717
+ f"field queId {key}: 选项「{text}」不存在,可选:{'/'.join(by_value.keys())}"
718
+ )
719
+ new_values.append(value)
720
+ item["values"] = new_values
721
+ return translated, changes, errors
722
+
723
+
724
+ # ---------------------------------------------------------------------------
725
+ # 公式校验的引用提取与选择类值翻译
726
+ #
727
+ # 实测(真实后端 /ai/coding/formula/validate):
728
+ # - 缺值字段静默变空(CONCAT 直接跳过)→ 空洞通过,需要覆盖门;
729
+ # - 单选/多选必须传 **[optId 数组]**:文案/optId 标量均报错;返回值为 optId 串(非文案);
730
+ # - 日期字段裸引用报错,套日期函数(YEAR 等)+ "yyyy-MM-dd" 字符串可用。
731
+ # ---------------------------------------------------------------------------
732
+
733
+ _FORMULA_REFERENCE = re.compile(r"#queId_(\d+)\$")
734
+
735
+
736
+ def referenced_formula_field_ids(formula: str) -> set[int]:
737
+ """提取公式 `#queId_<id>$` 引用的字段 id 集合(供覆盖校验)。"""
738
+ if not isinstance(formula, str):
739
+ return set()
740
+ return {int(m.group(1)) for m in _FORMULA_REFERENCE.finditer(formula)}
741
+
742
+
743
+ def translate_formula_test_case_values(
744
+ fields: list[dict] | None, test_case: dict
745
+ ) -> tuple[dict, list[dict[str, str]], list[str]]:
746
+ """公式 testCase 值归一化(全类型实测契约)。
747
+
748
+ 实测核心规律:**裸引用/函数求值统一要求 [数组] 形态**,标量一律报错(含文本/数字/日期);
749
+ 单选/多选传 ["选项文案"] 数组直接可过且求值结果是文案本身(优于内部 id)。
750
+ 因此本函数只做一件事:把所有标量值包装成 [标量];已是数组原样保留。
751
+
752
+ Args:
753
+ fields: 字段定义(当前未用,保留签名兼容;数组包装与类型无关)。
754
+ test_case: {queId: value} 对象。
755
+ Returns:
756
+ (归一化 test-case, 包装记录, 错误清单——恒空)
757
+ """
758
+ if not isinstance(test_case, dict):
759
+ return test_case, [], []
760
+ translated = dict(test_case)
761
+ changes: list[dict[str, str]] = []
762
+ for key, value in list(translated.items()):
763
+ if not isinstance(value, list):
764
+ translated[key] = [value]
765
+ changes.append({"queId": str(key), "from": f"scalar:{value}", "to": f"[{value}]"})
766
+ return translated, changes, []
@@ -19,6 +19,7 @@ from ..backend_client import BackendRequestContext
19
19
  from ..errors import QingflowApiError, backend_code_int, backend_code_value_int, is_auth_like_error
20
20
  from ..json_types import JSONObject
21
21
  from ..list_type_labels import RECORD_LIST_TYPE_LABELS, SYSTEM_VIEW_ID_TO_LIST_TYPE
22
+ from ..resource_uri import validate_positive_resource_id, validate_resource_identity
22
23
  from ..solution.build_assembly_store import BuildAssemblyStore, default_artifacts, default_manifest
23
24
  from ..solution.compiler.chart_compiler import qingbi_workspace_visible_auth
24
25
  from ..solution.compiler.form_compiler import build_question, default_form_payload, default_member_auth
@@ -1491,6 +1492,74 @@ class AiBuilderFacade:
1491
1492
  details={"solution_key": requested_solution_key},
1492
1493
  suggested_next_call={"tool_name": "solution_install", "arguments": {"profile": profile, **normalized_args}},
1493
1494
  )
1495
+ raw_result = created.get("result") if isinstance(created.get("result"), dict) else {}
1496
+ raw_tag_ids = raw_result.get("tagIds")
1497
+ raw_app_keys = raw_result.get("appKeys")
1498
+ tag_ids, tag_ids_complete = _unique_resource_tag_ids(raw_tag_ids)
1499
+ app_keys, app_keys_complete = _unique_resource_app_keys(raw_app_keys)
1500
+ resource_list_complete = tag_ids_complete and app_keys_complete
1501
+ resources: list[JSONObject] = []
1502
+ warnings: list[JSONObject] = []
1503
+
1504
+ for tag_id in tag_ids:
1505
+ name = None
1506
+ try:
1507
+ detail = self.packages.package_get(profile=profile, tag_id=tag_id, include_raw=False)
1508
+ package = detail.get("result") if isinstance(detail.get("result"), dict) else {}
1509
+ name = str(package.get("tagName") or package.get("tag_name") or "").strip() or None
1510
+ except (QingflowApiError, RuntimeError):
1511
+ pass
1512
+ if not name:
1513
+ warnings.append(_warning("RESOURCE_NAME_UNAVAILABLE", "installed package name could not be read", package_id=tag_id))
1514
+ resources.append(
1515
+ _compact_dict(
1516
+ {
1517
+ "resource_type": "package",
1518
+ "operation": "installed",
1519
+ "status": "success",
1520
+ "id": tag_id,
1521
+ "key": str(tag_id),
1522
+ "name": name,
1523
+ "ids": {"package_id": tag_id},
1524
+ }
1525
+ )
1526
+ )
1527
+
1528
+ for app_key in app_keys:
1529
+ name = None
1530
+ parent = None
1531
+ try:
1532
+ detail = self.apps.app_get_base(profile=profile, app_key=app_key, include_raw=False)
1533
+ app = detail.get("result") if isinstance(detail.get("result"), dict) else {}
1534
+ name = str(app.get("formTitle") or app.get("appName") or "").strip() or None
1535
+ matching_tag_ids = [tag_id for tag_id in _unique_positive_ints(app.get("tagIds")) if tag_id in tag_ids]
1536
+ if len(matching_tag_ids) == 1:
1537
+ parent = {"resource_type": "package", "id": matching_tag_ids[0], "key": str(matching_tag_ids[0])}
1538
+ except (QingflowApiError, RuntimeError):
1539
+ pass
1540
+ if not name:
1541
+ warnings.append(_warning("RESOURCE_NAME_UNAVAILABLE", "installed application name could not be read", app_key=app_key))
1542
+ resources.append(
1543
+ _compact_dict(
1544
+ {
1545
+ "resource_type": "app",
1546
+ "operation": "installed",
1547
+ "status": "success",
1548
+ "key": app_key,
1549
+ "name": name,
1550
+ "ids": {"app_key": app_key},
1551
+ "parent": parent,
1552
+ }
1553
+ )
1554
+ )
1555
+
1556
+ if not resource_list_complete:
1557
+ warnings.append(
1558
+ _warning(
1559
+ "RESOURCE_LIST_INCOMPLETE",
1560
+ "solution installation succeeded, but its returned package/application identity list was incomplete",
1561
+ )
1562
+ )
1494
1563
  return {
1495
1564
  "status": "success",
1496
1565
  "error_code": None,
@@ -1503,9 +1572,15 @@ class AiBuilderFacade:
1503
1572
  "request_id": created.get("request_id"),
1504
1573
  "suggested_next_call": None,
1505
1574
  "noop": False,
1506
- "verification": {},
1575
+ "warnings": warnings,
1576
+ "verified": False,
1577
+ "verification": {
1578
+ "resource_list_complete": resource_list_complete,
1579
+ "business_verified": False,
1580
+ },
1507
1581
  "write_executed": True,
1508
1582
  "safe_to_retry": False,
1583
+ "resources": resources,
1509
1584
  }
1510
1585
 
1511
1586
  def package_list(self, *, profile: str, trial_status: str = "all", query: str = "") -> JSONObject:
@@ -17148,6 +17223,49 @@ def _coerce_positive_int(value: Any) -> int | None:
17148
17223
  return None
17149
17224
 
17150
17225
 
17226
+ def _unique_positive_ints(value: Any) -> list[int]:
17227
+ if not isinstance(value, list):
17228
+ return []
17229
+ result: list[int] = []
17230
+ for item in value:
17231
+ number = _coerce_positive_int(item)
17232
+ if number is not None and number not in result:
17233
+ result.append(number)
17234
+ return result
17235
+
17236
+
17237
+ def _unique_resource_tag_ids(value: Any) -> tuple[list[int], bool]:
17238
+ if not isinstance(value, list):
17239
+ return [], False
17240
+ result: list[int] = []
17241
+ complete = True
17242
+ for item in value:
17243
+ try:
17244
+ tag_id = validate_positive_resource_id(item, "package_id")
17245
+ except (ValueError, UnicodeError):
17246
+ complete = False
17247
+ continue
17248
+ if tag_id not in result:
17249
+ result.append(tag_id)
17250
+ return result, complete
17251
+
17252
+
17253
+ def _unique_resource_app_keys(value: Any) -> tuple[list[str], bool]:
17254
+ if not isinstance(value, list):
17255
+ return [], False
17256
+ result: list[str] = []
17257
+ complete = True
17258
+ for item in value:
17259
+ try:
17260
+ app_key = validate_resource_identity(item, "app_key")
17261
+ except (ValueError, UnicodeError):
17262
+ complete = False
17263
+ continue
17264
+ if app_key not in result:
17265
+ result.append(app_key)
17266
+ return result, complete
17267
+
17268
+
17151
17269
  def _coerce_nonnegative_int(value: Any) -> int | None:
17152
17270
  if isinstance(value, bool) or value is None:
17153
17271
  return None
@@ -21167,6 +21285,11 @@ def _compact_public_field_read(*, field: dict[str, Any], layout: dict[str, Any],
21167
21285
  "required": bool(field.get("required")),
21168
21286
  "section_id": None if nested else _find_field_section_id(layout, str(field.get("name") or "")),
21169
21287
  }
21288
+ if field.get("type") in {FieldType.single_select.value, FieldType.multi_select.value} and field.get(
21289
+ "option_details"
21290
+ ):
21291
+ # 选项 id 透出:validate-code-block 需要把"选项文案"翻译成 optId(后端只认 optId)
21292
+ payload["option_details"] = deepcopy(field.get("option_details"))
21170
21293
  if field.get("type") == FieldType.relation.value:
21171
21294
  payload["target_app_key"] = field.get("target_app_key")
21172
21295
  payload["relation_mode"] = _normalize_relation_mode(field.get("relation_mode"))
@@ -40,11 +40,19 @@ def register(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) ->
40
40
  whoami = auth_subparsers.add_parser("whoami", help="查看当前登录态")
41
41
  whoami.set_defaults(handler=_handle_whoami, format_hint="auth_whoami")
42
42
 
43
+ login_link = auth_subparsers.add_parser("login-link", help="生成当前工作区的临时一次性登录链接(不自动打开)")
44
+ login_link.add_argument("--redirect-path", default="", help="登录后跳转的站内路径;资源路径必须属于当前工作区,其他业务路径可包含查询参数和锚点")
45
+ login_link.set_defaults(handler=_handle_login_link, format_hint="login_link")
46
+
43
47
  logout = auth_subparsers.add_parser("logout", help="退出登录")
44
48
  logout.add_argument("--forget-persisted", action="store_true")
45
49
  logout.set_defaults(handler=_handle_logout, format_hint="")
46
50
 
47
51
 
52
+ def _handle_login_link(args: argparse.Namespace, context: CliContext) -> dict:
53
+ return context.login_link.get_login_link(profile=args.profile, redirect_path=args.redirect_path)
54
+
55
+
48
56
  def _handle_login(args: argparse.Namespace, context: CliContext) -> dict:
49
57
  if args.method == "oauth":
50
58
  return _handle_oauth_login(args, context)