# 命令参考

> 命令参考

Source: https://docs.sommatic.ai/zh/command-center/commands/

## 读取类命令

### `/extract-from-insight`

`command_center.extract.from_insight`

从 InsightSource 中抽取结构化数据

#### 用途

从数据源的实时数据快照中提取指定字段。该命令不返回完整载荷（`read.insights.snapshot` 的做法），而只摘取所请求的字段，为综合 LLM 提供更简洁、更小的结果。

#### 使用场景

- LLM 只需要数据源中的特定字段，而不需要完整载荷时。
- 数据源载荷较大时，用于减小综合上下文的体积。
- 用户询问某个具体属性时，例如“当前项目的状态是什么？”→ 从 `page-context` 中提取 `project.status`。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `source_id` | `string` | 是 | 要从中提取数据的数据源 ID。 |
| `fields` | `string[]` | 否 | 要提取的点号路径（例如 `["project.name", "project.status"]`）。省略时返回所有顶层键。 |

#### 返回值

```js
{
  ok: true,
  source_id: "page-context",
  data: {
    "project.name": "Development",
    "project.status": "active"
  }
}
```

如果未提供 `fields`：

```js
{
  ok: true,
  source_id: "page-context",
  data: {
    context: "...",
    type: "project-detail",
    project: { /* full object */ },
    recentChats: [ /* ... */ ],
    metadata: { isLoading: false }
  }
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SOURCE_ID", message: "source_id is required" } }
{ ok: false, error: { code: "SOURCE_NOT_FOUND", message: "Source [xyz] is not registered" } }
{ ok: false, error: { code: "NO_DATA", message: "Source [page-context] has no data yet" } }
```

#### 实现

```js
// commands/read/extractFromInsight.action.js

const getNestedValue = (obj, path) => {
  return path.split('.').reduce((acc, key) => (acc != null ? acc[key] : undefined), obj);
};

export const action = (args, registry) => {
  const { source_id, fields } = args || {};

  if (!source_id) {
    return { ok: false, error: { code: 'MISSING_SOURCE_ID', message: 'source_id is required' } };
  }

  const metadata = registry?.getSourceMetadata?.(source_id);
  if (!metadata) {
    return { ok: false, error: { code: 'SOURCE_NOT_FOUND', message: `Source [${source_id}] is not registered` } };
  }

  const snapshot = registry?.getSnapshot?.(source_id);
  if (!snapshot?.payload) {
    return { ok: false, error: { code: 'NO_DATA', message: `Source [${source_id}] has no data yet` } };
  }

  const payload = snapshot.payload;

  if (!Array.isArray(fields) || fields.length === 0) {
    return { ok: true, source_id, data: payload };
  }

  const data = {};
  for (const field of fields) {
    data[field] = getNestedValue(payload, field);
  }

  return { ok: true, source_id, data };
};
```

#### 命令定义

```js
{
  id: 'command_center.extract.from_insight',
  label: '/extract-insight',
  description: 'Extract specific fields from an InsightSource snapshot',
  schema: {
    type: 'object',
    properties: {
      source_id: {
        type: 'string',
        description: "ID of the source. Use 'page-context' for the current page."
      },
      fields: {
        type: 'array',
        items: { type: 'string' },
        description: "Dot-notation paths to extract (e.g. 'project.name', 'metadata.isLoading'). Omit for all top-level keys."
      }
    },
    required: ['source_id']
  },
  action: (args) => Read.extractFromInsight(args, registry),
}
```

#### 说明

- 点号路径遍历支持两层：`"project.name"` → `payload.project.name`。
- 载荷中不存在的字段，其对应的键返回 `undefined`。
- 数据源载荷较大时，强烈建议使用 `fields`，可显著减少传给综合 LLM 的数据量。

### `/extract-from-targets`

`command_center.extract.from_targets`

从已发布的目标中抽取数据

#### 用途

读取一个或多个 UI 目标（表单字段、输入框、标签）的当前值。这使 LLM 无需提交表单，即可查看用户在表单中输入或选择的值。

可选择将提取的值映射到命名结构，以获得结构化输出。

#### 使用场景

- 用户问“表单里现在填了哪些值？”时。
- 在调用 `exec.ui.submit_form` 之前，校验或检查表单状态。
- 作为审计步骤：“读取当前应用在表格上的筛选值。”
- 根据当前表单状态预填 AI 建议。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `targets` | `string[]` | 是 | 目标引用数组（`{surface_id}::{target_id}` 格式）。 |
| `schema` | `object` | 否 | 可选的映射结构。键为输出字段名，值中的 `source_ref` 指向某个目标引用。 |

#### 返回值

不使用 schema：

```js
{
  ok: true,
  data: [
    { ref: "create-project-form::project-name-input", label: "Project Name", type: "input", value: "My New Project" },
    { ref: "create-project-form::status-dropdown", label: "Status", type: "select", value: "active" }
  ]
}
```

使用 schema：

```js
// schema: { name: { source_ref: "create-project-form::project-name-input" }, status: { source_ref: "create-project-form::status-dropdown" } }
{
  ok: true,
  data: {
    name: "My New Project",
    status: "active"
  }
}
```

如果部分目标失败：

```js
{
  ok: false,
  data: [
    { ref: "form::input-1", label: "Name", type: "input", value: "Test" },
  ],
  errors: [
    { target_ref: "form::unknown-input", error: "Target not found" }
  ]
}
```

#### 实现

```js
// commands/read/extractFromTargets.action.js
export const action = (args, registry) => {
  const { targets, schema } = args || {};

  if (!Array.isArray(targets) || targets.length === 0) {
    return { ok: false, error: { code: 'MISSING_TARGETS', message: 'targets array is required' } };
  }

  const extractedItems = [];
  const errors = [];

  for (const targetRef of targets) {
    const resolved = registry?.resolveTarget?.(targetRef);
    if (!resolved) {
      errors.push({ target_ref: targetRef, error: 'Target not found' });
      continue;
    }

    const { target } = resolved;
    const item = { ref: targetRef, label: target.label || '', type: target.type || 'unknown' };

    if (target.handlers?.getValue) {
      try { item.value = target.handlers.getValue(); }
      catch (err) { item.value = null; item.error = err.message; }
    } else if (target.value !== undefined) {
      item.value = target.value;
    }

    extractedItems.push(item);
  }

  // Apply schema mapping if provided
  if (schema && typeof schema === 'object' && schema.properties) {
    const mapped = {};
    for (const [key, descriptor] of Object.entries(schema.properties)) {
      const sourceRef = descriptor?.source_ref || key;
      const match = extractedItems.find((item) => item.ref === sourceRef);
      mapped[key] = match?.value ?? null;
    }
    return { ok: errors.length === 0, data: mapped, errors: errors.length > 0 ? errors : undefined };
  }

  return { ok: errors.length === 0, data: extractedItems, errors: errors.length > 0 ? errors : undefined };
};
```

#### 命令定义

```js
{
  id: 'command_center.extract.from_targets',
  label: '/extract-targets',
  description: 'Extract current values from specified UI targets',
  schema: {
    type: 'object',
    properties: {
      targets: {
        type: 'array',
        items: { type: 'string' },
        description: "Array of target references in format 'surface_id::target_id'."
      },
      schema: {
        type: 'object',
        description: 'Optional mapping schema: { properties: { fieldName: { source_ref: "surface::target" } } }'
      }
    },
    required: ['targets']
  },
  action: (args) => Read.extractFromTargets(args, registry),
}
```

#### 目标注册要求

目标必须暴露 `getValue` 处理器才能被提取：

```jsx
targets: [
  {
    id: 'project-name-input',
    label: 'Project Name',
    type: 'input',
    handlers: {
      getValue: () => nameValue,      // ← Required for extraction
      fill: (v) => setNameValue(v),
    },
  },
]
```

#### 说明

- 如果目标既没有 `getValue` 处理器，也没有 `value` 属性，其提取值为 `undefined`。
- 需要将结构化的表单数据传给后续执行类命令或综合步骤时，schema 映射非常有用。
- 先使用 `read.ui.targets.list` 查找可用的 `target_ref` 字符串。

### `/observe-ui`

`command_center.observe.ui`

根据指令发现候选操作

#### 用途

分析所有已注册的界面和目标，针对给定的自然语言指令建议相关的 UI 操作。这是“智能发现”命令：它根据指令为每个界面和目标打分，并返回最相关的候选项。

与返回原始列表的 `read.ui.targets.list` 不同，`observe.ui` 使用语义评分将指令匹配到具体的目标和方法。

#### 使用场景

- 用户问“我在这里能做什么？”或“怎么筛选这个列表？”时。
- 作为计划的第一步，LLM 需要确定与哪个界面/目标交互时。
- 用户指令含义模糊、LLM 需要缩小目标范围时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `instruction` | `string` | 是 | 用自然语言描述的期望操作。 |

#### 返回值

```js
{
  ok: true,
  candidates: [
    {
      surface_id: "project-list-grid",
      target_ref: "project-list-grid::applyFilter",
      label: "applyFilter",
      type: "virtual",
      method: "applyFilter",
      score: 3,
      hint: "Call 'applyFilter' on surface 'project-list-grid'"
    },
    {
      surface_id: "project-list-grid",
      target_ref: "project-list-grid::selectRows",
      label: "selectRows",
      type: "virtual",
      method: "selectRows",
      score: 2
    }
  ]
}
```

如果没有找到相关候选项：

```js
{ ok: true, candidates: [] }
```

#### 评分算法

每个界面通过 `computeSurfaceScore(instruction, surface, surfaceId)` 评分：
- 指令提到界面类型（例如“grid”）时 +1
- 界面字段（id、label、description）每与指令中的关键词匹配一次 +1
- 最低分为 0

每个目标通过将其标签、类型和支持的方法与指令进行关键词匹配来评分。

如果父界面得分为正，**虚拟目标**（当 `targets: []` 时由处理器生成）会跳过严格的 `isMethodRelevant` 检查，确保像“我在表格里能做什么？”这样的笼统查询仍能返回所有基于处理器的操作。

#### 虚拟目标

当界面的 `targets` 为空但暴露了 `handlers` 时，会动态生成虚拟目标：

```js
// Surface registered with:
handlers: {
  applyFilter: (value) => setFilter(value),
  selectRows: (ids) => setSelectedRowIds(ids),
}

// Generates virtual targets:
[
  { id: "project-list-grid::applyFilter", label: "applyFilter", type: "virtual", handlers: { applyFilter: fn } },
  { id: "project-list-grid::selectRows", label: "selectRows", type: "virtual", handlers: { selectRows: fn } }
]
```

#### 实现（概要）

```js
// commands/read/observeUi.action.js

export const action = (args, registry) => {
  const { instruction } = args || {};

  const surfaces = registry?.getSurfaces?.() || [];
  const candidates = [];

  for (const surface of surfaces) {
    let targets = registry?.getTargets?.(surface.id) || [];
    let isVirtualSurface = false;

    // If no explicit targets, generate virtual targets from handlers
    if (targets.length === 0 && surface.handlers) {
      targets = buildVirtualTargets(surface.id, surface);
      isVirtualSurface = true;
    }

    const surfaceScore = computeSurfaceScore(instruction, surface, surface.id);

    for (const target of targets) {
      const targetScore = scoreTarget(instruction, target);

      // For virtual targets on scored surfaces, skip method relevance filtering
      if (isVirtualSurface && surfaceScore > 0) {
        candidates.push({ surface_id: surface.id, target_ref: target.id, ...target, score: surfaceScore + targetScore });
        continue;
      }

      if (targetScore > 0 || surfaceScore > 0) {
        candidates.push({ surface_id: surface.id, target_ref: target.id, ...target, score: surfaceScore + targetScore });
      }
    }
  }

  candidates.sort((a, b) => b.score - a.score);
  return { ok: true, candidates };
};
```

#### 命令定义

```js
{
  id: 'command_center.observe.ui',
  label: '/observe-ui',
  description: 'Discover UI actions relevant to a given instruction',
  schema: {
    type: 'object',
    properties: {
      instruction: {
        type: 'string',
        description: 'Natural language description of what the user wants to do.'
      }
    },
    required: ['instruction']
  },
  action: (args) => Read.observeUi(args, registry),
}
```

#### 说明

- 当 LLM 不确定要操作哪个界面或目标时，最适合使用 `observe.ui`。对于已知界面，请直接调用执行类命令。
- 每个候选项中的 `target_ref` 就是要传给 `exec.ui.act` 或 `extract.from_targets` 的字符串。
- 候选项为空通常表示没有注册任何界面，或指令与任何界面/目标的关键词都不匹配。

### `/capabilities`

`command_center.read.capabilities`

查看宿主应用启用了哪些读取与执行能力

#### 用途

报告 Command Center 当前能做的所有事情：所有已注册的读取类命令、执行类命令、可用的 InsightSource 以及已注册的界面。这是系统的自我描述命令。

#### 使用场景

- 用户问“你能做什么？”或“有哪些可用命令？”时。
- 用于智能体自我发现：构建多步骤计划时，LLM 需要了解自己的工具集。
- 调试时：确认所有命令都已正确注册。

#### 参数

无。

#### 返回值

```js
{
  capabilities: {
    read_commands: [
      { id: "command_center.read.scope.get", label: "/get-scope", description: "Get current page context" },
      { id: "command_center.read.insights.list", label: "/list-sources", description: "List all available data sources" },
      // ... 16 more read commands
    ],
    exec_commands: [
      { id: "command_center.exec.navigate", label: "/navigate", description: "Navigate to a route" },
      { id: "command_center.exec.clipboard.copy", label: "/copy", description: "Copy text to clipboard" },
      // ... 14 more exec commands
    ],
    sources: [
      { id: "page-context", description: "Current page context." },
      { id: "org-context", description: "Organization metadata." }
    ],
    surfaces: [
      { id: "project-list-grid", type: "grid", label: "Project List" },
      { id: "create-project-form", type: "form", label: "Create Project Form" }
    ]
  }
}
```

#### 实现

```js
// commands/read/getCapabilities.action.js
export const action = (registry) => {
  const readCommands = [];
  const execCommands = [];

  const commands = registry?.commands || [];
  for (const cmd of commands) {
    const entry = { id: cmd.id, label: cmd.label, description: cmd.description };
    if (cmd.id.includes('.read.') || cmd.id.includes('.observe.') || cmd.id.includes('.extract.')) {
      readCommands.push(entry);
    } else {
      execCommands.push(entry);
    }
  }

  const sources = registry?.listAllSources?.() || [];

  return {
    capabilities: {
      read_commands: readCommands,
      exec_commands: execCommands,
      sources,
      surfaces: registry?.getSurfaces?.() || [],
    },
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.capabilities',
  label: '/capabilities',
  description: 'Report all available commands, sources, and surfaces',
  schema: {},
  action: () => Read.getCapabilities(registry),
}
```

#### 命令分类逻辑

命令根据 ID 片段分为 `read_commands` 或 `exec_commands`：
- 包含 `.read.`、`.observe.` 或 `.extract.` → 读取类命令
- 其他所有命令 → 执行类命令

也就是说，`command_center.exec.navigate` 归入 `exec_commands`，而 `command_center.observe.ui` 归入 `read_commands`。

#### 说明

- `sources` 和 `surfaces` 反映当前的挂载状态，不包含已卸载组件的注册项。
- `registry.commands` getter 从 `allCommandsRef.current` 读取，始终反映最新的已注册命令集合（包括由 Navbar 动态注册的命令）。
- 该命令适合用于引导：当 LLM 在没有任何先前上下文的情况下开始对话时，可以先调用它来了解所处环境。

### `/context-pack`

`command_center.read.context.pack`

拉取多个洞察数据（Top-N 或按 ID）

#### 用途

将多个 InsightSource 的实时数据载荷合并为一个聚合对象。当用户的查询同时需要多个数据源的上下文时非常有用。

#### 使用场景

- LLM 需要组合多个数据源的数据来回答问题时。
- 作为多次调用 `read.insights.snapshot` 的单步替代方案。
- 在综合处理或执行类命令之前，构建完整的上下文包时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `source_ids` | `string[]` | 否 | 要包含的数据源 ID 数组。省略时打包所有已注册的数据源。 |

#### 返回值

```js
{
  ok: true,
  context: {
    "page-context": {
      type: "project-detail",
      project: { id: "prj-...", name: "Development", status: "active" },
      metadata: { isLoading: false }
    },
    "org-context": {
      id: "org-232121",
      name: "Blackwood",
      plan: "enterprise"
    }
  },
  included: ["page-context", "org-context"],
  missing: []
}
```

如果部分数据源没有数据：

```js
{
  ok: true,
  context: { "page-context": { /* ... */ } },
  included: ["page-context"],
  missing: ["org-context"]   // Registered but no cached data yet
}
```

##### 错误情况

```js
{ ok: false, error: { code: "NO_SOURCES", message: "No sources available to pack" } }
```

#### 实现

```js
// commands/read/contextPack.action.js
export const action = (args, registry) => {
  let sourceIds = args?.source_ids;

  if (!Array.isArray(sourceIds) || sourceIds.length === 0) {
    const allSources = registry?.listAllSources?.() || [];
    sourceIds = allSources.map((s) => s.id);
  }

  if (sourceIds.length === 0) {
    return { ok: false, error: { code: 'NO_SOURCES', message: 'No sources available to pack' } };
  }

  const context = {};
  const included = [];
  const missing = [];

  for (const id of sourceIds) {
    const snapshot = registry?.getSnapshot?.(id);
    if (snapshot?.payload) {
      context[id] = snapshot.payload;
      included.push(id);
    } else {
      missing.push(id);
    }
  }

  return { ok: true, context, included, missing };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.context.pack',
  label: '/pack-context',
  description: 'Bundle multiple InsightSource payloads into a single context object',
  schema: {
    type: 'object',
    properties: {
      source_ids: {
        type: 'array',
        items: { type: 'string' },
        description: 'Source IDs to bundle. Omit to include all registered sources.'
      }
    }
  },
  action: (args) => Read.contextPack(args, registry),
}
```

#### 说明

- 省略 `source_ids` 时会包含所有已注册的数据源，可能产生非常大的载荷。配合上下文窗口有限的综合 LLM 使用时需谨慎。
- 必要时，`CognitiveEntryManager` 中的综合上下文截断逻辑会对其进行裁剪。
- 先使用 `read.insights.list` 查找可用的数据源 ID，再用筛选后的列表调用该命令。

### `/debug-exec-log`

`command_center.read.debug.execution_log`

查看最近 N 次执行及其回执

#### 用途

返回最近的命令执行历史：运行了哪些命令、使用了什么参数、产生了什么结果。这为 Command Center 执行过的所有操作提供了完整的审计记录。

#### 使用场景

- 用户问“执行过哪些命令？”或“给我看看执行历史”时。
- 调试时：确认之前的命令是否执行成功，并检查其输出。
- 审计时：回顾一次会话中执行的所有操作。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `limit` | `number` | 否 | 返回条目的最大数量，默认为 `10`。 |

#### 返回值

```js
{
  entries: [
    {
      command_id: "command_center.read.insights.describe",
      args: { source_id: "page-context" },
      status: "success",
      result: {
        ok: true,
        source: {
          id: "page-context",
          description: "Current Project Detail...",
          inferred_fields: ["context", "type", "project", "recentChats", "metadata"],
          has_data: true,
          captured_at: 1772075191118
        }
      },
      timestamp: 1772075191118
    },
    {
      command_id: "command_center.exec.clipboard.copy",
      args: { content: "hello world" },
      status: "success",
      result: { ok: true, title: "Copied to clipboard", receipt_id: "rcpt_1772075473717_byfawpr" },
      timestamp: 1772075473717
    }
  ]
}
```

#### 实现

```js
// commands/read/debugExecutionLog.action.js
export const action = (args, registry) => {
  const limit = args?.limit || 10;
  const entries = registry?.getExecutionLog?.(limit) || [];
  return { entries };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.debug.execution_log',
  label: '/execution-log',
  description: 'Show recent command execution history and results',
  schema: {
    type: 'object',
    properties: {
      limit: { type: 'number', description: 'Max entries to return (default: 10)' }
    }
  },
  action: (args) => Read.debugExecutionLog(args, registry),
}
```

#### 日志的写入方式

每次执行命令时，`executePlan` 会调用：

```js
registry.pushDebugEntry('execution', {
  command_id: step.command_id,
  args: step.args,
  status: result ? 'success' : 'error',
  result,
  timestamp: Date.now(),
});
```

#### 大日志下的综合行为

执行日志可能产生非常大的 JSON 载荷（数千个字符），尤其是之前的结果包含完整的数据源快照时。综合上下文管道通过以下方式处理：

1. **单条结果截断**：超过 4,000 个字符的结果会被替换为 `[truncated — N chars. Summary: ...]`。
2. **总量上限**：合并后的上下文超过 12,000 个字符时，多出的条目会被丢弃。

这样既能避免综合 LLM 触及上下文窗口上限，又能提供有用的摘要。

#### 说明

- 日志**仅存于内存**，刷新页面后即丢失。
- `status` 字段的值为 `"success"` 或 `"error"`。命令级别的成功/失败详情请查看 `result.ok`。
- 为减少干扰，综合调用请使用 `limit: 5` 或更小的值；手动调试时可使用更大的值。

### `/debug-router-log`

`command_center.read.debug.router_log`

查看最近 N 条路由决策

#### 用途

返回路由 LLM 最近的决策历史：路由器针对每条用户消息生成了哪些计划，包括思考过程、选定的命令和所用的提供方。

这主要是一个调试与可观测性工具。

#### 使用场景

- 排查 LLM 为什么在之前的查询中选择了某些命令时。
- 用户问“智能体做过哪些决策？”或“给我看看智能体的推理过程”时。
- 用于开发环境中的系统监控和审计追踪。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `limit` | `number` | 否 | 返回条目的最大数量，默认为 `10`。 |

#### 返回值

```js
{
  entries: [
    {
      user_prompt: "Describe the page-context source",
      plan: [
        {
          command_id: "command_center.read.insights.describe",
          reason: "User wants to see the metadata of the page-context source.",
          args: { source_id: "page-context" }
        }
      ],
      thought: "The user requests information about 'page-context'. I will describe it using the insights.describe command.",
      provider_id: "wf-llm-provider-3be6659683c4065",
      timestamp: 1772075190507
    },
    // ... more entries
  ]
}
```

#### 实现

```js
// commands/read/debugRouterLog.action.js
export const action = (args, registry) => {
  const limit = args?.limit || 10;
  const entries = registry?.getRouterLog?.(limit) || [];
  return { entries };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.debug.router_log',
  label: '/router-log',
  description: "Show recent router LLM decisions and execution plans",
  schema: {
    type: 'object',
    properties: {
      limit: { type: 'number', description: 'Max entries to return (default: 10)' }
    }
  },
  action: (args) => Read.debugRouterLog(args, registry),
}
```

#### 日志的写入方式

每处理一条用户消息，`classifyIntent` 函数（位于 `useCommandCenterAgent` 中）在收到成功的计划响应后会调用 `pushDebugEntry('router', entry)`：

```js
registry.pushDebugEntry('router', {
  user_prompt: userMessage,
  plan: response.execution_plan,
  thought: response.thought,
  provider_id: response.provider_id,
  timestamp: Date.now(),
});
```

日志存储在一个有上限的内存数组中（通常保留最近 N 条）。

#### 说明

- 日志**仅存于内存**，刷新页面后即丢失。
- 每个条目对应一次“用户消息 → 路由 LLM 调用”周期。
- 可用于比较同一查询在不同 LLM 提供方下的理解方式。
- `thought` 字段包含 LLM 在生成计划前的思维链推理，是最有用的调试字段。

### `/get-focus`

`command_center.read.focus.get`

获取当前焦点（实体/活动面板）

#### 用途

返回宿主组件报告的当前聚焦实体或活动面板。焦点表示“用户当前正在处理的内容”，通常是详情页上展示的实体。

#### 使用场景

- LLM 需要知道当前处于活动状态的具体实体时。
- 当 `page-context` 不可用或未直接暴露实体 ID 时，作为备选方案。
- 用户说“对这个项目执行 X”时，LLM 通过焦点将“这个项目”解析为具体的实体 ID。

#### 参数

无。

#### 返回值

##### 实体焦点（详情页）

```js
{
  focus: {
    entity_type: "project",
    entity_id: "prj-management-cc48809102397ed",
    label: "Development"
  }
}
```

##### 面板焦点

```js
{
  focus: {
    type: "panel",
    panel_id: "create-project-form",
    label: "Create Project"
  }
}
```

##### 未注册焦点

```js
{ focus: null }
```

#### 实现

```js
// commands/read/getFocus.action.js
export const action = (registry) => {
  if (!registry?.getFocusData) {
    return { focus: null };
  }

  const focus = registry.getFocusData();
  return { focus };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.focus.get',
  label: '/get-focus',
  description: 'Get currently focused entity or active panel',
  schema: {},
  action: () => Read.getFocus(registry),
}
```

#### 在宿主应用中报告焦点

在任意详情组件中使用 `useSommaticFocus` 暴露当前实体：

```jsx
import { useSommaticFocus } from 'sommatic-react-sdk';

// In a project detail component
useSommaticFocus(
  {
    entity_type: 'project',
    entity_id: project.id,
    label: project.name,
  },
  [project.id, project.name],
);
```

该 hook 会在注册表上调用 `setFocusData(data)`。卸载时，通过调用 `setFocusData(null)` 清除焦点。

#### 焦点与上下文数据源对比

| 特性 | `useSommaticFocus` | `useSommaticContextSource` |
|---------|-------------------|--------------------------|
| 用途 | 报告当前实体的 ID/类型 | 暴露完整的数据载荷 |
| 访问方式 | `read.focus.get` | `read.insights.snapshot` |
| 载荷 | `{ entity_type, entity_id, label }` | 任意结构 |
| 更新时机 | 实体变化时触发 | 任意数据变化时触发 |

两者结合使用可获得最佳的可发现性：焦点为 LLM 提供 ID，上下文数据源提供完整数据。

#### 说明

- 注册表中全局只有一个焦点条目，由最后一个调用 `useSommaticFocus` 的组件持有。
- 离开详情页时，React 的卸载生命周期会清除焦点。

### `/describe-insight`

`command_center.read.insights.describe`

查看 InsightSource 的元数据与结构

#### 用途

返回指定 InsightSource 的元数据和推断出的结构，而不获取其完整的实时载荷。这能让 LLM（以及用户）了解该数据源暴露数据的结构，包括字段名、数据存在标识和描述。

#### 使用场景

- 用户问“page-context 有哪些字段？”或“描述一下项目数据源”时。
- 只需要结构而不需要实时数据时，作为 `read.insights.snapshot` 的轻量替代。
- 在调用 `extract.from_insight` 之前，用于了解有哪些可用字段。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `source_id` | `string` | 是 | 要描述的数据源 ID。当前页面使用 `'page-context'`。 |

#### 返回值

```js
{
  ok: true,
  source: {
    id: "page-context",
    description: "Current Project Detail. Use this to know which project is active...",
    inferred_fields: ["context", "type", "project", "recentChats", "metadata"],
    has_data: true,
    captured_at: 1772075191118
  }
}
```

##### 错误情况

```js
// Missing argument
{ ok: false, error: { code: "MISSING_SOURCE_ID", message: "source_id is required" } }

// Source not registered
{ ok: false, error: { code: "SOURCE_NOT_FOUND", message: "Source [xyz] is not registered" } }
```

#### 实现

```js
// commands/read/describeInsight.action.js
export const action = (args, registry) => {
  const { source_id } = args || {};

  if (!source_id) {
    return { ok: false, error: { code: 'MISSING_SOURCE_ID', message: 'source_id is required' } };
  }

  const metadata = registry?.getSourceMetadata?.(source_id);
  if (!metadata) {
    return { ok: false, error: { code: 'SOURCE_NOT_FOUND', message: `Source [${source_id}] is not registered` } };
  }

  const snapshot = registry?.getSnapshot?.(source_id);
  const payload = snapshot?.payload;
  const inferred_fields = payload && typeof payload === 'object' ? Object.keys(payload) : [];

  return {
    ok: true,
    source: {
      id: source_id,
      description: metadata.description,
      inferred_fields,
      has_data: !!payload,
      captured_at: snapshot?.capturedAt || null,
    },
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.insights.describe',
  label: '/describe-insight',
  description: 'View metadata + schema of an InsightSource',
  schema: {
    type: 'object',
    properties: {
      source_id: {
        type: 'string',
        description: "ID of the InsightSource to describe. Use 'page-context' for the current page."
      }
    },
    required: ['source_id']
  },
  action: (args) => Read.describeInsight(args, registry),
}
```

#### 说明

- `inferred_fields` 通过对缓存的快照载荷调用 `Object.keys()` 得出，反映的是 `getData()` 最近一次返回内容的顶层键。
- `has_data: false` 表示数据源已注册，但 `getSnapshot()` 尚无缓存值（例如组件已挂载，但还未完成一次渲染）。
- 该命令**不会**重新获取数据，而是读取缓存的快照。

### `/list-insights`

`command_center.read.insights.list`

按作用域列出可用的 InsightSource

#### 用途

列出 Command Center 中当前注册的所有 InsightSource，包括其 ID 和描述。支持可选的关键词过滤。

#### 使用场景

- 用户想了解有哪些可用数据时，例如“你能访问哪些数据源？”
- 在执行 `read.insights.describe` 或 `read.insights.snapshot` 之前，用于查找有效的数据源 ID。
- 作为多命令计划中的发现步骤。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `scope_filter` | `string` | 否 | 按 ID 或描述过滤数据源的关键词，不区分大小写。 |

#### 返回值

```js
{
  sources: [
    { id: "page-context", description: "Current page context. Use to know the active entity." },
    { id: "org-context", description: "Global organization metadata." },
    { id: "user-context", description: "Currently logged-in user profile." }
  ]
}
```

如果提供了 `scope_filter`：

```js
// scope_filter = "project"
{
  sources: [
    { id: "page-context", description: "Current Project Detail. Use this to know which project is active..." }
  ]
}
```

#### 实现

```js
// commands/read/listInsights.action.js
export const action = (args, registry) => {
  if (!registry?.listAllSources) return { sources: [] };

  let sources = registry.listAllSources();

  const scopeFilter = args?.scope_filter;
  if (scopeFilter) {
    sources = sources.filter(
      (source) =>
        source.id.includes(scopeFilter) ||
        (source.description || '').toLowerCase().includes(scopeFilter.toLowerCase()),
    );
  }

  return { sources };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.insights.list',
  label: '/list-sources',
  description: 'List all available data sources (InsightSources)',
  schema: {
    type: 'object',
    properties: {
      scope_filter: { type: 'string', description: 'Optional keyword filter' }
    }
  },
  action: (args) => Read.listInsights(args, registry),
}
```

#### 在宿主应用中注册数据源

```jsx
import { useSommaticContextSource } from 'sommatic-react-sdk';

useSommaticContextSource(
  {
    id: 'org-context',
    description: 'Global organization metadata including name, plan, and settings.',
    getData: () => ({
      id: org.id,
      name: org.name,
      plan: org.plan,
    }),
  },
  [org],
);
```

#### 说明

- `listAllSources()` 只返回当前已注册的数据源（即宿主组件当前处于挂载状态的数据源）。
- 由已卸载组件注册的数据源，会通过其注销函数自动清理。

### `/snapshot-insight`

`command_center.read.insights.snapshot`

拉取快照（遵循 TTL/缓存）

#### 用途

返回指定 InsightSource 的**实时数据载荷**。与只返回元数据的 `read.insights.describe` 不同，该命令返回组件当前实际暴露的数据。

快照带有 TTL 缓存（默认 30 秒），以避免触发不必要的重新渲染。

#### 使用场景

- 用户请求某个数据源的当前实际数据时，例如“显示当前项目的详细信息”。
- 作为综合或分析之前的数据收集步骤。
- LLM 需要将特定值（如 ID 或名称）传递给后续执行类命令时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `source_id` | `string` | 是 | 要获取快照的 InsightSource ID。 |

#### 返回值

```js
{
  ok: true,
  source_id: "page-context",
  payload: {
    context: "This page displays the detailed view of a specific project.",
    type: "project-detail",
    project: {
      id: "prj-management-cc48809102397ed",
      name: "Development",
      status: "active",
      organization: "org-232121",
      ui: { emoji: { icon: "Code", color: "#4CAF50" }, theme: {} }
    },
    recentChats: [
      { id: "c-198763...", title: "Test chat", created: { timestamp: "1769607887018" } }
    ],
    metadata: { isLoading: false, error: false }
  },
  captured_at: 1772075191118
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SOURCE_ID", message: "source_id is required" } }
{ ok: false, error: { code: "SOURCE_NOT_FOUND", message: "Source [xyz] is not registered" } }
{ ok: false, error: { code: "NO_DATA", message: "Source [page-context] has no data yet" } }
```

#### 实现

```js
// commands/read/snapshotInsight.action.js
export const action = (args, registry) => {
  const { source_id } = args || {};

  if (!source_id) {
    return { ok: false, error: { code: 'MISSING_SOURCE_ID', message: 'source_id is required' } };
  }

  const metadata = registry?.getSourceMetadata?.(source_id);
  if (!metadata) {
    return { ok: false, error: { code: 'SOURCE_NOT_FOUND', message: `Source [${source_id}] is not registered` } };
  }

  const snapshot = registry?.getSnapshot?.(source_id);
  if (!snapshot?.payload) {
    return { ok: false, error: { code: 'NO_DATA', message: `Source [${source_id}] has no data yet` } };
  }

  return {
    ok: true,
    source_id,
    payload: snapshot.payload,
    captured_at: snapshot.capturedAt,
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.insights.snapshot',
  label: '/snapshot-insight',
  description: 'Retrieve live data payload from an InsightSource',
  schema: {
    type: 'object',
    properties: {
      source_id: {
        type: 'string',
        description: "ID of the source. Use 'page-context' for current page data."
      }
    },
    required: ['source_id']
  },
  action: (args) => Read.snapshotInsight(args, registry),
}
```

#### 快照缓存

`getSnapshot(source_id)` 调用从 TTL 缓存中读取。每当宿主组件重新渲染、`useSommaticContextSource` hook 触发时，缓存都会更新。这意味着：

- 数据最多滞后 30 秒（TTL 可配置）。
- 短时间内多次调用该命令会返回同一份快照。
- 不会产生额外的网络请求，完全在内存中完成。

#### 说明

- 只需要字段名而不需要值时，先使用 `read.insights.describe`，它占用的综合上下文更少。
- 如需将多个快照合并为一个载荷，请使用 `read.context.pack`。

### `/page-outline`

`command_center.read.page.outline`

基于洞察数据（非 DOM）说明页面上有什么。当用户问“我在这里能做什么？”“这个页面有什么？”时使用。若未发布 'page-context'，则回退到第一个已注册的 InsightSource。

#### 用途

返回当前页面的完整描述：路由、页面上下文载荷，以及所有已注册的 InsightSource 及其描述和载荷键。这是对“用户在哪里、有什么可用”最完整的一次性快照。

#### 使用场景

- 用户问“这个页面上有什么？”或“解释一下我正在看的内容”时。
- 作为任何需要 LLM 全面掌握当前情况的多命令计划的第一步。
- 调试时：查看注册了哪些数据源以及它们是否有数据。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `detail_level` | `string` | 否 | `"high"` 在数据源中返回完整载荷，`"low"` 只返回键。默认为 `"low"`。 |

#### 返回值

```js
{
  route: "/admin/project/management/prj-management-cc48809102397ed",
  page_context: {
    context: "This page displays the detailed view of a specific project...",
    type: "project-detail",
    project: {
      id: "prj-management-cc48809102397ed",
      name: "Development",
      status: "active",
      organization: "org-232121",
      ui: { emoji: { icon: "Code", color: "#4CAF50" } }
    },
    recentChats: [ /* ... */ ],
    metadata: { isLoading: false, error: false }
  },
  sources: [
    {
      id: "page-context",
      description: "Current Project Detail...",
      has_data: true,
      payload_keys: ["context", "type", "project", "recentChats", "metadata"]
    },
    {
      id: "org-context",
      description: "Organization metadata.",
      has_data: true,
      payload_keys: ["id", "name", "plan"]
    }
  ]
}
```

#### 实现

```js
// commands/read/getPageOutline.action.js
export const action = (args, registry) => {
  const detailLevel = args?.detail_level || 'low';
  const route = window?.location?.pathname || 'unknown';

  const pageSnapshot = registry?.getSnapshot?.('page-context');
  const pageContext = pageSnapshot?.payload || null;

  const allSources = registry?.listAllSources?.() || [];
  const sources = allSources.map((source) => {
    const snap = registry?.getSnapshot?.(source.id);
    const payload = snap?.payload;
    const entry = {
      id: source.id,
      description: source.description,
      has_data: !!payload,
    };

    if (detailLevel === 'high' && payload) {
      entry.payload = payload;
    } else if (payload) {
      entry.payload_keys = Object.keys(payload);
    }

    return entry;
  });

  return { route, page_context: pageContext, sources };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.page.outline',
  label: '/page-outline',
  description: 'Describe current page route, context, and registered sources',
  schema: {
    type: 'object',
    properties: {
      detail_level: {
        type: 'string',
        enum: ['low', 'high'],
        description: "'high' includes full source payloads; 'low' includes only field names."
      }
    }
  },
  action: (args) => Read.getPageOutline(args, registry),
}
```

#### 说明

- `detail_level: "high"` 可能产生非常大的响应（合并所有数据源的载荷）。若用于综合处理，将应用 `CognitiveEntryManager` 中的上下文截断逻辑。
- `route` 取自 `window.location.pathname`，因此始终反映执行时浏览器的当前 URL。
- `sources` 包含所有已注册的数据源，而不仅是 `page-context`，从而让 LLM 全面了解可用数据。

### `/get-current-scope`

`command_center.read.scope.get`

获取当前作用域（路由、模块、焦点）。当用户问“我在哪？”“这是哪个页面？”“告诉我页面名称”或类似问题时使用。若未发布 'page-context'，则回退到第一个已注册的 InsightSource。

#### 用途

返回当前页面上下文的快照，即当前页面组件在 `page-context` InsightSource 下注册的全部数据。

这是最简单的读取类命令：直接返回上下文对象，不做任何过滤或转换。

#### 使用场景

- 用户问“我在哪个页面？”或“当前上下文是什么？”时。
- 作为多命令计划的第一步，在进行更具体的查询前先确定当前作用域。
- LLM 在执行操作前需要知道当前实体（例如打开的是哪个项目）时。

#### 参数

该命令没有面向用户的参数。

在内部，它直接从 `getContext('page-context')` 接收页面上下文对象，而不是从 `registry` 获取。这是唯一一个接收原始上下文而非注册表的命令。

#### 返回值

返回 `page-context` InsightSource 的 `getData()` 所返回的内容。

```js
// Example return value on a project detail page
{
  context: "This page displays the detailed view of a specific project...",
  type: "project-detail",
  project: {
    id: "prj-management-cc48809102397ed",
    name: "Development",
    status: "active",
    organization: "org-232121"
  },
  recentChats: [
    { id: "c-198763...", title: "Test chat", created: { timestamp: "1769607887018" } }
  ],
  metadata: { isLoading: false, error: false }
}
```

在列表页面上：

```js
{
  type: "project-list",
  items: [
    { id: "prj-management-...", name: "MyProject", status: "active", slug: "my-project" }
  ],
  pagination: { page: 0, limit: 10, total: 42 },
  metadata: { isLoading: false }
}
```

#### 实现

```js
// commands/read/getCurrentScope.action.js
export const action = (context) => {
  return context;
};
```

在调用该操作之前，命令分发器会通过 `getContext('page-context')` 注入 `context` 参数。

#### 命令定义

```js
// commands/definitions.js
{
  id: 'command_center.read.scope.get',
  label: '/get-scope',
  description: 'Get current page context',
  schema: {},
  action: () => Read.getCurrentScope(getContext('page-context')),
}
```

#### 在宿主应用中实现上下文数据源

任何希望被 `read.scope.get` 发现的页面，都必须注册一个 `page-context` 数据源：

```jsx
import { useSommaticContextSource } from 'sommatic-react-sdk';

useSommaticContextSource(
  {
    id: 'page-context',
    description: 'Current page description visible to the Command Center.',
    getData: () => ({
      type: 'my-entity-detail',
      entity: { id: entity.id, name: entity.name },
      metadata: { isLoading },
    }),
  },
  [entity, isLoading],
);
```

#### 说明

- 同一时间只应有一个组件注册 `page-context`。React Router 的挂载/卸载生命周期天然保证了这一点，因为只有当前路由的组件处于挂载状态。
- 如果没有任何组件注册 `page-context`，返回值为 `null` 或 `undefined`。

### `/get-selection`

`command_center.read.selection.get`

获取用户主动提供的选中内容（文本/ID）

#### 用途

返回宿主组件报告的当前用户选择。选择可以是表格中选中的行、高亮的文本，或组件选择暴露的任何结构化选择数据。

#### 使用场景

- 用户问“我选中了什么？”或“介绍一下选中的项目”时。
- 在对选中项执行批量执行类命令之前。
- LLM 需要知道要操作哪些行/实体，又不想明确询问用户时。

#### 参数

无。

#### 返回值

##### 表格中选中的行

```js
{
  selection: {
    type: "rows",
    ids: ["prj-management-a4b0e53a9532edd", "prj-management-f00d4ca337d8dcb"],
    source: "project-list-grid"
  }
}
```

##### 文本选择

```js
{
  selection: {
    type: "text",
    value: "Hello world",
    source: "browser"
  }
}
```

##### 无选择

```js
{ selection: null }
```

#### 实现

```js
// commands/read/getSelection.action.js
export const action = (registry) => {
  if (!registry?.getSelectionData) {
    return { selection: null };
  }

  const selection = registry.getSelectionData();
  return { selection };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.selection.get',
  label: '/get-selection',
  description: 'Get current user selection (rows, text, or entities)',
  schema: {},
  action: () => Read.getSelection(registry),
}
```

#### 在宿主应用中报告选择

管理选择的组件必须调用 `useSommaticSelection`，使选择可见：

```jsx
import { useSommaticSelection } from 'sommatic-react-sdk';

// In a list component
useSommaticSelection(
  selectedRowIds.length > 0
    ? { type: 'rows', ids: selectedRowIds, source: 'project-list-grid' }
    : null,
  [selectedRowIds],
);
```

每当选择发生变化时，该 hook 会在注册表上调用 `setSelection(data)`。传入 `null` 会清除选择。

#### 与 `exec.ui.select_rows` 的集成

当用户让 Command Center“选中 slug 为 X 的行”时，`exec.ui.select_rows` 会更新组件中的 `selectedRowIds` 状态。如果已接入 `useSommaticSelection`，随后调用 `read.selection.get` 将返回这些行 ID。

由此形成完整的读写闭环：
1. `exec.ui.select_rows` → 在界面上选中行并更新状态
2. `useSommaticSelection` → 将新状态报告给注册表
3. `read.selection.get` → LLM 可以读取哪些行被选中

#### 说明

- 选择以单个全局条目的形式存储在注册表中。如果多个组件调用 `setSelection`，以最后一次调用为准。
- 如需跟踪多个组件的选择，可考虑使用不同的选择键，并在 `getData` 中返回合并后的对象。

### `/task-detail`

`command_center.read.tasks.detail`

查看详情及所需输入的结构

#### 用途

返回指定 HITL 任务的完整详情，包括状态、类型、输出结构、分配情况和历史记录。用于在认领或完成任务之前了解其要求。

#### 使用场景

- 用户问“介绍一下任务 XYZ”或“这个任务需要什么？”时。
- 在调用 `exec.tasks.complete` 之前，了解所需的 `outputs` 结构。
- 通过 `read.tasks.inbox` 列出任务后，深入查看某个具体条目。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `task_id` | `string` | 是 | 要获取的任务 ID。 |

#### 返回值

```js
{
  ok: true,
  task: {
    id: "task-abc123",
    title: "Review agent configuration",
    description: "Please review and approve the attached agent configuration before deployment.",
    status: "pending",
    type: "approval",
    outputs_schema: {
      approved: { type: "boolean", required: true },
      comment: { type: "string", required: false }
    },
    assigned_to: "user-xyz",
    created_by: "system",
    created_at: "2026-02-25T20:00:00.000Z",
    updated_at: "2026-02-25T20:05:00.000Z",
    context: {
      agent_id: "agent-001",
      config_version: "v2.1"
    }
  }
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "FETCH_FAILED", message: "..." } }
```

#### 实现

```js
// commands/read/getTaskDetail.action.js
export const action = async (args, registry) => {
  const { task_id } = args || {};

  if (!task_id) {
    return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const response = await taskStore.get({ queryselector: 'detail', id: task_id });
    const task = response?.result || response;

    return { ok: true, task };
  } catch (err) {
    return { ok: false, error: { code: 'FETCH_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.read.tasks.detail',
  label: '/task-detail',
  description: 'Get full details of a specific HITL task',
  schema: {
    type: 'object',
    properties: {
      task_id: {
        type: 'string',
        description: 'ID of the task to retrieve.'
      }
    },
    required: ['task_id']
  },
  action: (args) => Read.getTaskDetail(args, registry),
}
```

#### 典型的多命令流程

```
1. read.tasks.inbox { status: "pending" }
   → returns task list with IDs

2. read.tasks.detail { task_id: "task-abc123" }
   → returns full task with outputs_schema

3. exec.tasks.claim { task_id: "task-abc123" }
   → assigns task to current user

4. exec.tasks.complete { task_id: "task-abc123", outputs: { approved: true } }
   → marks task as complete
```

#### 说明

- `outputs_schema` 字段（如有）描述调用 `exec.tasks.complete` 时 `outputs` 对象必须包含的内容。
- `context` 字段包含工作流传给该任务的附加数据，可用于了解任务的业务背景。

### `/tasks-inbox`

`command_center.read.tasks.inbox`

列出分配给当前用户的 HITL 任务

#### 用途

列出分配给当前用户的人机协同（HITL）任务。按状态过滤，从已配置的 `taskService` 中查询任务。

HITL 任务代表需要人工校验、审批或输入后，自动化工作流才能继续的工作项。

#### 使用场景

- 用户问“我有哪些待处理的任务？”或“给我看看我的收件箱”时。
- 在执行 `exec.tasks.claim`、`exec.tasks.complete` 或 `exec.tasks.comment` 之前，用于获取任务 ID。
- 用于工作流自动化：查看待处理任务、认领其中一个，然后完成它。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `status` | `string` | 否 | 按状态过滤：`'pending'`、`'in_progress'`、`'completed'`。省略时返回所有状态。 |

#### 返回值

```js
{
  ok: true,
  tasks: [
    {
      id: "task-abc123",
      title: "Review agent configuration",
      status: "pending",
      type: "approval",
      created_at: "2026-02-25T20:00:00.000Z",
      assigned_to: "user-xyz"
    },
    {
      id: "task-def456",
      title: "Validate data source connection",
      status: "in_progress",
      type: "validation",
      created_at: "2026-02-25T18:30:00.000Z"
    }
  ]
}
```

如果没有匹配的任务：

```js
{ ok: true, tasks: [] }
```

##### 错误情况

```js
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "FETCH_FAILED", message: "Network error: ..." } }
```

#### 实现

```js
// commands/read/listTasksInbox.action.js
export const action = async (args, registry) => {
  const { status } = args || {};
  const taskStore = registry?.taskService;

  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const payload = { queryselector: 'list' };
    if (status) payload.status = status;

    const response = await taskStore.get(payload);
    const tasks = response?.result?.items || response?.items || [];

    return { ok: true, tasks };
  } catch (err) {
    return { ok: false, error: { code: 'FETCH_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.read.tasks.inbox',
  label: '/tasks-inbox',
  description: 'List HITL tasks assigned to the current user',
  schema: {
    type: 'object',
    properties: {
      status: {
        type: 'string',
        enum: ['pending', 'in_progress', 'completed'],
        description: 'Filter by task status. Omit for all tasks.'
      }
    }
  },
  action: (args) => Read.listTasksInbox(args, registry),
}
```

#### 任务服务配置

将 `taskService` 对象传给 `CommandCenterProvider`：

```jsx
const taskService = {
  get: async ({ queryselector, status }) => {
    // Your API call
    const data = await myApi.tasks.list({ status });
    return { result: { items: data } };
  },
  update: async ({ id, action, outputs, comment }) => {
    const data = await myApi.tasks.update(id, { action, outputs, comment });
    return { result: data };
  },
};

<CommandCenterProvider taskService={taskService} ...>
```

#### 说明

- 未配置 `taskService` 时，所有任务相关命令都会返回 `NO_TASK_SERVICE` 错误。
- 响应结构会被规范化：该操作先查找 `response?.result?.items`，再查找 `response?.items`。请据此调整你的 `taskService.get` 方法。
- 在认领或完成任务之前，使用 `read.tasks.detail` 获取该任务的完整详情。

### `/list-surfaces`

`command_center.read.ui.surfaces.list`

列出已发布的界面（模态框、表格、表单）

#### 用途

列出 Command Center 中当前注册的所有 UI 界面，包括其 ID、类型、标签和描述。界面是 Command Center 可以通过编程方式交互的 UI 元素（表格、表单、模态框、面板、应用）。

#### 使用场景

- 用户问“我可以和哪些 UI 元素交互？”时。
- 在调用 `exec.ui.apply_filter`、`exec.ui.select_rows`、`exec.ui.submit_form` 等命令之前，用于查找有效的界面 ID。
- 作为多命令计划中的发现步骤。

#### 参数

无。

#### 返回值

```js
{
  surfaces: [
    {
      id: "project-list-grid",
      type: "grid",
      label: "Project List",
      description: "Grid listing all projects with filter and row selection."
    },
    {
      id: "create-project-form",
      type: "form",
      label: "Create Project Form",
      description: "Form to create a new project."
    },
    {
      id: "agent-profile-list-grid",
      type: "grid",
      label: "Agent Profile List",
      description: "Grid of AI agent profiles."
    }
  ]
}
```

如果没有注册任何界面：

```js
{ surfaces: [] }
```

#### 实现

```js
// commands/read/listSurfaces.action.js
export const action = (registry) => {
  if (!registry?.getSurfaces) {
    return { surfaces: [] };
  }

  return { surfaces: registry.getSurfaces() };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.ui.surfaces.list',
  label: '/list-surfaces',
  description: 'List all registered UI surfaces (grids, forms, modals, panels)',
  schema: {},
  action: () => Read.listSurfaces(registry),
}
```

#### 在宿主应用中注册界面

使用 `useSommaticSurface` 注册界面：

```jsx
import { useSommaticSurface } from 'sommatic-react-sdk';

useSommaticSurface(
  {
    id: 'llm-provider-list-grid',
    type: 'grid',
    label: 'LLM Provider List',
    description: 'Grid listing all configured LLM providers.',
    handlers: {
      applyFilter: (value) => setFilter(value),
      selectRows: (ids) => setSelectedRowIds(ids),
    },
    targets: [],
  },
  [],
);
```

`getSurfaces()` 返回的列表包含 `id`、`type`、`label`、`description`，以及可选的 `targets`。

#### 相关命令

- `read.ui.targets.list`：列出指定界面中的各个 UI 目标。
- `observe.ui`：针对给定的自然语言指令，建议相关的界面/目标。
- `exec.ui.open_surface`、`exec.ui.close_surface`：打开/关闭模态框或面板界面。
- `exec.ui.apply_filter`、`exec.ui.select_rows`：与表格界面交互。

#### 说明

- 宿主组件卸载时，界面会自动清理（通过 `registerSurface` 返回的注销函数）。
- `getSurfaces()` 方法只返回当前已挂载的界面。

### `/list-targets`

`command_center.read.ui.targets.list`

列出某个界面的目标

#### 用途

列出指定界面中所有可操作的目标。目标代表单个 UI 元素（按钮、输入框、下拉框等），Command Center 可以通过 `exec.ui.act` 或 `extract.from_targets` 命令与之交互。

#### 使用场景

- 在调用 `exec.ui.act` 之前，用于查找有效的 `target_ref` 值。
- 用户问“这个表单里有哪些可用操作？”时。
- 在调用 `exec.ui.set_fields` 之前，了解表单界面中有哪些可用字段。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 要检查的界面 ID。 |

#### 返回值

每个目标都包含格式为 `surface_id::target_id` 的 **`target_ref`**。在 `exec.ui.act` 和 `extract.from_targets` 中请原样使用该字符串（不要手动拼接）。

```js
{
  ok: true,
  surface_id: "create-project-form",
  targets: [
    {
      ref: "project-name-input",
      id: "project-name-input",
      label: "Project Name",
      type: "input",
      methods: ["getValue", "fill"],
      target_ref: "create-project-form::project-name-input"
    },
    {
      ref: "submit-btn",
      id: "submit-btn",
      label: "Submit",
      type: "button",
      methods: ["click"],
      target_ref: "create-project-form::submit-btn"
    },
    {
      ref: "status-dropdown",
      id: "status-dropdown",
      label: "Status",
      type: "select",
      methods: ["getValue", "fill"],
      target_ref: "create-project-form::status-dropdown"
    }
  ]
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
```

#### 实现

```js
// commands/read/listTargets.action.js
export const action = (args, registry) => {
  const { surface_id } = args || {};

  if (!surface_id) {
    return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };
  }

  if (!registry?.getTargets) {
    return { surface_id, targets: [] };
  }

  const rawTargets = registry.getTargets(surface_id);
  const targets = rawTargets.map((t) => {
    const ref = t.ref || t.id || '';
    return {
      ref,
      id: ref,
      label: t.label || '',
      type: t.type || 'unknown',
      methods: t.methods || [],
      target_ref: `${surface_id}::${ref}`,
    };
  });

  return { surface_id, targets };
};
```

#### 命令定义

```js
{
  id: 'command_center.read.ui.targets.list',
  label: '/list-targets',
  description: 'List all actionable targets within a surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: {
        type: 'string',
        description: 'ID of the surface to inspect.'
      }
    },
    required: ['surface_id']
  },
  action: (args) => Read.listTargets(args, registry),
}
```

#### 在宿主应用中定义目标

目标在界面的 `targets` 数组中指定：

```jsx
useSommaticSurface({
  id: 'create-agent-form',
  type: 'form',
  label: 'Create Agent Form',
  targets: [
    {
      id: 'agent-name-input',
      label: 'Agent Name',
      type: 'input',
      handlers: {
        getValue: () => nameValue,
        fill: (value) => setNameValue(value),
      },
    },
    {
      id: 'submit-btn',
      label: 'Submit',
      type: 'button',
      handlers: {
        click: () => handleSubmit(),
      },
    },
  ],
  handlers: {
    setFields: (fields) => { if (fields.name) setNameValue(fields.name); },
    submit: () => handleSubmit(),
  },
}, []);
```

#### 目标引用格式

`read.ui.targets.list` 的响应为每个目标提供格式为 `{surface_id}::{target_id}` 的 **`target_ref`**。调用 `exec.ui.act` 或 `extract.from_targets` 时请原样使用该字符串：

```
{surface_id}::{target_id}
```

示例（来自目标列表的响应）：
```
create-agent-form::agent-name-input
create-agent-form::submit-btn
```

`registry.resolveTarget(targetRef)` 解析该格式并返回 `{ surface, target }`。

#### 虚拟目标

如果界面没有显式定义 `targets`，但注册了 `handlers`，`observe.ui` 命令会为这些处理器生成**虚拟目标**。由于 `getTargets()` 只返回显式定义的目标，这些虚拟目标不会出现在 `list-targets` 的结果中。请使用 `observe.ui` 发现虚拟目标。

#### 说明

- 对于只通过处理器暴露功能的表格和面板，`targets: []` 为空很常见。请使用 `observe.ui` 发现它们的能力。
- 响应中的 `methods` 数组由 `Object.keys(target.handlers)` 得出。

## 执行类命令

### `/open-app`

`command_center.exec.app.open`

在 Command Center 中打开一个 Sommatic AI 应用。将用户意图（任意语言、任意措辞或拼写）与 `context.client.navigation.available_apps` 做语义匹配——每个条目都包含 `slug`、`name`、`description`、`tags` 和 `default_route`。将匹配到的 `slug` 作为 `app_slug` 输出。若匹配条目带有 `default_route`，除非用户明确要求其他路由，否则将其用作 `route_path`。作为最后的兜底方案，也可以传入 `app_name`（便于阅读的名称），由运行时从目录中解析。

#### 用途

打开 HITL（人机协同）应用界面并等待其输出。与即发即弃的 `exec.ui.open_surface` 不同，该命令会等待应用完成，并返回用户在应用内交互产生的输出。

HITL 应用界面是复杂的 UI（向导、多步表单、嵌入式工具），由智能体启动，用于向用户收集结构化输入。

#### 使用场景

- 工作流需要结构化的人工输入才能继续时。
- 需要启动智能体无法自动填写的向导或多步数据采集表单时。
- 当 `exec.ui.set_fields` + `exec.ui.submit_form` 不足以完成任务、需要用户与复杂 UI 交互时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `app_id` | `string` | 是 | 要打开的应用的界面 ID。该界面的类型必须为 `'app'`，且具备 `open` 处理器。 |
| `initial_state` | `object` | 否 | 可选状态，在应用展示给用户之前预先填充。 |

#### 返回值

```js
{
  ok: true,
  title: "Opened app [create-project-wizard]",
  outputs: {
    name: "My New Project",
    status: "active",
    organization: "org-232121",
    confirmed: true
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

如果用户取消了应用：

```js
{
  ok: true,
  title: "Opened app [create-project-wizard]",
  outputs: { cancelled: true },
  receipt_id: "..."
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_APP_ID", message: "app_id is required" } }
{ ok: false, error: { code: "APP_NOT_FOUND", message: "App [xyz] not found in surface registry" } }
{ ok: false, error: { code: "NO_OPEN_HANDLER", message: "App [xyz] has no open handler" } }
{ ok: false, error: { code: "APP_OPEN_FAILED", message: "App threw: ..." } }
```

#### 实现

```js
// commands/exec/openApp.action.js
export const action = async (args, registry) => {
  const { app_id, initial_state } = args || {};

  if (!app_id) return { ok: false, error: { code: 'MISSING_APP_ID', message: 'app_id is required' } };

  const surface = registry?.getSurface?.(app_id);
  if (!surface) return { ok: false, error: { code: 'APP_NOT_FOUND', message: `App [${app_id}] not found` } };

  if (!surface.handlers?.open) {
    return { ok: false, error: { code: 'NO_OPEN_HANDLER', message: `App [${app_id}] has no open handler` } };
  }

  let outputs;
  try {
    outputs = await surface.handlers.open(initial_state);
  } catch (err) {
    return { ok: false, error: { code: 'APP_OPEN_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.app.open',
    args,
    reversible: false,
    outputs,
  });

  return { ok: true, title: `Opened app [${app_id}]`, outputs, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.app.open',
  label: '/open-app',
  description: 'Open a HITL app surface and wait for user outputs',
  schema: {
    type: 'object',
    properties: {
      app_id: { type: 'string', description: 'Surface ID of the app to open.' },
      initial_state: { type: 'object', description: 'Optional initial state to pre-populate the app.' }
    },
    required: ['app_id']
  },
  action: (args) => Exec.openApp(args, registry),
}
```

#### 实现应用界面

`open` 处理器必须返回一个 Promise，在用户完成或取消应用时 resolve：

```jsx
const [isOpen, setIsOpen] = useState(false);
const [resolveOutputs, setResolveOutputs] = useState(null);

useSommaticSurface({
  id: 'create-project-wizard',
  type: 'app',
  label: 'Create Project Wizard',
  handlers: {
    open: (initialState) => new Promise((resolve) => {
      if (initialState?.name) setPrefillName(initialState.name);
      setIsOpen(true);
      setResolveOutputs(() => resolve);  // Store resolver for later
    }),
  },
}, []);

// When user completes the wizard:
const handleComplete = (outputs) => {
  setIsOpen(false);
  resolveOutputs?.(outputs);  // Resolves the promise → command returns
};

// When user cancels:
const handleCancel = () => {
  setIsOpen(false);
  resolveOutputs?.({ cancelled: true });
};
```

#### 说明

- `open` 处理器必须是异步函数（或返回 Promise）。命令会 `await` 它，因此在用户完成应用之前，Command Center 会一直显示“思考中”。
- 该模式实现了真正的人机协同：智能体会暂停，等待结构化的人工输入后再继续执行计划。
- `outputs` 的结构完全由应用定义，Command Center 不强制任何 schema。

### `/copy`

`command_center.exec.clipboard.copy`

将制品复制到剪贴板

#### 用途

使用浏览器的 Clipboard API 将一段文本复制到用户剪贴板。适用于从上下文中提取值，方便用户直接粘贴。

#### 使用场景

- 用户说“把项目 ID 复制到剪贴板”时。
- 综合回复中包含用户想在别处使用的值时。
- 作为计划的最后一步：获取数据 → 复制指定字段。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `content` | `string` | 是 | 要复制到剪贴板的文本。 |

#### 返回值

```js
{
  ok: true,
  title: "Copied to clipboard",
  receipt_id: "rcpt_1772075473717_byfawpr"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_CONTENT", message: "content is required" } }
{ ok: false, error: { code: "CLIPBOARD_UNAVAILABLE", message: "Clipboard API is not available" } }
{ ok: false, error: { code: "COPY_FAILED", message: "Permission denied" } }
```

#### 实现

```js
// commands/exec/copyToClipboard.action.js
export const action = async (args, registry) => {
  const { content } = args || {};

  if (!content) return { ok: false, error: { code: 'MISSING_CONTENT', message: 'content is required' } };

  if (!navigator?.clipboard?.writeText) {
    return { ok: false, error: { code: 'CLIPBOARD_UNAVAILABLE', message: 'Clipboard API is not available' } };
  }

  try {
    await navigator.clipboard.writeText(content);
  } catch (err) {
    return { ok: false, error: { code: 'COPY_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.clipboard.copy',
    args,
    reversible: false,
    content,
  });

  return { ok: true, title: 'Copied to clipboard', receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.clipboard.copy',
  label: '/copy',
  description: 'Copy text to the clipboard',
  schema: {
    type: 'object',
    properties: {
      content: { type: 'string', description: 'Text to copy to the clipboard.' }
    },
    required: ['content']
  },
  action: (args) => Exec.copyToClipboard(args, registry),
}
```

#### 说明

- Clipboard API 需要安全上下文（HTTPS 或 localhost）。在非安全上下文中，`navigator.clipboard` 为 `undefined`，命令返回 `CLIPBOARD_UNAVAILABLE`。
- `content` 可以是任意字符串：ID、URL、JSON 片段，或从数据源快照中提取的整段文本。
- 该命令不可撤销，“撤销”剪贴板复制没有实际意义。

### `/invoke-command`

`command_center.exec.command.invoke`

执行功能模块发布的语义命令

#### 用途

按 ID 执行另一条已注册的 Command Center 命令。这是一条元命令：LLM 可借此以编程方式串联或重复执行命令，功能模块也可借此发布供系统其他部分调用的语义化命令。

#### 使用场景

- 当功能模块发布了高层命令（例如 `project.refresh`、`org.reload`），而另一条命令或自动化流程需要调用它时。
- 用于动态组合：LLM 从上下文中得知某个命令 ID，需要在不了解其实现的情况下调用它。
- 用于测试：在一条命令中按名称调用另一条命令。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `command_id` | `string` | 是 | 要调用的命令的完整 ID。 |
| `args` | `object` | 否 | 传给被调用命令 action 的参数。 |

#### 返回值

```js
{
  ok: true,
  title: "Invoked command [command_center.read.page.outline]",
  result: { /* whatever the invoked command returned */ },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_COMMAND_ID", message: "command_id is required" } }
{ ok: false, error: { code: "COMMAND_NOT_FOUND", message: "Command [xyz] not found" } }
{ ok: false, error: { code: "NO_ACTION", message: "Command [xyz] has no action defined" } }
{ ok: false, error: { code: "INVOKE_FAILED", message: "Command threw: ..." } }
```

#### 实现

```js
// commands/exec/invokeCommand.action.js
export const action = async (args, registry) => {
  const { command_id, args: commandArgs } = args || {};

  if (!command_id) return { ok: false, error: { code: 'MISSING_COMMAND_ID', message: 'command_id is required' } };

  const commands = registry?.commands || [];
  const cmdDef = commands.find((cmd) => cmd.id === command_id);

  if (!cmdDef) return { ok: false, error: { code: 'COMMAND_NOT_FOUND', message: `Command [${command_id}] not found` } };
  if (!cmdDef.action) return { ok: false, error: { code: 'NO_ACTION', message: `Command [${command_id}] has no action` } };

  let result;
  try {
    result = await cmdDef.action(commandArgs);
  } catch (err) {
    return { ok: false, error: { code: 'INVOKE_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.command.invoke',
    args,
    reversible: false,
    invoked_command: command_id,
    result,
  });

  return { ok: true, title: `Invoked command [${command_id}]`, result, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.command.invoke',
  label: '/invoke-command',
  description: 'Execute a registered command by ID',
  schema: {
    type: 'object',
    properties: {
      command_id: {
        type: 'string',
        description: 'Full ID of the command to invoke (e.g. "command_center.read.capabilities").'
      },
      args: {
        type: 'object',
        description: 'Arguments to pass to the invoked command.'
      }
    },
    required: ['command_id']
  },
  action: (args) => Exec.invokeCommand(args, registry),
}
```

#### 说明

- 该命令通过 `registry.commands`（读取 `allCommandsRef.current`）查找目标命令，静态注册和动态注册的命令均可访问。
- 避免循环调用（即命令通过此机制调用自身）。
- 被调用命令的 action 会直接以 `commandArgs` 调用，不会再次经过 LLM 路由管线。

### `/navigate`

`command_center.exec.navigate`

导航到某个页面。将用户意图（任意语言、任意措辞或拼写）与 `context.client.navigation.available_pages` 中的页面做语义匹配。每个条目都包含 `path` 和 `description`。选出最匹配页面的 `path`，并原样输出。

#### 用途

使用 React Router 的 `navigate` 函数将应用导航到指定路由。导航后命令会等待 1.5 秒，让新页面完成挂载，再执行计划的下一步。

#### 使用场景

- 用户说“去项目页面”或“打开智能体配置”时。
- 作为计划的第一步，需要先导航再读取页面上下文时。
- 用于深度链接：“跳转到项目 XYZ 的详情页。”

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `route` | `string` | 是 | 要导航到的绝对路径（例如 `/admin/projects`）。 |

#### 返回值

```js
{
  success: true,
  message: "Navigating to /admin/project/management"
}
```

未提供路由时：

```js
{ success: false, message: "Route not provided" }
```

#### 实现

```js
// commands/exec/navigate.action.js
export const action = async ({ route }, navigate) => {
  if (route) {
    navigate(route);
    await new Promise((resolve) => setTimeout(resolve, 1500));
    return { success: true, message: `Navigating to ${route}` };
  }
  return { success: false, message: 'Route not provided' };
};
```

`navigate` 函数在注册命令时注入（而非通过注册表）：

```js
// In getExecCommands({ navigate, routeMap, ... })
{
  id: 'command_center.exec.navigate',
  action: (args) => Exec.navigate(args, navigate),  // navigate is closed over
}
```

#### 命令定义

```js
{
  id: 'command_center.exec.navigate',
  label: '/navigate',
  description: 'Navigate to a specific route in the application',
  schema: {
    type: 'object',
    properties: {
      route: {
        type: 'string',
        description: "Absolute route path (e.g. '/admin/projects', '/admin/agent-profiles'). Use routeMap for known routes."
      }
    },
    required: ['route']
  },
  action: (args) => Exec.navigate(args, navigate),
}
```

#### 路由映射集成

传给 `getExecCommands` 的 `routeMap` 常量可以写入命令描述，帮助 LLM 了解有效路由：

```js
// In definitions.js or via schema description:
description: `Navigate to a route. Known routes: ${Object.entries(ROUTE_MAP).map(([k,v]) => `${k}: ${v}`).join(', ')}`
```

#### 说明

- 导航后的 1.5 秒等待是有意设计的：让新页面有时间挂载 `useSommaticContextSource` 和 `useSommaticSurface` hook，再执行计划中的下一条命令。
- 如果计划的后续步骤需要新页面的 page-context 数据，1.5 秒通常足够；但高度动态的页面（例如异步拉取数据的页面）在生成快照时仍可能处于 `isLoading: true`。
- 该命令使用 React Router `useNavigate` hook 提供的 `navigate`，它必须在调用 `getExecCommands` 的作用域内可用（即位于 `<Router>` 内的组件中）。

### `/claim-task`

`command_center.exec.tasks.claim`

认领一个 HITL 任务

#### 用途

将 HITL 任务分配给当前用户，认领其所有权。认领后，任务状态变为 `in_progress`，并锁定给认领用户。

#### 使用场景

- 用户说“认领任务 XYZ”或“把这个任务分配给我”时。
- 作为 HITL 工作流的第二步：查看收件箱 → 认领任务 → 完成任务。
- 在调用 `exec.tasks.complete` 之前：只有已认领的任务才能完成。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `task_id` | `string` | 是 | 要认领的任务 ID。 |

#### 返回值

```js
{
  ok: true,
  title: "Claimed task [task-abc123]",
  data: {
    id: "task-abc123",
    status: "in_progress",
    assigned_to: "user-xyz",
    claimed_at: "2026-02-25T21:00:00.000Z"
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "CLAIM_FAILED", message: "Task is already claimed by another user" } }
```

#### 实现

```js
// commands/exec/claimTask.action.js
export const action = async (args, registry) => {
  const { task_id } = args || {};

  if (!task_id) return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };

  const taskStore = registry?.taskService;
  if (!taskStore) return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };

  try {
    const response = await taskStore.update({ id: task_id, action: 'claim' });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.claim',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Claimed task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'CLAIM_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.tasks.claim',
  label: '/claim-task',
  description: 'Claim a HITL task and assign it to the current user',
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to claim.' }
    },
    required: ['task_id']
  },
  action: (args) => Exec.claimTask(args, registry),
}
```

#### 任务服务契约

`taskService.update` 方法接收：

```js
{ id: "task-abc123", action: "claim" }
```

应返回：

```js
{ result: { id, status, assigned_to, ... } }
// or directly: { id, status, assigned_to, ... }
```

#### 说明

- 在大多数工作流中，认领不可撤销，任务认领没有撤销操作。
- 如果任务服务返回错误（例如任务已被认领），错误信息将以 `CLAIM_FAILED` 返回。

### `/comment-task`

`command_center.exec.tasks.comment`

为任务添加评论

#### 用途

为 HITL 任务添加文本评论，不改变其状态。评论提供轻量的审计记录，用户可借此记录判断依据、提出问题或给其他审阅者留言。

#### 使用场景

- 用户想为任务添加批注时：“给任务 XYZ 加一条备注：'Needs review from legal.'”
- 用于异步协作：在移交任务前留下反馈。
- 当用户需要先获取更多信息时，作为完成任务的替代操作。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `task_id` | `string` | 是 | 要评论的任务 ID。 |
| `comment` | `string` | 是 | 评论内容，不能为空。 |

#### 返回值

```js
{
  ok: true,
  title: "Added comment to task [task-abc123]",
  data: {
    id: "task-abc123",
    comment_id: "comment-xyz",
    text: "Needs review from legal team.",
    created_at: "2026-02-25T22:30:00.000Z",
    created_by: "user-xyz"
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "MISSING_COMMENT", message: "A non-empty comment is required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "COMMENT_FAILED", message: "..." } }
```

#### 实现

```js
// commands/exec/commentTask.action.js
export const action = async (args, registry) => {
  const { task_id, comment } = args || {};

  if (!task_id) return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };

  if (!comment || typeof comment !== 'string' || comment.trim().length === 0) {
    return { ok: false, error: { code: 'MISSING_COMMENT', message: 'A non-empty comment is required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };

  try {
    const response = await taskStore.update({ id: task_id, action: 'comment', comment: comment.trim() });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.comment',
      args: { task_id, comment: comment.trim() },
      reversible: false,
      result,
    });

    return { ok: true, title: `Added comment to task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'COMMENT_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.tasks.comment',
  label: '/comment-task',
  description: 'Add a comment to a HITL task',
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to comment on.' },
      comment: { type: 'string', description: 'Comment text to add. Must be non-empty.' }
    },
    required: ['task_id', 'comment']
  },
  action: (args) => Exec.commentTask(args, registry),
}
```

#### 任务服务契约

`taskService.update` 方法接收：

```js
{ id: "task-abc123", action: "comment", comment: "Needs review from legal team." }
```

#### 说明

- 评论不会改变任务状态。无论任务处于 `pending`、`in_progress` 还是 `completed`，都可以评论。
- 评论在发送给服务之前会去除首尾空白。
- 该命令不可撤销，评论无法通过 Command Center 删除。

### `/complete-task`

`command_center.exec.tasks.complete`

使用已校验的输出完成任务

#### 用途

提交所需输出以完成 HITL 任务。任务状态变为 `completed`，创建该任务的自动化工作流即可继续执行。

#### 使用场景

- 用户审阅完任务、准备提交决定或输出时。
- 作为 HITL 工作流的最后一步：列出 → 认领 → 完成。
- 用户说“以 approved: true 完成任务 XYZ”时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `task_id` | `string` | 是 | 要完成的任务 ID。 |
| `outputs` | `object` | 是 | 任务要求的结构化输出，结构由 `task.outputs_schema` 定义。 |

#### 返回值

```js
{
  ok: true,
  title: "Completed task [task-abc123]",
  data: {
    id: "task-abc123",
    status: "completed",
    outputs: { approved: true, comment: "Looks good." },
    completed_at: "2026-02-25T22:00:00.000Z"
  },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_TASK_ID", message: "task_id is required" } }
{ ok: false, error: { code: "MISSING_OUTPUTS", message: "outputs are required to complete a task" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "COMPLETE_FAILED", message: "Task is not in a completable state" } }
```

#### 实现

```js
// commands/exec/completeTask.action.js
export const action = async (args, registry) => {
  const { task_id, outputs } = args || {};

  if (!task_id) return { ok: false, error: { code: 'MISSING_TASK_ID', message: 'task_id is required' } };
  if (!outputs) return { ok: false, error: { code: 'MISSING_OUTPUTS', message: 'outputs are required to complete a task' } };

  const taskStore = registry?.taskService;
  if (!taskStore) return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };

  try {
    const response = await taskStore.update({ id: task_id, action: 'complete', outputs });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.complete',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Completed task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'COMPLETE_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.tasks.complete',
  label: '/complete-task',
  description: 'Complete a HITL task with the provided outputs',
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to complete.' },
      outputs: {
        type: 'object',
        description: 'Task outputs. Structure defined by task outputs_schema. Use read.tasks.detail to inspect requirements.'
      }
    },
    required: ['task_id', 'outputs']
  },
  action: (args) => Exec.completeTask(args, registry),
}
```

#### 任务服务契约

`taskService.update` 方法接收：

```js
{ id: "task-abc123", action: "complete", outputs: { approved: true } }
```

#### 典型的完整 HITL 流程

```
1. read.tasks.inbox { status: "pending" }
   → [{ id: "task-abc123", title: "Review agent config" }]

2. read.tasks.detail { task_id: "task-abc123" }
   → { outputs_schema: { approved: { type: "boolean" } } }

3. exec.tasks.claim { task_id: "task-abc123" }

4. exec.tasks.complete { task_id: "task-abc123", outputs: { approved: true, comment: "OK" } }
```

### `/create-task`

`command_center.exec.tasks.create`

创建新的 HITL 任务

#### 用途

新建一个人机协同任务。当智能体或操作员需要将契约性决策（审批、数据补全、审阅、处置、委派）交给某个人或某个组时使用。

在此创建的任务与其他 HITL 任务行为一致：会出现在 `/tasks-inbox` 中，可以被认领、评论、流转和完成。

#### 使用场景

- 用户希望正式移交需要人工判断的工作时。
- 用户说“创建一个任务来审批这个”“把这个委派给运维”“给财务排一个审阅”时。
- 作为工作流中生成任务的步骤，在继续之前需要经过人工关卡时。

不要将其用于临时通知或无需审计记录的个人提醒：任务是契约性的，不是随手记录。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `title` | `string` | 是 | 简短的任务标题（目标），显示在收件箱和通知中。 |
| `type` | `object` | 是 | 任务类型，包含 `id` 和 `name`。取值之一：`approval`、`data_completion`、`review`、`resolution`、`delegation`。 |
| `priority` | `object` | 是 | 优先级，包含 `id` 和 `name`。取值之一：`low`、`medium`、`high`、`critical`。 |
| `required_output` | `object` | 是 | 定义处理人必须产出的内容。包含 JSON `schema` 和可选的 `ui_hint`。 |
| `assignee` | `object` | 否 | 处理人，包含 `assignee_type: 'user' \| 'group'` 以及对应的 `user` 或 `group` 引用。省略处理人表示任务未被认领。 |
| `sla` | `object` | 否 | SLA，包含 `due_at`（Unix 毫秒时间戳字符串）和 `sla_ms`（时长，单位毫秒）。 |
| `payload` | `object` | 否 | 上下文载荷，包含 `summary`、`evidence[]` 和 `linked_entities[]`，为处理人提供足够的信息来采取行动。 |

#### 返回值

```js
{
  ok: true,
  title: "Created task [task-abc123]",
  data: {
    id: "task-abc123",
    title: "Review onboarding evidence",
    status: "pending",
    type: { id: "review", name: "Review" },
    priority: { id: "high", name: "High" },
    organization_id: "org-xyz",
    created_at: "2026-05-01T10:00:00.000Z"
  },
  receipt_id: "rcpt_1772075473717_create"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_ARGS", message: "title, type, priority and required_output are required" } }
{ ok: false, error: { code: "NO_TASK_SERVICE", message: "Task service is not configured" } }
{ ok: false, error: { code: "CREATE_FAILED", message: "<service error>" } }
```

回执**不可**撤销：无法通过 `/undo` 撤销任务创建。如有需要，请通过 `/task-transition { transition_name: 'invalidate' }` 取消。

#### 实现

```js
// commands/exec/createTask.action.js
export const action = async (args, registry) => {
  const { title, type, priority, required_output, assignee, sla, payload } = args || {};

  if (!title || !type || !priority || !required_output) {
    return { ok: false, error: { code: 'MISSING_ARGS', message: 'title, type, priority and required_output are required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const organization_id = registry?.currentUser?.payload?.organization_id || '';
    const response = await taskStore.create({ title, type, priority, required_output, assignee, sla, payload, organization_id });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.create',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Created task [${result?.id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'CREATE_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.tasks.create',
  label: '/create-task',
  description: 'Create a new HITL Task',
  schema: {
    type: 'object',
    properties: {
      title: { type: 'string', description: 'Short task title (the goal).' },
      type: { type: 'object', description: 'Task type object with id and name (approval, data_completion, review, resolution, delegation).' },
      priority: { type: 'object', description: 'Task priority object with id and name (low, medium, high, critical).' },
      required_output: { type: 'object', description: 'Required output definition with schema and optional ui_hint.' },
      assignee: { type: 'object', description: 'Optional. Assignee object with assignee_type (user|group) and user or group reference.' },
      sla: { type: 'object', description: 'Optional. SLA object with due_at (Unix ms string) and sla_ms (duration in ms).' },
      payload: { type: 'object', description: 'Optional. Context payload with summary, evidence[] and linked_entities[].' }
    },
    required: ['title', 'type', 'priority', 'required_output']
  },
  action: (args) => Exec.createTask(args, registry),
}
```

#### 任务服务契约

`taskService.create` 方法接收：

```js
{
  title: "Review onboarding evidence",
  type: { id: "review", name: "Review" },
  priority: { id: "high", name: "High" },
  required_output: {
    schema: { type: 'object', properties: { approved: { type: 'boolean' } }, required: ['approved'] },
    ui_hint: 'checkbox',
  },
  assignee: { assignee_type: 'user', user: { id: 'user-12345' } },
  sla: { due_at: '1772075473717', sla_ms: 86400000 },
  payload: {
    summary: 'Review the latest onboarding evidence batch',
    evidence: [{ url: '...', kind: 'document' }],
    linked_entities: [{ type: 'organization', id: 'org-xyz' }],
  },
  organization_id: "org-xyz",
}
```

`organization_id` 会根据 `registry.currentUser.payload.organization_id` 自动附加，无需由 LLM 提供。

#### 典型流程

```
1. exec.tasks.create {
     title: "Approve refund #4421",
     type: { id: "approval", name: "Approval" },
     priority: { id: "high", name: "High" },
     required_output: { schema: { type: 'object', properties: { approved: { type: 'boolean' } } } },
     assignee: { assignee_type: 'group', group: { id: 'finance-leads' } }
   }
   → { id: "task-9988", status: "pending" }

2. (later) read.tasks.inbox { status: "pending" }
   → [{ id: "task-9988", title: "Approve refund #4421" }]

3. exec.tasks.claim { task_id: "task-9988" }

4. exec.tasks.complete { task_id: "task-9988", outputs: { approved: true } }
```

#### 另请参阅

- `read.tasks.inbox.md`：列出已分配的任务
- `read.tasks.detail.md`：查看所需输出的 schema
- `exec.tasks.claim.md`：认领任务
- `exec.tasks.complete.md`：提交输出
- `exec.tasks.transition.md`：执行生命周期流转
- [docs/command-center/changelog-recent.en.md](../../../../../docs/command-center/changelog-recent.en.md)：完整的 HITL 命令集概览

### `/task-transition`

`command_center.exec.tasks.transition`

对任务执行生命周期状态转换（assign、claim、start、complete、reject、invalidate、expire）

#### 用途

对 HITL 任务执行生命周期流转：`assign`、`claim`、`start`、`complete`、`reject`、`invalidate` 或 `expire`。它是 `exec.tasks.claim` 和 `exec.tasks.complete` 的通用形式，也是唯一可以驳回、作废或使任务过期的命令。

#### 使用场景

- “驳回任务 XYZ，因为文件无法辨认。”
- “把任务 XYZ 分配给 Ana。”
- 任何没有专用命令的流转。

适用时，优先使用 `exec.tasks.claim` 和 `exec.tasks.complete`。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `task_id` | `string` | 是 | 要流转的任务 ID。 |
| `transition_name` | `string` | 是 | 取值之一：`assign`、`claim`、`start`、`complete`、`reject`、`invalidate`、`expire`。 |
| `payload` | `object` | 否 | 流转所需的附加数据，例如 `assignee`、`outputs`、`claimed_by`、`reason`。 |

该 action 本身不校验 `transition_name` 或 `payload`：由后端根据任务当前状态判断是否允许该流转。

#### 返回值

```js
{
  ok: true,
  title: "Transition 'reject' applied to task [task-abc123]",
  data: { id: 'task-abc123', status: '<status after the transition>' /* task as returned by the backend */ },
  receipt_id: 'rcpt_1772075473717_abc'
}
```

存在 `response.result` 时，`data` 即为该值，否则为原始响应。

##### 错误情况

```js
{ ok: false, error: { code: 'MISSING_ARGS', message: 'task_id and transition_name are required' } }
{ ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } }
{ ok: false, error: { code: 'TRANSITION_FAILED', message: '<backend error message>' } }
```

#### 实现

```js
// commands/exec/taskTransition.action.js
export const action = async (args, registry) => {
  const { task_id, transition_name, payload } = args || {};

  if (!task_id || !transition_name) {
    return { ok: false, error: { code: 'MISSING_ARGS', message: 'task_id and transition_name are required' } };
  }

  const taskStore = registry?.taskService;
  if (!taskStore) {
    return { ok: false, error: { code: 'NO_TASK_SERVICE', message: 'Task service is not configured' } };
  }

  try {
    const response = await taskStore.transition({ id: task_id, transition_name, payload });
    const result = response?.result || response;

    const receipt = registry.pushReceipt?.({
      command_id: 'command_center.exec.tasks.transition',
      args,
      reversible: false,
      result,
    });

    return { ok: true, title: `Transition '${transition_name}' applied to task [${task_id}]`, data: result, receipt_id: receipt?.id };
  } catch (err) {
    return { ok: false, error: { code: 'TRANSITION_FAILED', message: err.message } };
  }
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.tasks.transition',
  label: '/task-transition',
  description: 'Apply a lifecycle transition to a Task (assign, claim, start, complete, reject, invalidate, expire)',
  isPriority: true,
  schema: {
    type: 'object',
    properties: {
      task_id: { type: 'string', description: 'ID of the task to transition.' },
      transition_name: {
        type: 'string',
        enum: ['assign', 'claim', 'start', 'complete', 'reject', 'invalidate', 'expire'],
        description: 'Transition to apply.'
      },
      payload: { type: 'object', nullable: true, description: 'Extra data for the transition (e.g. assignee, outputs, claimed_by).' }
    },
    required: ['task_id', 'transition_name']
  },
  action: (args) => Exec.taskTransition(args, registry),
}
```

#### 任务服务契约

`registry.taskService.transition(data)` 接收：

```js
{ id: 'task-abc123', transition_name: 'reject', payload: { reason: 'Illegible document' } }
```

使用 SDK 的 `WorkManagementTaskService` 时，对应向 `/work-management/task/transition/` 发起 `PATCH` 请求。

### `/act-ui`

`command_center.exec.ui.act`

对目标执行确定性操作

#### 用途

在已注册的 UI 目标上触发单个操作，是粒度最细的 UI 交互命令。它解析目标引用，并调用该目标已注册的某个处理器方法。

#### 使用场景

- LLM 需要点击按钮、填写输入框或触发任何特定目标处理器时。
- 用于单次、精确的交互（多步操作请使用 `exec.ui.act_batch`）。
- 在通过 `observe.ui` 或 `read.ui.targets.list` 发现可用目标之后。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `target_ref` | `string` | 是 | 目标引用，格式为 `{surface_id}::{target_id}`。 |
| `method` | `string` | 是 | 要调用的处理器方法（例如 `click`、`fill`、`getValue`、`select`）。 |
| `arguments` | `any[]` | 否 | 传给处理器方法的参数。 |

#### 返回值

```js
{
  ok: true,
  title: "Executed [click] on [create-project-form::submit-btn]",
  result: { /* whatever the handler returned */ },
  receipt_id: "rcpt_1772075473717_abc123"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_TARGET_REF", message: "target_ref is required" } }
{ ok: false, error: { code: "MISSING_METHOD", message: "method is required" } }
{ ok: false, error: { code: "TARGET_NOT_FOUND", message: "Target [xyz::btn] not found" } }
{ ok: false, error: { code: "METHOD_NOT_FOUND", message: "Method [click] not supported on target [xyz::btn]" } }
{ ok: false, error: { code: "ACTION_FAILED", message: "Handler threw: ..." } }
```

#### 实现

```js
// commands/exec/actUi.action.js
export const action = async (args, registry) => {
  const { target_ref, method, arguments: methodArgs } = args || {};

  if (!target_ref) return { ok: false, error: { code: 'MISSING_TARGET_REF', message: 'target_ref is required' } };
  if (!method) return { ok: false, error: { code: 'MISSING_METHOD', message: 'method is required' } };

  const resolved = registry?.resolveTarget?.(target_ref);
  if (!resolved) return { ok: false, error: { code: 'TARGET_NOT_FOUND', message: `Target [${target_ref}] not found` } };

  const handler = resolved.target.handlers?.[method];
  if (!handler) return { ok: false, error: { code: 'METHOD_NOT_FOUND', message: `Method [${method}] not supported` } };

  let result;
  try {
    result = await handler(...(methodArgs || []));
  } catch (err) {
    return { ok: false, error: { code: 'ACTION_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.act',
    args,
    reversible: false,
    result,
  });

  return { ok: true, title: `Executed [${method}] on [${target_ref}]`, result, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.act',
  label: '/act',
  description: 'Trigger a single UI action on a registered target',
  schema: {
    type: 'object',
    properties: {
      target_ref: {
        type: 'string',
        description: "Target reference: 'surface_id::target_id' (e.g. 'create-project-form::submit-btn')"
      },
      method: {
        type: 'string',
        description: "Handler method to call (e.g. 'click', 'fill', 'select')"
      },
      arguments: {
        type: 'array',
        description: "Optional arguments to pass to the handler"
      }
    },
    required: ['target_ref', 'method']
  },
  action: (args) => Exec.actUi(args, registry),
}
```

#### 用法示例

```js
// Click a button
{ target_ref: "create-project-form::submit-btn", method: "click" }

// Fill an input
{ target_ref: "create-project-form::name-input", method: "fill", arguments: ["My New Project"] }

// Select an option
{ target_ref: "create-project-form::status-dropdown", method: "select", arguments: ["active"] }
```

#### 说明

- `resolveTarget(targetRef)` 通过解析 `::` 分隔符定位界面和目标。
- `receipt` 始终为 `reversible: false`，因为单个 UI 操作通常无法简单撤销。
- 对于按顺序执行的多步 UI 交互，建议使用 `exec.ui.act_batch`。

### `/act-batch-ui`

`command_center.exec.ui.act_batch`

执行一组 UI 操作序列

#### 用途

在已注册的目标上逐步执行一系列 UI 操作。适用于用户希望在一条命令中填写多个表单字段或与多个目标交互的场景。

所有步骤按顺序依次尝试。某一步失败时，相互独立的步骤会继续执行，但整体结果会返回 `ok: false`。

#### 使用场景

- 表单在提交前需要填写多个字段时。
- LLM 生成的计划需要点击多个目标时。
- 用于批量自动化：“填写名称、状态和组织，然后点击提交。”

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `steps` | `object[]` | 是 | 操作步骤数组。 |
| `steps[].target_ref` | `string` | 是 | 目标引用（`surface_id::target_id`）。 |
| `steps[].method` | `string` | 是 | 要调用的处理器方法。 |
| `steps[].arguments` | `any[]` | 否 | 传给该方法的参数。 |

#### 返回值

```js
{
  ok: true,
  title: "Executed 3/3 steps",
  step_results: [
    { target_ref: "create-form::name-input", method: "fill", ok: true, result: undefined },
    { target_ref: "create-form::status-select", method: "fill", ok: true, result: undefined },
    { target_ref: "create-form::submit-btn", method: "click", ok: true, result: { submitted: true } }
  ],
  receipt_id: "rcpt_1772075473717_xyz"
}
```

部分失败时：

```js
{
  ok: false,
  title: "Executed 2/3 steps",
  step_results: [
    { target_ref: "form::name-input", method: "fill", ok: true, result: undefined },
    { target_ref: "form::unknown-btn", method: "click", ok: false, error: "Target [form::unknown-btn] not found" },
    { target_ref: "form::submit-btn", method: "click", ok: true, result: { submitted: true } }
  ],
  receipt_id: "..."
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_STEPS", message: "steps array is required and must not be empty" } }
```

#### 实现

```js
// commands/exec/actBatchUi.action.js
export const action = async (args, registry) => {
  const { steps } = args || {};

  if (!Array.isArray(steps) || steps.length === 0) {
    return { ok: false, error: { code: 'MISSING_STEPS', message: 'steps array is required and must not be empty' } };
  }

  const stepResults = [];
  let hasError = false;

  for (const step of steps) {
    const { target_ref, method, arguments: methodArgs } = step;

    if (!target_ref || !method) {
      stepResults.push({ target_ref, method, ok: false, error: 'Missing target_ref or method' });
      hasError = true;
      continue;
    }

    const resolved = registry?.resolveTarget?.(target_ref);
    if (!resolved) {
      stepResults.push({ target_ref, method, ok: false, error: `Target [${target_ref}] not found` });
      hasError = true;
      continue;
    }

    const handler = resolved.target.handlers?.[method];
    if (!handler) {
      stepResults.push({ target_ref, method, ok: false, error: `Method [${method}] not supported` });
      hasError = true;
      continue;
    }

    try {
      const result = await handler(...(methodArgs || []));
      stepResults.push({ target_ref, method, ok: true, result });
    } catch (err) {
      stepResults.push({ target_ref, method, ok: false, error: err.message });
      hasError = true;
    }
  }

  const receipt = registry?.pushReceipt?.({
    command_id: 'command_center.exec.ui.act_batch',
    args,
    reversible: false,
    step_count: steps.length,
    success_count: stepResults.filter((r) => r.ok).length,
  });

  return {
    ok: !hasError,
    title: `Executed ${stepResults.filter((r) => r.ok).length}/${steps.length} steps`,
    step_results: stepResults,
    receipt_id: receipt?.id,
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.act_batch',
  label: '/act-batch',
  description: 'Execute multiple UI actions sequentially',
  schema: {
    type: 'object',
    properties: {
      steps: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            target_ref: { type: 'string' },
            method: { type: 'string' },
            arguments: { type: 'array' }
          },
          required: ['target_ref', 'method']
        }
      }
    },
    required: ['steps']
  },
  action: (args) => Exec.actBatchUi(args, registry),
}
```

#### 说明

- 失败时执行**不会**中止，无论是否出错，所有步骤都会被尝试执行。
- 只要**任一**步骤失败，顶层响应中的 `ok` 字段即为 `false`。
- 对于相互独立的步骤，某一步的错误不会影响后续步骤。
- 不支持依赖上一步结果数据的步骤（此时请在计划中使用多条单独的 `exec.ui.act` 命令）。

### `/apply-filter`

`command_center.exec.ui.apply_filter`

在 Grid/List 界面上应用筛选条件

#### 用途

对已注册的表格或列表界面应用文本筛选。以给定的筛选值调用界面的 `applyFilter` 处理器，更新表格中显示的内容。

#### 使用场景

- 用户说“按 'active' 筛选项目列表”或“只显示名称为 'Test' 的智能体”时。
- 在使用 `exec.ui.select_rows` 之前缩小列表范围。
- 用于快速搜索：“找到名为 'Development' 的项目。”

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 要筛选的表格/列表界面 ID。 |
| `filter` | `string` | 是 | 要应用的筛选字符串。传入空字符串可清除筛选。 |

#### 返回值

```js
{
  ok: true,
  title: "Applied filter 'active' to [project-list-grid]",
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "MISSING_FILTER", message: "filter is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_FILTER_HANDLER", message: "Surface [xyz] has no applyFilter handler" } }
{ ok: false, error: { code: "FILTER_FAILED", message: "Handler threw: ..." } }
```

#### 实现

```js
// commands/exec/applyFilter.action.js
export const action = async (args, registry) => {
  const { surface_id, filter } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };
  if (filter === undefined || filter === null) {
    return { ok: false, error: { code: 'MISSING_FILTER', message: 'filter is required' } };
  }

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.applyFilter) {
    return { ok: false, error: { code: 'NO_FILTER_HANDLER', message: `Surface [${surface_id}] has no applyFilter handler` } };
  }

  try {
    await surface.handlers.applyFilter(filter);
  } catch (err) {
    return { ok: false, error: { code: 'FILTER_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.apply_filter',
    args,
    reversible: true,
    undo: async () => surface.handlers.applyFilter(''),
  });

  return { ok: true, title: `Applied filter '${filter}' to [${surface_id}]`, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.apply_filter',
  label: '/apply-filter',
  description: 'Apply a text filter to a grid or list surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: {
        type: 'string',
        description: "ID of the grid surface. Known surfaces: 'project-list-grid', 'agent-profile-list-grid', 'llm-provider-list-grid', 'cognitive-tool-list-grid', 'prompt-template-list-grid', 'external-datasource-list-grid'."
      },
      filter: {
        type: 'string',
        description: "Text to filter by. Pass empty string '' to clear the filter."
      }
    },
    required: ['surface_id', 'filter']
  },
  action: (args) => Exec.applyFilter(args, registry),
}
```

#### 注册可筛选的表格

```jsx
const [filter, setFilter] = useState('');

useSommaticSurface({
  id: 'project-list-grid',
  type: 'grid',
  label: 'Project List',
  handlers: {
    applyFilter: (value) => setFilter(value),
    selectRows: (ids) => setSelectedRowIds(ids),
  },
}, []);

// In the DataGrid:
rows={projects.filter(p => p.name.toLowerCase().includes(filter.toLowerCase()))}
```

#### 说明

- `applyFilter` 在回执中为 `reversible: true`，撤销处理器会调用 `applyFilter('')` 清除筛选。
- 筛选逻辑由宿主组件实现，命令只负责以该字符串调用处理器。如果处理器会触发 API 调用，也可以实现服务端筛选。
- 如需清除筛选，请以 `filter: ""` 调用 `exec.ui.apply_filter`。

### `/close-surface`

`command_center.exec.ui.close_surface`

关闭界面

#### 用途

通过调用已注册界面的 `close` 处理器将其关闭，适用于模态框、抽屉或侧边面板。

#### 使用场景

- 在模态框内完成或取消表单之后。
- 用户说“关闭这个”或“关掉这个面板”时。
- 作为 `exec.ui.submit_form` 之后的清理步骤。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 要关闭的界面 ID。 |

#### 返回值

```js
{
  ok: true,
  title: "Closed surface [create-project-modal]",
  receipt_id: "rcpt_1772075473717_xyz"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_CLOSE_HANDLER", message: "Surface [xyz] has no close handler" } }
{ ok: false, error: { code: "CLOSE_FAILED", message: "Handler threw: ..." } }
```

#### 实现

```js
// commands/exec/closeSurface.action.js
export const action = async (args, registry) => {
  const { surface_id } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.close) {
    return { ok: false, error: { code: 'NO_CLOSE_HANDLER', message: `Surface [${surface_id}] has no close handler` } };
  }

  try {
    await surface.handlers.close();
  } catch (err) {
    return { ok: false, error: { code: 'CLOSE_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.close_surface',
    args,
    reversible: false,
  });

  return { ok: true, title: `Closed surface [${surface_id}]`, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.close_surface',
  label: '/close-surface',
  description: 'Close a modal, drawer, or panel surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the surface to close.' }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.closeSurface(args, registry),
}
```

#### 说明

- 该界面必须注册 `close` 处理器。如果界面通过 `useState` 的 setter 控制自身可见性，处理器应调用该 setter。
- 关闭后，界面仍会注册在 Command Center 中，直到其宿主组件卸载。调用 `getSurface(id)` 仍会返回该界面对象。

### `/open-surface`

`command_center.exec.ui.open_surface`

打开已发布的界面

#### 用途

通过调用已注册界面的 `open` 处理器将其打开，通常是模态框、抽屉或侧边面板。该界面必须注册一个控制其可见性的 `open` 处理器。

#### 使用场景

- 用户要求打开表单、模态框或面板时：“打开新建项目表单。”
- 当表单位于模态框内时，作为 `exec.ui.set_fields` 或 `exec.ui.submit_form` 的前置步骤。
- 对于 HITL 应用界面，建议使用支持异步输出的 `exec.app.open`。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 要打开的界面 ID。 |
| `params` | `object` | 否 | 传给 `open` 处理器的可选参数（例如表单初始值）。 |

#### 返回值

```js
{
  ok: true,
  title: "Opened surface [create-project-form]",
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_OPEN_HANDLER", message: "Surface [xyz] has no open handler" } }
{ ok: false, error: { code: "OPEN_FAILED", message: "Handler threw: ..." } }
```

#### 实现

```js
// commands/exec/openSurface.action.js
export const action = async (args, registry) => {
  const { surface_id, params } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.open) {
    return { ok: false, error: { code: 'NO_OPEN_HANDLER', message: `Surface [${surface_id}] has no open handler` } };
  }

  try {
    await surface.handlers.open(params);
  } catch (err) {
    return { ok: false, error: { code: 'OPEN_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.open_surface',
    args,
    reversible: false,
  });

  return { ok: true, title: `Opened surface [${surface_id}]`, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.open_surface',
  label: '/open-surface',
  description: 'Open a modal, drawer, or panel surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the surface to open.' },
      params: { type: 'object', description: 'Optional parameters to pass to the open handler.' }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.openSurface(args, registry),
}
```

#### 注册可打开的界面

```jsx
const [isOpen, setIsOpen] = useState(false);

useSommaticSurface({
  id: 'create-project-modal',
  type: 'modal',
  label: 'Create Project',
  handlers: {
    open: (params) => {
      if (params?.initialName) setProjectName(params.initialName);
      setIsOpen(true);
    },
    close: () => setIsOpen(false),
    submit: () => handleSubmit(),
  },
}, []);
```

#### 典型的串联流程

```
1. exec.ui.open_surface { surface_id: "create-project-modal" }
2. exec.ui.set_fields { surface_id: "create-project-modal", fields: { name: "New Project", status: "active" } }
3. exec.ui.submit_form { surface_id: "create-project-modal" }
```

### `/select-rows`

`command_center.exec.ui.select_rows`

选择行/条目

#### 用途

在已注册的表格界面中选中行。支持两种选择模式：
1. **按行 ID 直接选择**：已知确切 ID 时使用。
2. **按标识值 + 字段匹配**：不知道 ID、但知道 slug 或名称等值时使用。借助 `page-context` 快照将标识值解析为 ID。

执行后，相应行会在表格中高亮显示，选择结果会上报给 `useSommaticSelection`，并可通过 `read.selection.get` 读取。

#### 使用场景

- 用户说“选中 slug 为 'my-project' 的行”时。
- 对选中的行执行批量操作之前。
- LLM 借助页面上下文将实体名称解析为 ID 时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 表格界面的 ID。 |
| `row_ids` | `string[]` | 否 | 要选中的确切行 ID 数组。 |
| `identifiers` | `string[]` | 否 | 不知道确切 ID 时用于匹配的值（例如 slug 或名称）。需要同时提供 `match_field`。 |
| `match_field` | `string` | 否 | 在 page-context 的 `items` 数组中用于匹配 `identifiers` 的字段（例如 `'slug'`、`'name'`）。默认为 `'id'`。 |

`row_ids` 与 `identifiers` 至少需要提供一个。

#### 返回值

```js
{
  ok: true,
  title: "Selected 2 rows in [project-list-grid]",
  selected_count: 2,
  selected_ids: ["prj-management-a4b0e53a9532edd", "prj-management-f00d4ca337d8dcb"],
  receipt_id: "rcpt_1772112464496_2kolnjx"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "MISSING_ROW_IDS", message: "Either row_ids or identifiers must be provided" } }
{ ok: false, error: { code: "NO_SELECTION_HANDLER", message: "Surface [xyz] has no selectRows handler" } }
{ ok: false, error: { code: "NO_PAGE_CONTEXT", message: "page-context snapshot unavailable for identifier resolution" } }
{ ok: false, error: { code: "NO_ITEMS_IN_CONTEXT", message: "page-context snapshot has no 'items' array" } }
{ ok: false, error: { code: "NO_MATCHES", message: "No items matched the provided identifiers" } }
```

#### 实现

```js
// commands/exec/selectRows.action.js
export const action = async (args, registry) => {
  const { surface_id, row_ids, identifiers, match_field = 'id' } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.selectRows) {
    return { ok: false, error: { code: 'NO_SELECTION_HANDLER', message: `Surface [${surface_id}] has no selectRows handler` } };
  }

  let resolvedIds = Array.isArray(row_ids) ? [...row_ids] : [];

  // Resolve identifiers to IDs using page-context snapshot
  if (Array.isArray(identifiers) && identifiers.length > 0 && match_field !== 'id') {
    const snapshot = registry?.getSnapshot?.('page-context');
    const items = snapshot?.payload?.items;

    if (!items) return { ok: false, error: { code: 'NO_PAGE_CONTEXT', message: 'page-context snapshot unavailable' } };
    if (!Array.isArray(items)) return { ok: false, error: { code: 'NO_ITEMS_IN_CONTEXT', message: 'page-context has no items array' } };

    const normalized = identifiers.map((v) => String(v).toLowerCase());
    const matched = items.filter((item) =>
      normalized.includes(String(item[match_field] ?? '').toLowerCase())
    );

    if (matched.length === 0) {
      return { ok: false, error: { code: 'NO_MATCHES', message: `No items matched identifiers via field '${match_field}'` } };
    }

    resolvedIds = [...resolvedIds, ...matched.map((item) => item.id)];
  }

  if (resolvedIds.length === 0 && (!Array.isArray(identifiers) || identifiers.length === 0)) {
    return { ok: false, error: { code: 'MISSING_ROW_IDS', message: 'Either row_ids or identifiers must be provided' } };
  }

  await surface.handlers.selectRows(resolvedIds);

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.select_rows',
    args,
    reversible: true,
    undo: async () => surface.handlers.selectRows([]),
  });

  return {
    ok: true,
    title: `Selected ${resolvedIds.length} rows in [${surface_id}]`,
    selected_count: resolvedIds.length,
    selected_ids: resolvedIds,
    receipt_id: receipt?.id,
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.select_rows',
  label: '/select-rows',
  description: 'Select rows in a grid by IDs or by matching field values',
  schema: {
    type: 'object',
    properties: {
      surface_id: {
        type: 'string',
        description: "ID of the grid surface. Known surfaces: 'project-list-grid', etc."
      },
      row_ids: {
        type: 'array',
        items: { type: 'string' },
        description: 'Array of exact row IDs to select.'
      },
      identifiers: {
        type: 'array',
        items: { type: 'string' },
        description: "Values to match when IDs are unknown (e.g., slugs or names). Use with match_field."
      },
      match_field: {
        type: 'string',
        description: "Field to match identifiers against (e.g. 'slug', 'name'). Requires page-context items array."
      }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.selectRows(args, registry),
}
```

#### 视觉反馈要求

要让行在 MUI DataGrid 中显示为选中状态，宿主组件必须：

```jsx
const [selectedRowIds, setSelectedRowIds] = useState([]);

// In the surface handler:
handlers: {
  selectRows: (ids) => setSelectedRowIds(ids),
}

// In the DataGrid:
<DataGrid
  checkboxSelection
  rowSelectionModel={selectedRowIds}
  onRowSelectionModelChange={(ids) => setSelectedRowIds(ids)}
  disableRowSelectionOnClick={true}
/>
```

如果没有将 `rowSelectionModel` 绑定到状态，命令只会在内部更新状态，行不会高亮显示。

#### 说明

- 将标识值解析为 ID 要求 `page-context` 的载荷中包含 `items` 数组。宿主组件的 `getData()` 必须返回该数组。
- 回执为 `reversible: true`。撤销操作会调用 `selectRows([])` 清除选择。
- 选中行后，如果已接入 `useSommaticSelection`，`read.selection.get` 将返回所选 ID。

### `/set-fields`

`command_center.exec.ui.set_fields`

在 FormSurface 中批量设置字段

#### 用途

通过键值映射调用界面的 `setFields` 处理器，填写一个或多个表单字段。它是对单个目标调用 `exec.ui.act` 的高层替代方案，面向提供批量设置 API 的表单界面。

#### 使用场景

- 用户要求预填表单时：“把表单的名称填为 'Test Project'，状态填为 'active'。”
- 作为流程的一部分：打开模态框 → 设置字段 → 提交表单。
- 当表单界面注册了接受 `fields` 对象的 `setFields` 处理器时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 表单界面的 ID。 |
| `fields` | `object` | 是 | 字段名到值的键值映射。 |

#### 返回值

```js
{
  ok: true,
  title: "Set fields on [create-project-form]",
  fields_set: ["name", "status", "organization"],
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "MISSING_FIELDS", message: "fields object is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_SET_FIELDS_HANDLER", message: "Surface [xyz] has no setFields handler" } }
{ ok: false, error: { code: "SET_FIELDS_FAILED", message: "Handler threw: ..." } }
```

#### 实现

```js
// commands/exec/setFields.action.js
export const action = async (args, registry) => {
  const { surface_id, fields } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };
  if (!fields || typeof fields !== 'object') {
    return { ok: false, error: { code: 'MISSING_FIELDS', message: 'fields object is required' } };
  }

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.setFields) {
    return { ok: false, error: { code: 'NO_SET_FIELDS_HANDLER', message: `Surface [${surface_id}] has no setFields handler` } };
  }

  try {
    await surface.handlers.setFields(fields);
  } catch (err) {
    return { ok: false, error: { code: 'SET_FIELDS_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.set_fields',
    args,
    reversible: false,
    fields_set: Object.keys(fields),
  });

  return {
    ok: true,
    title: `Set fields on [${surface_id}]`,
    fields_set: Object.keys(fields),
    receipt_id: receipt?.id,
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.set_fields',
  label: '/set-fields',
  description: 'Fill form fields with a key-value map',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the form surface.' },
      fields: {
        type: 'object',
        description: 'Key-value map of fields to fill (e.g. { "name": "My Project", "status": "active" }).'
      }
    },
    required: ['surface_id', 'fields']
  },
  action: (args) => Exec.setFields(args, registry),
}
```

#### 使用 `setFields` 注册表单

```jsx
const [name, setName] = useState('');
const [status, setStatus] = useState('active');

useSommaticSurface({
  id: 'create-project-form',
  type: 'form',
  label: 'Create Project Form',
  handlers: {
    setFields: (fields) => {
      if (fields.name !== undefined) setName(fields.name);
      if (fields.status !== undefined) setStatus(fields.status);
    },
    submit: () => handleSubmit(),
  },
}, []);
```

#### 说明

- `setFields` 是界面级的批量设置器。单个目标级的设置通过 `exec.ui.act` 的 `fill` 方法完成。
- 界面中的 `setFields` 处理器负责决定更新哪些字段，未知的键可以被静默忽略。
- 调用 `set_fields` 后，可在提交前使用 `extract.from_targets` 校验字段值。

### `/submit-form`

`command_center.exec.ui.submit_form`

提交已发布的表单

#### 用途

通过调用已注册表单界面的 `submit` 处理器，以编程方式提交表单。所有校验和提交逻辑都由界面内部处理。

#### 使用场景

- 作为使用 `exec.ui.set_fields` 填写表单后的最后一步。
- 用户说“提交表单”或“保存”时。
- 在自动化流程中：打开模态框 → 设置字段 → 提交。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `surface_id` | `string` | 是 | 要提交的表单界面 ID。 |

#### 返回值

```js
{
  ok: true,
  title: "Submitted form [create-project-form]",
  data: { /* whatever the submit handler returned */ },
  receipt_id: "rcpt_1772075473717_abc"
}
```

##### 错误情况

```js
{ ok: false, error: { code: "MISSING_SURFACE_ID", message: "surface_id is required" } }
{ ok: false, error: { code: "SURFACE_NOT_FOUND", message: "Surface [xyz] not found" } }
{ ok: false, error: { code: "NO_SUBMIT_HANDLER", message: "Surface [xyz] has no submit handler" } }
{ ok: false, error: { code: "SUBMIT_FAILED", message: "Handler threw: Validation error: name is required" } }
```

#### 实现

```js
// commands/exec/submitForm.action.js
export const action = async (args, registry) => {
  const { surface_id } = args || {};

  if (!surface_id) return { ok: false, error: { code: 'MISSING_SURFACE_ID', message: 'surface_id is required' } };

  const surface = registry?.getSurface?.(surface_id);
  if (!surface) return { ok: false, error: { code: 'SURFACE_NOT_FOUND', message: `Surface [${surface_id}] not found` } };

  if (!surface.handlers?.submit) {
    return { ok: false, error: { code: 'NO_SUBMIT_HANDLER', message: `Surface [${surface_id}] has no submit handler` } };
  }

  let result;
  try {
    result = await surface.handlers.submit();
  } catch (err) {
    return { ok: false, error: { code: 'SUBMIT_FAILED', message: err.message } };
  }

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.ui.submit_form',
    args,
    reversible: false,
    result,
  });

  return { ok: true, title: `Submitted form [${surface_id}]`, data: result, receipt_id: receipt?.id };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.ui.submit_form',
  label: '/submit-form',
  description: 'Submit a registered form surface',
  schema: {
    type: 'object',
    properties: {
      surface_id: { type: 'string', description: 'ID of the form surface to submit.' }
    },
    required: ['surface_id']
  },
  action: (args) => Exec.submitForm(args, registry),
}
```

#### 注册带提交处理器的表单

```jsx
const handleSubmit = async () => {
  try {
    await createProject({ name, status, organizationId });
    setIsOpen(false);
    return { success: true };
  } catch (err) {
    throw new Error(`Validation error: ${err.message}`);
  }
};

useSommaticSurface({
  id: 'create-project-form',
  type: 'form',
  label: 'Create Project Form',
  handlers: {
    submit: handleSubmit,
    setFields: (f) => { /* ... */ },
  },
}, []);
```

#### 说明

- 校验失败时，`submit` 处理器应抛出异常，错误信息将以 `SUBMIT_FAILED` 返回。
- 如果表单提交成功后会关闭模态框，请单独注册 `close` 处理器，并在需要时后续调用 `exec.ui.close_surface`。
- 成功响应中的 `data` 即 `submit()` 的返回值，可用于在后续步骤中获取新建实体的 ID。

### `/undo`

`command_center.exec.undo`

尝试撤销某个操作

#### 用途

撤销回执栈中最近一次可撤销的操作。查找最近一条 `reversible: true` 的回执，并调用其 `undo` 处理器。

#### 使用场景

- 用户说“撤销”或“回退上一步操作”时。
- 误应用了筛选，或选中了用户并不想选的行之后。
- 用于自动化流程中的快速回滚。

#### 参数

无。

#### 返回值

```js
{
  ok: true,
  title: "Undone: exec.ui.apply_filter",
  undone_receipt_id: "rcpt_1772075473717_abc",
  receipt_id: "rcpt_1772075480000_undo"
}
```

不存在可撤销的操作时：

```js
{
  ok: false,
  error: { code: "NOTHING_TO_UNDO", message: "No reversible action found in receipt stack" }
}
```

撤销失败时：

```js
{
  ok: false,
  error: { code: "UNDO_FAILED", message: "Undo handler threw: ..." }
}
```

#### 实现

```js
// commands/exec/undo.action.js
export const action = async (args, registry) => {
  const stack = registry?.getReceiptStack?.() || [];

  const reversibleReceipt = stack.find((receipt) => receipt.reversible && receipt.undo);

  if (!reversibleReceipt) {
    return { ok: false, error: { code: 'NOTHING_TO_UNDO', message: 'No reversible action found in receipt stack' } };
  }

  try {
    await reversibleReceipt.undo();
  } catch (err) {
    return { ok: false, error: { code: 'UNDO_FAILED', message: err.message } };
  }

  // Remove the undone receipt from the stack
  registry?.removeReceipt?.(reversibleReceipt.id);

  const receipt = registry.pushReceipt?.({
    command_id: 'command_center.exec.undo',
    args: {},
    reversible: false,
    undone_command: reversibleReceipt.command_id,
  });

  return {
    ok: true,
    title: `Undone: ${reversibleReceipt.command_id}`,
    undone_receipt_id: reversibleReceipt.id,
    receipt_id: receipt?.id,
  };
};
```

#### 命令定义

```js
{
  id: 'command_center.exec.undo',
  label: '/undo',
  description: 'Undo the last reversible action',
  schema: {},
  action: () => Exec.undo(registry),
}
```

#### 哪些命令可撤销？

| 命令 | 可撤销 | 撤销操作 |
|---------|-----------|-------------|
| `exec.ui.apply_filter` | 是 | `applyFilter('')`（清除筛选） |
| `exec.ui.select_rows` | 是 | `selectRows([])`（清除选择） |
| `exec.ui.act` | 否 | — |
| `exec.ui.act_batch` | 否 | — |
| `exec.ui.open_surface` | 否 | — |
| `exec.ui.close_surface` | 否 | — |
| `exec.ui.set_fields` | 否 | — |
| `exec.ui.submit_form` | 否 | — |
| `exec.navigate` | 否 | — |
| `exec.clipboard.copy` | 否 | — |
| `exec.app.open` | 否 | — |
| `exec.command.invoke` | 否 | — |
| `exec.tasks.*` | 否 | — |

#### 让命令可撤销

实现执行类命令时，向 `pushReceipt` 传入 `reversible: true` 和一个 `undo` 函数：

```js
const receipt = registry.pushReceipt?.({
  command_id: 'command_center.exec.ui.apply_filter',
  args,
  reversible: true,
  undo: async () => {
    await surface.handlers.applyFilter('');
  },
});
```

`undo` 函数必须是一个闭包，捕获撤销该操作所需的全部信息。

#### 说明

- 系统会从最新到最旧搜索回执栈，找到第一条 `reversible: true` 的记录。
- `exec.undo` 自身的回执不可撤销（无法“撤销一次撤销”）。
- 撤销栈仅保存在内存中，刷新页面后即丢失。
- 复杂的状态变更（API 调用、数据库修改）除非后端具备真正的回滚机制，否则不应标记为可撤销。

### `/run-workflow`

`command_center.exec.workflow.run`

按意图运行工作流（例如“运行这个工作流”或“运行宠物推荐工作流”）。该命令会把工作流交给 Workflow Navigator 应用执行，实时展示每个节点的进度，并返回结果以继续执行计划。无需提供 id：屏幕上已打开工作流时，会从当前页面上下文自动解析；否则传入 `workflow_name`，填写用户提到的名称，系统会在你的组织内解析。必要时传入 `input` 描述用户的请求（例如把用户给出的宠物描述设为 input.text）；省略时使用工作流的示例输入。传入 `flow_version_id` 可强制运行已发布版本，传入 `flow_definition_id` 可强制运行指定草稿。

#### 用途

按意图解析工作流，并交给 **Workflow Navigator** 应用（`sommatic-workflow-navigator`）处理，该应用以 `command-center` 启动模式打开。命令本身**不会**执行工作流：由应用运行工作流、实时展示各节点进度，并通过 `sdk.submitOutput()` 返回结果，从而让执行计划得以继续（例如串联到另一个应用）。

无需预先定义 Trigger 制品。运行的归属通过标记在描述符上的 `execution_source` 记录。

#### 使用场景

- 屏幕上打开了某个工作流时说“运行这个工作流”。
- 在任意页面说“运行宠物推荐工作流”：系统会在组织内按名称解析该工作流。
- 作为执行计划中的一步，需要先拿到工作流结果才能继续时。

#### 参数

| 参数 | 类型 | 必填 | 说明 |
|----------|------|----------|-------------|
| `workflow_name` | `string` | 否 | 用户提到的名称。仅在未提供 ID 且屏幕上没有打开可运行的工作流时使用。 |
| `flow_definition_id` | `string` | 否 | 以测试模式运行的定义（草稿）。 |
| `flow_version_id` | `string` | 否 | 以生产模式运行的编译版本。优先级高于 `flow_definition_id`。 |
| `input` | `object` | 否 | 输入载荷。会逐字段合并到触发器的示例载荷之上。 |

三种解析途径中至少有一种必须成功（见下文），否则命令返回 `MISSING_FLOW_ID`。

#### 解析顺序

显式参数始终优先：

1. 参数中的 **`flow_definition_id` / `flow_version_id`**。
2. **屏幕上打开的工作流：**当 `run.runnable` 为 true 时，使用 `page-context` 快照中的 `payload.run` 描述符。它还会提供运行名称和触发器的 `input_example`。
3. **`workflow_name`：**通过 `WorkflowOrchestrationFlowDefinitionService.getByParameters({ queryselector: 'search', search, organization_id, exclude_status: 'deleted', pageSize: 1 })` 在组织内搜索。使用第一个匹配结果，其触发器节点的 `config.payload_template` 将作为示例输入。

#### 输入绑定

运行输入为 `{ ...inputExample, ...args.input }`。随后，仅针对触发器载荷中已声明的键：

| 键 | 为空时绑定为 |
|-----|----------------------|
| `source_url` | Command Center 中最近附加文件的 URL（`registry.getActiveAttachments()`），除非调用方已传入 `input.source_url`。 |
| `assignee` | 当前用户的身份。 |
| `organization_id` | 当前用户所属的组织。 |

#### 返回值

用于打开 Navigator 的 `app-embed` 描述符：

```js
{
  ok: true,
  type: 'app-embed',
  title: 'Running workflow "Pet recommendations"',
  app_embed: {
    app_slug: 'sommatic-workflow-navigator',
    route_path: '/run',
    launch_mode: 'command-center',
    input_payload: {
      run: {
        flow_definition_id: 'flow-def-abc123',
        flow_version_id: null,
        input: { text: 'Small dog, lives in an apartment' },
        organization_id: 'org-xyz',
        user_identity: 'user-123',
        execution_source: {
          source: 'command-center',
          app_slug: 'sommatic-workflow-navigator',
          actor: 'user-123',
          intent_text: 'pet recommendations'
        },
        name: 'Pet recommendations'
      }
    }
  },
  receipt_id: 'rcpt_1772075473717_abc'
}
```

##### 错误情况

```js
{ ok: false, error: { code: 'MISSING_FLOW_ID', message: 'No workflow could be resolved. Provide flow_definition_id, flow_version_id, or a workflow_name that matches one in your organization.' } }
```

按名称查找失败本身不算错误，会继续落到 `MISSING_FLOW_ID`。

#### 命令定义

```js
{
  id: 'command_center.exec.workflow.run',
  label: '/run-workflow',
  description: 'Run a workflow by intent. Hands the workflow to the Workflow Navigator app, which executes it, shows live per-node progress, and returns the result to continue the plan...',
  isPriority: true,
  schema: {
    type: 'object',
    properties: {
      workflow_name: { type: 'string' },
      flow_definition_id: { type: 'string' },
      flow_version_id: { type: 'string' },
      input: { type: 'object' }
    }
  },
  action: (args) => Exec.runWorkflow(args, registry),
}
```

完整的描述文本位于 `commands/definitions.js`。

#### 回执

系统会推送一条 `command_id: 'command_center.exec.workflow.run'`、`reversible: false` 的回执。已启动的运行无法通过 `exec.undo` 撤销。
