@qingflow-tech/qingflow-cli 1.1.45 → 1.1.47-beta.1

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.45
10
+ npm install @qingflow-tech/qingflow-cli@1.1.47-beta.1
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.45 qingflow
24
+ npx -y -p @qingflow-tech/qingflow-cli@1.1.47-beta.1 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.45 qingflow-skills install --agent codex --scope user --copy
65
+ npx -y -p @qingflow-tech/qingflow-cli@1.1.47-beta.1 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.45",
3
+ "version": "1.1.47-beta.1",
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.45"
7
+ version = "1.1.47b1"
8
8
  description = "User-authenticated MCP server for Qingflow"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -439,14 +439,28 @@ qingflow auth logout --forget-persisted
439
439
 
440
440
  | 分组 | 骨架(细则见上文章节 + 「关联文件」) |
441
441
  | ---- | ------------------------------------ |
442
- | **auth** | `auth whoami` · `auth use-credential --base-url "$QINGFLOW_BASE_URL" --credential-stdin --persist` · `auth login …`(见「失败恢复时的认证方式」)· `auth logout --forget-persisted` |
442
+ | **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
443
  | **workspace** | `workspace list` · `workspace get --ws-id` · `workspace select`(慎用,可读数前不必;可能 **59004**) |
444
444
  | **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
445
  | **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
446
  | **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)。 |
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)。**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
448
  | **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
449
 
450
+ ### 临时网页登录链接
451
+
452
+ 仅在用户需要进入网页查看或继续操作时生成,纯数据查询不自动调用:
453
+
454
+ ```bash
455
+ qingflow --json auth login-link
456
+ qingflow --profile default --json auth login-link --redirect-path "/index/app/123?view=abc"
457
+ ```
458
+
459
+ - 默认使用当前会话和已选工作区;缺失时按实际错误恢复,不额外预查或重新登录。
460
+ - `--redirect-path` 可选,仅接受已确认的站内业务路径,可包含 query/hash;不接受外域或认证入口。示例 ID 仅作格式展示,不得照抄或编造实际目标;省略时进入工作区首页。
461
+ - 将返回的 `url` 作为可点击链接交付,不修改或拼造。链接短时有效且仅可使用一次,失效后重新获取,不写入公共文档或日志。
462
+ - 命令不会自动打开浏览器;用户仅索取链接时不提前打开,明确要求打开时才调用浏览器。
463
+
450
464
  **高发必败**:旧应用搜索入口 · **`record list`/`browse`/`access` 缺 `--view-id`** · **`task report` 缺 `--report-id`** · **`record update` 批量与单条参数混用**。
451
465
 
452
466
  更多成员策略:**[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)**。
@@ -20,6 +20,8 @@ Workflow examples depend on live `builder flow schema`, field ids, role ids, and
20
20
 
21
21
  ## Recommended write path
22
22
 
23
+ - Workflow editing is temporarily unavailable in the CLI. Before a flow write, the CLI reads the current `spec.nodes`; when the current node count exceeds 5, it stops without writing and reports that the feature is under maintenance. The submitted spec node count does not affect this decision.
24
+ - Writes remain available when the current flow has 5 or fewer nodes, including initial workflow creation.
23
25
  - Before applying a workflow, verify the app has an explicit business status select field such as `状态`, `处理状态`, `审批状态`, `工单状态`, `计划状态`, `报工状态`, or `单据状态`. Domain result fields are not enough by themselves: for example, `检验结论` should be paired with `处理状态`.
24
26
  - For workflow creation or replacement, always use `builder flow get` / `builder flow schema`, then submit a complete WorkflowSpec with `--spec-file`.
25
27
  - Do not use `--nodes-file` + `--transitions-file` in skill-led workflow builds. Even simple linear workflows should be represented as WorkflowSpec.
@@ -30,6 +32,8 @@ Workflow examples depend on live `builder flow schema`, field ids, role ids, and
30
32
 
31
33
  All workflow creation and replacement uses WorkflowSpec through `--spec-file`. Existing-node maintenance can use `--patch-nodes-file` after readback. This is the only skill-led workflow write path for linear, branching, Q-Robot, approval, filling, and cc flows.
32
34
 
35
+ While editing is under maintenance, the CLI blocks either input mode when the current flow has more than 5 nodes. It does not reject a creation because the new WorkflowSpec itself has more than 5 nodes.
36
+
33
37
  ## Detailed workflow docs
34
38
 
35
39
  Use [workflow/README.md](./workflow/README.md) for full staged workflow modeling and [workflow/workflow-schema.json](./workflow/workflow-schema.json) for schema validation.
@@ -19,8 +19,8 @@
19
19
  |------|------|
20
20
  | `qingflow builder flow schema --json` | 获取最新 WorkflowSpecDTO JSON Schema |
21
21
  | `qingflow builder flow get --app-key <KEY>` | 读取当前工作流 spec |
22
- | `qingflow --json builder flow apply --app-key <KEY> --spec-file <FILE>` | 主链路:部署/更新 WorkflowSpec |
23
- | `qingflow --json builder flow apply --app-key <KEY> --patch-nodes-file <PATCH>` | 局部修改现有节点 |
22
+ | `qingflow --json builder flow apply --app-key <KEY> --spec-file <FILE>` | 主链路:创建 WorkflowSpec;当前流程节点数超过 5 时,编辑功能维护中 |
23
+ | `qingflow --json builder flow apply --app-key <KEY> --patch-nodes-file <PATCH>` | 局部修改现有节点;当前功能维护中 |
24
24
  | `qingflow builder member search --query <关键词>` | 搜索成员 |
25
25
  | `qingflow builder role search --keyword <关键词>` | 搜索角色 |
26
26
  | `qingflow --json app get --app-key <KEY>` | 获取应用信息(字段列表等) |
@@ -42,7 +42,7 @@
42
42
 
43
43
  ---
44
44
 
45
- 无论线性、分支、Q-Robot、审批、填写还是抄送流程,新建和替换都使用 WorkflowSpec `--spec-file`;已有节点的小修改才使用 `--patch-nodes-file`。不要在技能主链路使用 `--nodes-file` + `--transitions-file`。
45
+ 无论线性、分支、Q-Robot、审批、填写还是抄送流程,新建和替换都使用 WorkflowSpec `--spec-file`;已有节点的小修改才使用 `--patch-nodes-file`。当前 CLI 会按调用前的 `spec.nodes` 数判断:超过 5 个节点即停止编辑并提示功能维护中,不以提交后的节点数判断;当前节点数为 5 个及以下时允许写入,初始流程创建包含在内。不要在技能主链路使用 `--nodes-file` + `--transitions-file`。
46
46
 
47
47
  ← 返回主流程:[../SKILL.md](../../../SKILL.md)
48
48
  → 下一步:[02-update-mode.md](02-update-mode.md)
@@ -2,6 +2,8 @@
2
2
 
3
3
  当应用已有工作流时,进入**更新模式**。核心原则是**最小修改**——只改动必要的部分,保持其他结构不变。
4
4
 
5
+ 当前 CLI 的流程编辑功能维护中:写入前读取当前 `spec.nodes`,节点数超过 5 时会停止操作并返回维护提示,不会发起流程写入。判定只基于更新前的节点数,不基于本次提交后会变成多少节点;当前节点数为 5 个及以下时仍允许写入,初始流程创建包含在内。
6
+
5
7
  ## 为什么要保持节点 ID 稳定
6
8
 
7
9
  后端可能存储了 spec 中不支持的运行时配置(如审批策略、超时规则、高级权限等),这些配置与节点 ID 绑定。一旦修改节点 ID,后端会将其视为「删除旧节点 + 创建新节点」,导致不支持的配置全部丢失。
@@ -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,21 @@ 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
+ 用户需要查看结果、继续编辑、处理业务或进入工作区页面时,MCP 调用 `get_login_link`,CLI 调用 `qingflow --json auth login-link`。纯数据查询无需页面,不自动生成链接。
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`,文案贴合“查看记录”“继续编辑”等上下文,不展示工作区数字 ID 或原始 JSON。
57
+ - CLI 示例:`qingflow --json auth login-link`;指定目标使用 `qingflow --profile default --json auth login-link --redirect-path "/index/app/123?view=abc"`,同样不得编造实际路径。
58
+ - 链接短时有效且仅可使用一次,失效后重新获取,不修改或拼造链接;只交付给请求用户,不写入公共文档或日志。
59
+ - 用户要求“给我链接”时仅交付,不提前消费;要求“打开”时才使用可用浏览器打开。浏览器不可用时提供可点击链接,不假称已经打开。
60
+
45
61
  ## Route Next
46
62
 
47
63
  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, []
@@ -21167,6 +21167,11 @@ def _compact_public_field_read(*, field: dict[str, Any], layout: dict[str, Any],
21167
21167
  "required": bool(field.get("required")),
21168
21168
  "section_id": None if nested else _find_field_section_id(layout, str(field.get("name") or "")),
21169
21169
  }
21170
+ if field.get("type") in {FieldType.single_select.value, FieldType.multi_select.value} and field.get(
21171
+ "option_details"
21172
+ ):
21173
+ # 选项 id 透出:validate-code-block 需要把"选项文案"翻译成 optId(后端只认 optId)
21174
+ payload["option_details"] = deepcopy(field.get("option_details"))
21170
21175
  if field.get("type") == FieldType.relation.value:
21171
21176
  payload["target_app_key"] = field.get("target_app_key")
21172
21177
  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)